2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
8 // (C) 2003, 2004 Novell, Inc.
12 namespace Mono.CSharp {
14 using System.Collections;
15 using System.Reflection;
16 using System.Reflection.Emit;
18 using Microsoft.VisualBasic;
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 public StaticCallExpr (MethodInfo m, ArrayList a, Location l)
35 eclass = ExprClass.Value;
39 public override Expression DoResolve (EmitContext ec)
42 // We are born fully resolved
47 public override void Emit (EmitContext ec)
50 Invocation.EmitArguments (ec, mi, args, false, null);
52 ec.ig.Emit (OpCodes.Call, mi);
56 static public StaticCallExpr MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
57 Expression e, Location loc)
62 args = new ArrayList (1);
63 Argument a = new Argument (e, Argument.AType.Expression);
65 // We need to resolve the arguments before sending them in !
66 if (!a.Resolve (ec, loc))
70 method = Invocation.OverloadResolve (
71 ec, (MethodGroupExpr) mg, args, false, loc);
76 return new StaticCallExpr ((MethodInfo) method, args, loc);
79 public override void EmitStatement (EmitContext ec)
82 if (TypeManager.TypeToCoreType (type) != TypeManager.void_type)
83 ec.ig.Emit (OpCodes.Pop);
86 public MethodInfo Method {
91 public class ParenthesizedExpression : Expression
93 public Expression Expr;
95 public ParenthesizedExpression (Expression expr, Location loc)
101 public override Expression DoResolve (EmitContext ec)
103 Expr = Expr.Resolve (ec);
107 public override void Emit (EmitContext ec)
109 throw new Exception ("Should not happen");
114 /// Unary expressions.
118 /// Unary implements unary expressions. It derives from
119 /// ExpressionStatement becuase the pre/post increment/decrement
120 /// operators can be used in a statement context.
122 public class Unary : Expression {
123 public enum Operator : byte {
124 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
125 Indirection, AddressOf, TOP
128 public Operator Oper;
129 public Expression Expr;
131 public Unary (Operator op, Expression expr, Location loc)
139 /// Returns a stringified representation of the Operator
141 static public string OperName (Operator oper)
144 case Operator.UnaryPlus:
146 case Operator.UnaryNegation:
148 case Operator.LogicalNot:
150 case Operator.OnesComplement:
152 case Operator.AddressOf:
154 case Operator.Indirection:
158 return oper.ToString ();
161 public static readonly string [] oper_names;
165 oper_names = new string [(int)Operator.TOP];
167 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
168 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
169 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
170 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
171 oper_names [(int) Operator.Indirection] = "op_Indirection";
172 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
175 void Error23 (Type t)
178 23, "Operator " + OperName (Oper) +
179 " cannot be applied to operand of type `" +
180 TypeManager.CSharpName (t) + "'");
184 /// The result has been already resolved:
186 /// FIXME: a minus constant -128 sbyte cant be turned into a
189 static Expression TryReduceNegative (Constant expr)
193 if (expr is IntConstant)
194 e = new IntConstant (-((IntConstant) expr).Value);
195 else if (expr is UIntConstant){
196 uint value = ((UIntConstant) expr).Value;
198 if (value < 2147483649)
199 return new IntConstant (-(int)value);
201 e = new LongConstant (-value);
203 else if (expr is LongConstant)
204 e = new LongConstant (-((LongConstant) expr).Value);
205 else if (expr is ULongConstant){
206 ulong value = ((ULongConstant) expr).Value;
208 if (value < 9223372036854775809)
209 return new LongConstant(-(long)value);
211 else if (expr is FloatConstant)
212 e = new FloatConstant (-((FloatConstant) expr).Value);
213 else if (expr is DoubleConstant)
214 e = new DoubleConstant (-((DoubleConstant) expr).Value);
215 else if (expr is DecimalConstant)
216 e = new DecimalConstant (-((DecimalConstant) expr).Value);
217 else if (expr is ShortConstant)
218 e = new IntConstant (-((ShortConstant) expr).Value);
219 else if (expr is UShortConstant)
220 e = new IntConstant (-((UShortConstant) expr).Value);
221 else if (expr is SByteConstant)
222 e = new IntConstant (-((SByteConstant) expr).Value);
223 else if (expr is ByteConstant)
224 e = new IntConstant (-((ByteConstant) expr).Value);
229 // This routine will attempt to simplify the unary expression when the
230 // argument is a constant. The result is returned in `result' and the
231 // function returns true or false depending on whether a reduction
232 // was performed or not
234 bool Reduce (EmitContext ec, Constant e, out Expression result)
236 Type expr_type = e.Type;
239 case Operator.UnaryPlus:
243 case Operator.UnaryNegation:
244 result = TryReduceNegative (e);
245 return result != null;
247 case Operator.LogicalNot:
248 if (expr_type != TypeManager.bool_type) {
254 BoolConstant b = (BoolConstant) e;
255 result = new BoolConstant (!(b.Value));
258 case Operator.OnesComplement:
259 if (!((expr_type == TypeManager.int32_type) ||
260 (expr_type == TypeManager.uint32_type) ||
261 (expr_type == TypeManager.int64_type) ||
262 (expr_type == TypeManager.uint64_type) ||
263 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
266 if (Convert.WideningConversionExists (ec, e, TypeManager.int32_type)){
267 result = new Cast (new TypeExpression (TypeManager.int32_type, loc), e, loc);
268 result = result.Resolve (ec);
269 } else if (Convert.WideningConversionExists (ec, e, TypeManager.uint32_type)){
270 result = new Cast (new TypeExpression (TypeManager.uint32_type, loc), e, loc);
271 result = result.Resolve (ec);
272 } else if (Convert.WideningConversionExists (ec, e, TypeManager.int64_type)){
273 result = new Cast (new TypeExpression (TypeManager.int64_type, loc), e, loc);
274 result = result.Resolve (ec);
275 } else if (Convert.WideningConversionExists (ec, e, TypeManager.uint64_type)){
276 result = new Cast (new TypeExpression (TypeManager.uint64_type, loc), e, loc);
277 result = result.Resolve (ec);
280 if (result == null || !(result is Constant)){
286 expr_type = result.Type;
287 e = (Constant) result;
290 if (e is EnumConstant){
291 EnumConstant enum_constant = (EnumConstant) e;
294 if (Reduce (ec, enum_constant.Child, out reduced)){
295 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
303 if (expr_type == TypeManager.int32_type){
304 result = new IntConstant (~ ((IntConstant) e).Value);
305 } else if (expr_type == TypeManager.uint32_type){
306 result = new UIntConstant (~ ((UIntConstant) e).Value);
307 } else if (expr_type == TypeManager.int64_type){
308 result = new LongConstant (~ ((LongConstant) e).Value);
309 } else if (expr_type == TypeManager.uint64_type){
310 result = new ULongConstant (~ ((ULongConstant) e).Value);
318 case Operator.AddressOf:
322 case Operator.Indirection:
326 throw new Exception ("Can not constant fold: " + Oper.ToString());
329 Expression ResolveOperator (EmitContext ec)
332 // Step 1: Default operations on CLI native types.
335 // Attempt to use a constant folding operation.
336 if (Expr is Constant){
339 if (Reduce (ec, (Constant) Expr, out result))
344 // Step 2: Perform Operator Overload location
346 Type expr_type = Expr.Type;
350 op_name = oper_names [(int) Oper];
352 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
355 Expression e = StaticCallExpr.MakeSimpleCall (
356 ec, (MethodGroupExpr) mg, Expr, loc);
366 // Only perform numeric promotions on:
369 if (expr_type == null)
373 case Operator.LogicalNot:
374 if (expr_type != TypeManager.bool_type) {
375 Expr = ResolveBoolean (ec, Expr, loc);
382 type = TypeManager.bool_type;
385 case Operator.OnesComplement:
386 if (!((expr_type == TypeManager.int32_type) ||
387 (expr_type == TypeManager.uint32_type) ||
388 (expr_type == TypeManager.int64_type) ||
389 (expr_type == TypeManager.uint64_type) ||
390 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
393 e = Convert.WideningConversion (ec, Expr, TypeManager.int32_type, loc);
395 type = TypeManager.int32_type;
398 e = Convert.WideningConversion (ec, Expr, TypeManager.uint32_type, loc);
400 type = TypeManager.uint32_type;
403 e = Convert.WideningConversion (ec, Expr, TypeManager.int64_type, loc);
405 type = TypeManager.int64_type;
408 e = Convert.WideningConversion (ec, Expr, TypeManager.uint64_type, loc);
410 type = TypeManager.uint64_type;
419 case Operator.AddressOf:
420 if (Expr.eclass != ExprClass.Variable){
421 Error (211, "Cannot take the address of non-variables");
430 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
434 IVariable variable = Expr as IVariable;
435 bool is_fixed = variable != null && variable.VerifyFixed (false);
437 if (!ec.InFixedInitializer && !is_fixed) {
438 Error (212, "You can only take the address of an unfixed expression inside " +
439 "of a fixed statement initializer");
443 if (ec.InFixedInitializer && is_fixed) {
444 Error (213, "You can not fix an already fixed expression");
448 LocalVariableReference lr = Expr as LocalVariableReference;
450 if (lr.local_info.IsCaptured){
451 AnonymousMethod.Error_AddressOfCapturedVar (lr.Name, loc);
454 lr.local_info.AddressTaken = true;
455 lr.local_info.Used = true;
458 // According to the specs, a variable is considered definitely assigned if you take
460 if ((variable != null) && (variable.VariableInfo != null))
461 variable.VariableInfo.SetAssigned (ec);
463 type = TypeManager.GetPointerType (Expr.Type);
466 case Operator.Indirection:
472 if (!expr_type.IsPointer){
473 Error (193, "The * or -> operator can only be applied to pointers");
478 // We create an Indirection expression, because
479 // it can implement the IMemoryLocation.
481 return new Indirection (Expr, loc);
483 case Operator.UnaryPlus:
485 // A plus in front of something is just a no-op, so return the child.
489 case Operator.UnaryNegation:
491 // Deals with -literals
492 // int operator- (int x)
493 // long operator- (long x)
494 // float operator- (float f)
495 // double operator- (double d)
496 // decimal operator- (decimal d)
498 Expression expr = null;
501 // transform - - expr into expr
504 Unary unary = (Unary) Expr;
506 if (unary.Oper == Operator.UnaryNegation)
511 // perform numeric promotions to int,
515 // The following is inneficient, because we call
516 // WideningConversion too many times.
518 // It is also not clear if we should convert to Float
519 // or Double initially.
521 if (expr_type == TypeManager.uint32_type){
523 // FIXME: handle exception to this rule that
524 // permits the int value -2147483648 (-2^31) to
525 // bt wrote as a decimal interger literal
527 type = TypeManager.int64_type;
528 Expr = Convert.WideningConversion (ec, Expr, type, loc);
532 if (expr_type == TypeManager.uint64_type){
534 // FIXME: Handle exception of `long value'
535 // -92233720368547758087 (-2^63) to be wrote as
536 // decimal integer literal.
542 if (expr_type == TypeManager.float_type){
547 expr = Convert.WideningConversion (ec, Expr, TypeManager.int32_type, loc);
554 expr = Convert.WideningConversion (ec, Expr, TypeManager.int64_type, loc);
561 expr = Convert.WideningConversion (ec, Expr, TypeManager.double_type, loc);
572 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
573 TypeManager.CSharpName (expr_type) + "'");
577 public override Expression DoResolve (EmitContext ec)
579 if (Oper == Operator.AddressOf)
580 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
582 Expr = Expr.Resolve (ec);
587 if (TypeManager.IsNullableType (Expr.Type))
588 return new Nullable.LiftedUnaryOperator (Oper, Expr, loc).Resolve (ec);
590 eclass = ExprClass.Value;
591 return ResolveOperator (ec);
594 public override Expression DoResolveLValue (EmitContext ec, Expression right)
596 if (Oper == Operator.Indirection)
597 return base.DoResolveLValue (ec, right);
599 Error (131, "The left-hand side of an assignment must be a " +
600 "variable, property or indexer");
604 public override void Emit (EmitContext ec)
606 ILGenerator ig = ec.ig;
609 case Operator.UnaryPlus:
610 throw new Exception ("This should be caught by Resolve");
612 case Operator.UnaryNegation:
614 ig.Emit (OpCodes.Ldc_I4_0);
615 if (type == TypeManager.int64_type)
616 ig.Emit (OpCodes.Conv_U8);
618 ig.Emit (OpCodes.Sub_Ovf);
621 ig.Emit (OpCodes.Neg);
626 case Operator.LogicalNot:
628 ig.Emit (OpCodes.Ldc_I4_0);
629 ig.Emit (OpCodes.Ceq);
632 case Operator.OnesComplement:
634 ig.Emit (OpCodes.Not);
637 case Operator.AddressOf:
638 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
642 throw new Exception ("This should not happen: Operator = "
647 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
649 if (Oper == Operator.LogicalNot)
650 Expr.EmitBranchable (ec, target, !onTrue);
652 base.EmitBranchable (ec, target, onTrue);
655 public override string ToString ()
657 return "Unary (" + Oper + ", " + Expr + ")";
663 // Unary operators are turned into Indirection expressions
664 // after semantic analysis (this is so we can take the address
665 // of an indirection).
667 public class Indirection : Expression, IMemoryLocation, IAssignMethod, IVariable {
669 LocalTemporary temporary;
672 public Indirection (Expression expr, Location l)
675 this.type = TypeManager.GetElementType (expr.Type);
676 eclass = ExprClass.Variable;
680 void LoadExprValue (EmitContext ec)
684 public override void Emit (EmitContext ec)
689 LoadFromPtr (ec.ig, Type);
692 public void Emit (EmitContext ec, bool leave_copy)
696 ec.ig.Emit (OpCodes.Dup);
697 temporary = new LocalTemporary (ec, expr.Type);
698 temporary.Store (ec);
702 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
704 prepared = prepare_for_load;
708 if (prepare_for_load)
709 ec.ig.Emit (OpCodes.Dup);
713 ec.ig.Emit (OpCodes.Dup);
714 temporary = new LocalTemporary (ec, expr.Type);
715 temporary.Store (ec);
718 StoreFromPtr (ec.ig, type);
720 if (temporary != null)
724 public void AddressOf (EmitContext ec, AddressOp Mode)
729 public override Expression DoResolve (EmitContext ec)
732 // Born fully resolved
737 public override string ToString ()
739 return "*(" + expr + ")";
742 #region IVariable Members
744 public VariableInfo VariableInfo {
750 public bool VerifyFixed (bool is_expression)
759 /// Unary Mutator expressions (pre and post ++ and --)
763 /// UnaryMutator implements ++ and -- expressions. It derives from
764 /// ExpressionStatement becuase the pre/post increment/decrement
765 /// operators can be used in a statement context.
767 /// FIXME: Idea, we could split this up in two classes, one simpler
768 /// for the common case, and one with the extra fields for more complex
769 /// classes (indexers require temporary access; overloaded require method)
772 public class UnaryMutator : ExpressionStatement {
774 public enum Mode : byte {
781 PreDecrement = IsDecrement,
782 PostIncrement = IsPost,
783 PostDecrement = IsPost | IsDecrement
787 bool is_expr = false;
788 bool recurse = false;
793 // This is expensive for the simplest case.
795 StaticCallExpr method;
797 public UnaryMutator (Mode m, Expression e, Location l)
804 static string OperName (Mode mode)
806 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
810 void Error23 (Type t)
813 23, "Operator " + OperName (mode) +
814 " cannot be applied to operand of type `" +
815 TypeManager.CSharpName (t) + "'");
819 /// Returns whether an object of type `t' can be incremented
820 /// or decremented with add/sub (ie, basically whether we can
821 /// use pre-post incr-decr operations on it, but it is not a
822 /// System.Decimal, which we require operator overloading to catch)
824 static bool IsIncrementableNumber (Type t)
826 return (t == TypeManager.sbyte_type) ||
827 (t == TypeManager.byte_type) ||
828 (t == TypeManager.short_type) ||
829 (t == TypeManager.ushort_type) ||
830 (t == TypeManager.int32_type) ||
831 (t == TypeManager.uint32_type) ||
832 (t == TypeManager.int64_type) ||
833 (t == TypeManager.uint64_type) ||
834 (t == TypeManager.char_type) ||
835 (t.IsSubclassOf (TypeManager.enum_type)) ||
836 (t == TypeManager.float_type) ||
837 (t == TypeManager.double_type) ||
838 (t.IsPointer && t != TypeManager.void_ptr_type);
841 Expression ResolveOperator (EmitContext ec)
843 Type expr_type = expr.Type;
846 // Step 1: Perform Operator Overload location
851 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
852 op_name = "op_Increment";
854 op_name = "op_Decrement";
856 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
858 if (mg == null && expr_type.BaseType != null)
859 mg = MemberLookup (ec, expr_type.BaseType, op_name,
860 MemberTypes.Method, AllBindingFlags, loc);
863 method = StaticCallExpr.MakeSimpleCall (
864 ec, (MethodGroupExpr) mg, expr, loc);
871 // The operand of the prefix/postfix increment decrement operators
872 // should be an expression that is classified as a variable,
873 // a property access or an indexer access
876 if (expr.eclass == ExprClass.Variable){
877 LocalVariableReference var = expr as LocalVariableReference;
878 if ((var != null) && var.IsReadOnly)
879 Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
880 if (IsIncrementableNumber (expr_type) ||
881 expr_type == TypeManager.decimal_type){
884 } else if (expr.eclass == ExprClass.IndexerAccess){
885 IndexerAccess ia = (IndexerAccess) expr;
887 expr = ia.ResolveLValue (ec, this);
892 } else if (expr.eclass == ExprClass.PropertyAccess){
893 PropertyExpr pe = (PropertyExpr) expr;
895 if (pe.VerifyAssignable ())
900 expr.Error_UnexpectedKind ("variable, indexer or property access", loc);
904 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
905 TypeManager.CSharpName (expr_type) + "'");
909 public override Expression DoResolve (EmitContext ec)
911 expr = expr.Resolve (ec);
916 eclass = ExprClass.Value;
918 if (TypeManager.IsNullableType (expr.Type))
919 return new Nullable.LiftedUnaryMutator (mode, expr, loc).Resolve (ec);
921 return ResolveOperator (ec);
924 static int PtrTypeSize (Type t)
926 return GetTypeSize (TypeManager.GetElementType (t));
930 // Loads the proper "1" into the stack based on the type, then it emits the
931 // opcode for the operation requested
933 void LoadOneAndEmitOp (EmitContext ec, Type t)
936 // Measure if getting the typecode and using that is more/less efficient
937 // that comparing types. t.GetTypeCode() is an internal call.
939 ILGenerator ig = ec.ig;
941 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
942 LongConstant.EmitLong (ig, 1);
943 else if (t == TypeManager.double_type)
944 ig.Emit (OpCodes.Ldc_R8, 1.0);
945 else if (t == TypeManager.float_type)
946 ig.Emit (OpCodes.Ldc_R4, 1.0F);
947 else if (t.IsPointer){
948 int n = PtrTypeSize (t);
951 ig.Emit (OpCodes.Sizeof, t);
953 IntConstant.EmitInt (ig, n);
955 ig.Emit (OpCodes.Ldc_I4_1);
958 // Now emit the operation
961 if (t == TypeManager.int32_type ||
962 t == TypeManager.int64_type){
963 if ((mode & Mode.IsDecrement) != 0)
964 ig.Emit (OpCodes.Sub_Ovf);
966 ig.Emit (OpCodes.Add_Ovf);
967 } else if (t == TypeManager.uint32_type ||
968 t == TypeManager.uint64_type){
969 if ((mode & Mode.IsDecrement) != 0)
970 ig.Emit (OpCodes.Sub_Ovf_Un);
972 ig.Emit (OpCodes.Add_Ovf_Un);
974 if ((mode & Mode.IsDecrement) != 0)
975 ig.Emit (OpCodes.Sub_Ovf);
977 ig.Emit (OpCodes.Add_Ovf);
980 if ((mode & Mode.IsDecrement) != 0)
981 ig.Emit (OpCodes.Sub);
983 ig.Emit (OpCodes.Add);
986 if (t == TypeManager.sbyte_type){
988 ig.Emit (OpCodes.Conv_Ovf_I1);
990 ig.Emit (OpCodes.Conv_I1);
991 } else if (t == TypeManager.byte_type){
993 ig.Emit (OpCodes.Conv_Ovf_U1);
995 ig.Emit (OpCodes.Conv_U1);
996 } else if (t == TypeManager.short_type){
998 ig.Emit (OpCodes.Conv_Ovf_I2);
1000 ig.Emit (OpCodes.Conv_I2);
1001 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
1003 ig.Emit (OpCodes.Conv_Ovf_U2);
1005 ig.Emit (OpCodes.Conv_U2);
1010 void EmitCode (EmitContext ec, bool is_expr)
1013 this.is_expr = is_expr;
1014 ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
1017 public override void Emit (EmitContext ec)
1020 // We use recurse to allow ourselfs to be the source
1021 // of an assignment. This little hack prevents us from
1022 // having to allocate another expression
1025 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
1027 LoadOneAndEmitOp (ec, expr.Type);
1029 ec.ig.Emit (OpCodes.Call, method.Method);
1034 EmitCode (ec, true);
1037 public override void EmitStatement (EmitContext ec)
1039 EmitCode (ec, false);
1044 /// Base class for the `Is' and `As' classes.
1048 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1051 public abstract class Probe : Expression {
1052 public Expression ProbeType;
1053 protected Expression expr;
1054 protected Type probe_type;
1056 public Probe (Expression expr, Expression probe_type, Location l)
1058 ProbeType = probe_type;
1063 public Expression Expr {
1069 public override Expression DoResolve (EmitContext ec)
1071 TypeExpr texpr = ProbeType.ResolveAsTypeTerminal (ec);
1074 probe_type = texpr.Type;
1076 CheckObsoleteAttribute (probe_type);
1078 expr = expr.Resolve (ec);
1082 if (expr.Type.IsPointer) {
1083 Report.Error (244, loc, "\"is\" or \"as\" are not valid on pointer types");
1091 /// Implementation of the `is' operator.
1093 public class Is : Probe {
1094 public Is (Expression expr, Expression probe_type, Location l)
1095 : base (expr, probe_type, l)
1100 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1105 public override void Emit (EmitContext ec)
1107 ILGenerator ig = ec.ig;
1112 case Action.AlwaysFalse:
1113 ig.Emit (OpCodes.Pop);
1114 IntConstant.EmitInt (ig, 0);
1116 case Action.AlwaysTrue:
1117 ig.Emit (OpCodes.Pop);
1118 IntConstant.EmitInt (ig, 1);
1120 case Action.LeaveOnStack:
1121 // the `e != null' rule.
1122 ig.Emit (OpCodes.Ldnull);
1123 ig.Emit (OpCodes.Ceq);
1124 ig.Emit (OpCodes.Ldc_I4_0);
1125 ig.Emit (OpCodes.Ceq);
1128 ig.Emit (OpCodes.Isinst, probe_type);
1129 ig.Emit (OpCodes.Ldnull);
1130 ig.Emit (OpCodes.Cgt_Un);
1133 throw new Exception ("never reached");
1136 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
1138 ILGenerator ig = ec.ig;
1141 case Action.AlwaysFalse:
1143 ig.Emit (OpCodes.Br, target);
1146 case Action.AlwaysTrue:
1148 ig.Emit (OpCodes.Br, target);
1151 case Action.LeaveOnStack:
1152 // the `e != null' rule.
1154 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1158 ig.Emit (OpCodes.Isinst, probe_type);
1159 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1162 throw new Exception ("never reached");
1165 public override Expression DoResolve (EmitContext ec)
1167 Expression e = base.DoResolve (ec);
1169 if ((e == null) || (expr == null))
1172 Type etype = expr.Type;
1173 bool warning_always_matches = false;
1174 bool warning_never_matches = false;
1176 type = TypeManager.bool_type;
1177 eclass = ExprClass.Value;
1180 // First case, if at compile time, there is an implicit conversion
1181 // then e != null (objects) or true (value types)
1183 e = Convert.WideningConversionStandard (ec, expr, probe_type, loc);
1186 if (etype.IsValueType)
1187 action = Action.AlwaysTrue;
1189 action = Action.LeaveOnStack;
1191 warning_always_matches = true;
1192 } else if (Convert.NarrowingReferenceConversionExists (etype, probe_type)){
1193 if (etype.IsGenericParameter)
1194 expr = new BoxedCast (expr, etype);
1197 // Second case: explicit reference convresion
1199 if (expr is NullLiteral)
1200 action = Action.AlwaysFalse;
1202 action = Action.Probe;
1204 action = Action.AlwaysFalse;
1205 warning_never_matches = true;
1208 if (warning_always_matches)
1209 Warning (183, "The given expression is always of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1210 else if (warning_never_matches){
1211 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1212 Warning (184, "The given expression is never of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1220 /// Implementation of the `as' operator.
1222 public class As : Probe {
1223 public As (Expression expr, Expression probe_type, Location l)
1224 : base (expr, probe_type, l)
1228 bool do_isinst = false;
1230 public override void Emit (EmitContext ec)
1232 ILGenerator ig = ec.ig;
1237 ig.Emit (OpCodes.Isinst, probe_type);
1240 static void Error_CannotConvertType (Type source, Type target, Location loc)
1243 39, loc, "as operator can not convert from `" +
1244 TypeManager.CSharpName (source) + "' to `" +
1245 TypeManager.CSharpName (target) + "'");
1248 public override Expression DoResolve (EmitContext ec)
1250 Expression e = base.DoResolve (ec);
1256 eclass = ExprClass.Value;
1257 Type etype = expr.Type;
1259 if (TypeManager.IsValueType (probe_type)){
1260 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1261 TypeManager.CSharpName (probe_type) + " is a value type)");
1266 e = Convert.WideningConversion (ec, expr, probe_type, loc);
1273 if (Convert.NarrowingReferenceConversionExists (etype, probe_type)){
1274 if (etype.IsGenericParameter)
1275 expr = new BoxedCast (expr, etype);
1281 Error_CannotConvertType (etype, probe_type, loc);
1287 /// This represents a typecast in the source language.
1289 /// FIXME: Cast expressions have an unusual set of parsing
1290 /// rules, we need to figure those out.
1292 public class Cast : Expression {
1293 Expression target_type;
1296 public Cast (Expression cast_type, Expression expr, Location loc)
1298 this.target_type = cast_type;
1303 public Expression TargetType {
1309 public Expression Expr {
1318 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1320 if (!ec.ConstantCheckState)
1323 if ((value < min) || (value > max)) {
1324 Error (221, "Constant value `" + value + "' cannot be converted " +
1325 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1326 "syntax to override)");
1333 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1335 if (!ec.ConstantCheckState)
1339 Error (221, "Constant value `" + value + "' cannot be converted " +
1340 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1341 "syntax to override)");
1348 bool CheckUnsigned (EmitContext ec, long value, Type type)
1350 if (!ec.ConstantCheckState)
1354 Error (221, "Constant value `" + value + "' cannot be converted " +
1355 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1356 "syntax to override)");
1364 /// Attempts to do a compile-time folding of a constant cast.
1366 Expression TryReduce (EmitContext ec, Type target_type)
1368 Expression real_expr = expr;
1369 if (real_expr is EnumConstant)
1370 real_expr = ((EnumConstant) real_expr).Child;
1372 if (real_expr is ByteConstant){
1373 byte v = ((ByteConstant) real_expr).Value;
1375 if (target_type == TypeManager.sbyte_type) {
1376 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1378 return new SByteConstant ((sbyte) v);
1380 if (target_type == TypeManager.short_type)
1381 return new ShortConstant ((short) v);
1382 if (target_type == TypeManager.ushort_type)
1383 return new UShortConstant ((ushort) v);
1384 if (target_type == TypeManager.int32_type)
1385 return new IntConstant ((int) v);
1386 if (target_type == TypeManager.uint32_type)
1387 return new UIntConstant ((uint) v);
1388 if (target_type == TypeManager.int64_type)
1389 return new LongConstant ((long) v);
1390 if (target_type == TypeManager.uint64_type)
1391 return new ULongConstant ((ulong) v);
1392 if (target_type == TypeManager.float_type)
1393 return new FloatConstant ((float) v);
1394 if (target_type == TypeManager.double_type)
1395 return new DoubleConstant ((double) v);
1396 if (target_type == TypeManager.char_type)
1397 return new CharConstant ((char) v);
1398 if (target_type == TypeManager.decimal_type)
1399 return new DecimalConstant ((decimal) v);
1401 if (real_expr is SByteConstant){
1402 sbyte v = ((SByteConstant) real_expr).Value;
1404 if (target_type == TypeManager.byte_type) {
1405 if (!CheckUnsigned (ec, v, target_type))
1407 return new ByteConstant ((byte) v);
1409 if (target_type == TypeManager.short_type)
1410 return new ShortConstant ((short) v);
1411 if (target_type == TypeManager.ushort_type) {
1412 if (!CheckUnsigned (ec, v, target_type))
1414 return new UShortConstant ((ushort) v);
1415 } if (target_type == TypeManager.int32_type)
1416 return new IntConstant ((int) v);
1417 if (target_type == TypeManager.uint32_type) {
1418 if (!CheckUnsigned (ec, v, target_type))
1420 return new UIntConstant ((uint) v);
1421 } if (target_type == TypeManager.int64_type)
1422 return new LongConstant ((long) v);
1423 if (target_type == TypeManager.uint64_type) {
1424 if (!CheckUnsigned (ec, v, target_type))
1426 return new ULongConstant ((ulong) v);
1428 if (target_type == TypeManager.float_type)
1429 return new FloatConstant ((float) v);
1430 if (target_type == TypeManager.double_type)
1431 return new DoubleConstant ((double) v);
1432 if (target_type == TypeManager.char_type) {
1433 if (!CheckUnsigned (ec, v, target_type))
1435 return new CharConstant ((char) v);
1437 if (target_type == TypeManager.decimal_type)
1438 return new DecimalConstant ((decimal) v);
1440 if (real_expr is ShortConstant){
1441 short v = ((ShortConstant) real_expr).Value;
1443 if (target_type == TypeManager.byte_type) {
1444 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1446 return new ByteConstant ((byte) v);
1448 if (target_type == TypeManager.sbyte_type) {
1449 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1451 return new SByteConstant ((sbyte) v);
1453 if (target_type == TypeManager.ushort_type) {
1454 if (!CheckUnsigned (ec, v, target_type))
1456 return new UShortConstant ((ushort) v);
1458 if (target_type == TypeManager.int32_type)
1459 return new IntConstant ((int) v);
1460 if (target_type == TypeManager.uint32_type) {
1461 if (!CheckUnsigned (ec, v, target_type))
1463 return new UIntConstant ((uint) v);
1465 if (target_type == TypeManager.int64_type)
1466 return new LongConstant ((long) v);
1467 if (target_type == TypeManager.uint64_type) {
1468 if (!CheckUnsigned (ec, v, target_type))
1470 return new ULongConstant ((ulong) v);
1472 if (target_type == TypeManager.float_type)
1473 return new FloatConstant ((float) v);
1474 if (target_type == TypeManager.double_type)
1475 return new DoubleConstant ((double) v);
1476 if (target_type == TypeManager.char_type) {
1477 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1479 return new CharConstant ((char) v);
1481 if (target_type == TypeManager.decimal_type)
1482 return new DecimalConstant ((decimal) v);
1484 if (real_expr is UShortConstant){
1485 ushort v = ((UShortConstant) real_expr).Value;
1487 if (target_type == TypeManager.byte_type) {
1488 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1490 return new ByteConstant ((byte) v);
1492 if (target_type == TypeManager.sbyte_type) {
1493 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1495 return new SByteConstant ((sbyte) v);
1497 if (target_type == TypeManager.short_type) {
1498 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1500 return new ShortConstant ((short) v);
1502 if (target_type == TypeManager.int32_type)
1503 return new IntConstant ((int) v);
1504 if (target_type == TypeManager.uint32_type)
1505 return new UIntConstant ((uint) v);
1506 if (target_type == TypeManager.int64_type)
1507 return new LongConstant ((long) v);
1508 if (target_type == TypeManager.uint64_type)
1509 return new ULongConstant ((ulong) v);
1510 if (target_type == TypeManager.float_type)
1511 return new FloatConstant ((float) v);
1512 if (target_type == TypeManager.double_type)
1513 return new DoubleConstant ((double) v);
1514 if (target_type == TypeManager.char_type) {
1515 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1517 return new CharConstant ((char) v);
1519 if (target_type == TypeManager.decimal_type)
1520 return new DecimalConstant ((decimal) v);
1522 if (real_expr is IntConstant){
1523 int v = ((IntConstant) real_expr).Value;
1525 if (target_type == TypeManager.byte_type) {
1526 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1528 return new ByteConstant ((byte) v);
1530 if (target_type == TypeManager.sbyte_type) {
1531 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1533 return new SByteConstant ((sbyte) v);
1535 if (target_type == TypeManager.short_type) {
1536 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1538 return new ShortConstant ((short) v);
1540 if (target_type == TypeManager.ushort_type) {
1541 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1543 return new UShortConstant ((ushort) v);
1545 if (target_type == TypeManager.uint32_type) {
1546 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1548 return new UIntConstant ((uint) v);
1550 if (target_type == TypeManager.int64_type)
1551 return new LongConstant ((long) v);
1552 if (target_type == TypeManager.uint64_type) {
1553 if (!CheckUnsigned (ec, v, target_type))
1555 return new ULongConstant ((ulong) v);
1557 if (target_type == TypeManager.float_type)
1558 return new FloatConstant ((float) v);
1559 if (target_type == TypeManager.double_type)
1560 return new DoubleConstant ((double) v);
1561 if (target_type == TypeManager.char_type) {
1562 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1564 return new CharConstant ((char) v);
1566 if (target_type == TypeManager.decimal_type)
1567 return new DecimalConstant ((decimal) v);
1569 if (real_expr is UIntConstant){
1570 uint v = ((UIntConstant) real_expr).Value;
1572 if (target_type == TypeManager.byte_type) {
1573 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1575 return new ByteConstant ((byte) v);
1577 if (target_type == TypeManager.sbyte_type) {
1578 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1580 return new SByteConstant ((sbyte) v);
1582 if (target_type == TypeManager.short_type) {
1583 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1585 return new ShortConstant ((short) v);
1587 if (target_type == TypeManager.ushort_type) {
1588 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1590 return new UShortConstant ((ushort) v);
1592 if (target_type == TypeManager.int32_type) {
1593 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1595 return new IntConstant ((int) v);
1597 if (target_type == TypeManager.int64_type)
1598 return new LongConstant ((long) v);
1599 if (target_type == TypeManager.uint64_type)
1600 return new ULongConstant ((ulong) v);
1601 if (target_type == TypeManager.float_type)
1602 return new FloatConstant ((float) v);
1603 if (target_type == TypeManager.double_type)
1604 return new DoubleConstant ((double) v);
1605 if (target_type == TypeManager.char_type) {
1606 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1608 return new CharConstant ((char) v);
1610 if (target_type == TypeManager.decimal_type)
1611 return new DecimalConstant ((decimal) v);
1613 if (real_expr is LongConstant){
1614 long v = ((LongConstant) real_expr).Value;
1616 if (target_type == TypeManager.byte_type) {
1617 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1619 return new ByteConstant ((byte) v);
1621 if (target_type == TypeManager.sbyte_type) {
1622 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1624 return new SByteConstant ((sbyte) v);
1626 if (target_type == TypeManager.short_type) {
1627 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1629 return new ShortConstant ((short) v);
1631 if (target_type == TypeManager.ushort_type) {
1632 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1634 return new UShortConstant ((ushort) v);
1636 if (target_type == TypeManager.int32_type) {
1637 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1639 return new IntConstant ((int) v);
1641 if (target_type == TypeManager.uint32_type) {
1642 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1644 return new UIntConstant ((uint) v);
1646 if (target_type == TypeManager.uint64_type) {
1647 if (!CheckUnsigned (ec, v, target_type))
1649 return new ULongConstant ((ulong) v);
1651 if (target_type == TypeManager.float_type)
1652 return new FloatConstant ((float) v);
1653 if (target_type == TypeManager.double_type)
1654 return new DoubleConstant ((double) v);
1655 if (target_type == TypeManager.char_type) {
1656 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1658 return new CharConstant ((char) v);
1660 if (target_type == TypeManager.decimal_type)
1661 return new DecimalConstant ((decimal) v);
1663 if (real_expr is ULongConstant){
1664 ulong v = ((ULongConstant) real_expr).Value;
1666 if (target_type == TypeManager.byte_type) {
1667 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1669 return new ByteConstant ((byte) v);
1671 if (target_type == TypeManager.sbyte_type) {
1672 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1674 return new SByteConstant ((sbyte) v);
1676 if (target_type == TypeManager.short_type) {
1677 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1679 return new ShortConstant ((short) v);
1681 if (target_type == TypeManager.ushort_type) {
1682 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1684 return new UShortConstant ((ushort) v);
1686 if (target_type == TypeManager.int32_type) {
1687 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1689 return new IntConstant ((int) v);
1691 if (target_type == TypeManager.uint32_type) {
1692 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1694 return new UIntConstant ((uint) v);
1696 if (target_type == TypeManager.int64_type) {
1697 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1699 return new LongConstant ((long) v);
1701 if (target_type == TypeManager.float_type)
1702 return new FloatConstant ((float) v);
1703 if (target_type == TypeManager.double_type)
1704 return new DoubleConstant ((double) v);
1705 if (target_type == TypeManager.char_type) {
1706 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1708 return new CharConstant ((char) v);
1710 if (target_type == TypeManager.decimal_type)
1711 return new DecimalConstant ((decimal) v);
1713 if (real_expr is FloatConstant){
1714 float v = ((FloatConstant) real_expr).Value;
1716 if (target_type == TypeManager.byte_type)
1717 return new ByteConstant ((byte) v);
1718 if (target_type == TypeManager.sbyte_type)
1719 return new SByteConstant ((sbyte) v);
1720 if (target_type == TypeManager.short_type)
1721 return new ShortConstant ((short) v);
1722 if (target_type == TypeManager.ushort_type)
1723 return new UShortConstant ((ushort) v);
1724 if (target_type == TypeManager.int32_type)
1725 return new IntConstant ((int) v);
1726 if (target_type == TypeManager.uint32_type)
1727 return new UIntConstant ((uint) v);
1728 if (target_type == TypeManager.int64_type)
1729 return new LongConstant ((long) v);
1730 if (target_type == TypeManager.uint64_type)
1731 return new ULongConstant ((ulong) v);
1732 if (target_type == TypeManager.double_type)
1733 return new DoubleConstant ((double) v);
1734 if (target_type == TypeManager.char_type)
1735 return new CharConstant ((char) v);
1736 if (target_type == TypeManager.decimal_type)
1737 return new DecimalConstant ((decimal) v);
1739 if (real_expr is DoubleConstant){
1740 double v = ((DoubleConstant) real_expr).Value;
1742 if (target_type == TypeManager.byte_type){
1743 return new ByteConstant ((byte) v);
1744 } if (target_type == TypeManager.sbyte_type)
1745 return new SByteConstant ((sbyte) v);
1746 if (target_type == TypeManager.short_type)
1747 return new ShortConstant ((short) v);
1748 if (target_type == TypeManager.ushort_type)
1749 return new UShortConstant ((ushort) v);
1750 if (target_type == TypeManager.int32_type)
1751 return new IntConstant ((int) v);
1752 if (target_type == TypeManager.uint32_type)
1753 return new UIntConstant ((uint) v);
1754 if (target_type == TypeManager.int64_type)
1755 return new LongConstant ((long) v);
1756 if (target_type == TypeManager.uint64_type)
1757 return new ULongConstant ((ulong) v);
1758 if (target_type == TypeManager.float_type)
1759 return new FloatConstant ((float) v);
1760 if (target_type == TypeManager.char_type)
1761 return new CharConstant ((char) v);
1762 if (target_type == TypeManager.decimal_type)
1763 return new DecimalConstant ((decimal) v);
1766 if (real_expr is CharConstant){
1767 char v = ((CharConstant) real_expr).Value;
1769 if (target_type == TypeManager.byte_type) {
1770 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1772 return new ByteConstant ((byte) v);
1774 if (target_type == TypeManager.sbyte_type) {
1775 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1777 return new SByteConstant ((sbyte) v);
1779 if (target_type == TypeManager.short_type) {
1780 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1782 return new ShortConstant ((short) v);
1784 if (target_type == TypeManager.int32_type)
1785 return new IntConstant ((int) v);
1786 if (target_type == TypeManager.uint32_type)
1787 return new UIntConstant ((uint) v);
1788 if (target_type == TypeManager.int64_type)
1789 return new LongConstant ((long) v);
1790 if (target_type == TypeManager.uint64_type)
1791 return new ULongConstant ((ulong) v);
1792 if (target_type == TypeManager.float_type)
1793 return new FloatConstant ((float) v);
1794 if (target_type == TypeManager.double_type)
1795 return new DoubleConstant ((double) v);
1796 if (target_type == TypeManager.char_type) {
1797 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1799 return new CharConstant ((char) v);
1801 if (target_type == TypeManager.decimal_type)
1802 return new DecimalConstant ((decimal) v);
1808 public override Expression DoResolve (EmitContext ec)
1810 expr = expr.Resolve (ec);
1814 TypeExpr target = target_type.ResolveAsTypeTerminal (ec);
1820 CheckObsoleteAttribute (type);
1822 if (type.IsAbstract && type.IsSealed) {
1823 Report.Error (716, loc, "Cannot convert to static type '{0}'", TypeManager.CSharpName (type));
1827 eclass = ExprClass.Value;
1829 if (expr is Constant){
1830 Expression e = TryReduce (ec, type);
1836 if (type.IsPointer && !ec.InUnsafe) {
1840 expr = Convert.WideningAndNarrowingConversion (ec, expr, type, loc);
1844 public override void Emit (EmitContext ec)
1847 // This one will never happen
1849 throw new Exception ("Should not happen");
1854 /// Binary operators
1856 public class Binary : Expression {
1857 public enum Operator : byte {
1862 Addition, Subtraction,
1864 LeftShift, RightShift,
1865 Equality, Inequality, LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual, Like, Is,
1866 BitwiseAnd, LogicalAndAlso,
1867 BitwiseOr, LogicalOrElse,
1873 Expression left, right;
1874 Expression intermediate;
1876 // This must be kept in sync with Operator!!!
1877 public static readonly string [] oper_names;
1881 oper_names = new string [(int) Operator.TOP];
1883 oper_names [(int) Operator.Multiply] = "op_Multiply";
1884 oper_names [(int) Operator.Division] = "op_Division";
1885 oper_names [(int) Operator.Modulus] = "op_Modulus";
1886 oper_names [(int) Operator.Addition] = "op_Addition";
1887 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1888 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1889 oper_names [(int) Operator.RightShift] = "op_RightShift";
1890 oper_names [(int) Operator.LessThan] = "op_LessThan";
1891 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1892 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1893 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1894 oper_names [(int) Operator.Equality] = "op_Equality";
1895 oper_names [(int) Operator.Inequality] = "op_Inequality";
1896 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1897 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1898 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1899 oper_names [(int) Operator.LogicalOrElse] = "op_LogicalOr";
1900 oper_names [(int) Operator.LogicalAndAlso] = "op_LogicalAnd";
1903 public Binary (Operator oper, Expression left, Expression right, Location loc)
1911 public Operator Oper {
1920 public Expression Left {
1929 public Expression Right {
1940 /// Returns a stringified representation of the Operator
1942 static string OperName (Operator oper)
1945 case Operator.Multiply:
1947 case Operator.Division:
1949 case Operator.Modulus:
1951 case Operator.Addition:
1953 case Operator.Subtraction:
1955 case Operator.LeftShift:
1957 case Operator.RightShift:
1959 case Operator.LessThan:
1961 case Operator.GreaterThan:
1963 case Operator.LessThanOrEqual:
1965 case Operator.GreaterThanOrEqual:
1967 case Operator.Equality:
1969 case Operator.Inequality:
1971 case Operator.BitwiseAnd:
1973 case Operator.BitwiseOr:
1975 case Operator.ExclusiveOr:
1977 case Operator.LogicalOrElse:
1979 case Operator.LogicalAndAlso:
1983 return oper.ToString ();
1986 public override string ToString ()
1988 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1989 right.ToString () + ")";
1992 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1994 if (expr.Type == target_type)
1997 return Convert.WideningConversion (ec, expr, target_type, loc);
2000 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
2003 34, loc, "Operator `" + OperName (oper)
2004 + "' is ambiguous on operands of type `"
2005 + TypeManager.CSharpName (l) + "' "
2006 + "and `" + TypeManager.CSharpName (r)
2010 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
2012 if ((l == t) || (r == t))
2015 if (!check_user_conversions)
2019 // VB.NET has no notion of User defined conversions
2022 // if (Convert.ImplicitUserConversionExists (ec, l, t))
2024 // else if (Convert.ImplicitUserConversionExists (ec, r, t))
2033 // Note that handling the case l == Decimal || r == Decimal
2034 // is taken care of by the Step 1 Operator Overload resolution.
2036 // If `check_user_conv' is true, we also check whether a user-defined conversion
2037 // exists. Note that we only need to do this if both arguments are of a user-defined
2038 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
2039 // so we don't explicitly check for performance reasons.
2041 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
2043 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
2045 // If either operand is of type double, the other operand is
2046 // conveted to type double.
2048 if (r != TypeManager.double_type)
2049 right = Convert.WideningConversion (ec, right, TypeManager.double_type, loc);
2050 if (l != TypeManager.double_type)
2051 left = Convert.WideningConversion (ec, left, TypeManager.double_type, loc);
2053 type = TypeManager.double_type;
2054 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
2056 // if either operand is of type float, the other operand is
2057 // converted to type float.
2059 if (r != TypeManager.double_type)
2060 right = Convert.WideningConversion (ec, right, TypeManager.float_type, loc);
2061 if (l != TypeManager.double_type)
2062 left = Convert.WideningConversion (ec, left, TypeManager.float_type, loc);
2063 type = TypeManager.float_type;
2064 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2068 // If either operand is of type ulong, the other operand is
2069 // converted to type ulong. or an error ocurrs if the other
2070 // operand is of type sbyte, short, int or long
2072 if (l == TypeManager.uint64_type){
2073 if (r != TypeManager.uint64_type){
2074 if (right is IntConstant){
2075 IntConstant ic = (IntConstant) right;
2077 e = Convert.TryWideningIntConversion (l, ic);
2080 } else if (right is LongConstant){
2081 long ll = ((LongConstant) right).Value;
2084 right = new ULongConstant ((ulong) ll);
2086 e = Convert.WideningNumericConversion (ec, right, l, loc);
2093 if (left is IntConstant){
2094 e = Convert.TryWideningIntConversion (r, (IntConstant) left);
2097 } else if (left is LongConstant){
2098 long ll = ((LongConstant) left).Value;
2101 left = new ULongConstant ((ulong) ll);
2103 e = Convert.WideningNumericConversion (ec, left, r, loc);
2110 if ((other == TypeManager.sbyte_type) ||
2111 (other == TypeManager.short_type) ||
2112 (other == TypeManager.int32_type) ||
2113 (other == TypeManager.int64_type))
2114 Error_OperatorAmbiguous (loc, oper, l, r);
2116 left = ForceConversion (ec, left, TypeManager.uint64_type);
2117 right = ForceConversion (ec, right, TypeManager.uint64_type);
2119 type = TypeManager.uint64_type;
2120 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2122 // If either operand is of type long, the other operand is converted
2125 if (l != TypeManager.int64_type)
2126 left = Convert.WideningConversion (ec, left, TypeManager.int64_type, loc);
2127 if (r != TypeManager.int64_type)
2128 right = Convert.WideningConversion (ec, right, TypeManager.int64_type, loc);
2130 type = TypeManager.int64_type;
2131 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2133 // If either operand is of type uint, and the other
2134 // operand is of type sbyte, short or int, othe operands are
2135 // converted to type long (unless we have an int constant).
2139 if (l == TypeManager.uint32_type){
2140 if (right is IntConstant){
2141 IntConstant ic = (IntConstant) right;
2145 right = new UIntConstant ((uint) val);
2152 } else if (r == TypeManager.uint32_type){
2153 if (left is IntConstant){
2154 IntConstant ic = (IntConstant) left;
2158 left = new UIntConstant ((uint) val);
2167 if ((other == TypeManager.sbyte_type) ||
2168 (other == TypeManager.short_type) ||
2169 (other == TypeManager.int32_type)){
2170 left = ForceConversion (ec, left, TypeManager.int64_type);
2171 right = ForceConversion (ec, right, TypeManager.int64_type);
2172 type = TypeManager.int64_type;
2175 // if either operand is of type uint, the other
2176 // operand is converd to type uint
2178 left = ForceConversion (ec, left, TypeManager.uint32_type);
2179 right = ForceConversion (ec, right, TypeManager.uint32_type);
2180 type = TypeManager.uint32_type;
2182 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2183 if (l != TypeManager.decimal_type)
2184 left = Convert.WideningConversion (ec, left, TypeManager.decimal_type, loc);
2186 if (r != TypeManager.decimal_type)
2187 right = Convert.WideningConversion (ec, right, TypeManager.decimal_type, loc);
2188 type = TypeManager.decimal_type;
2190 left = ForceConversion (ec, left, TypeManager.int32_type);
2191 right = ForceConversion (ec, right, TypeManager.int32_type);
2193 type = TypeManager.int32_type;
2196 return (left != null) && (right != null);
2199 public void Error_OperatorCannotBeAppliedToObjectOperands ()
2201 Report.Error (30038, loc,
2202 "Operator " + OperName (oper) + " cannot be applied to operands of type `" +
2203 TypeManager.CSharpName (TypeManager.object_type) + "'");
2206 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2208 Report.Error (19, loc,
2209 "Operator " + name + " cannot be applied to operands of type `" +
2210 TypeManager.CSharpName (l) + "' and `" +
2211 TypeManager.CSharpName (r) + "'");
2214 void Error_OperatorCannotBeApplied ()
2216 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2219 static bool is_unsigned (Type t)
2221 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2222 t == TypeManager.short_type || t == TypeManager.byte_type);
2225 static bool is_user_defined (Type t)
2227 if (t.IsSubclassOf (TypeManager.value_type) &&
2228 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2234 Expression Make32or64 (EmitContext ec, Expression e)
2238 if (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2239 t == TypeManager.int64_type || t == TypeManager.uint64_type)
2241 Expression ee = Convert.WideningConversion (ec, e, TypeManager.int32_type, loc);
2244 ee = Convert.WideningConversion (ec, e, TypeManager.uint32_type, loc);
2247 ee = Convert.WideningConversion (ec, e, TypeManager.int64_type, loc);
2250 ee = Convert.WideningConversion (ec, e, TypeManager.uint64_type, loc);
2256 void CheckShiftArguments (EmitContext ec)
2260 e = Convert.ImplicitVBConversion (ec, right, TypeManager.int32_type, Location);
2262 Error_OperatorCannotBeApplied ();
2267 if ( !IsOperatorDefinedForType (left.Type)) {
2268 Expression target_left_expr = ConvertOperandToDefinedType(ec, left);
2270 if (target_left_expr == null) {
2271 Error_OperatorCannotBeApplied();
2275 left = target_left_expr;
2282 if (type == TypeManager.byte_type)
2284 else if (type == TypeManager.short_type)
2286 else if (type == TypeManager.int32_type)
2288 else if (type == TypeManager.int64_type)
2291 throw new Exception ("This should not happen");
2293 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (mask), loc);
2294 right = right.DoResolve (ec);
2298 Expression ResolveOperator (EmitContext ec)
2301 Type r = right.Type;
2304 // Special cases: string or type parameter comapred to null
2306 if (oper == Operator.Equality || oper == Operator.Inequality){
2307 if ((!TypeManager.IsValueType (l) && r == TypeManager.null_type) ||
2308 (!TypeManager.IsValueType (r) && l == TypeManager.null_type)) {
2309 Type = TypeManager.bool_type;
2314 if (l.IsGenericParameter && (right is NullLiteral)) {
2315 if (l.BaseType == TypeManager.value_type) {
2316 Error_OperatorCannotBeApplied ();
2320 left = new BoxedCast (left);
2321 Type = TypeManager.bool_type;
2325 if (r.IsGenericParameter && (left is NullLiteral)) {
2326 if (r.BaseType == TypeManager.value_type) {
2327 Error_OperatorCannotBeApplied ();
2331 right = new BoxedCast (right);
2332 Type = TypeManager.bool_type;
2337 if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
2338 Type = TypeManager.bool_type;
2345 // Do not perform operator overload resolution when both sides are
2348 if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
2350 // Step 1: Perform Operator Overload location
2352 Expression left_expr, right_expr;
2354 string op = oper_names [(int) oper];
2356 MethodGroupExpr union;
2357 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2359 right_expr = MemberLookup (
2360 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2361 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2363 union = (MethodGroupExpr) left_expr;
2365 if (union != null) {
2366 ArrayList args = new ArrayList (2);
2367 args.Add (new Argument (left, Argument.AType.Expression));
2368 args.Add (new Argument (right, Argument.AType.Expression));
2370 MethodBase method = Invocation.OverloadResolve (
2371 ec, union, args, true, Location.Null);
2373 if (method != null) {
2374 MethodInfo mi = (MethodInfo) method;
2376 return new BinaryMethod (mi.ReturnType, method, args);
2382 // Step 0: String concatenation (because overloading will get this wrong)
2384 if (oper == Operator.Addition){
2386 // If any of the arguments is a string, cast to string
2389 // Simple constant folding
2390 if (left is StringConstant && right is StringConstant)
2391 return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value);
2393 if (l == TypeManager.string_type || r == TypeManager.string_type) {
2395 if (r == TypeManager.void_type || l == TypeManager.void_type) {
2396 Error_OperatorCannotBeApplied ();
2400 // try to fold it in on the left
2401 if (left is StringConcat) {
2404 // We have to test here for not-null, since we can be doubly-resolved
2405 // take care of not appending twice
2408 type = TypeManager.string_type;
2409 ((StringConcat) left).Append (ec, right);
2410 return left.Resolve (ec);
2416 // Otherwise, start a new concat expression
2417 return new StringConcat (ec, loc, left, right).Resolve (ec);
2421 // Transform a + ( - b) into a - b
2423 if (right is Unary){
2424 Unary right_unary = (Unary) right;
2426 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2427 oper = Operator.Subtraction;
2428 right = right_unary.Expr;
2434 if (oper == Operator.Equality || oper == Operator.Inequality){
2435 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2436 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2437 Error_OperatorCannotBeApplied ();
2441 type = TypeManager.bool_type;
2445 bool left_is_null = left is NullLiteral;
2446 bool right_is_null = right is NullLiteral;
2447 if (left_is_null || right_is_null) {
2448 if (oper == Operator.Equality)
2449 return new BoolLiteral (left_is_null == right_is_null);
2451 return new BoolLiteral (left_is_null != right_is_null);
2455 // operator != (object a, object b)
2456 // operator == (object a, object b)
2458 // For this to be used, both arguments have to be reference-types.
2459 // Read the rationale on the spec (14.9.6)
2461 // Also, if at compile time we know that the classes do not inherit
2462 // one from the other, then we catch the error there.
2464 if (!(l.IsValueType || r.IsValueType)){
2465 type = TypeManager.bool_type;
2470 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2474 // Also, a standard conversion must exist from either one
2476 if (!(Convert.WideningStandardConversionExists (ec, left, r) ||
2477 Convert.WideningStandardConversionExists (ec, right, l))){
2478 Error_OperatorCannotBeApplied ();
2482 // We are going to have to convert to an object to compare
2484 if (l != TypeManager.object_type)
2485 left = new EmptyCast (left, TypeManager.object_type);
2486 if (r != TypeManager.object_type)
2487 right = new EmptyCast (right, TypeManager.object_type);
2490 // FIXME: CSC here catches errors cs254 and cs252
2496 // One of them is a valuetype, but the other one is not.
2498 if (!l.IsValueType || !r.IsValueType) {
2499 Error_OperatorCannotBeApplied ();
2504 // Only perform numeric promotions on:
2505 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2507 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2508 if (TypeManager.IsDelegateType (l)){
2509 if (((right.eclass == ExprClass.MethodGroup) ||
2510 (r == TypeManager.anonymous_method_type))){
2511 if ((RootContext.Version != LanguageVersion.ISO_1)){
2512 Expression tmp = Convert.WideningConversionRequired (ec, right, l, loc);
2520 if (TypeManager.IsDelegateType (r)){
2522 ArrayList args = new ArrayList (2);
2524 args = new ArrayList (2);
2525 args.Add (new Argument (left, Argument.AType.Expression));
2526 args.Add (new Argument (right, Argument.AType.Expression));
2528 if (oper == Operator.Addition)
2529 method = TypeManager.delegate_combine_delegate_delegate;
2531 method = TypeManager.delegate_remove_delegate_delegate;
2533 if (!TypeManager.IsEqual (l, r)) {
2534 Error_OperatorCannotBeApplied ();
2538 return new BinaryDelegate (l, method, args);
2543 // Pointer arithmetic:
2545 // T* operator + (T* x, int y);
2546 // T* operator + (T* x, uint y);
2547 // T* operator + (T* x, long y);
2548 // T* operator + (T* x, ulong y);
2550 // T* operator + (int y, T* x);
2551 // T* operator + (uint y, T *x);
2552 // T* operator + (long y, T *x);
2553 // T* operator + (ulong y, T *x);
2555 // T* operator - (T* x, int y);
2556 // T* operator - (T* x, uint y);
2557 // T* operator - (T* x, long y);
2558 // T* operator - (T* x, ulong y);
2560 // long operator - (T* x, T *y)
2563 if (r.IsPointer && oper == Operator.Subtraction){
2565 return new PointerArithmetic (
2566 false, left, right, TypeManager.int64_type,
2569 Expression t = Make32or64 (ec, right);
2571 return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc).Resolve (ec);
2573 } else if (r.IsPointer && oper == Operator.Addition){
2574 Expression t = Make32or64 (ec, left);
2576 return new PointerArithmetic (true, right, t, r, loc).Resolve (ec);
2581 // Enumeration operators
2583 bool lie = TypeManager.IsEnumType (l);
2584 bool rie = TypeManager.IsEnumType (r);
2588 // U operator - (E e, E f)
2590 if (oper == Operator.Subtraction){
2592 type = TypeManager.EnumToUnderlying (l);
2595 Error_OperatorCannotBeApplied ();
2601 // operator + (E e, U x)
2602 // operator - (E e, U x)
2604 if (oper == Operator.Addition || oper == Operator.Subtraction){
2605 Type enum_type = lie ? l : r;
2606 Type other_type = lie ? r : l;
2607 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2609 if (underlying_type != other_type){
2610 temp = Convert.WideningConversion (ec, lie ? right : left, underlying_type, loc);
2620 Error_OperatorCannotBeApplied ();
2629 temp = Convert.WideningConversion (ec, right, l, loc);
2633 Error_OperatorCannotBeApplied ();
2637 temp = Convert.WideningConversion (ec, left, r, loc);
2642 Error_OperatorCannotBeApplied ();
2647 if (oper == Operator.Equality || oper == Operator.Inequality ||
2648 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2649 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2650 if (left.Type != right.Type){
2651 Error_OperatorCannotBeApplied ();
2654 type = TypeManager.bool_type;
2658 if (oper == Operator.BitwiseAnd ||
2659 oper == Operator.BitwiseOr ||
2660 oper == Operator.ExclusiveOr){
2664 Error_OperatorCannotBeApplied ();
2668 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2669 return CheckShiftArguments (ec);
2671 if (oper == Operator.LogicalOrElse || oper == Operator.LogicalAndAlso){
2672 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2673 type = TypeManager.bool_type;
2678 Error_OperatorCannotBeApplied ();
2682 Expression e = new ConditionalLogicalOperator (
2683 oper == Operator.LogicalAndAlso, left, right, l, loc);
2684 return e.Resolve (ec);
2688 // operator & (bool x, bool y)
2689 // operator | (bool x, bool y)
2690 // operator ^ (bool x, bool y)
2692 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2693 if (oper == Operator.BitwiseAnd ||
2694 oper == Operator.BitwiseOr ||
2695 oper == Operator.ExclusiveOr){
2702 // Pointer comparison
2704 if (l.IsPointer && r.IsPointer){
2705 if (oper == Operator.Equality || oper == Operator.Inequality ||
2706 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2707 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2708 type = TypeManager.bool_type;
2714 // This will leave left or right set to null if there is an error
2716 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2717 DoNumericPromotions (ec, l, r, check_user_conv);
2718 if (left == null || right == null){
2719 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2724 // reload our cached types if required
2729 if (oper == Operator.BitwiseAnd ||
2730 oper == Operator.BitwiseOr ||
2731 oper == Operator.ExclusiveOr){
2733 if (((l == TypeManager.int32_type) ||
2734 (l == TypeManager.uint32_type) ||
2735 (l == TypeManager.short_type) ||
2736 (l == TypeManager.ushort_type) ||
2737 (l == TypeManager.int64_type) ||
2738 (l == TypeManager.uint64_type))){
2741 Error_OperatorCannotBeApplied ();
2745 Error_OperatorCannotBeApplied ();
2750 if (oper == Operator.Equality ||
2751 oper == Operator.Inequality ||
2752 oper == Operator.LessThanOrEqual ||
2753 oper == Operator.LessThan ||
2754 oper == Operator.GreaterThanOrEqual ||
2755 oper == Operator.GreaterThan){
2756 type = TypeManager.bool_type;
2763 public override Expression DoResolve (EmitContext ec)
2765 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2766 left = ((ParenthesizedExpression) left).Expr;
2767 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2771 if (left.eclass == ExprClass.Type) {
2772 Error (75, "Casting a negative value needs to have the value in parentheses.");
2776 left = left.Resolve (ec);
2781 Constant lc = left as Constant;
2782 if (lc != null && lc.Type == TypeManager.bool_type &&
2783 ((oper == Operator.LogicalAndAlso && (bool)lc.GetValue () == false) ||
2784 (oper == Operator.LogicalOrElse && (bool)lc.GetValue () == true))) {
2786 // TODO: make a sense to resolve unreachable expression as we do for statement
2787 Report.Warning (429, 4, loc, "Unreachable expression code detected");
2791 right = right.Resolve (ec);
2795 eclass = ExprClass.Value;
2797 Constant rc = right as Constant;
2798 if (rc != null & lc != null){
2799 Expression e = ConstantFold.BinaryFold (
2800 ec, oper, lc, rc, loc);
2805 if (TypeManager.IsNullableType (left.Type) || TypeManager.IsNullableType (right.Type))
2806 return new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
2808 return ResolveVisualBasicOperator (ec);
2812 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2813 /// context of a conditional bool expression. This function will return
2814 /// false if it is was possible to use EmitBranchable, or true if it was.
2816 /// The expression's code is generated, and we will generate a branch to `target'
2817 /// if the resulting expression value is equal to isTrue
2819 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2821 ILGenerator ig = ec.ig;
2824 // This is more complicated than it looks, but its just to avoid
2825 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2826 // but on top of that we want for == and != to use a special path
2827 // if we are comparing against null
2829 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
2830 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2833 // put the constant on the rhs, for simplicity
2835 if (left is Constant) {
2836 Expression swap = right;
2841 if (((Constant) right).IsZeroInteger) {
2844 ig.Emit (OpCodes.Brtrue, target);
2846 ig.Emit (OpCodes.Brfalse, target);
2849 } else if (right is BoolConstant){
2851 if (my_on_true != ((BoolConstant) right).Value)
2852 ig.Emit (OpCodes.Brtrue, target);
2854 ig.Emit (OpCodes.Brfalse, target);
2859 } else if (oper == Operator.LogicalAndAlso) {
2862 Label tests_end = ig.DefineLabel ();
2864 left.EmitBranchable (ec, tests_end, false);
2865 right.EmitBranchable (ec, target, true);
2866 ig.MarkLabel (tests_end);
2868 left.EmitBranchable (ec, target, false);
2869 right.EmitBranchable (ec, target, false);
2874 } else if (oper == Operator.LogicalOrElse){
2876 left.EmitBranchable (ec, target, true);
2877 right.EmitBranchable (ec, target, true);
2880 Label tests_end = ig.DefineLabel ();
2881 left.EmitBranchable (ec, tests_end, true);
2882 right.EmitBranchable (ec, target, false);
2883 ig.MarkLabel (tests_end);
2888 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2889 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2890 oper == Operator.Equality || oper == Operator.Inequality)) {
2891 base.EmitBranchable (ec, target, onTrue);
2899 bool isUnsigned = is_unsigned (t) || t == TypeManager.double_type || t == TypeManager.float_type;
2902 case Operator.Equality:
2904 ig.Emit (OpCodes.Beq, target);
2906 ig.Emit (OpCodes.Bne_Un, target);
2909 case Operator.Inequality:
2911 ig.Emit (OpCodes.Bne_Un, target);
2913 ig.Emit (OpCodes.Beq, target);
2916 case Operator.LessThan:
2919 ig.Emit (OpCodes.Blt_Un, target);
2921 ig.Emit (OpCodes.Blt, target);
2924 ig.Emit (OpCodes.Bge_Un, target);
2926 ig.Emit (OpCodes.Bge, target);
2929 case Operator.GreaterThan:
2932 ig.Emit (OpCodes.Bgt_Un, target);
2934 ig.Emit (OpCodes.Bgt, target);
2937 ig.Emit (OpCodes.Ble_Un, target);
2939 ig.Emit (OpCodes.Ble, target);
2942 case Operator.LessThanOrEqual:
2945 ig.Emit (OpCodes.Ble_Un, target);
2947 ig.Emit (OpCodes.Ble, target);
2950 ig.Emit (OpCodes.Bgt_Un, target);
2952 ig.Emit (OpCodes.Bgt, target);
2956 case Operator.GreaterThanOrEqual:
2959 ig.Emit (OpCodes.Bge_Un, target);
2961 ig.Emit (OpCodes.Bge, target);
2964 ig.Emit (OpCodes.Blt_Un, target);
2966 ig.Emit (OpCodes.Blt, target);
2969 Console.WriteLine (oper);
2970 throw new Exception ("what is THAT");
2974 public override void Emit (EmitContext ec)
2976 ILGenerator ig = ec.ig;
2979 OpCode opcode1 = OpCodes.Nop;
2982 // Handle short-circuit operators differently
2985 if (oper == Operator.LogicalAndAlso) {
2986 Label load_zero = ig.DefineLabel ();
2987 Label end = ig.DefineLabel ();
2989 left.EmitBranchable (ec, load_zero, false);
2991 ig.Emit (OpCodes.Br, end);
2993 ig.MarkLabel (load_zero);
2994 ig.Emit (OpCodes.Ldc_I4_0);
2997 } else if (oper == Operator.LogicalOrElse) {
2998 Label load_one = ig.DefineLabel ();
2999 Label end = ig.DefineLabel ();
3001 left.EmitBranchable (ec, load_one, true);
3003 ig.Emit (OpCodes.Br, end);
3005 ig.MarkLabel (load_one);
3006 ig.Emit (OpCodes.Ldc_I4_1);
3011 if (intermediate != null) {
3012 intermediate.Emit (ec);
3013 ig.Emit (OpCodes.Ldc_I4_0);
3020 bool is_int32_or_int64_type = (Type == TypeManager.int32_type) || (Type == TypeManager.int64_type);
3023 case Operator.Multiply:
3025 if (is_int32_or_int64_type)
3026 opcode = OpCodes.Mul_Ovf;
3028 opcode = OpCodes.Mul;
3030 opcode = OpCodes.Mul;
3034 case Operator.Division:
3035 case Operator.IntegerDivision:
3036 opcode = OpCodes.Div;
3039 case Operator.Modulus:
3040 opcode = OpCodes.Rem;
3043 case Operator.Addition:
3045 if (is_int32_or_int64_type)
3046 opcode = OpCodes.Add_Ovf;
3048 opcode = OpCodes.Add;
3050 opcode = OpCodes.Add;
3053 case Operator.Subtraction:
3055 if (is_int32_or_int64_type)
3056 opcode = OpCodes.Sub_Ovf;
3058 opcode = OpCodes.Sub;
3060 opcode = OpCodes.Sub;
3063 case Operator.RightShift:
3064 opcode = OpCodes.Shr;
3067 case Operator.LeftShift:
3068 opcode = OpCodes.Shl;
3071 case Operator.Equality:
3072 opcode = OpCodes.Ceq;
3075 case Operator.Inequality:
3076 ig.Emit (OpCodes.Ceq);
3077 ig.Emit (OpCodes.Ldc_I4_0);
3079 opcode = OpCodes.Ceq;
3082 case Operator.LessThan:
3083 opcode = OpCodes.Clt;
3086 case Operator.GreaterThan:
3087 opcode = OpCodes.Cgt;
3090 case Operator.LessThanOrEqual:
3091 ig.Emit (OpCodes.Cgt);
3092 ig.Emit (OpCodes.Ldc_I4_0);
3094 opcode = OpCodes.Ceq;
3097 case Operator.GreaterThanOrEqual:
3098 ig.Emit (OpCodes.Clt);
3099 ig.Emit (OpCodes.Ldc_I4_0);
3101 opcode = OpCodes.Ceq;
3104 case Operator.BitwiseOr:
3105 opcode = OpCodes.Or;
3108 case Operator.BitwiseAnd:
3109 opcode = OpCodes.And;
3112 case Operator.ExclusiveOr:
3113 opcode = OpCodes.Xor;
3117 throw new Exception ("This should not happen: Operator = "
3118 + oper.ToString ());
3123 if (!IsArithmeticExpression && !IsShiftExpression)
3126 if (type == TypeManager.byte_type)
3127 ig.Emit (ec.CheckState && ! IsShiftExpression ? OpCodes.Conv_Ovf_U1 : OpCodes.Conv_U1);
3129 if (type == TypeManager.short_type)
3130 ig.Emit (ec.CheckState && ! IsShiftExpression ? OpCodes.Conv_Ovf_I2 : OpCodes.Conv_I2);
3133 Expression ResolveVisualBasicOperator (EmitContext ec)
3136 Expression ret_expr;
3139 Type r = right.Type;
3141 errors = Report.Errors;
3142 ret_expr = HandleObjectOperands (ec);
3143 if (Report.Errors > errors)
3145 if (ret_expr != null)
3148 errors = Report.Errors;
3149 CheckArguments (ec);
3150 if (Report.Errors > errors)
3153 if (oper == Operator.Exponentiation)
3154 return new HelperMethodInvocation (ec, Location, TypeManager.double_type,
3155 TypeManager.math_pow_double_double, left, right);
3157 if (type == TypeManager.decimal_type) {
3158 MethodInfo helper_method = null;
3160 case Operator.Addition:
3161 helper_method = TypeManager.decimal_add_decimal_decimal;
3163 case Operator.Subtraction:
3164 helper_method = TypeManager.decimal_subtract_decimal_decimal;
3166 case Operator.Multiply:
3167 helper_method = TypeManager.decimal_multiply_decimal_decimal;
3169 case Operator.Division:
3170 helper_method = TypeManager.decimal_divide_decimal_decimal;
3172 case Operator.Modulus:
3173 helper_method = TypeManager.decimal_remainder_decimal_decimal;
3177 return new HelperMethodInvocation (ec, Location, TypeManager.decimal_type,
3178 helper_method, left, right);
3181 if (IsRelationalExpression) {
3182 Type = TypeManager.bool_type;
3183 if (left.Type == TypeManager.string_type) {
3184 Expression is_text_mode;
3186 is_text_mode = new BoolConstant (RootContext.StringComparisonMode == CompareMethod.Text);
3187 intermediate = new HelperMethodInvocation (ec, Location, TypeManager.int32_type,
3188 TypeManager.msvbcs_stringtype_strcmp_string_string_boolean,
3189 left, right, is_text_mode);
3192 if (left.Type == TypeManager.decimal_type) {
3193 intermediate = new HelperMethodInvocation (ec, Location, TypeManager.int32_type,
3194 TypeManager.decimal_compare_decimal_decimal, left, right);
3197 if (left.Type == TypeManager.date_type) {
3198 intermediate = new HelperMethodInvocation (ec, Location, TypeManager.int32_type,
3199 TypeManager.datetime_compare_datetime_datetime, left, right);
3204 if (IsShiftExpression)
3207 if (IsShortCircuitedLogicalExpression)
3212 // Step 0: String concatenation (because overloading will get this wrong)
3214 if (oper == Operator.Addition){
3216 // If any of the arguments is a string, cast to string
3219 // Simple constant folding
3220 if (left is StringConstant && right is StringConstant)
3221 return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value);
3223 if (l == TypeManager.string_type || r == TypeManager.string_type) {
3225 if (r == TypeManager.void_type || l == TypeManager.void_type) {
3226 Error_OperatorCannotBeApplied ();
3230 // try to fold it in on the left
3231 if (left is StringConcat) {
3234 // We have to test here for not-null, since we can be doubly-resolved
3235 // take care of not appending twice
3238 type = TypeManager.string_type;
3239 ((StringConcat) left).Append (ec, right);
3240 return left.Resolve (ec);
3246 // Otherwise, start a new concat expression
3247 return new StringConcat (ec, loc, left, right).Resolve (ec);
3251 // Transform a + ( - b) into a - b
3253 if (right is Unary){
3254 Unary right_unary = (Unary) right;
3256 if (right_unary.Oper == Unary.Operator.UnaryNegation){
3257 oper = Operator.Subtraction;
3258 right = right_unary.Expr;
3267 Expression HandleObjectOperands (EmitContext ec)
3270 Type r = right.Type;
3272 Expression target_left_expr = left;
3273 Expression target_right_expr = right;
3275 if (IsShortCircuitedLogicalExpression)
3278 if (l != TypeManager.object_type && r != TypeManager.object_type)
3281 if (RootContext.StricterTypeChecking)
3282 if (oper != Operator.Equality &&
3283 oper != Operator.Inequality && oper != Operator.Is) {
3284 Error_OperatorCannotBeAppliedToObjectOperands ();
3288 if (l != TypeManager.object_type && ! IsOperatorDefinedForType (l) && ConvertOperandToDefinedType(ec, target_left_expr) == null) {
3289 Error_OperatorCannotBeApplied ();
3292 if (!IsShiftExpression && r != TypeManager.object_type && ! IsOperatorDefinedForType (r) && ConvertOperandToDefinedType(ec, target_right_expr) == null) {
3293 Error_OperatorCannotBeApplied ();
3297 if (l != TypeManager.object_type)
3298 left = Convert.ImplicitVBConversionRequired (ec, left, TypeManager.object_type, Location);
3300 if (IsShiftExpression) {
3301 if (r != TypeManager.int32_type) {
3302 target_right_expr = Convert.ImplicitVBConversionRequired (ec, right, TypeManager.int32_type, Location);
3303 if (target_right_expr == null) {
3304 Error_OperatorCannotBeApplied ();
3307 right = target_right_expr;
3310 } else if (r != TypeManager.object_type) {
3311 right = Convert.ImplicitVBConversionRequired (ec, right, TypeManager.object_type, Location);
3315 Type = TypeManager.object_type;
3316 if (IsRelationalExpression) {
3317 Type = TypeManager.bool_type;
3318 Expression is_text_mode = new BoolConstant (RootContext.StringComparisonMode == CompareMethod.Text);
3319 intermediate = new HelperMethodInvocation (ec, Location, TypeManager.int32_type, HelperMethod, left, right, is_text_mode);
3323 if (oper == Operator.Like) {
3324 Type = TypeManager.bool_type;
3325 Expression compare_mode = new EnumConstant (new IntConstant ((int) RootContext.StringComparisonMode),
3326 typeof (Microsoft.VisualBasic.CompareMethod));
3327 return new HelperMethodInvocation (ec, Location, TypeManager.bool_type, HelperMethod, left, right, compare_mode);
3330 if (IsShiftExpression)
3331 return new HelperMethodInvocation (ec, Location, TypeManager.object_type, HelperMethod, left, right);
3333 return new HelperMethodInvocation (ec, Location, TypeManager.object_type, HelperMethod, left, right);
3336 void CheckArguments (EmitContext ec)
3341 Type r = right.Type;
3343 Expression target_left_expr = left;
3344 Expression target_right_expr = right;
3346 Type target_left_expr_type = target_left_expr.Type;
3347 Type target_right_expr_type = target_right_expr.Type;
3350 if (IsShiftExpression) {
3351 CheckShiftArguments (ec);
3358 // Console.WriteLine ("STEP " + step + ":");
3359 // Console.WriteLine (" left => " + target_left_expr_type + " right => " + target_right_expr_type);
3361 if ((target_left_expr_type == target_right_expr_type) &&
3362 IsOperatorDefinedForType (target_left_expr_type)) {
3363 left = target_left_expr;
3364 right = target_right_expr;
3365 type = target_left_expr_type;
3369 if ( !IsOperatorDefinedForType (target_left_expr_type)) {
3370 target_left_expr = ConvertOperandToDefinedType(ec, target_left_expr);
3372 if (target_left_expr == null) {
3373 Error_OperatorCannotBeApplied();
3377 target_left_expr_type = target_left_expr.Type;
3381 if ( !IsOperatorDefinedForType(target_right_expr_type)) {
3382 target_right_expr = ConvertOperandToDefinedType(ec, target_right_expr);
3384 if(target_right_expr == null) {
3385 Error_OperatorCannotBeApplied();
3389 target_right_expr_type = target_right_expr.Type;
3393 if (target_left_expr_type == TypeManager.string_type) {
3395 if (target_right_expr_type == TypeManager.date_type)
3396 target_type = TypeManager.date_type;
3397 else if (target_right_expr_type == TypeManager.bool_type)
3398 target_type = TypeManager.bool_type;
3400 target_type = TypeManager.double_type;
3402 if (l == target_type)
3403 target_left_expr = left;
3405 target_left_expr = Convert.ImplicitVBConversionRequired (ec, left, target_type, Location);
3407 if (target_left_expr == null) {
3408 Error_OperatorCannotBeApplied();
3412 target_left_expr_type = target_left_expr.Type;
3416 if (target_right_expr_type == TypeManager.string_type) {
3418 if (target_left_expr_type == TypeManager.date_type)
3419 target_type = TypeManager.date_type;
3420 else if (target_left_expr_type == TypeManager.bool_type)
3421 target_type = TypeManager.bool_type;
3423 target_type = TypeManager.double_type;
3425 if (r == target_type)
3426 target_right_expr = right;
3428 target_right_expr = Convert.ImplicitVBConversionRequired (ec, right, target_type, Location);
3430 if (target_right_expr == null) {
3431 Error_OperatorCannotBeApplied();
3435 target_right_expr_type = target_right_expr.Type;
3439 if ( !DoOperandPromotions(ec, target_left_expr, target_right_expr)) {
3440 Error_OperatorCannotBeApplied();
3446 bool IsOperatorDefinedForType (Type t)
3451 case Operator.Exponentiation:
3452 if (t == TypeManager.double_type)
3456 case Operator.Concatenation:
3458 if (t == TypeManager.string_type)
3463 case Operator.BitwiseAnd:
3464 case Operator.BitwiseOr:
3465 case Operator.ExclusiveOr:
3466 if (t == TypeManager.bool_type ||
3467 TypeManager.IsFixedNumericType (t))
3472 case Operator.RightShift:
3473 case Operator.LeftShift:
3475 if (TypeManager.IsFixedNumericType (t))
3480 case Operator.Equality:
3481 case Operator.Inequality:
3482 case Operator.LessThan:
3483 case Operator.LessThanOrEqual:
3484 case Operator.GreaterThan:
3485 case Operator.GreaterThanOrEqual:
3486 if (t == TypeManager.bool_type ||
3487 t == TypeManager.date_type ||
3488 t == TypeManager.char_type ||
3489 t == TypeManager.string_type ||
3490 TypeManager.IsNumericType (t))
3495 case Operator.Addition:
3496 if (t == TypeManager.string_type ||
3497 TypeManager.IsNumericType (t))
3501 case Operator.Subtraction:
3502 case Operator.Multiply:
3503 case Operator.Division:
3504 case Operator.Modulus:
3505 if (TypeManager.IsNumericType (t))
3509 case Operator.IntegerDivision:
3510 if (TypeManager.IsFixedNumericType (t))
3520 Expression ConvertOperandToDefinedType (EmitContext ec, Expression expr)
3522 Type target_type = null;
3523 Type operand_type = expr.Type;
3525 if (IsOperatorDefinedForType (operand_type))
3529 case Operator.Addition:
3530 case Operator.Subtraction:
3531 case Operator.Multiply:
3532 if (operand_type == TypeManager.bool_type)
3533 target_type = TypeManager.short_type;
3535 if (operand_type == TypeManager.char_type)
3536 target_type = TypeManager.string_type;
3538 if (operand_type == TypeManager.date_type)
3539 target_type = TypeManager.string_type;
3544 case Operator.Concatenation:
3545 return Convert.ExplicitVBConversion(ec, expr, TypeManager.string_type, expr.Location);
3548 case Operator.LogicalAndAlso:
3549 case Operator.LogicalOrElse:
3550 return Convert.ExplicitVBConversion(ec, expr, TypeManager.bool_type, expr.Location);
3553 case Operator.Exponentiation:
3554 return Convert.ExplicitVBConversion(ec, expr, TypeManager.double_type, expr.Location);
3559 if (target_type != null)
3560 return Convert.ImplicitVBConversion(ec, expr, target_type, expr.Location);
3565 static Type GetWiderOfTypes (Type t1, Type t2)
3567 // char array and Nothing should be handled here ?
3573 if (t1 == TypeManager.date_type || t1 == TypeManager.char_type) {
3574 if (t2 == TypeManager.string_type)
3580 if (t2 == TypeManager.date_type || t2 == TypeManager.char_type) {
3581 if (t1 == TypeManager.string_type)
3587 object order1 = TypeManager.relative_type_order[t1];
3591 object order2 = TypeManager.relative_type_order[t2];
3596 if ((int) order1 > (int) order2)
3603 bool DoOperandPromotions (EmitContext ec, Expression target_left_expr, Expression target_right_expr)
3605 Type l = target_left_expr.Type;
3606 Type r = target_right_expr.Type;
3608 Type target_type = GetWiderOfTypes(l, r);
3611 if (target_type == null) {
3612 throw new Exception ("Types " + l + " " + r +" cannot be compared");
3615 if (r != target_type) {
3616 target_right_expr = Convert.ImplicitVBConversion (ec, target_right_expr, target_type, Location);
3618 if (target_right_expr == null)
3623 if (l != target_type) {
3624 target_left_expr = Convert.ImplicitVBConversion (ec, target_left_expr, target_type, Location);
3626 if (target_left_expr == null)
3630 left = target_left_expr;
3631 right = target_right_expr;
3636 bool IsArithmeticExpression {
3638 if (oper == Operator.Addition|| oper == Operator.Subtraction||
3639 oper == Operator.Multiply|| oper == Operator.Division||
3640 oper == Operator.IntegerDivision|| oper == Operator.Modulus)
3647 bool IsRelationalExpression {
3649 if (oper == Operator.Equality || oper == Operator.Inequality ||
3650 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
3651 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual)
3658 bool IsShiftExpression {
3660 if (oper == Operator.LeftShift || oper == Operator.RightShift)
3667 bool IsShortCircuitedLogicalExpression {
3669 if (oper == Operator.LogicalAndAlso|| oper == Operator.LogicalOrElse)
3676 MethodInfo HelperMethod {
3678 MethodInfo helper_method = null;
3680 case Operator.Multiply:
3681 helper_method = TypeManager.msvbcs_objecttype_mulobj_object_object;
3683 case Operator.Division:
3684 helper_method = TypeManager.msvbcs_objecttype_divobj_object_object;
3686 case Operator.IntegerDivision:
3687 helper_method = TypeManager.msvbcs_objecttype_idivobj_object_object;
3689 case Operator.Modulus:
3690 helper_method = TypeManager.msvbcs_objecttype_modobj_object_object;
3692 case Operator.Addition:
3693 helper_method = TypeManager.msvbcs_objecttype_addobj_object_object;
3695 case Operator.Subtraction:
3696 helper_method = TypeManager.msvbcs_objecttype_subobj_object_object;
3698 case Operator.LessThan:
3699 case Operator.GreaterThan:
3700 case Operator.LessThanOrEqual:
3701 case Operator.GreaterThanOrEqual:
3702 case Operator.Equality:
3703 case Operator.Inequality:
3704 helper_method = TypeManager.msvbcs_objecttype_objtst_object_object_boolean;
3706 case Operator.BitwiseAnd:
3707 helper_method = TypeManager.msvbcs_objecttype_bitandobj_object_object;
3709 case Operator.BitwiseOr:
3710 helper_method = TypeManager.msvbcs_objecttype_bitorobj_object_object;
3712 case Operator.ExclusiveOr:
3713 helper_method = TypeManager.msvbcs_objecttype_bitxorobj_object_object;
3717 helper_method = TypeManager.msvbcs_objecttype_likeobj_object_object_comparemethod;
3720 case Operator.Concatenation:
3721 helper_method = TypeManager.msvbcs_objecttype_strcatobj_object_object;
3724 case Operator.Exponentiation:
3725 helper_method = TypeManager.msvbcs_objecttype_powobj_object_object;
3727 case Operator.LeftShift:
3728 helper_method = TypeManager.msvbcs_objecttype_shiftleftobj_object_int32;
3730 case Operator.RightShift:
3731 helper_method = TypeManager.msvbcs_objecttype_shiftrightobj_object_int32;
3736 return helper_method;
3742 // Object created by Binary when the binary operator uses an method instead of being
3743 // a binary operation that maps to a CIL binary operation.
3745 public class BinaryMethod : Expression {
3746 public MethodBase method;
3747 public ArrayList Arguments;
3749 public BinaryMethod (Type t, MethodBase m, ArrayList args)
3754 eclass = ExprClass.Value;
3757 public override Expression DoResolve (EmitContext ec)
3762 public override void Emit (EmitContext ec)
3764 ILGenerator ig = ec.ig;
3766 if (Arguments != null)
3767 Invocation.EmitArguments (ec, method, Arguments, false, null);
3769 if (method is MethodInfo)
3770 ig.Emit (OpCodes.Call, (MethodInfo) method);
3772 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3777 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3778 // b, c, d... may be strings or objects.
3780 public class StringConcat : Expression {
3782 bool invalid = false;
3783 bool emit_conv_done = false;
3785 // Are we also concating objects?
3787 bool is_strings_only = true;
3789 public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
3792 type = TypeManager.string_type;
3793 eclass = ExprClass.Value;
3795 operands = new ArrayList (2);
3800 public override Expression DoResolve (EmitContext ec)
3808 public void Append (EmitContext ec, Expression operand)
3813 if (operand is StringConstant && operands.Count != 0) {
3814 StringConstant last_operand = operands [operands.Count - 1] as StringConstant;
3815 if (last_operand != null) {
3816 operands [operands.Count - 1] = new StringConstant (last_operand.Value + ((StringConstant) operand).Value);
3822 // Conversion to object
3824 if (operand.Type != TypeManager.string_type) {
3825 Expression no = Convert.WideningConversion (ec, operand, TypeManager.object_type, loc);
3828 Binary.Error_OperatorCannotBeApplied (loc, "+", TypeManager.string_type, operand.Type);
3834 operands.Add (operand);
3837 public override void Emit (EmitContext ec)
3839 MethodInfo concat_method = null;
3842 // Do conversion to arguments; check for strings only
3845 // This can get called multiple times, so we have to deal with that.
3846 if (!emit_conv_done) {
3847 emit_conv_done = true;
3848 for (int i = 0; i < operands.Count; i ++) {
3849 Expression e = (Expression) operands [i];
3850 is_strings_only &= e.Type == TypeManager.string_type;
3853 for (int i = 0; i < operands.Count; i ++) {
3854 Expression e = (Expression) operands [i];
3856 if (! is_strings_only && e.Type == TypeManager.string_type) {
3857 // need to make sure this is an object, because the EmitParams
3858 // method might look at the type of this expression, see it is a
3859 // string and emit a string [] when we want an object [];
3861 e = new EmptyCast (e, TypeManager.object_type);
3863 operands [i] = new Argument (e, Argument.AType.Expression);
3868 // Find the right method
3870 switch (operands.Count) {
3873 // This should not be possible, because simple constant folding
3874 // is taken care of in the Binary code.
3876 throw new Exception ("how did you get here?");
3879 concat_method = is_strings_only ?
3880 TypeManager.string_concat_string_string :
3881 TypeManager.string_concat_object_object ;
3884 concat_method = is_strings_only ?
3885 TypeManager.string_concat_string_string_string :
3886 TypeManager.string_concat_object_object_object ;
3890 // There is not a 4 param overlaod for object (the one that there is
3891 // is actually a varargs methods, and is only in corlib because it was
3892 // introduced there before.).
3894 if (!is_strings_only)
3897 concat_method = TypeManager.string_concat_string_string_string_string;
3900 concat_method = is_strings_only ?
3901 TypeManager.string_concat_string_dot_dot_dot :
3902 TypeManager.string_concat_object_dot_dot_dot ;
3906 Invocation.EmitArguments (ec, concat_method, operands, false, null);
3907 ec.ig.Emit (OpCodes.Call, concat_method);
3912 // Object created with +/= on delegates
3914 public class BinaryDelegate : Expression {
3918 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3923 eclass = ExprClass.Value;
3926 public override Expression DoResolve (EmitContext ec)
3931 public override void Emit (EmitContext ec)
3933 ILGenerator ig = ec.ig;
3935 Invocation.EmitArguments (ec, method, args, false, null);
3937 ig.Emit (OpCodes.Call, (MethodInfo) method);
3938 ig.Emit (OpCodes.Castclass, type);
3941 public Expression Right {
3943 Argument arg = (Argument) args [1];
3948 public bool IsAddition {
3950 return method == TypeManager.delegate_combine_delegate_delegate;
3956 // User-defined conditional logical operator
3957 public class ConditionalLogicalOperator : Expression {
3958 Expression left, right;
3961 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3964 eclass = ExprClass.Value;
3968 this.is_and = is_and;
3971 protected void Error19 ()
3973 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3976 protected void Error218 ()
3978 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3979 "declarations of operator true and operator false");
3982 Expression op_true, op_false, op;
3983 LocalTemporary left_temp;
3985 public override Expression DoResolve (EmitContext ec)
3988 Expression operator_group;
3990 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3991 if (operator_group == null) {
3996 left_temp = new LocalTemporary (ec, type);
3998 ArrayList arguments = new ArrayList ();
3999 arguments.Add (new Argument (left_temp, Argument.AType.Expression));
4000 arguments.Add (new Argument (right, Argument.AType.Expression));
4001 method = Invocation.OverloadResolve (
4002 ec, (MethodGroupExpr) operator_group, arguments, false, loc)
4004 if ((method == null) || (method.ReturnType != type)) {
4009 op = new StaticCallExpr (method, arguments, loc);
4011 op_true = GetOperatorTrue (ec, left_temp, loc);
4012 op_false = GetOperatorFalse (ec, left_temp, loc);
4013 if ((op_true == null) || (op_false == null)) {
4021 public override void Emit (EmitContext ec)
4023 ILGenerator ig = ec.ig;
4024 Label false_target = ig.DefineLabel ();
4025 Label end_target = ig.DefineLabel ();
4028 left_temp.Store (ec);
4030 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
4031 left_temp.Emit (ec);
4032 ig.Emit (OpCodes.Br, end_target);
4033 ig.MarkLabel (false_target);
4035 ig.MarkLabel (end_target);
4039 public class PointerArithmetic : Expression {
4040 Expression left, right;
4044 // We assume that `l' is always a pointer
4046 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
4052 is_add = is_addition;
4055 public override Expression DoResolve (EmitContext ec)
4057 eclass = ExprClass.Variable;
4059 if (left.Type == TypeManager.void_ptr_type) {
4060 Error (242, "The operation in question is undefined on void pointers");
4067 public override void Emit (EmitContext ec)
4069 Type op_type = left.Type;
4070 ILGenerator ig = ec.ig;
4071 Type element = TypeManager.GetElementType (op_type);
4072 int size = GetTypeSize (element);
4073 Type rtype = right.Type;
4075 if (rtype.IsPointer){
4077 // handle (pointer - pointer)
4081 ig.Emit (OpCodes.Sub);
4085 ig.Emit (OpCodes.Sizeof, element);
4087 IntLiteral.EmitInt (ig, size);
4088 ig.Emit (OpCodes.Div);
4090 ig.Emit (OpCodes.Conv_I8);
4093 // handle + and - on (pointer op int)
4096 ig.Emit (OpCodes.Conv_I);
4098 Constant right_const = right as Constant;
4099 if (right_const != null && size != 0) {
4100 Expression ex = ConstantFold.BinaryFold (ec, Binary.Operator.Multiply, new IntConstant (size), right_const, loc);
4108 ig.Emit (OpCodes.Sizeof, element);
4110 IntLiteral.EmitInt (ig, size);
4111 if (rtype == TypeManager.int64_type)
4112 ig.Emit (OpCodes.Conv_I8);
4113 else if (rtype == TypeManager.uint64_type)
4114 ig.Emit (OpCodes.Conv_U8);
4115 ig.Emit (OpCodes.Mul);
4119 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
4120 ig.Emit (OpCodes.Conv_I);
4123 ig.Emit (OpCodes.Add);
4125 ig.Emit (OpCodes.Sub);
4131 /// Implements the ternary conditional operator (?:)
4133 public class Conditional : Expression {
4134 Expression expr, trueExpr, falseExpr;
4136 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
4139 this.trueExpr = trueExpr;
4140 this.falseExpr = falseExpr;
4144 public Expression Expr {
4150 public Expression TrueExpr {
4156 public Expression FalseExpr {
4162 public override Expression DoResolve (EmitContext ec)
4164 expr = expr.Resolve (ec);
4169 if (TypeManager.IsNullableType (expr.Type))
4170 return new Nullable.LiftedConditional (expr, trueExpr, falseExpr, loc).Resolve (ec);
4172 if (expr.Type != TypeManager.bool_type){
4173 expr = Expression.ResolveBoolean (
4180 trueExpr = trueExpr.Resolve (ec);
4181 falseExpr = falseExpr.Resolve (ec);
4183 if (trueExpr == null || falseExpr == null)
4186 eclass = ExprClass.Value;
4187 if (trueExpr.Type == falseExpr.Type)
4188 type = trueExpr.Type;
4191 Type true_type = trueExpr.Type;
4192 Type false_type = falseExpr.Type;
4195 // First, if an implicit conversion exists from trueExpr
4196 // to falseExpr, then the result type is of type falseExpr.Type
4198 conv = Convert.WideningConversion (ec, trueExpr, false_type, loc);
4201 // Check if both can convert implicitl to each other's type
4203 if (Convert.WideningConversion (ec, falseExpr, true_type, loc) != null){
4205 "Can not compute type of conditional expression " +
4206 "as `" + TypeManager.CSharpName (trueExpr.Type) +
4207 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
4208 "' convert implicitly to each other");
4213 } else if ((conv = Convert.WideningConversion(ec, falseExpr, true_type,loc))!= null){
4217 Error (173, "The type of the conditional expression can " +
4218 "not be computed because there is no implicit conversion" +
4219 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
4220 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
4225 // Dead code optimalization
4226 if (expr is BoolConstant){
4227 BoolConstant bc = (BoolConstant) expr;
4229 Report.Warning (429, 4, bc.Value ? falseExpr.Location : trueExpr.Location, "Unreachable expression code detected");
4230 return bc.Value ? trueExpr : falseExpr;
4236 public override void Emit (EmitContext ec)
4238 ILGenerator ig = ec.ig;
4239 Label false_target = ig.DefineLabel ();
4240 Label end_target = ig.DefineLabel ();
4242 expr.EmitBranchable (ec, false_target, false);
4244 ig.Emit (OpCodes.Br, end_target);
4245 ig.MarkLabel (false_target);
4246 falseExpr.Emit (ec);
4247 ig.MarkLabel (end_target);
4255 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
4256 public readonly string Name;
4257 public readonly Block Block;
4258 public LocalInfo local_info;
4261 LocalTemporary temp;
4263 public LocalVariableReference (Block block, string name, Location l)
4268 eclass = ExprClass.Variable;
4272 // Setting `is_readonly' to false will allow you to create a writable
4273 // reference to a read-only variable. This is used by foreach and using.
4275 public LocalVariableReference (Block block, string name, Location l,
4276 LocalInfo local_info, bool is_readonly)
4277 : this (block, name, l)
4279 this.local_info = local_info;
4280 this.is_readonly = is_readonly;
4283 public VariableInfo VariableInfo {
4285 return local_info.VariableInfo;
4289 public bool IsReadOnly {
4295 protected Expression DoResolveBase (EmitContext ec, Expression lvalue_right_side)
4297 if (local_info == null) {
4298 local_info = Block.GetLocalInfo (Name);
4301 if (lvalue_right_side == EmptyExpression.Null)
4302 local_info.Used = true;
4304 is_readonly = local_info.ReadOnly;
4307 type = local_info.VariableType;
4309 VariableInfo variable_info = local_info.VariableInfo;
4310 if (lvalue_right_side != null){
4312 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
4316 if (variable_info != null)
4317 variable_info.SetAssigned (ec);
4320 Expression e = Block.GetConstantExpression (Name);
4322 local_info.Used = true;
4323 eclass = ExprClass.Value;
4324 return e.Resolve (ec);
4327 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
4330 if (lvalue_right_side == null)
4331 local_info.Used = true;
4333 if (ec.CurrentAnonymousMethod != null){
4335 // If we are referencing a variable from the external block
4336 // flag it for capturing
4338 if (local_info.Block.Toplevel != ec.CurrentBlock.Toplevel){
4339 if (local_info.AddressTaken){
4340 AnonymousMethod.Error_AddressOfCapturedVar (local_info.Name, loc);
4343 ec.CaptureVariable (local_info);
4350 public override Expression DoResolve (EmitContext ec)
4352 return DoResolveBase (ec, null);
4355 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4357 Expression ret = DoResolveBase (ec, right_side);
4359 CheckObsoleteAttribute (ret.Type);
4364 public bool VerifyFixed (bool is_expression)
4366 return !is_expression || local_info.IsFixed;
4369 public override void Emit (EmitContext ec)
4371 ILGenerator ig = ec.ig;
4373 if (local_info.FieldBuilder == null){
4375 // A local variable on the local CLR stack
4377 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
4380 // A local variable captured by anonymous methods.
4383 ec.EmitCapturedVariableInstance (local_info);
4385 ig.Emit (OpCodes.Ldfld, local_info.FieldBuilder);
4389 public void Emit (EmitContext ec, bool leave_copy)
4393 ec.ig.Emit (OpCodes.Dup);
4394 if (local_info.FieldBuilder != null){
4395 temp = new LocalTemporary (ec, Type);
4401 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
4403 ILGenerator ig = ec.ig;
4404 prepared = prepare_for_load;
4406 if (local_info.FieldBuilder == null){
4408 // A local variable on the local CLR stack
4410 if (local_info.LocalBuilder == null)
4411 throw new Exception ("This should not happen: both Field and Local are null");
4415 ec.ig.Emit (OpCodes.Dup);
4416 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
4419 // A local variable captured by anonymous methods or itereators.
4421 ec.EmitCapturedVariableInstance (local_info);
4423 if (prepare_for_load)
4424 ig.Emit (OpCodes.Dup);
4427 ig.Emit (OpCodes.Dup);
4428 temp = new LocalTemporary (ec, Type);
4431 ig.Emit (OpCodes.Stfld, local_info.FieldBuilder);
4437 public void AddressOf (EmitContext ec, AddressOp mode)
4439 ILGenerator ig = ec.ig;
4441 if (local_info.FieldBuilder == null){
4443 // A local variable on the local CLR stack
4445 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
4448 // A local variable captured by anonymous methods or iterators
4450 ec.EmitCapturedVariableInstance (local_info);
4451 ig.Emit (OpCodes.Ldflda, local_info.FieldBuilder);
4455 public override string ToString ()
4457 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
4462 /// This represents a reference to a parameter in the intermediate
4465 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
4471 public Parameter.Modifier mod;
4472 public bool is_ref, is_out, prepared;
4486 LocalTemporary temp;
4488 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
4495 eclass = ExprClass.Variable;
4498 public VariableInfo VariableInfo {
4502 public bool VerifyFixed (bool is_expression)
4504 return !is_expression || TypeManager.IsValueType (type);
4507 public bool IsAssigned (EmitContext ec, Location loc)
4509 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsAssigned (vi))
4512 Report.Error (165, loc,
4513 "Use of unassigned parameter `" + name + "'");
4517 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
4519 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsFieldAssigned (vi, field_name))
4522 Report.Error (170, loc,
4523 "Use of possibly unassigned field `" + field_name + "'");
4527 public void SetAssigned (EmitContext ec)
4529 if (is_out && ec.DoFlowAnalysis)
4530 ec.CurrentBranching.SetAssigned (vi);
4533 public void SetFieldAssigned (EmitContext ec, string field_name)
4535 if (is_out && ec.DoFlowAnalysis)
4536 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
4539 protected void DoResolveBase (EmitContext ec)
4541 type = pars.GetParameterInfo (ec, idx, out mod);
4542 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
4543 is_out = (mod & Parameter.Modifier.OUT) != 0;
4544 eclass = ExprClass.Variable;
4547 vi = block.ParameterMap [idx];
4549 if (ec.CurrentAnonymousMethod != null){
4551 Report.Error (1628, Location,
4552 "Can not reference a ref or out parameter in an anonymous method");
4557 // If we are referencing the parameter from the external block
4558 // flag it for capturing
4560 //Console.WriteLine ("Is parameter `{0}' local? {1}", name, block.IsLocalParameter (name));
4561 if (!block.IsLocalParameter (name)){
4562 ec.CaptureParameter (name, type, idx);
4568 // Notice that for ref/out parameters, the type exposed is not the
4569 // same type exposed externally.
4572 // externally we expose "int&"
4573 // here we expose "int".
4575 // We record this in "is_ref". This means that the type system can treat
4576 // the type as it is expected, but when we generate the code, we generate
4577 // the alternate kind of code.
4579 public override Expression DoResolve (EmitContext ec)
4583 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
4586 if (ec.RemapToProxy)
4587 return ec.RemapParameter (idx);
4592 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4598 if (ec.RemapToProxy)
4599 return ec.RemapParameterLValue (idx, right_side);
4604 static public void EmitLdArg (ILGenerator ig, int x)
4608 case 0: ig.Emit (OpCodes.Ldarg_0); break;
4609 case 1: ig.Emit (OpCodes.Ldarg_1); break;
4610 case 2: ig.Emit (OpCodes.Ldarg_2); break;
4611 case 3: ig.Emit (OpCodes.Ldarg_3); break;
4612 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
4615 ig.Emit (OpCodes.Ldarg, x);
4619 // This method is used by parameters that are references, that are
4620 // being passed as references: we only want to pass the pointer (that
4621 // is already stored in the parameter, not the address of the pointer,
4622 // and not the value of the variable).
4624 public void EmitLoad (EmitContext ec)
4626 ILGenerator ig = ec.ig;
4632 EmitLdArg (ig, arg_idx);
4635 // FIXME: Review for anonymous methods
4639 public override void Emit (EmitContext ec)
4641 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4642 ec.EmitParameter (name);
4649 public void Emit (EmitContext ec, bool leave_copy)
4651 ILGenerator ig = ec.ig;
4657 EmitLdArg (ig, arg_idx);
4661 ec.ig.Emit (OpCodes.Dup);
4664 // If we are a reference, we loaded on the stack a pointer
4665 // Now lets load the real value
4667 LoadFromPtr (ig, type);
4671 ec.ig.Emit (OpCodes.Dup);
4674 temp = new LocalTemporary (ec, type);
4680 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
4682 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4683 ec.EmitAssignParameter (name, source, leave_copy, prepare_for_load);
4687 ILGenerator ig = ec.ig;
4690 prepared = prepare_for_load;
4695 if (is_ref && !prepared)
4696 EmitLdArg (ig, arg_idx);
4701 ec.ig.Emit (OpCodes.Dup);
4705 temp = new LocalTemporary (ec, type);
4709 StoreFromPtr (ig, type);
4715 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
4717 ig.Emit (OpCodes.Starg, arg_idx);
4721 public void AddressOf (EmitContext ec, AddressOp mode)
4723 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4724 ec.EmitAddressOfParameter (name);
4735 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
4737 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
4740 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
4742 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
4749 /// Used for arguments to New(), Invocation()
4751 public class Argument {
4752 public enum AType : byte {
4757 //FIXME: These two are mbas specific and the
4758 // related changes need to be propagated
4763 public readonly AType ArgType;
4764 public Expression Expr;
4766 public Argument (Expression expr, AType type)
4769 this.ArgType = type;
4772 public Argument (Expression expr)
4775 this.ArgType = AType.Expression;
4780 if (ArgType == AType.Ref || ArgType == AType.Out)
4781 return TypeManager.GetReferenceType (Expr.Type);
4787 public Parameter.Modifier GetParameterModifier ()
4791 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
4794 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
4797 return Parameter.Modifier.NONE;
4801 public static string FullDesc (Argument a)
4803 if (a.ArgType == AType.ArgList)
4806 return (a.ArgType == AType.Ref ? "ref " :
4807 (a.ArgType == AType.Out ? "out " : "")) +
4808 TypeManager.CSharpName (a.Expr.Type);
4811 public bool ResolveMethodGroup (EmitContext ec, Location loc)
4813 ConstructedType ctype = Expr as ConstructedType;
4815 Expr = ctype.GetSimpleName (ec);
4817 // FIXME: csc doesn't report any error if you try to use `ref' or
4818 // `out' in a delegate creation expression.
4819 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4826 public bool Resolve (EmitContext ec, Location loc)
4828 if (ArgType == AType.Ref) {
4829 Expr = Expr.Resolve (ec);
4833 if (!ec.IsConstructor) {
4834 FieldExpr fe = Expr as FieldExpr;
4835 if (fe != null && fe.FieldInfo.IsInitOnly) {
4836 if (fe.FieldInfo.IsStatic)
4837 Report.Error (199, loc, "A static readonly field cannot be passed ref or out (except in a static constructor)");
4839 Report.Error (192, loc, "A readonly field cannot be passed ref or out (except in a constructor)");
4843 Expr = Expr.ResolveLValue (ec, Expr);
4844 } else if (ArgType == AType.Out)
4845 Expr = Expr.ResolveLValue (ec, EmptyExpression.Null);
4847 Expr = Expr.Resolve (ec);
4852 if (ArgType == AType.Expression)
4856 // Catch errors where fields of a MarshalByRefObject are passed as ref or out
4857 // This is only allowed for `this'
4859 FieldExpr fe = Expr as FieldExpr;
4860 if (fe != null && !fe.IsStatic){
4861 Expression instance = fe.InstanceExpression;
4863 if (instance.GetType () != typeof (This)){
4864 if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
4865 Report.SymbolRelatedToPreviousError (fe.InstanceExpression.Type);
4866 Report.Error (197, loc, "Cannot pass '{0}' as ref or out or take its address because it is a member of a marshal-by-reference class",
4874 if (Expr.eclass != ExprClass.Variable){
4876 // We just probe to match the CSC output
4878 if (Expr.eclass == ExprClass.PropertyAccess ||
4879 Expr.eclass == ExprClass.IndexerAccess){
4882 "A property or indexer can not be passed as an out or ref " +
4887 "An lvalue is required as an argument to out or ref");
4895 public void Emit (EmitContext ec)
4898 // Ref and Out parameters need to have their addresses taken.
4900 // ParameterReferences might already be references, so we want
4901 // to pass just the value
4903 if (ArgType == AType.Ref || ArgType == AType.Out){
4904 AddressOp mode = AddressOp.Store;
4906 if (ArgType == AType.Ref)
4907 mode |= AddressOp.Load;
4909 if (Expr is ParameterReference){
4910 ParameterReference pr = (ParameterReference) Expr;
4916 pr.AddressOf (ec, mode);
4919 if (Expr is IMemoryLocation)
4920 ((IMemoryLocation) Expr).AddressOf (ec, mode);
4923 1510, Expr.Location,
4924 "An lvalue is required as an argument to out or ref");
4934 /// Invocation of methods or delegates.
4936 public class Invocation : ExpressionStatement {
4937 public readonly ArrayList Arguments;
4939 public Expression expr;
4940 MethodBase method = null;
4942 static Hashtable method_parameter_cache;
4944 static Invocation ()
4946 method_parameter_cache = new PtrHashtable ();
4950 // arguments is an ArrayList, but we do not want to typecast,
4951 // as it might be null.
4953 // FIXME: only allow expr to be a method invocation or a
4954 // delegate invocation (7.5.5)
4956 public Invocation (Expression expr, ArrayList arguments, Location l)
4959 Arguments = arguments;
4963 public Expression Expr {
4970 /// Returns the Parameters (a ParameterData interface) for the
4973 public static ParameterData GetParameterData (MethodBase mb)
4975 object pd = method_parameter_cache [mb];
4979 return (ParameterData) pd;
4981 ip = TypeManager.LookupParametersByBuilder (mb);
4983 method_parameter_cache [mb] = ip;
4985 return (ParameterData) ip;
4987 ReflectionParameters rp = new ReflectionParameters (mb);
4988 method_parameter_cache [mb] = rp;
4990 return (ParameterData) rp;
4995 /// Determines "better conversion" as specified in 7.4.2.3
4997 /// Returns : p if a->p is better,
4998 /// q if a->q is better,
4999 /// null if neither is better
5001 static Type BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
5003 Type argument_type = TypeManager.TypeToCoreType (a.Type);
5004 Expression argument_expr = a.Expr;
5006 // p = TypeManager.TypeToCoreType (p);
5007 // q = TypeManager.TypeToCoreType (q);
5009 if (argument_type == null)
5010 throw new Exception ("Expression of type " + a.Expr +
5011 " does not resolve its type");
5013 if (p == null || q == null)
5014 throw new InternalErrorException ("BetterConversion Got a null conversion");
5019 if (argument_expr is NullLiteral) {
5021 // If the argument is null and one of the types to compare is 'object' and
5022 // the other is a reference type, we prefer the other.
5024 // This follows from the usual rules:
5025 // * There is an implicit conversion from 'null' to type 'object'
5026 // * There is an implicit conversion from 'null' to any reference type
5027 // * There is an implicit conversion from any reference type to type 'object'
5028 // * There is no implicit conversion from type 'object' to other reference types
5029 // => Conversion of 'null' to a reference type is better than conversion to 'object'
5031 // FIXME: This probably isn't necessary, since the type of a NullLiteral is the
5032 // null type. I think it used to be 'object' and thus needed a special
5033 // case to avoid the immediately following two checks.
5035 if (!p.IsValueType && q == TypeManager.object_type)
5037 if (!q.IsValueType && p == TypeManager.object_type)
5041 if (argument_type == p)
5044 if (argument_type == q)
5047 Expression p_tmp = new EmptyExpression (p);
5048 Expression q_tmp = new EmptyExpression (q);
5050 bool p_to_q = Convert.WideningConversionExists (ec, p_tmp, q);
5051 bool q_to_p = Convert.WideningConversionExists (ec, q_tmp, p);
5053 if (p_to_q && !q_to_p)
5056 if (q_to_p && !p_to_q)
5059 if (p == TypeManager.sbyte_type)
5060 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
5061 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
5063 if (q == TypeManager.sbyte_type)
5064 if (p == TypeManager.byte_type || p == TypeManager.ushort_type ||
5065 p == TypeManager.uint32_type || p == TypeManager.uint64_type)
5068 if (p == TypeManager.short_type)
5069 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
5070 q == TypeManager.uint64_type)
5073 if (q == TypeManager.short_type)
5074 if (p == TypeManager.ushort_type || p == TypeManager.uint32_type ||
5075 p == TypeManager.uint64_type)
5078 if (p == TypeManager.int32_type)
5079 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
5082 if (q == TypeManager.int32_type)
5083 if (p == TypeManager.uint32_type || p == TypeManager.uint64_type)
5086 if (p == TypeManager.int64_type)
5087 if (q == TypeManager.uint64_type)
5089 if (q == TypeManager.int64_type)
5090 if (p == TypeManager.uint64_type)
5097 /// Determines "Better function" between candidate
5098 /// and the current best match
5101 /// Returns a boolean indicating :
5102 /// false if candidate ain't better
5103 /// true if candidate is better than the current best match
5105 static bool BetterFunction (EmitContext ec, ArrayList args, int argument_count,
5106 MethodBase candidate, bool candidate_params,
5107 MethodBase best, bool best_params, Location loc)
5109 ParameterData candidate_pd = GetParameterData (candidate);
5110 ParameterData best_pd = GetParameterData (best);
5112 int cand_count = candidate_pd.Count;
5115 // If there is no best method, than this one
5116 // is better, however, if we already found a
5117 // best method, we cant tell. This happens
5128 // interface IFooBar : IFoo, IBar {}
5130 // We cant tell if IFoo.DoIt is better than IBar.DoIt
5132 // However, we have to consider that
5133 // Trim (); is better than Trim (params char[] chars);
5135 if (cand_count == 0 && argument_count == 0)
5136 return !candidate_params && best_params;
5138 if ((candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS) &&
5139 (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.ARGLIST))
5140 if (cand_count != argument_count)
5143 bool better_at_least_one = false;
5144 bool is_equal = true;
5146 for (int j = 0; j < argument_count; ++j) {
5147 Argument a = (Argument) args [j];
5149 Type ct = TypeManager.TypeToCoreType (candidate_pd.ParameterType (j));
5150 Type bt = TypeManager.TypeToCoreType (best_pd.ParameterType (j));
5152 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
5153 if (candidate_params)
5154 ct = TypeManager.GetElementType (ct);
5156 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
5158 bt = TypeManager.GetElementType (bt);
5160 if (!ct.Equals (bt))
5163 Type better = BetterConversion (ec, a, ct, bt, loc);
5164 // for each argument, the conversion to 'ct' should be no worse than
5165 // the conversion to 'bt'.
5169 // for at least one argument, the conversion to 'ct' should be better than
5170 // the conversion to 'bt'.
5172 better_at_least_one = true;
5176 // If a method (in the normal form) with the
5177 // same signature as the expanded form of the
5178 // current best params method already exists,
5179 // the expanded form is not applicable so we
5180 // force it to select the candidate
5182 if (!candidate_params && best_params && cand_count == argument_count)
5186 // If two methods have equal parameter types, but
5187 // only one of them is generic, the non-generic one wins.
5190 if (TypeManager.IsGenericMethod (best) && !TypeManager.IsGenericMethod (candidate))
5192 else if (!TypeManager.IsGenericMethod (best) && TypeManager.IsGenericMethod (candidate))
5196 return better_at_least_one;
5199 public static string FullMethodDesc (MethodBase mb)
5201 string ret_type = "";
5206 if (mb is MethodInfo)
5207 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
5209 StringBuilder sb = new StringBuilder (ret_type);
5211 sb.Append (mb.ReflectedType.ToString ());
5213 sb.Append (mb.Name);
5215 ParameterData pd = GetParameterData (mb);
5217 int count = pd.Count;
5220 for (int i = count; i > 0; ) {
5223 sb.Append (pd.ParameterDesc (count - i - 1));
5229 return sb.ToString ();
5232 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
5234 MemberInfo [] miset;
5235 MethodGroupExpr union;
5240 return (MethodGroupExpr) mg2;
5243 return (MethodGroupExpr) mg1;
5246 MethodGroupExpr left_set = null, right_set = null;
5247 int length1 = 0, length2 = 0;
5249 left_set = (MethodGroupExpr) mg1;
5250 length1 = left_set.Methods.Length;
5252 right_set = (MethodGroupExpr) mg2;
5253 length2 = right_set.Methods.Length;
5255 ArrayList common = new ArrayList ();
5257 foreach (MethodBase r in right_set.Methods){
5258 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
5262 miset = new MemberInfo [length1 + length2 - common.Count];
5263 left_set.Methods.CopyTo (miset, 0);
5267 foreach (MethodBase r in right_set.Methods) {
5268 if (!common.Contains (r))
5272 union = new MethodGroupExpr (miset, loc);
5277 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
5278 ArrayList arguments, int arg_count,
5279 ref MethodBase candidate)
5281 return IsParamsMethodApplicable (
5282 ec, me, arguments, arg_count, false, ref candidate) ||
5283 IsParamsMethodApplicable (
5284 ec, me, arguments, arg_count, true, ref candidate);
5289 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
5290 ArrayList arguments, int arg_count,
5291 bool do_varargs, ref MethodBase candidate)
5293 if (!me.HasTypeArguments &&
5294 !TypeManager.InferParamsTypeArguments (ec, arguments, ref candidate))
5297 return IsParamsMethodApplicable (
5298 ec, arguments, arg_count, candidate, do_varargs);
5302 /// Determines if the candidate method, if a params method, is applicable
5303 /// in its expanded form to the given set of arguments
5305 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
5306 int arg_count, MethodBase candidate,
5309 ParameterData pd = GetParameterData (candidate);
5311 int pd_count = pd.Count;
5316 int count = pd_count - 1;
5318 if (pd.ParameterModifier (count) != Parameter.Modifier.ARGLIST)
5320 if (pd_count != arg_count)
5323 if (pd.ParameterModifier (count) != Parameter.Modifier.PARAMS)
5327 if (count > arg_count)
5330 if (pd_count == 1 && arg_count == 0)
5334 // If we have come this far, the case which
5335 // remains is when the number of parameters is
5336 // less than or equal to the argument count.
5338 for (int i = 0; i < count; ++i) {
5340 Argument a = (Argument) arguments [i];
5342 Parameter.Modifier a_mod = a.GetParameterModifier () &
5343 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
5344 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
5345 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
5347 if (a_mod == p_mod) {
5349 if (a_mod == Parameter.Modifier.NONE)
5350 if (!Convert.WideningConversionExists (ec,
5352 pd.ParameterType (i)))
5355 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
5356 Type pt = pd.ParameterType (i);
5359 pt = TypeManager.GetReferenceType (pt);
5370 Argument a = (Argument) arguments [count];
5371 if (!(a.Expr is Arglist))
5377 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
5379 for (int i = pd_count - 1; i < arg_count; i++) {
5380 Argument a = (Argument) arguments [i];
5382 if (!Convert.WideningConversionExists (ec, a.Expr, element_type))
5389 static bool IsApplicable (EmitContext ec, MethodGroupExpr me,
5390 ArrayList arguments, int arg_count,
5391 ref MethodBase candidate)
5393 if (!me.HasTypeArguments &&
5394 !TypeManager.InferTypeArguments (ec, arguments, ref candidate))
5397 return IsApplicable (ec, arguments, arg_count, candidate);
5401 /// Determines if the candidate method is applicable (section 14.4.2.1)
5402 /// to the given set of arguments
5404 static bool IsApplicable (EmitContext ec, ArrayList arguments, int arg_count,
5405 MethodBase candidate)
5407 ParameterData pd = GetParameterData (candidate);
5409 if (arg_count != pd.Count)
5412 for (int i = arg_count; i > 0; ) {
5415 Argument a = (Argument) arguments [i];
5417 Parameter.Modifier a_mod = a.GetParameterModifier () &
5418 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5419 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
5420 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5423 if (a_mod == p_mod ||
5424 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
5425 if (a_mod == Parameter.Modifier.NONE) {
5426 if (!Convert.WideningConversionExists (ec,
5428 pd.ParameterType (i)))
5432 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
5433 Type pt = pd.ParameterType (i);
5436 pt = TypeManager.GetReferenceType (pt);
5448 static private bool IsAncestralType (Type first_type, Type second_type)
5450 return first_type != second_type &&
5451 (second_type.IsSubclassOf (first_type) ||
5452 TypeManager.ImplementsInterface (second_type, first_type));
5456 /// Find the Applicable Function Members (7.4.2.1)
5458 /// me: Method Group expression with the members to select.
5459 /// it might contain constructors or methods (or anything
5460 /// that maps to a method).
5462 /// Arguments: ArrayList containing resolved Argument objects.
5464 /// loc: The location if we want an error to be reported, or a Null
5465 /// location for "probing" purposes.
5467 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
5468 /// that is the best match of me on Arguments.
5471 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
5472 ArrayList Arguments, bool may_fail,
5475 MethodBase method = null;
5476 bool method_params = false;
5477 Type applicable_type = null;
5479 ArrayList candidates = new ArrayList ();
5482 // Used to keep a map between the candidate
5483 // and whether it is being considered in its
5484 // normal or expanded form
5486 // false is normal form, true is expanded form
5488 Hashtable candidate_to_form = null;
5490 if (Arguments != null)
5491 arg_count = Arguments.Count;
5493 if ((me.Name == "Invoke") &&
5494 TypeManager.IsDelegateType (me.DeclaringType)) {
5495 Error_InvokeOnDelegate (loc);
5499 MethodBase[] methods = me.Methods;
5502 // First we construct the set of applicable methods
5504 bool is_sorted = true;
5505 for (int i = 0; i < methods.Length; i++){
5506 Type decl_type = methods [i].DeclaringType;
5509 // If we have already found an applicable method
5510 // we eliminate all base types (Section 14.5.5.1)
5512 if ((applicable_type != null) &&
5513 IsAncestralType (decl_type, applicable_type))
5517 // Check if candidate is applicable (section 14.4.2.1)
5518 // Is candidate applicable in normal form?
5520 bool is_applicable = IsApplicable (
5521 ec, me, Arguments, arg_count, ref methods [i]);
5523 if (!is_applicable &&
5524 (IsParamsMethodApplicable (
5525 ec, me, Arguments, arg_count, ref methods [i]))) {
5526 MethodBase candidate = methods [i];
5527 if (candidate_to_form == null)
5528 candidate_to_form = new PtrHashtable ();
5529 candidate_to_form [candidate] = candidate;
5530 // Candidate is applicable in expanded form
5531 is_applicable = true;
5537 candidates.Add (methods [i]);
5539 if (applicable_type == null)
5540 applicable_type = decl_type;
5541 else if (applicable_type != decl_type) {
5543 if (IsAncestralType (applicable_type, decl_type))
5544 applicable_type = decl_type;
5548 int candidate_top = candidates.Count;
5550 if (candidate_top == 0) {
5552 // Okay so we have failed to find anything so we
5553 // return by providing info about the closest match
5555 for (int i = 0; i < methods.Length; ++i) {
5556 MethodBase c = (MethodBase) methods [i];
5557 ParameterData pd = GetParameterData (c);
5559 if (pd.Count != arg_count)
5562 if (!TypeManager.InferTypeArguments (ec, Arguments, ref c))
5565 VerifyArgumentsCompat (ec, Arguments, arg_count,
5566 c, false, null, may_fail, loc);
5571 string report_name = me.Name;
5572 if (report_name == ".ctor")
5573 report_name = me.DeclaringType.ToString ();
5575 for (int i = 0; i < methods.Length; ++i) {
5576 MethodBase c = methods [i];
5577 ParameterData pd = GetParameterData (c);
5579 if (pd.Count != arg_count)
5582 if (TypeManager.InferTypeArguments (ec, Arguments, ref c))
5586 411, loc, "The type arguments for " +
5587 "method `{0}' cannot be infered from " +
5588 "the usage. Try specifying the type " +
5589 "arguments explicitly.", report_name);
5593 Error_WrongNumArguments (
5594 loc, report_name, arg_count);
5603 // At this point, applicable_type is _one_ of the most derived types
5604 // in the set of types containing the methods in this MethodGroup.
5605 // Filter the candidates so that they only contain methods from the
5606 // most derived types.
5609 int finalized = 0; // Number of finalized candidates
5612 // Invariant: applicable_type is a most derived type
5614 // We'll try to complete Section 14.5.5.1 for 'applicable_type' by
5615 // eliminating all it's base types. At the same time, we'll also move
5616 // every unrelated type to the end of the array, and pick the next
5617 // 'applicable_type'.
5619 Type next_applicable_type = null;
5620 int j = finalized; // where to put the next finalized candidate
5621 int k = finalized; // where to put the next undiscarded candidate
5622 for (int i = finalized; i < candidate_top; ++i) {
5623 Type decl_type = ((MethodBase) candidates[i]).DeclaringType;
5625 if (decl_type == applicable_type) {
5626 candidates[k++] = candidates[j];
5627 candidates[j++] = candidates[i];
5631 if (IsAncestralType (decl_type, applicable_type))
5634 if (next_applicable_type != null &&
5635 IsAncestralType (decl_type, next_applicable_type))
5638 candidates[k++] = candidates[i];
5640 if (next_applicable_type == null ||
5641 IsAncestralType (next_applicable_type, decl_type))
5642 next_applicable_type = decl_type;
5645 applicable_type = next_applicable_type;
5648 } while (applicable_type != null);
5652 // Now we actually find the best method
5655 method = (MethodBase) candidates[0];
5656 method_params = candidate_to_form != null && candidate_to_form.Contains (method);
5657 for (int ix = 1; ix < candidate_top; ix++){
5658 MethodBase candidate = (MethodBase) candidates [ix];
5659 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
5661 if (BetterFunction (ec, Arguments, arg_count,
5662 candidate, cand_params,
5663 method, method_params, loc)) {
5665 method_params = cand_params;
5670 // Now check that there are no ambiguities i.e the selected method
5671 // should be better than all the others
5673 bool ambiguous = false;
5674 for (int ix = 0; ix < candidate_top; ix++){
5675 MethodBase candidate = (MethodBase) candidates [ix];
5677 if (candidate == method)
5680 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
5681 if (!BetterFunction (ec, Arguments, arg_count,
5682 method, method_params,
5683 candidate, cand_params,
5685 Report.SymbolRelatedToPreviousError (candidate);
5691 Report.SymbolRelatedToPreviousError (method);
5692 Report.Error (121, loc, "Ambiguous call when selecting function due to implicit casts");
5697 // And now check if the arguments are all
5698 // compatible, perform conversions if
5699 // necessary etc. and return if everything is
5702 if (!VerifyArgumentsCompat (ec, Arguments, arg_count, method,
5703 method_params, null, may_fail, loc))
5709 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
5711 Report.Error (1501, loc,
5712 "No overload for method `" + name + "' takes `" +
5713 arg_count + "' arguments");
5716 static void Error_InvokeOnDelegate (Location loc)
5718 Report.Error (1533, loc,
5719 "Invoke cannot be called directly on a delegate");
5722 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
5723 Type delegate_type, string arg_sig, string par_desc)
5725 if (delegate_type == null)
5726 Report.Error (1502, loc,
5727 "The best overloaded match for method '" +
5728 FullMethodDesc (method) +
5729 "' has some invalid arguments");
5731 Report.Error (1594, loc,
5732 "Delegate '" + delegate_type.ToString () +
5733 "' has some invalid arguments.");
5734 Report.Error (1503, loc,
5735 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
5736 idx, arg_sig, par_desc));
5739 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
5740 int arg_count, MethodBase method,
5741 bool chose_params_expanded,
5742 Type delegate_type, bool may_fail,
5745 ParameterData pd = GetParameterData (method);
5746 int pd_count = pd.Count;
5748 for (int j = 0; j < arg_count; j++) {
5749 Argument a = (Argument) Arguments [j];
5750 Expression a_expr = a.Expr;
5751 Type parameter_type = pd.ParameterType (j);
5752 Parameter.Modifier pm = pd.ParameterModifier (j);
5754 if (pm == Parameter.Modifier.PARAMS){
5755 if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
5757 Error_InvalidArguments (
5758 loc, j, method, delegate_type,
5759 Argument.FullDesc (a), pd.ParameterDesc (j));
5763 if (chose_params_expanded)
5764 parameter_type = TypeManager.GetElementType (parameter_type);
5765 } else if (pm == Parameter.Modifier.ARGLIST){
5771 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
5773 Error_InvalidArguments (
5774 loc, j, method, delegate_type,
5775 Argument.FullDesc (a), pd.ParameterDesc (j));
5783 if (!TypeManager.IsEqual (a.Type, parameter_type)){
5786 conv = Convert.WideningConversion (ec, a_expr, parameter_type, loc);
5790 Error_InvalidArguments (
5791 loc, j, method, delegate_type,
5792 Argument.FullDesc (a), pd.ParameterDesc (j));
5797 // Update the argument with the implicit conversion
5803 if (parameter_type.IsPointer){
5810 Parameter.Modifier a_mod = a.GetParameterModifier () &
5811 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5812 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
5813 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5815 if (a_mod != p_mod &&
5816 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
5818 Report.Error (1502, loc,
5819 "The best overloaded match for method '" + FullMethodDesc (method)+
5820 "' has some invalid arguments");
5821 Report.Error (1503, loc,
5822 "Argument " + (j+1) +
5823 ": Cannot convert from '" + Argument.FullDesc (a)
5824 + "' to '" + pd.ParameterDesc (j) + "'");
5834 public override Expression DoResolve (EmitContext ec)
5837 // First, resolve the expression that is used to
5838 // trigger the invocation
5840 if (expr is ConstructedType)
5841 expr = ((ConstructedType) expr).GetSimpleName (ec);
5843 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
5847 if (!(expr is MethodGroupExpr)) {
5848 Type expr_type = expr.Type;
5850 if (expr_type != null){
5851 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
5853 return (new DelegateInvocation (
5854 this.expr, Arguments, loc)).Resolve (ec);
5858 if (!(expr is MethodGroupExpr)){
5859 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup, loc);
5864 // Next, evaluate all the expressions in the argument list
5866 if (Arguments != null){
5867 foreach (Argument a in Arguments){
5868 if (!a.Resolve (ec, loc))
5873 MethodGroupExpr mg = (MethodGroupExpr) expr;
5874 method = OverloadResolve (ec, mg, Arguments, false, loc);
5879 MethodInfo mi = method as MethodInfo;
5881 type = TypeManager.TypeToCoreType (mi.ReturnType);
5882 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null)) {
5883 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
5887 Expression iexpr = mg.InstanceExpression;
5888 if (mi.IsStatic && (iexpr != null) && !(iexpr is This)) {
5889 if (mg.IdenticalTypeName)
5890 mg.InstanceExpression = null;
5892 MemberAccess.error176 (loc, mi.Name);
5898 if (type.IsPointer){
5906 // Only base will allow this invocation to happen.
5908 if (mg.IsBase && method.IsAbstract){
5909 Report.Error (205, loc, "Cannot call an abstract base member: " +
5910 FullMethodDesc (method));
5914 if (method.Name == "Finalize" && Arguments == null) {
5916 Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
5918 Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
5922 if ((method.Attributes & MethodAttributes.SpecialName) != 0){
5923 if (TypeManager.LookupDeclSpace (method.DeclaringType) != null || TypeManager.IsSpecialMethod (method)) {
5924 Report.Error (571, loc, TypeManager.CSharpSignature (method) + ": can not call operator or accessor");
5929 if (mg.InstanceExpression != null)
5930 mg.InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
5932 eclass = ExprClass.Value;
5937 // Emits the list of arguments as an array
5939 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
5941 ILGenerator ig = ec.ig;
5942 int count = arguments.Count - idx;
5943 Argument a = (Argument) arguments [idx];
5944 Type t = a.Expr.Type;
5946 IntConstant.EmitInt (ig, count);
5947 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
5949 int top = arguments.Count;
5950 for (int j = idx; j < top; j++){
5951 a = (Argument) arguments [j];
5953 ig.Emit (OpCodes.Dup);
5954 IntConstant.EmitInt (ig, j - idx);
5956 bool is_stobj, has_type_arg;
5957 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj, out has_type_arg);
5959 ig.Emit (OpCodes.Ldelema, t);
5971 /// Emits a list of resolved Arguments that are in the arguments
5974 /// The MethodBase argument might be null if the
5975 /// emission of the arguments is known not to contain
5976 /// a `params' field (for example in constructors or other routines
5977 /// that keep their arguments in this structure)
5979 /// if `dup_args' is true, a copy of the arguments will be left
5980 /// on the stack. If `dup_args' is true, you can specify `this_arg'
5981 /// which will be duplicated before any other args. Only EmitCall
5982 /// should be using this interface.
5984 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments, bool dup_args, LocalTemporary this_arg)
5988 pd = GetParameterData (mb);
5992 LocalTemporary [] temps = null;
5995 temps = new LocalTemporary [arguments.Count];
5998 // If we are calling a params method with no arguments, special case it
6000 if (arguments == null){
6001 if (pd != null && pd.Count > 0 &&
6002 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
6003 ILGenerator ig = ec.ig;
6005 IntConstant.EmitInt (ig, 0);
6006 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
6012 int top = arguments.Count;
6014 for (int i = 0; i < top; i++){
6015 Argument a = (Argument) arguments [i];
6018 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
6020 // Special case if we are passing the same data as the
6021 // params argument, do not put it in an array.
6023 if (pd.ParameterType (i) == a.Type)
6026 EmitParams (ec, i, arguments);
6033 ec.ig.Emit (OpCodes.Dup);
6034 (temps [i] = new LocalTemporary (ec, a.Type)).Store (ec);
6039 if (this_arg != null)
6042 for (int i = 0; i < top; i ++)
6043 temps [i].Emit (ec);
6046 if (pd != null && pd.Count > top &&
6047 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
6048 ILGenerator ig = ec.ig;
6050 IntConstant.EmitInt (ig, 0);
6051 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
6055 static Type[] GetVarargsTypes (EmitContext ec, MethodBase mb,
6056 ArrayList arguments)
6058 ParameterData pd = GetParameterData (mb);
6060 if (arguments == null)
6061 return new Type [0];
6063 Argument a = (Argument) arguments [pd.Count - 1];
6064 Arglist list = (Arglist) a.Expr;
6066 return list.ArgumentTypes;
6070 /// This checks the ConditionalAttribute on the method
6072 static bool IsMethodExcluded (MethodBase method, EmitContext ec)
6074 if (method.IsConstructor)
6077 IMethodData md = TypeManager.GetMethod (method);
6079 return md.IsExcluded (ec);
6081 // For some methods (generated by delegate class) GetMethod returns null
6082 // because they are not included in builder_to_method table
6083 if (method.DeclaringType is TypeBuilder)
6086 return AttributeTester.IsConditionalMethodExcluded (method);
6090 /// is_base tells whether we want to force the use of the `call'
6091 /// opcode instead of using callvirt. Call is required to call
6092 /// a specific method, while callvirt will always use the most
6093 /// recent method in the vtable.
6095 /// is_static tells whether this is an invocation on a static method
6097 /// instance_expr is an expression that represents the instance
6098 /// it must be non-null if is_static is false.
6100 /// method is the method to invoke.
6102 /// Arguments is the list of arguments to pass to the method or constructor.
6104 public static void EmitCall (EmitContext ec, bool is_base,
6105 bool is_static, Expression instance_expr,
6106 MethodBase method, ArrayList Arguments, Location loc)
6108 EmitCall (ec, is_base, is_static, instance_expr, method, Arguments, loc, false, false);
6111 // `dup_args' leaves an extra copy of the arguments on the stack
6112 // `omit_args' does not leave any arguments at all.
6113 // So, basically, you could make one call with `dup_args' set to true,
6114 // and then another with `omit_args' set to true, and the two calls
6115 // would have the same set of arguments. However, each argument would
6116 // only have been evaluated once.
6117 public static void EmitCall (EmitContext ec, bool is_base,
6118 bool is_static, Expression instance_expr,
6119 MethodBase method, ArrayList Arguments, Location loc,
6120 bool dup_args, bool omit_args)
6122 ILGenerator ig = ec.ig;
6123 bool struct_call = false;
6124 bool this_call = false;
6125 LocalTemporary this_arg = null;
6127 Type decl_type = method.DeclaringType;
6129 if (!RootContext.StdLib) {
6130 // Replace any calls to the system's System.Array type with calls to
6131 // the newly created one.
6132 if (method == TypeManager.system_int_array_get_length)
6133 method = TypeManager.int_array_get_length;
6134 else if (method == TypeManager.system_int_array_get_rank)
6135 method = TypeManager.int_array_get_rank;
6136 else if (method == TypeManager.system_object_array_clone)
6137 method = TypeManager.object_array_clone;
6138 else if (method == TypeManager.system_int_array_get_length_int)
6139 method = TypeManager.int_array_get_length_int;
6140 else if (method == TypeManager.system_int_array_get_lower_bound_int)
6141 method = TypeManager.int_array_get_lower_bound_int;
6142 else if (method == TypeManager.system_int_array_get_upper_bound_int)
6143 method = TypeManager.int_array_get_upper_bound_int;
6144 else if (method == TypeManager.system_void_array_copyto_array_int)
6145 method = TypeManager.void_array_copyto_array_int;
6148 if (ec.TestObsoleteMethodUsage) {
6150 // This checks ObsoleteAttribute on the method and on the declaring type
6152 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
6154 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
6156 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
6158 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
6162 if (IsMethodExcluded (method, ec))
6166 this_call = instance_expr == null;
6167 if (decl_type.IsValueType || (!this_call && instance_expr.Type.IsValueType))
6171 // If this is ourselves, push "this"
6176 ig.Emit (OpCodes.Ldarg_0);
6179 Type iexpr_type = instance_expr.Type;
6182 // Push the instance expression
6184 if (TypeManager.IsValueType (iexpr_type)) {
6186 // Special case: calls to a function declared in a
6187 // reference-type with a value-type argument need
6188 // to have their value boxed.
6189 if (decl_type.IsValueType ||
6190 iexpr_type.IsGenericParameter) {
6192 // If the expression implements IMemoryLocation, then
6193 // we can optimize and use AddressOf on the
6196 // If not we have to use some temporary storage for
6198 if (instance_expr is IMemoryLocation) {
6199 ((IMemoryLocation)instance_expr).
6200 AddressOf (ec, AddressOp.LoadStore);
6202 LocalTemporary temp = new LocalTemporary (ec, iexpr_type);
6203 instance_expr.Emit (ec);
6205 temp.AddressOf (ec, AddressOp.Load);
6208 // avoid the overhead of doing this all the time.
6210 t = TypeManager.GetReferenceType (iexpr_type);
6212 instance_expr.Emit (ec);
6213 ig.Emit (OpCodes.Box, instance_expr.Type);
6214 t = TypeManager.object_type;
6217 instance_expr.Emit (ec);
6218 t = instance_expr.Type;
6223 this_arg = new LocalTemporary (ec, t);
6224 ig.Emit (OpCodes.Dup);
6225 this_arg.Store (ec);
6231 EmitArguments (ec, method, Arguments, dup_args, this_arg);
6233 if ((instance_expr != null) && (instance_expr.Type.IsGenericParameter))
6234 ig.Emit (OpCodes.Constrained, instance_expr.Type);
6237 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
6238 call_op = OpCodes.Call;
6240 call_op = OpCodes.Callvirt;
6242 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
6243 Type[] varargs_types = GetVarargsTypes (ec, method, Arguments);
6244 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
6251 // and DoFoo is not virtual, you can omit the callvirt,
6252 // because you don't need the null checking behavior.
6254 if (method is MethodInfo)
6255 ig.Emit (call_op, (MethodInfo) method);
6257 ig.Emit (call_op, (ConstructorInfo) method);
6260 public override void Emit (EmitContext ec)
6262 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
6264 EmitCall (ec, mg.IsBase, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
6267 public override void EmitStatement (EmitContext ec)
6272 // Pop the return value if there is one
6274 if (method is MethodInfo){
6275 Type ret = ((MethodInfo)method).ReturnType;
6276 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
6277 ec.ig.Emit (OpCodes.Pop);
6282 public class InvocationOrCast : ExpressionStatement
6285 Expression argument;
6287 public InvocationOrCast (Expression expr, Expression argument, Location loc)
6290 this.argument = argument;
6294 public override Expression DoResolve (EmitContext ec)
6297 // First try to resolve it as a cast.
6299 TypeExpr te = expr.ResolveAsTypeStep (ec) as TypeExpr;
6300 if ((te != null) && (te.eclass == ExprClass.Type)) {
6301 Cast cast = new Cast (te, argument, loc);
6302 return cast.Resolve (ec);
6306 // This can either be a type or a delegate invocation.
6307 // Let's just resolve it and see what we'll get.
6309 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
6314 // Ok, so it's a Cast.
6316 if (expr.eclass == ExprClass.Type) {
6317 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
6318 return cast.Resolve (ec);
6322 // It's a delegate invocation.
6324 if (!TypeManager.IsDelegateType (expr.Type)) {
6325 Error (149, "Method name expected");
6329 ArrayList args = new ArrayList ();
6330 args.Add (new Argument (argument, Argument.AType.Expression));
6331 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
6332 return invocation.Resolve (ec);
6337 Error (201, "Only assignment, call, increment, decrement and new object " +
6338 "expressions can be used as a statement");
6341 public override ExpressionStatement ResolveStatement (EmitContext ec)
6344 // First try to resolve it as a cast.
6346 TypeExpr te = expr.ResolveAsTypeStep (ec) as TypeExpr;
6347 if ((te != null) && (te.eclass == ExprClass.Type)) {
6353 // This can either be a type or a delegate invocation.
6354 // Let's just resolve it and see what we'll get.
6356 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
6357 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
6363 // It's a delegate invocation.
6365 if (!TypeManager.IsDelegateType (expr.Type)) {
6366 Error (149, "Method name expected");
6370 ArrayList args = new ArrayList ();
6371 args.Add (new Argument (argument, Argument.AType.Expression));
6372 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
6373 return invocation.ResolveStatement (ec);
6376 public override void Emit (EmitContext ec)
6378 throw new Exception ("Cannot happen");
6381 public override void EmitStatement (EmitContext ec)
6383 throw new Exception ("Cannot happen");
6388 // This class is used to "disable" the code generation for the
6389 // temporary variable when initializing value types.
6391 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
6392 public void AddressOf (EmitContext ec, AddressOp Mode)
6399 /// Implements the new expression
6401 public class New : ExpressionStatement, IMemoryLocation {
6402 public readonly ArrayList Arguments;
6405 // During bootstrap, it contains the RequestedType,
6406 // but if `type' is not null, it *might* contain a NewDelegate
6407 // (because of field multi-initialization)
6409 public Expression RequestedType;
6411 MethodBase method = null;
6414 // If set, the new expression is for a value_target, and
6415 // we will not leave anything on the stack.
6417 Expression value_target;
6418 bool value_target_set = false;
6419 bool is_type_parameter = false;
6421 public New (Expression requested_type, ArrayList arguments, Location l)
6423 RequestedType = requested_type;
6424 Arguments = arguments;
6428 public bool SetValueTypeVariable (Expression value)
6430 value_target = value;
6431 value_target_set = true;
6432 if (!(value_target is IMemoryLocation)){
6433 Error_UnexpectedKind ("variable", loc);
6440 // This function is used to disable the following code sequence for
6441 // value type initialization:
6443 // AddressOf (temporary)
6447 // Instead the provide will have provided us with the address on the
6448 // stack to store the results.
6450 static Expression MyEmptyExpression;
6452 public void DisableTemporaryValueType ()
6454 if (MyEmptyExpression == null)
6455 MyEmptyExpression = new EmptyAddressOf ();
6458 // To enable this, look into:
6459 // test-34 and test-89 and self bootstrapping.
6461 // For instance, we can avoid a copy by using `newobj'
6462 // instead of Call + Push-temp on value types.
6463 // value_target = MyEmptyExpression;
6466 public override Expression DoResolve (EmitContext ec)
6469 // The New DoResolve might be called twice when initializing field
6470 // expressions (see EmitFieldInitializers, the call to
6471 // GetInitializerExpression will perform a resolve on the expression,
6472 // and later the assign will trigger another resolution
6474 // This leads to bugs (#37014)
6477 if (RequestedType is NewDelegate)
6478 return RequestedType;
6482 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec);
6490 CheckObsoleteAttribute (type);
6492 bool IsDelegate = TypeManager.IsDelegateType (type);
6495 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
6496 if (RequestedType != null)
6497 if (!(RequestedType is DelegateCreation))
6498 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
6499 return RequestedType;
6502 if (type.IsGenericParameter) {
6503 if (!TypeManager.HasConstructorConstraint (type)) {
6504 Error (304, String.Format (
6505 "Cannot create an instance of the " +
6506 "variable type '{0}' because it " +
6507 "doesn't have the new() constraint",
6512 if ((Arguments != null) && (Arguments.Count != 0)) {
6513 Error (417, String.Format (
6514 "`{0}': cannot provide arguments " +
6515 "when creating an instance of a " +
6516 "variable type.", type));
6520 is_type_parameter = true;
6521 eclass = ExprClass.Value;
6525 if (type.IsInterface || type.IsAbstract){
6526 Error (144, "It is not possible to create instances of interfaces or abstract classes");
6530 if (type.IsAbstract && type.IsSealed) {
6531 Report.Error (712, loc, "Cannot create an instance of the static class '{0}'", TypeManager.CSharpName (type));
6535 bool is_struct = type.IsValueType;
6536 eclass = ExprClass.Value;
6539 // SRE returns a match for .ctor () on structs (the object constructor),
6540 // so we have to manually ignore it.
6542 if (is_struct && Arguments == null)
6546 ml = MemberLookupFinal (ec, type, type, ".ctor",
6547 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
6548 MemberTypes.Constructor,
6549 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
6554 if (! (ml is MethodGroupExpr)){
6556 ml.Error_UnexpectedKind ("method group", loc);
6562 if (Arguments != null){
6563 foreach (Argument a in Arguments){
6564 if (!a.Resolve (ec, loc))
6569 method = Invocation.OverloadResolve (
6570 ec, (MethodGroupExpr) ml, Arguments, true, loc);
6574 if (method == null) {
6575 if (almostMatchedMembers.Count != 0) {
6576 MemberLookupFailed (ec, type, type, ".ctor", null, loc);
6580 if (!is_struct || Arguments.Count > 0) {
6581 Error (1501, String.Format (
6582 "New invocation: Can not find a constructor in `{0}' for this argument list",
6583 TypeManager.CSharpName (type)));
6591 bool DoEmitTypeParameter (EmitContext ec)
6593 ILGenerator ig = ec.ig;
6595 ig.Emit (OpCodes.Ldtoken, type);
6596 ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6597 ig.Emit (OpCodes.Call, TypeManager.activator_create_instance);
6598 ig.Emit (OpCodes.Unbox_Any, type);
6604 // This DoEmit can be invoked in two contexts:
6605 // * As a mechanism that will leave a value on the stack (new object)
6606 // * As one that wont (init struct)
6608 // You can control whether a value is required on the stack by passing
6609 // need_value_on_stack. The code *might* leave a value on the stack
6610 // so it must be popped manually
6612 // If we are dealing with a ValueType, we have a few
6613 // situations to deal with:
6615 // * The target is a ValueType, and we have been provided
6616 // the instance (this is easy, we are being assigned).
6618 // * The target of New is being passed as an argument,
6619 // to a boxing operation or a function that takes a
6622 // In this case, we need to create a temporary variable
6623 // that is the argument of New.
6625 // Returns whether a value is left on the stack
6627 bool DoEmit (EmitContext ec, bool need_value_on_stack)
6629 bool is_value_type = TypeManager.IsValueType (type);
6630 ILGenerator ig = ec.ig;
6635 // Allow DoEmit() to be called multiple times.
6636 // We need to create a new LocalTemporary each time since
6637 // you can't share LocalBuilders among ILGeneators.
6638 if (!value_target_set)
6639 value_target = new LocalTemporary (ec, type);
6641 ml = (IMemoryLocation) value_target;
6642 ml.AddressOf (ec, AddressOp.Store);
6646 Invocation.EmitArguments (ec, method, Arguments, false, null);
6650 ig.Emit (OpCodes.Initobj, type);
6652 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6653 if (need_value_on_stack){
6654 value_target.Emit (ec);
6659 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
6664 public override void Emit (EmitContext ec)
6666 if (is_type_parameter)
6667 DoEmitTypeParameter (ec);
6672 public override void EmitStatement (EmitContext ec)
6674 if (is_type_parameter)
6675 throw new InvalidOperationException ();
6677 if (DoEmit (ec, false))
6678 ec.ig.Emit (OpCodes.Pop);
6681 public void AddressOf (EmitContext ec, AddressOp Mode)
6683 if (is_type_parameter)
6684 throw new InvalidOperationException ();
6686 if (!type.IsValueType){
6688 // We throw an exception. So far, I believe we only need to support
6690 // foreach (int j in new StructType ())
6693 throw new Exception ("AddressOf should not be used for classes");
6696 if (!value_target_set)
6697 value_target = new LocalTemporary (ec, type);
6699 IMemoryLocation ml = (IMemoryLocation) value_target;
6700 ml.AddressOf (ec, AddressOp.Store);
6702 Invocation.EmitArguments (ec, method, Arguments, false, null);
6705 ec.ig.Emit (OpCodes.Initobj, type);
6707 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6709 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
6714 /// 14.5.10.2: Represents an array creation expression.
6718 /// There are two possible scenarios here: one is an array creation
6719 /// expression that specifies the dimensions and optionally the
6720 /// initialization data and the other which does not need dimensions
6721 /// specified but where initialization data is mandatory.
6723 public class ArrayCreation : Expression {
6724 Expression requested_base_type;
6725 ArrayList initializers;
6728 // The list of Argument types.
6729 // This is used to construct the `newarray' or constructor signature
6731 ArrayList arguments;
6734 // Method used to create the array object.
6736 MethodBase new_method = null;
6738 Type array_element_type;
6739 Type underlying_type;
6740 bool is_one_dimensional = false;
6741 bool is_builtin_type = false;
6742 bool expect_initializers = false;
6743 int num_arguments = 0;
6747 ArrayList array_data;
6752 // The number of array initializers that we can handle
6753 // via the InitializeArray method - through EmitStaticInitializers
6755 int num_automatic_initializers;
6757 const int max_automatic_initializers = 6;
6759 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
6761 this.requested_base_type = requested_base_type;
6762 this.initializers = initializers;
6766 arguments = new ArrayList ();
6768 foreach (Expression e in exprs) {
6769 arguments.Add (new Argument (e, Argument.AType.Expression));
6774 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
6776 this.requested_base_type = requested_base_type;
6777 this.initializers = initializers;
6781 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
6783 //string tmp = rank.Substring (rank.LastIndexOf ('['));
6785 //dimensions = tmp.Length - 1;
6786 expect_initializers = true;
6789 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
6791 StringBuilder sb = new StringBuilder (rank);
6794 for (int i = 1; i < idx_count; i++)
6799 return new ComposedCast (base_type, sb.ToString (), loc);
6802 void Error_IncorrectArrayInitializer ()
6804 Error (178, "Incorrectly structured array initializer");
6807 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
6809 if (specified_dims) {
6810 Argument a = (Argument) arguments [idx];
6812 if (!a.Resolve (ec, loc))
6815 if (!(a.Expr is Constant)) {
6816 Error (150, "A constant value is expected");
6820 int value = (int) ((Constant) a.Expr).GetValue ();
6822 if (value != probe.Count) {
6823 Error_IncorrectArrayInitializer ();
6827 bounds [idx] = value;
6830 int child_bounds = -1;
6831 foreach (object o in probe) {
6832 if (o is ArrayList) {
6833 int current_bounds = ((ArrayList) o).Count;
6835 if (child_bounds == -1)
6836 child_bounds = current_bounds;
6838 else if (child_bounds != current_bounds){
6839 Error_IncorrectArrayInitializer ();
6842 if (specified_dims && (idx + 1 >= arguments.Count)){
6843 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
6847 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
6851 if (child_bounds != -1){
6852 Error_IncorrectArrayInitializer ();
6856 Expression tmp = (Expression) o;
6857 tmp = tmp.Resolve (ec);
6861 // Console.WriteLine ("I got: " + tmp);
6862 // Handle initialization from vars, fields etc.
6864 Expression conv = Convert.WideningConversionRequired (
6865 ec, tmp, underlying_type, loc);
6870 if (conv is StringConstant || conv is DecimalConstant || conv is NullCast) {
6871 // These are subclasses of Constant that can appear as elements of an
6872 // array that cannot be statically initialized (with num_automatic_initializers
6873 // > max_automatic_initializers), so num_automatic_initializers should be left as zero.
6874 array_data.Add (conv);
6875 } else if (conv is Constant) {
6876 // These are the types of Constant that can appear in arrays that can be
6877 // statically allocated.
6878 array_data.Add (conv);
6879 num_automatic_initializers++;
6881 array_data.Add (conv);
6888 public void UpdateIndices (EmitContext ec)
6891 for (ArrayList probe = initializers; probe != null;) {
6892 if (probe.Count > 0 && probe [0] is ArrayList) {
6893 Expression e = new IntConstant (probe.Count);
6894 arguments.Add (new Argument (e, Argument.AType.Expression));
6896 bounds [i++] = probe.Count;
6898 probe = (ArrayList) probe [0];
6901 Expression e = new IntConstant (probe.Count);
6902 arguments.Add (new Argument (e, Argument.AType.Expression));
6904 bounds [i++] = probe.Count;
6911 public bool ValidateInitializers (EmitContext ec, Type array_type)
6913 if (initializers == null) {
6914 if (expect_initializers)
6920 if (underlying_type == null)
6924 // We use this to store all the date values in the order in which we
6925 // will need to store them in the byte blob later
6927 array_data = new ArrayList ();
6928 bounds = new Hashtable ();
6932 if (arguments != null) {
6933 ret = CheckIndices (ec, initializers, 0, true);
6936 arguments = new ArrayList ();
6938 ret = CheckIndices (ec, initializers, 0, false);
6945 if (arguments.Count != dimensions) {
6946 Error_IncorrectArrayInitializer ();
6955 // Converts `source' to an int, uint, long or ulong.
6957 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
6961 bool old_checked = ec.CheckState;
6962 ec.CheckState = true;
6964 target = Convert.WideningConversion (ec, source, TypeManager.int32_type, loc);
6965 if (target == null){
6966 target = Convert.WideningConversion (ec, source, TypeManager.uint32_type, loc);
6967 if (target == null){
6968 target = Convert.WideningConversion (ec, source, TypeManager.int64_type, loc);
6969 if (target == null){
6970 target = Convert.WideningConversion (ec, source, TypeManager.uint64_type, loc);
6972 Convert.Error_CannotWideningConversion (loc, source.Type, TypeManager.int32_type);
6976 ec.CheckState = old_checked;
6979 // Only positive constants are allowed at compile time
6981 if (target is Constant){
6982 if (target is IntConstant){
6983 if (((IntConstant) target).Value < 0){
6984 Expression.Error_NegativeArrayIndex (loc);
6989 if (target is LongConstant){
6990 if (((LongConstant) target).Value < 0){
6991 Expression.Error_NegativeArrayIndex (loc);
7002 // Creates the type of the array
7004 bool LookupType (EmitContext ec)
7006 StringBuilder array_qualifier = new StringBuilder (rank);
7009 // `In the first form allocates an array instace of the type that results
7010 // from deleting each of the individual expression from the expression list'
7012 if (num_arguments > 0) {
7013 array_qualifier.Append ("[");
7014 for (int i = num_arguments-1; i > 0; i--)
7015 array_qualifier.Append (",");
7016 array_qualifier.Append ("]");
7022 TypeExpr array_type_expr;
7023 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
7024 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec);
7025 if (array_type_expr == null)
7028 type = array_type_expr.Type;
7030 if (!type.IsArray) {
7031 Error (622, "Can only use array initializer expressions to assign to array types. Try using a new expression instead.");
7034 underlying_type = TypeManager.GetElementType (type);
7035 dimensions = type.GetArrayRank ();
7040 public override Expression DoResolve (EmitContext ec)
7044 if (!LookupType (ec))
7048 // First step is to validate the initializers and fill
7049 // in any missing bits
7051 if (!ValidateInitializers (ec, type))
7054 if (arguments == null)
7057 arg_count = arguments.Count;
7058 foreach (Argument a in arguments){
7059 if (!a.Resolve (ec, loc))
7062 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
7063 if (real_arg == null)
7070 array_element_type = TypeManager.GetElementType (type);
7072 if (array_element_type.IsAbstract && array_element_type.IsSealed) {
7073 Report.Error (719, loc, "'{0}': array elements cannot be of static type", TypeManager.CSharpName (array_element_type));
7077 if (arg_count == 1) {
7078 is_one_dimensional = true;
7079 eclass = ExprClass.Value;
7083 is_builtin_type = TypeManager.IsBuiltinType (type);
7085 if (is_builtin_type) {
7088 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
7089 AllBindingFlags, loc);
7091 if (!(ml is MethodGroupExpr)) {
7092 ml.Error_UnexpectedKind ("method group", loc);
7097 Error (-6, "New invocation: Can not find a constructor for " +
7098 "this argument list");
7102 new_method = Invocation.OverloadResolve (
7103 ec, (MethodGroupExpr) ml, arguments, false, loc);
7105 if (new_method == null) {
7106 Error (-6, "New invocation: Can not find a constructor for " +
7107 "this argument list");
7111 eclass = ExprClass.Value;
7114 ModuleBuilder mb = CodeGen.Module.Builder;
7115 ArrayList args = new ArrayList ();
7117 if (arguments != null) {
7118 for (int i = 0; i < arg_count; i++)
7119 args.Add (TypeManager.int32_type);
7122 Type [] arg_types = null;
7125 arg_types = new Type [args.Count];
7127 args.CopyTo (arg_types, 0);
7129 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
7132 if (new_method == null) {
7133 Error (-6, "New invocation: Can not find a constructor for " +
7134 "this argument list");
7138 eclass = ExprClass.Value;
7143 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
7148 int count = array_data.Count;
7150 if (underlying_type.IsEnum)
7151 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
7153 factor = GetTypeSize (underlying_type);
7155 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
7157 data = new byte [(count * factor + 4) & ~3];
7160 for (int i = 0; i < count; ++i) {
7161 object v = array_data [i];
7163 if (v is EnumConstant)
7164 v = ((EnumConstant) v).Child;
7166 if (v is Constant && !(v is StringConstant))
7167 v = ((Constant) v).GetValue ();
7173 if (underlying_type == TypeManager.int64_type){
7174 if (!(v is Expression)){
7175 long val = (long) v;
7177 for (int j = 0; j < factor; ++j) {
7178 data [idx + j] = (byte) (val & 0xFF);
7182 } else if (underlying_type == TypeManager.uint64_type){
7183 if (!(v is Expression)){
7184 ulong val = (ulong) v;
7186 for (int j = 0; j < factor; ++j) {
7187 data [idx + j] = (byte) (val & 0xFF);
7191 } else if (underlying_type == TypeManager.float_type) {
7192 if (!(v is Expression)){
7193 element = BitConverter.GetBytes ((float) v);
7195 for (int j = 0; j < factor; ++j)
7196 data [idx + j] = element [j];
7198 } else if (underlying_type == TypeManager.double_type) {
7199 if (!(v is Expression)){
7200 element = BitConverter.GetBytes ((double) v);
7202 for (int j = 0; j < factor; ++j)
7203 data [idx + j] = element [j];
7205 } else if (underlying_type == TypeManager.char_type){
7206 if (!(v is Expression)){
7207 int val = (int) ((char) v);
7209 data [idx] = (byte) (val & 0xff);
7210 data [idx+1] = (byte) (val >> 8);
7212 } else if (underlying_type == TypeManager.short_type){
7213 if (!(v is Expression)){
7214 int val = (int) ((short) v);
7216 data [idx] = (byte) (val & 0xff);
7217 data [idx+1] = (byte) (val >> 8);
7219 } else if (underlying_type == TypeManager.ushort_type){
7220 if (!(v is Expression)){
7221 int val = (int) ((ushort) v);
7223 data [idx] = (byte) (val & 0xff);
7224 data [idx+1] = (byte) (val >> 8);
7226 } else if (underlying_type == TypeManager.int32_type) {
7227 if (!(v is Expression)){
7230 data [idx] = (byte) (val & 0xff);
7231 data [idx+1] = (byte) ((val >> 8) & 0xff);
7232 data [idx+2] = (byte) ((val >> 16) & 0xff);
7233 data [idx+3] = (byte) (val >> 24);
7235 } else if (underlying_type == TypeManager.uint32_type) {
7236 if (!(v is Expression)){
7237 uint val = (uint) v;
7239 data [idx] = (byte) (val & 0xff);
7240 data [idx+1] = (byte) ((val >> 8) & 0xff);
7241 data [idx+2] = (byte) ((val >> 16) & 0xff);
7242 data [idx+3] = (byte) (val >> 24);
7244 } else if (underlying_type == TypeManager.sbyte_type) {
7245 if (!(v is Expression)){
7246 sbyte val = (sbyte) v;
7247 data [idx] = (byte) val;
7249 } else if (underlying_type == TypeManager.byte_type) {
7250 if (!(v is Expression)){
7251 byte val = (byte) v;
7252 data [idx] = (byte) val;
7254 } else if (underlying_type == TypeManager.bool_type) {
7255 if (!(v is Expression)){
7256 bool val = (bool) v;
7257 data [idx] = (byte) (val ? 1 : 0);
7259 } else if (underlying_type == TypeManager.decimal_type){
7260 if (!(v is Expression)){
7261 int [] bits = Decimal.GetBits ((decimal) v);
7264 // FIXME: For some reason, this doesn't work on the MS runtime.
7265 int [] nbits = new int [4];
7266 nbits [0] = bits [3];
7267 nbits [1] = bits [2];
7268 nbits [2] = bits [0];
7269 nbits [3] = bits [1];
7271 for (int j = 0; j < 4; j++){
7272 data [p++] = (byte) (nbits [j] & 0xff);
7273 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
7274 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
7275 data [p++] = (byte) (nbits [j] >> 24);
7279 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
7288 // Emits the initializers for the array
7290 void EmitStaticInitializers (EmitContext ec)
7293 // First, the static data
7296 ILGenerator ig = ec.ig;
7298 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
7300 fb = RootContext.MakeStaticData (data);
7302 ig.Emit (OpCodes.Dup);
7303 ig.Emit (OpCodes.Ldtoken, fb);
7304 ig.Emit (OpCodes.Call,
7305 TypeManager.void_initializearray_array_fieldhandle);
7309 // Emits pieces of the array that can not be computed at compile
7310 // time (variables and string locations).
7312 // This always expect the top value on the stack to be the array
7314 void EmitDynamicInitializers (EmitContext ec)
7316 ILGenerator ig = ec.ig;
7317 int dims = bounds.Count;
7318 int [] current_pos = new int [dims];
7319 int top = array_data.Count;
7321 MethodInfo set = null;
7325 ModuleBuilder mb = null;
7326 mb = CodeGen.Module.Builder;
7327 args = new Type [dims + 1];
7330 for (j = 0; j < dims; j++)
7331 args [j] = TypeManager.int32_type;
7333 args [j] = array_element_type;
7335 set = mb.GetArrayMethod (
7337 CallingConventions.HasThis | CallingConventions.Standard,
7338 TypeManager.void_type, args);
7341 for (int i = 0; i < top; i++){
7343 Expression e = null;
7345 if (array_data [i] is Expression)
7346 e = (Expression) array_data [i];
7350 // Basically we do this for string literals and
7351 // other non-literal expressions
7353 if (e is EnumConstant){
7354 e = ((EnumConstant) e).Child;
7357 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
7358 num_automatic_initializers <= max_automatic_initializers) {
7359 Type etype = e.Type;
7361 ig.Emit (OpCodes.Dup);
7363 for (int idx = 0; idx < dims; idx++)
7364 IntConstant.EmitInt (ig, current_pos [idx]);
7367 // If we are dealing with a struct, get the
7368 // address of it, so we can store it.
7370 if ((dims == 1) && etype.IsValueType &&
7371 (!TypeManager.IsBuiltinOrEnum (etype) ||
7372 etype == TypeManager.decimal_type)) {
7377 // Let new know that we are providing
7378 // the address where to store the results
7380 n.DisableTemporaryValueType ();
7383 ig.Emit (OpCodes.Ldelema, etype);
7389 bool is_stobj, has_type_arg;
7390 OpCode op = ArrayAccess.GetStoreOpcode (
7391 etype, out is_stobj,
7394 ig.Emit (OpCodes.Stobj, etype);
7395 else if (has_type_arg)
7396 ig.Emit (op, etype);
7400 ig.Emit (OpCodes.Call, set);
7407 for (int j = dims - 1; j >= 0; j--){
7409 if (current_pos [j] < (int) bounds [j])
7411 current_pos [j] = 0;
7416 void EmitArrayArguments (EmitContext ec)
7418 ILGenerator ig = ec.ig;
7420 foreach (Argument a in arguments) {
7421 Type atype = a.Type;
7424 if (atype == TypeManager.uint64_type)
7425 ig.Emit (OpCodes.Conv_Ovf_U4);
7426 else if (atype == TypeManager.int64_type)
7427 ig.Emit (OpCodes.Conv_Ovf_I4);
7431 public override void Emit (EmitContext ec)
7433 ILGenerator ig = ec.ig;
7435 EmitArrayArguments (ec);
7436 if (is_one_dimensional)
7437 ig.Emit (OpCodes.Newarr, array_element_type);
7439 if (is_builtin_type)
7440 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
7442 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
7445 if (initializers != null){
7447 // FIXME: Set this variable correctly.
7449 bool dynamic_initializers = true;
7451 // This will never be true for array types that cannot be statically
7452 // initialized. num_automatic_initializers will always be zero. See
7454 if (num_automatic_initializers > max_automatic_initializers)
7455 EmitStaticInitializers (ec);
7457 if (dynamic_initializers)
7458 EmitDynamicInitializers (ec);
7462 public object EncodeAsAttribute ()
7464 if (!is_one_dimensional){
7465 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
7469 if (array_data == null){
7470 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
7474 object [] ret = new object [array_data.Count];
7476 foreach (Expression e in array_data){
7479 if (e is NullLiteral)
7482 if (!Attribute.GetAttributeArgumentExpression (e, Location, array_element_type, out v))
7492 /// Represents the `this' construct
7494 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
7497 VariableInfo variable_info;
7499 public This (Block block, Location loc)
7505 public This (Location loc)
7510 public VariableInfo VariableInfo {
7511 get { return variable_info; }
7514 public bool VerifyFixed (bool is_expression)
7516 if ((variable_info == null) || (variable_info.LocalInfo == null))
7519 return variable_info.LocalInfo.IsFixed;
7522 public bool ResolveBase (EmitContext ec)
7524 eclass = ExprClass.Variable;
7526 if (ec.TypeContainer.CurrentType != null)
7527 type = ec.TypeContainer.CurrentType;
7529 type = ec.ContainerType;
7532 Error (26, "Keyword this not valid in static code");
7536 if ((block != null) && (block.ThisVariable != null))
7537 variable_info = block.ThisVariable.VariableInfo;
7542 public override Expression DoResolve (EmitContext ec)
7544 if (!ResolveBase (ec))
7547 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
7548 Error (188, "The this object cannot be used before all " +
7549 "of its fields are assigned to");
7550 variable_info.SetAssigned (ec);
7554 if (ec.IsFieldInitializer) {
7555 Error (27, "Keyword `this' can't be used outside a constructor, " +
7556 "a method or a property.");
7563 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
7565 if (!ResolveBase (ec))
7568 if (variable_info != null)
7569 variable_info.SetAssigned (ec);
7571 if (ec.TypeContainer is Class){
7572 Error (1604, "Cannot assign to `this'");
7579 public void Emit (EmitContext ec, bool leave_copy)
7583 ec.ig.Emit (OpCodes.Dup);
7586 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
7588 ILGenerator ig = ec.ig;
7590 if (ec.TypeContainer is Struct){
7594 ec.ig.Emit (OpCodes.Dup);
7595 ig.Emit (OpCodes.Stobj, type);
7597 throw new Exception ("how did you get here");
7601 public override void Emit (EmitContext ec)
7603 ILGenerator ig = ec.ig;
7606 if (ec.TypeContainer is Struct)
7607 ig.Emit (OpCodes.Ldobj, type);
7610 public void AddressOf (EmitContext ec, AddressOp mode)
7615 // FIGURE OUT WHY LDARG_S does not work
7617 // consider: struct X { int val; int P { set { val = value; }}}
7619 // Yes, this looks very bad. Look at `NOTAS' for
7621 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
7626 /// Represents the `__arglist' construct
7628 public class ArglistAccess : Expression
7630 public ArglistAccess (Location loc)
7635 public bool ResolveBase (EmitContext ec)
7637 eclass = ExprClass.Variable;
7638 type = TypeManager.runtime_argument_handle_type;
7642 public override Expression DoResolve (EmitContext ec)
7644 if (!ResolveBase (ec))
7647 if (ec.IsFieldInitializer || !ec.CurrentBlock.HasVarargs) {
7648 Error (190, "The __arglist construct is valid only within " +
7649 "a variable argument method.");
7656 public override void Emit (EmitContext ec)
7658 ec.ig.Emit (OpCodes.Arglist);
7663 /// Represents the `__arglist (....)' construct
7665 public class Arglist : Expression
7667 public readonly Argument[] Arguments;
7669 public Arglist (Argument[] args, Location l)
7675 public Type[] ArgumentTypes {
7677 Type[] retval = new Type [Arguments.Length];
7678 for (int i = 0; i < Arguments.Length; i++)
7679 retval [i] = Arguments [i].Type;
7684 public override Expression DoResolve (EmitContext ec)
7686 eclass = ExprClass.Variable;
7687 type = TypeManager.runtime_argument_handle_type;
7689 foreach (Argument arg in Arguments) {
7690 if (!arg.Resolve (ec, loc))
7697 public override void Emit (EmitContext ec)
7699 foreach (Argument arg in Arguments)
7705 // This produces the value that renders an instance, used by the iterators code
7707 public class ProxyInstance : Expression, IMemoryLocation {
7708 public override Expression DoResolve (EmitContext ec)
7710 eclass = ExprClass.Variable;
7711 type = ec.ContainerType;
7715 public override void Emit (EmitContext ec)
7717 ec.ig.Emit (OpCodes.Ldarg_0);
7721 public void AddressOf (EmitContext ec, AddressOp mode)
7723 ec.ig.Emit (OpCodes.Ldarg_0);
7728 /// Implements the typeof operator
7730 public class TypeOf : Expression {
7731 public Expression QueriedType;
7732 protected Type typearg;
7734 public TypeOf (Expression queried_type, Location l)
7736 QueriedType = queried_type;
7740 public override Expression DoResolve (EmitContext ec)
7742 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec);
7746 typearg = texpr.Type;
7748 if (typearg == TypeManager.void_type) {
7749 Error (673, "System.Void cannot be used from C# - " +
7750 "use typeof (void) to get the void type object");
7754 if (typearg.IsPointer && !ec.InUnsafe){
7758 CheckObsoleteAttribute (typearg);
7760 type = TypeManager.type_type;
7761 eclass = ExprClass.Type;
7765 public override void Emit (EmitContext ec)
7767 ec.ig.Emit (OpCodes.Ldtoken, typearg);
7768 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
7771 public Type TypeArg {
7772 get { return typearg; }
7777 /// Implements the `typeof (void)' operator
7779 public class TypeOfVoid : TypeOf {
7780 public TypeOfVoid (Location l) : base (null, l)
7785 public override Expression DoResolve (EmitContext ec)
7787 type = TypeManager.type_type;
7788 typearg = TypeManager.void_type;
7789 eclass = ExprClass.Type;
7795 /// Implements the sizeof expression
7797 public class SizeOf : Expression {
7798 public Expression QueriedType;
7801 public SizeOf (Expression queried_type, Location l)
7803 this.QueriedType = queried_type;
7807 public override Expression DoResolve (EmitContext ec)
7811 233, loc, "Sizeof may only be used in an unsafe context " +
7812 "(consider using System.Runtime.InteropServices.Marshal.SizeOf");
7816 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec);
7820 if (texpr is TypeParameterExpr){
7821 ((TypeParameterExpr)texpr).Error_CannotUseAsUnmanagedType (loc);
7825 type_queried = texpr.Type;
7827 CheckObsoleteAttribute (type_queried);
7829 if (!TypeManager.IsUnmanagedType (type_queried)){
7830 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
7834 type = TypeManager.int32_type;
7835 eclass = ExprClass.Value;
7839 public override void Emit (EmitContext ec)
7841 int size = GetTypeSize (type_queried);
7844 ec.ig.Emit (OpCodes.Sizeof, type_queried);
7846 IntConstant.EmitInt (ec.ig, size);
7851 /// Implements the member access expression
7853 public class MemberAccess : Expression {
7854 public string Identifier;
7855 protected Expression expr;
7856 protected TypeArguments args;
7858 public MemberAccess (Expression expr, string id, Location l)
7865 public MemberAccess (Expression expr, string id, TypeArguments args,
7867 : this (expr, id, l)
7872 public Expression Expr {
7878 public static void error176 (Location loc, string name)
7880 Report.Error (176, loc, "Static member `" +
7881 name + "' cannot be accessed " +
7882 "with an instance reference, qualify with a " +
7883 "type name instead");
7886 public static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Expression left, Location loc)
7888 SimpleName sn = left_original as SimpleName;
7889 if (sn == null || left == null || left.Type.Name != sn.Name)
7892 return ec.DeclSpace.LookupType (sn.Name, true, loc) != null;
7895 // TODO: possible optimalization
7896 // Cache resolved constant result in FieldBuilder <-> expresion map
7897 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
7898 Expression left, Location loc,
7899 Expression left_original)
7901 bool left_is_type, left_is_explicit;
7903 // If `left' is null, then we're called from SimpleNameResolve and this is
7904 // a member in the currently defining class.
7906 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
7907 left_is_explicit = false;
7909 // Implicitly default to `this' unless we're static.
7910 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
7911 left = ec.GetThis (loc);
7913 left_is_type = left is TypeExpr;
7914 left_is_explicit = true;
7917 if (member_lookup is FieldExpr){
7918 FieldExpr fe = (FieldExpr) member_lookup;
7919 FieldInfo fi = fe.FieldInfo.Mono_GetGenericFieldDefinition ();
7920 Type decl_type = fi.DeclaringType;
7922 bool is_emitted = fi is FieldBuilder;
7923 Type t = fi.FieldType;
7926 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
7930 if (!c.LookupConstantValue (out o))
7933 object real_value = ((Constant) c.Expr).GetValue ();
7935 Expression exp = Constantify (real_value, t);
7937 if (left_is_explicit && !left_is_type && !IdenticalNameAndTypeName (ec, left_original, left, loc)) {
7938 Report.SymbolRelatedToPreviousError (c);
7939 error176 (loc, c.GetSignatureForError ());
7947 // IsInitOnly is because of MS compatibility, I don't know why but they emit decimal constant as InitOnly
7948 if (fi.IsInitOnly && !is_emitted && t == TypeManager.decimal_type) {
7949 object[] attrs = fi.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
7950 if (attrs.Length == 1)
7951 return new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
7958 o = TypeManager.GetValue ((FieldBuilder) fi);
7960 o = fi.GetValue (fi);
7962 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
7963 if (left_is_explicit && !left_is_type &&
7964 !IdenticalNameAndTypeName (ec, left_original, member_lookup, loc)) {
7965 error176 (loc, fe.FieldInfo.Name);
7969 Expression enum_member = MemberLookup (
7970 ec, decl_type, "value__", MemberTypes.Field,
7971 AllBindingFlags, loc);
7973 Enum en = TypeManager.LookupEnum (decl_type);
7977 c = Constantify (o, en.UnderlyingType);
7979 c = Constantify (o, enum_member.Type);
7981 return new EnumConstant (c, decl_type);
7984 Expression exp = Constantify (o, t);
7986 if (left_is_explicit && !left_is_type) {
7987 error176 (loc, fe.FieldInfo.Name);
7994 if (t.IsPointer && !ec.InUnsafe){
8000 if (member_lookup is EventExpr) {
8001 EventExpr ee = (EventExpr) member_lookup;
8004 // If the event is local to this class, we transform ourselves into
8008 if (ee.EventInfo.DeclaringType == ec.ContainerType ||
8009 TypeManager.IsNestedChildOf(ec.ContainerType, ee.EventInfo.DeclaringType)) {
8010 MemberInfo mi = GetFieldFromEvent (ee);
8014 // If this happens, then we have an event with its own
8015 // accessors and private field etc so there's no need
8016 // to transform ourselves.
8018 ee.InstanceExpression = left;
8022 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
8025 Report.Error (-200, loc, "Internal error!!");
8029 if (!left_is_explicit)
8032 ee.InstanceExpression = left;
8034 return ResolveMemberAccess (ec, ml, left, loc, left_original);
8038 if (member_lookup is IMemberExpr) {
8039 IMemberExpr me = (IMemberExpr) member_lookup;
8040 MethodGroupExpr mg = me as MethodGroupExpr;
8043 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
8044 mg.IsExplicitImpl = left_is_explicit;
8047 if ((ec.IsFieldInitializer || ec.IsStatic) &&
8048 IdenticalNameAndTypeName (ec, left_original, member_lookup, loc))
8049 return member_lookup;
8051 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
8056 if (!me.IsInstance){
8057 if (IdenticalNameAndTypeName (ec, left_original, left, loc))
8058 return member_lookup;
8060 if (left_is_explicit) {
8061 error176 (loc, me.Name);
8067 // Since we can not check for instance objects in SimpleName,
8068 // becaue of the rule that allows types and variables to share
8069 // the name (as long as they can be de-ambiguated later, see
8070 // IdenticalNameAndTypeName), we have to check whether left
8071 // is an instance variable in a static context
8073 // However, if the left-hand value is explicitly given, then
8074 // it is already our instance expression, so we aren't in
8078 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
8079 IMemberExpr mexp = (IMemberExpr) left;
8081 if (!mexp.IsStatic){
8082 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
8087 if ((mg != null) && IdenticalNameAndTypeName (ec, left_original, left, loc))
8088 mg.IdenticalTypeName = true;
8090 me.InstanceExpression = left;
8093 return member_lookup;
8096 Console.WriteLine ("Left is: " + left);
8097 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
8098 Environment.Exit (1);
8102 public virtual Expression DoResolve (EmitContext ec, Expression right_side,
8106 throw new Exception ();
8109 // Resolve the expression with flow analysis turned off, we'll do the definite
8110 // assignment checks later. This is because we don't know yet what the expression
8111 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
8112 // definite assignment check on the actual field and not on the whole struct.
8115 Expression original = expr;
8116 expr = expr.Resolve (ec, flags | ResolveFlags.Intermediate | ResolveFlags.DisableFlowAnalysis);
8120 if (expr is Namespace) {
8121 Namespace ns = (Namespace) expr;
8122 string lookup_id = MemberName.MakeName (Identifier, args);
8123 FullNamedExpression retval = ns.Lookup (ec.DeclSpace, lookup_id, loc);
8124 if ((retval != null) && (args != null))
8125 retval = new ConstructedType (retval, args, loc).ResolveAsTypeStep (ec);
8127 Report.Error (234, loc, "The type or namespace name `{0}' could not be found in namespace `{1}'", Identifier, ns.FullName);
8132 // TODO: I mailed Ravi about this, and apparently we can get rid
8133 // of this and put it in the right place.
8135 // Handle enums here when they are in transit.
8136 // Note that we cannot afford to hit MemberLookup in this case because
8137 // it will fail to find any members at all
8141 if (expr is TypeExpr){
8142 expr_type = expr.Type;
8144 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
8145 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", expr_type);
8149 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
8150 Enum en = TypeManager.LookupEnum (expr_type);
8153 object value = en.LookupEnumValue (ec, Identifier, loc);
8156 MemberCore mc = en.GetDefinition (Identifier);
8157 ObsoleteAttribute oa = mc.GetObsoleteAttribute (en);
8159 AttributeTester.Report_ObsoleteMessage (oa, mc.GetSignatureForError (), Location);
8161 oa = en.GetObsoleteAttribute (en);
8163 AttributeTester.Report_ObsoleteMessage (oa, en.GetSignatureForError (), Location);
8166 Constant c = Constantify (value, en.UnderlyingType);
8167 return new EnumConstant (c, expr_type);
8170 CheckObsoleteAttribute (expr_type);
8172 FieldInfo fi = expr_type.GetField (Identifier);
8174 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
8176 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), Location);
8181 expr_type = expr.Type;
8183 if (expr_type.IsPointer){
8184 Error (23, "The `.' operator can not be applied to pointer operands (" +
8185 TypeManager.CSharpName (expr_type) + ")");
8189 Expression member_lookup;
8190 member_lookup = MemberLookup (
8191 ec, expr_type, expr_type, Identifier, loc);
8192 if ((member_lookup == null) && (args != null)) {
8193 string lookup_id = MemberName.MakeName (Identifier, args);
8194 member_lookup = MemberLookup (
8195 ec, expr_type, expr_type, lookup_id, loc);
8197 if (member_lookup == null) {
8198 MemberLookupFailed (
8199 ec, expr_type, expr_type, Identifier, null, loc);
8203 if (member_lookup is TypeExpr) {
8204 if (!(expr is TypeExpr) &&
8205 !IdenticalNameAndTypeName (ec, original, expr, loc)) {
8206 Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
8207 member_lookup.Type + "' instead");
8211 return member_lookup;
8215 string full_name = expr_type + "." + Identifier;
8217 if (member_lookup is FieldExpr) {
8218 Report.Error (307, loc, "The field `{0}' cannot " +
8219 "be used with type arguments", full_name);
8221 } else if (member_lookup is EventExpr) {
8222 Report.Error (307, loc, "The event `{0}' cannot " +
8223 "be used with type arguments", full_name);
8225 } else if (member_lookup is PropertyExpr) {
8226 Report.Error (307, loc, "The property `{0}' cannot " +
8227 "be used with type arguments", full_name);
8232 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
8233 if (member_lookup == null)
8237 MethodGroupExpr mg = member_lookup as MethodGroupExpr;
8239 throw new InternalErrorException ();
8241 return mg.ResolveGeneric (ec, args);
8244 // The following DoResolve/DoResolveLValue will do the definite assignment
8247 if (right_side != null)
8248 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
8250 member_lookup = member_lookup.DoResolve (ec);
8252 return member_lookup;
8255 public override Expression DoResolve (EmitContext ec)
8257 return DoResolve (ec, null, ResolveFlags.VariableOrValue | ResolveFlags.Type);
8260 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8262 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue | ResolveFlags.Type);
8265 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
8267 return ResolveNamespaceOrType (ec, false);
8270 public FullNamedExpression ResolveNamespaceOrType (EmitContext ec, bool silent)
8272 FullNamedExpression new_expr = expr.ResolveAsTypeStep (ec);
8274 if (new_expr == null)
8277 string lookup_id = MemberName.MakeName (Identifier, args);
8279 if (new_expr is Namespace) {
8280 Namespace ns = (Namespace) new_expr;
8281 FullNamedExpression retval = ns.Lookup (ec.DeclSpace, lookup_id, loc);
8282 if ((retval != null) && (args != null))
8283 retval = new ConstructedType (retval, args, loc).ResolveAsTypeStep (ec);
8284 if (!silent && retval == null)
8285 Report.Error (234, loc, "The type or namespace name `{0}' could not be found in namespace `{1}'", Identifier, ns.FullName);
8289 TypeExpr tnew_expr = new_expr.ResolveAsTypeTerminal (ec);
8290 if (tnew_expr == null)
8293 Type expr_type = tnew_expr.Type;
8295 if (expr_type.IsPointer){
8296 Error (23, "The `.' operator can not be applied to pointer operands (" +
8297 TypeManager.CSharpName (expr_type) + ")");
8301 Expression member_lookup;
8302 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, lookup_id, loc);
8303 if (!silent && member_lookup == null) {
8304 Report.Error (234, loc, "The type name `{0}' could not be found in type `{1}'",
8305 Identifier, new_expr.FullName);
8309 if (!(member_lookup is TypeExpr)) {
8310 Report.Error (118, loc, "'{0}.{1}' denotes a '{2}', where a type was expected",
8311 new_expr.FullName, Identifier, member_lookup.ExprClassName ());
8315 TypeExpr texpr = member_lookup.ResolveAsTypeTerminal (ec);
8319 TypeArguments the_args = args;
8320 if (TypeManager.HasGenericArguments (expr_type)) {
8321 Type[] decl_args = TypeManager.GetTypeArguments (expr_type);
8323 TypeArguments new_args = new TypeArguments (loc);
8324 foreach (Type decl in decl_args)
8325 new_args.Add (new TypeExpression (decl, loc));
8328 new_args.Add (args);
8330 the_args = new_args;
8333 if (the_args != null) {
8334 ConstructedType ctype = new ConstructedType (texpr.Type, the_args, loc);
8335 return ctype.ResolveAsTypeStep (ec);
8341 public override void Emit (EmitContext ec)
8343 throw new Exception ("Should not happen");
8346 public override string ToString ()
8348 return expr + "." + MemberName.MakeName (Identifier, args);
8353 /// Implements checked expressions
8355 public class CheckedExpr : Expression {
8357 public Expression Expr;
8359 public CheckedExpr (Expression e, Location l)
8365 public override Expression DoResolve (EmitContext ec)
8367 bool last_check = ec.CheckState;
8368 bool last_const_check = ec.ConstantCheckState;
8370 ec.CheckState = true;
8371 ec.ConstantCheckState = true;
8372 Expr = Expr.Resolve (ec);
8373 ec.CheckState = last_check;
8374 ec.ConstantCheckState = last_const_check;
8379 if (Expr is Constant)
8382 eclass = Expr.eclass;
8387 public override void Emit (EmitContext ec)
8389 bool last_check = ec.CheckState;
8390 bool last_const_check = ec.ConstantCheckState;
8392 ec.CheckState = true;
8393 ec.ConstantCheckState = true;
8395 ec.CheckState = last_check;
8396 ec.ConstantCheckState = last_const_check;
8402 /// Implements the unchecked expression
8404 public class UnCheckedExpr : Expression {
8406 public Expression Expr;
8408 public UnCheckedExpr (Expression e, Location l)
8414 public override Expression DoResolve (EmitContext ec)
8416 bool last_check = ec.CheckState;
8417 bool last_const_check = ec.ConstantCheckState;
8419 ec.CheckState = false;
8420 ec.ConstantCheckState = false;
8421 Expr = Expr.Resolve (ec);
8422 ec.CheckState = last_check;
8423 ec.ConstantCheckState = last_const_check;
8428 if (Expr is Constant)
8431 eclass = Expr.eclass;
8436 public override void Emit (EmitContext ec)
8438 bool last_check = ec.CheckState;
8439 bool last_const_check = ec.ConstantCheckState;
8441 ec.CheckState = false;
8442 ec.ConstantCheckState = false;
8444 ec.CheckState = last_check;
8445 ec.ConstantCheckState = last_const_check;
8451 /// An Element Access expression.
8453 /// During semantic analysis these are transformed into
8454 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
8456 public class ElementAccess : Expression {
8457 public ArrayList Arguments;
8458 public Expression Expr;
8460 public ElementAccess (Expression e, ArrayList e_list, Location l)
8469 Arguments = new ArrayList ();
8470 foreach (Expression tmp in e_list)
8471 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
8475 bool CommonResolve (EmitContext ec)
8477 Expr = Expr.Resolve (ec);
8482 if (Arguments == null)
8485 foreach (Argument a in Arguments){
8486 if (!a.Resolve (ec, loc))
8493 Expression MakePointerAccess (EmitContext ec)
8497 if (t == TypeManager.void_ptr_type){
8498 Error (242, "The array index operation is not valid for void pointers");
8501 if (Arguments.Count != 1){
8502 Error (196, "A pointer must be indexed by a single value");
8507 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc).Resolve (ec);
8510 return new Indirection (p, loc).Resolve (ec);
8513 public override Expression DoResolve (EmitContext ec)
8515 if (!CommonResolve (ec))
8519 // We perform some simple tests, and then to "split" the emit and store
8520 // code we create an instance of a different class, and return that.
8522 // I am experimenting with this pattern.
8526 if (t == TypeManager.array_type){
8527 Report.Error (21, loc, "Cannot use indexer on System.Array");
8532 return (new ArrayAccess (this, loc)).Resolve (ec);
8533 else if (t.IsPointer)
8534 return MakePointerAccess (ec);
8536 return (new IndexerAccess (this, loc)).Resolve (ec);
8539 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8541 if (!CommonResolve (ec))
8546 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
8547 else if (t.IsPointer)
8548 return MakePointerAccess (ec);
8550 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
8553 public override void Emit (EmitContext ec)
8555 throw new Exception ("Should never be reached");
8560 /// Implements array access
8562 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
8564 // Points to our "data" repository
8568 LocalTemporary temp;
8571 public ArrayAccess (ElementAccess ea_data, Location l)
8574 eclass = ExprClass.Variable;
8578 public override Expression DoResolve (EmitContext ec)
8581 ExprClass eclass = ea.Expr.eclass;
8583 // As long as the type is valid
8584 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
8585 eclass == ExprClass.Value)) {
8586 ea.Expr.Error_UnexpectedKind ("variable or value");
8591 Type t = ea.Expr.Type;
8592 if (t.GetArrayRank () != ea.Arguments.Count){
8594 "Incorrect number of indexes for array " +
8595 " expected: " + t.GetArrayRank () + " got: " +
8596 ea.Arguments.Count);
8600 type = TypeManager.GetElementType (t);
8601 if (type.IsPointer && !ec.InUnsafe){
8602 UnsafeError (ea.Location);
8606 foreach (Argument a in ea.Arguments){
8607 Type argtype = a.Type;
8609 if (argtype == TypeManager.int32_type ||
8610 argtype == TypeManager.uint32_type ||
8611 argtype == TypeManager.int64_type ||
8612 argtype == TypeManager.uint64_type) {
8613 Constant c = a.Expr as Constant;
8614 if (c != null && c.IsNegative) {
8615 Report.Warning (251, 2, a.Expr.Location, "Indexing an array with a negative index (array indices always start at zero)");
8621 // Mhm. This is strage, because the Argument.Type is not the same as
8622 // Argument.Expr.Type: the value changes depending on the ref/out setting.
8624 // Wonder if I will run into trouble for this.
8626 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
8631 eclass = ExprClass.Variable;
8637 /// Emits the right opcode to load an object of Type `t'
8638 /// from an array of T
8640 static public void EmitLoadOpcode (ILGenerator ig, Type type)
8642 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
8643 ig.Emit (OpCodes.Ldelem_U1);
8644 else if (type == TypeManager.sbyte_type)
8645 ig.Emit (OpCodes.Ldelem_I1);
8646 else if (type == TypeManager.short_type)
8647 ig.Emit (OpCodes.Ldelem_I2);
8648 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
8649 ig.Emit (OpCodes.Ldelem_U2);
8650 else if (type == TypeManager.int32_type)
8651 ig.Emit (OpCodes.Ldelem_I4);
8652 else if (type == TypeManager.uint32_type)
8653 ig.Emit (OpCodes.Ldelem_U4);
8654 else if (type == TypeManager.uint64_type)
8655 ig.Emit (OpCodes.Ldelem_I8);
8656 else if (type == TypeManager.int64_type)
8657 ig.Emit (OpCodes.Ldelem_I8);
8658 else if (type == TypeManager.float_type)
8659 ig.Emit (OpCodes.Ldelem_R4);
8660 else if (type == TypeManager.double_type)
8661 ig.Emit (OpCodes.Ldelem_R8);
8662 else if (type == TypeManager.intptr_type)
8663 ig.Emit (OpCodes.Ldelem_I);
8664 else if (TypeManager.IsEnumType (type)){
8665 EmitLoadOpcode (ig, TypeManager.EnumToUnderlying (type));
8666 } else if (type.IsValueType){
8667 ig.Emit (OpCodes.Ldelema, type);
8668 ig.Emit (OpCodes.Ldobj, type);
8669 } else if (type.IsGenericParameter)
8670 ig.Emit (OpCodes.Ldelem_Any, type);
8672 ig.Emit (OpCodes.Ldelem_Ref);
8676 /// Returns the right opcode to store an object of Type `t'
8677 /// from an array of T.
8679 static public OpCode GetStoreOpcode (Type t, out bool is_stobj, out bool has_type_arg)
8681 //Console.WriteLine (new System.Diagnostics.StackTrace ());
8682 has_type_arg = false; is_stobj = false;
8683 t = TypeManager.TypeToCoreType (t);
8684 if (TypeManager.IsEnumType (t))
8685 t = TypeManager.EnumToUnderlying (t);
8686 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
8687 t == TypeManager.bool_type)
8688 return OpCodes.Stelem_I1;
8689 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
8690 t == TypeManager.char_type)
8691 return OpCodes.Stelem_I2;
8692 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
8693 return OpCodes.Stelem_I4;
8694 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
8695 return OpCodes.Stelem_I8;
8696 else if (t == TypeManager.float_type)
8697 return OpCodes.Stelem_R4;
8698 else if (t == TypeManager.double_type)
8699 return OpCodes.Stelem_R8;
8700 else if (t == TypeManager.intptr_type) {
8701 has_type_arg = true;
8703 return OpCodes.Stobj;
8704 } else if (t.IsValueType) {
8705 has_type_arg = true;
8707 return OpCodes.Stobj;
8708 } else if (t.IsGenericParameter) {
8709 has_type_arg = true;
8710 return OpCodes.Stelem_Any;
8712 return OpCodes.Stelem_Ref;
8715 MethodInfo FetchGetMethod ()
8717 ModuleBuilder mb = CodeGen.Module.Builder;
8718 int arg_count = ea.Arguments.Count;
8719 Type [] args = new Type [arg_count];
8722 for (int i = 0; i < arg_count; i++){
8723 //args [i++] = a.Type;
8724 args [i] = TypeManager.int32_type;
8727 get = mb.GetArrayMethod (
8728 ea.Expr.Type, "Get",
8729 CallingConventions.HasThis |
8730 CallingConventions.Standard,
8736 MethodInfo FetchAddressMethod ()
8738 ModuleBuilder mb = CodeGen.Module.Builder;
8739 int arg_count = ea.Arguments.Count;
8740 Type [] args = new Type [arg_count];
8744 ret_type = TypeManager.GetReferenceType (type);
8746 for (int i = 0; i < arg_count; i++){
8747 //args [i++] = a.Type;
8748 args [i] = TypeManager.int32_type;
8751 address = mb.GetArrayMethod (
8752 ea.Expr.Type, "Address",
8753 CallingConventions.HasThis |
8754 CallingConventions.Standard,
8761 // Load the array arguments into the stack.
8763 // If we have been requested to cache the values (cached_locations array
8764 // initialized), then load the arguments the first time and store them
8765 // in locals. otherwise load from local variables.
8767 void LoadArrayAndArguments (EmitContext ec)
8769 ILGenerator ig = ec.ig;
8772 foreach (Argument a in ea.Arguments){
8773 Type argtype = a.Expr.Type;
8777 if (argtype == TypeManager.int64_type)
8778 ig.Emit (OpCodes.Conv_Ovf_I);
8779 else if (argtype == TypeManager.uint64_type)
8780 ig.Emit (OpCodes.Conv_Ovf_I_Un);
8784 public void Emit (EmitContext ec, bool leave_copy)
8786 int rank = ea.Expr.Type.GetArrayRank ();
8787 ILGenerator ig = ec.ig;
8790 LoadArrayAndArguments (ec);
8793 EmitLoadOpcode (ig, type);
8797 method = FetchGetMethod ();
8798 ig.Emit (OpCodes.Call, method);
8801 LoadFromPtr (ec.ig, this.type);
8804 ec.ig.Emit (OpCodes.Dup);
8805 temp = new LocalTemporary (ec, this.type);
8810 public override void Emit (EmitContext ec)
8815 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8817 int rank = ea.Expr.Type.GetArrayRank ();
8818 ILGenerator ig = ec.ig;
8819 Type t = source.Type;
8820 prepared = prepare_for_load;
8822 if (prepare_for_load) {
8823 AddressOf (ec, AddressOp.LoadStore);
8824 ec.ig.Emit (OpCodes.Dup);
8827 ec.ig.Emit (OpCodes.Dup);
8828 temp = new LocalTemporary (ec, this.type);
8831 StoreFromPtr (ec.ig, t);
8839 LoadArrayAndArguments (ec);
8842 bool is_stobj, has_type_arg;
8843 OpCode op = GetStoreOpcode (t, out is_stobj, out has_type_arg);
8846 // The stobj opcode used by value types will need
8847 // an address on the stack, not really an array/array
8851 ig.Emit (OpCodes.Ldelema, t);
8855 ec.ig.Emit (OpCodes.Dup);
8856 temp = new LocalTemporary (ec, this.type);
8861 ig.Emit (OpCodes.Stobj, t);
8862 else if (has_type_arg)
8867 ModuleBuilder mb = CodeGen.Module.Builder;
8868 int arg_count = ea.Arguments.Count;
8869 Type [] args = new Type [arg_count + 1];
8874 ec.ig.Emit (OpCodes.Dup);
8875 temp = new LocalTemporary (ec, this.type);
8879 for (int i = 0; i < arg_count; i++){
8880 //args [i++] = a.Type;
8881 args [i] = TypeManager.int32_type;
8884 args [arg_count] = type;
8886 set = mb.GetArrayMethod (
8887 ea.Expr.Type, "Set",
8888 CallingConventions.HasThis |
8889 CallingConventions.Standard,
8890 TypeManager.void_type, args);
8892 ig.Emit (OpCodes.Call, set);
8899 public void AddressOf (EmitContext ec, AddressOp mode)
8901 int rank = ea.Expr.Type.GetArrayRank ();
8902 ILGenerator ig = ec.ig;
8904 LoadArrayAndArguments (ec);
8907 ig.Emit (OpCodes.Ldelema, type);
8909 MethodInfo address = FetchAddressMethod ();
8910 ig.Emit (OpCodes.Call, address);
8917 public ArrayList Properties;
8918 static Hashtable map;
8920 public struct Indexer {
8921 public readonly Type Type;
8922 public readonly MethodInfo Getter, Setter;
8924 public Indexer (Type type, MethodInfo get, MethodInfo set)
8934 map = new Hashtable ();
8939 Properties = new ArrayList ();
8942 void Append (MemberInfo [] mi)
8944 foreach (PropertyInfo property in mi){
8945 MethodInfo get, set;
8947 get = property.GetGetMethod (true);
8948 set = property.GetSetMethod (true);
8949 Properties.Add (new Indexer (property.PropertyType, get, set));
8953 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
8955 string p_name = TypeManager.IndexerPropertyName (lookup_type);
8957 MemberInfo [] mi = TypeManager.MemberLookup (
8958 caller_type, caller_type, lookup_type, MemberTypes.Property,
8959 BindingFlags.Public | BindingFlags.Instance |
8960 BindingFlags.DeclaredOnly, p_name, null);
8962 if (mi == null || mi.Length == 0)
8968 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
8970 Indexers ix = (Indexers) map [lookup_type];
8975 Type copy = lookup_type;
8976 while (copy != TypeManager.object_type && copy != null){
8977 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
8981 ix = new Indexers ();
8986 copy = copy.BaseType;
8989 if (!lookup_type.IsInterface)
8992 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
8993 if (ifaces != null) {
8994 foreach (Type itype in ifaces) {
8995 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
8998 ix = new Indexers ();
9010 /// Expressions that represent an indexer call.
9012 public class IndexerAccess : Expression, IAssignMethod {
9014 // Points to our "data" repository
9016 MethodInfo get, set;
9017 ArrayList set_arguments;
9018 bool is_base_indexer;
9020 protected Type indexer_type;
9021 protected Type current_type;
9022 protected Expression instance_expr;
9023 protected ArrayList arguments;
9025 public IndexerAccess (ElementAccess ea, Location loc)
9026 : this (ea.Expr, false, loc)
9028 this.arguments = ea.Arguments;
9031 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
9034 this.instance_expr = instance_expr;
9035 this.is_base_indexer = is_base_indexer;
9036 this.eclass = ExprClass.Value;
9040 protected virtual bool CommonResolve (EmitContext ec)
9042 indexer_type = instance_expr.Type;
9043 current_type = ec.ContainerType;
9048 public override Expression DoResolve (EmitContext ec)
9050 ArrayList AllGetters = new ArrayList();
9051 if (!CommonResolve (ec))
9055 // Step 1: Query for all `Item' *properties*. Notice
9056 // that the actual methods are pointed from here.
9058 // This is a group of properties, piles of them.
9060 bool found_any = false, found_any_getters = false;
9061 Type lookup_type = indexer_type;
9064 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
9065 if (ilist != null) {
9067 if (ilist.Properties != null) {
9068 foreach (Indexers.Indexer ix in ilist.Properties) {
9069 if (ix.Getter != null)
9070 AllGetters.Add(ix.Getter);
9075 if (AllGetters.Count > 0) {
9076 found_any_getters = true;
9077 get = (MethodInfo) Invocation.OverloadResolve (
9078 ec, new MethodGroupExpr (AllGetters, loc),
9079 arguments, false, loc);
9083 Report.Error (21, loc,
9084 "Type `" + TypeManager.CSharpName (indexer_type) +
9085 "' does not have any indexers defined");
9089 if (!found_any_getters) {
9090 Error (154, "indexer can not be used in this context, because " +
9091 "it lacks a `get' accessor");
9096 Error (1501, "No Overload for method `this' takes `" +
9097 arguments.Count + "' arguments");
9102 // Only base will allow this invocation to happen.
9104 if (get.IsAbstract && this is BaseIndexerAccess){
9105 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
9109 type = get.ReturnType;
9110 if (type.IsPointer && !ec.InUnsafe){
9115 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
9117 eclass = ExprClass.IndexerAccess;
9121 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
9123 ArrayList AllSetters = new ArrayList();
9124 if (!CommonResolve (ec))
9127 bool found_any = false, found_any_setters = false;
9129 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
9130 if (ilist != null) {
9132 if (ilist.Properties != null) {
9133 foreach (Indexers.Indexer ix in ilist.Properties) {
9134 if (ix.Setter != null)
9135 AllSetters.Add(ix.Setter);
9139 if (AllSetters.Count > 0) {
9140 found_any_setters = true;
9141 set_arguments = (ArrayList) arguments.Clone ();
9142 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
9143 set = (MethodInfo) Invocation.OverloadResolve (
9144 ec, new MethodGroupExpr (AllSetters, loc),
9145 set_arguments, false, loc);
9149 Report.Error (21, loc,
9150 "Type `" + TypeManager.CSharpName (indexer_type) +
9151 "' does not have any indexers defined");
9155 if (!found_any_setters) {
9156 Error (154, "indexer can not be used in this context, because " +
9157 "it lacks a `set' accessor");
9162 Error (1501, "No Overload for method `this' takes `" +
9163 arguments.Count + "' arguments");
9168 // Only base will allow this invocation to happen.
9170 if (set.IsAbstract && this is BaseIndexerAccess){
9171 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
9176 // Now look for the actual match in the list of indexers to set our "return" type
9178 type = TypeManager.void_type; // default value
9179 foreach (Indexers.Indexer ix in ilist.Properties){
9180 if (ix.Setter == set){
9186 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
9188 eclass = ExprClass.IndexerAccess;
9192 bool prepared = false;
9193 LocalTemporary temp;
9195 public void Emit (EmitContext ec, bool leave_copy)
9197 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc, prepared, false);
9199 ec.ig.Emit (OpCodes.Dup);
9200 temp = new LocalTemporary (ec, Type);
9206 // source is ignored, because we already have a copy of it from the
9207 // LValue resolution and we have already constructed a pre-cached
9208 // version of the arguments (ea.set_arguments);
9210 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
9212 prepared = prepare_for_load;
9213 Argument a = (Argument) set_arguments [set_arguments.Count - 1];
9218 ec.ig.Emit (OpCodes.Dup);
9219 temp = new LocalTemporary (ec, Type);
9222 } else if (leave_copy) {
9223 temp = new LocalTemporary (ec, Type);
9229 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc, false, prepared);
9236 public override void Emit (EmitContext ec)
9243 /// The base operator for method names
9245 public class BaseAccess : Expression {
9246 public string member;
9248 public BaseAccess (string member, Location l)
9250 this.member = member;
9254 public override Expression DoResolve (EmitContext ec)
9256 Expression c = CommonResolve (ec);
9262 // MethodGroups use this opportunity to flag an error on lacking ()
9264 if (!(c is MethodGroupExpr))
9265 return c.Resolve (ec);
9269 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
9271 Expression c = CommonResolve (ec);
9277 // MethodGroups use this opportunity to flag an error on lacking ()
9279 if (! (c is MethodGroupExpr))
9280 return c.DoResolveLValue (ec, right_side);
9285 Expression CommonResolve (EmitContext ec)
9287 Expression member_lookup;
9288 Type current_type = ec.ContainerType;
9289 Type base_type = current_type.BaseType;
9293 Error (1511, "Keyword base is not allowed in static method");
9297 if (ec.IsFieldInitializer){
9298 Error (1512, "Keyword base is not available in the current context");
9302 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type,
9303 member, AllMemberTypes, AllBindingFlags,
9305 if (member_lookup == null) {
9306 MemberLookupFailed (
9307 ec, base_type, base_type, member, null, loc);
9314 left = new TypeExpression (base_type, loc);
9316 left = ec.GetThis (loc);
9318 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
9320 if (e is PropertyExpr){
9321 PropertyExpr pe = (PropertyExpr) e;
9326 if (e is MethodGroupExpr)
9327 ((MethodGroupExpr) e).IsBase = true;
9332 public override void Emit (EmitContext ec)
9334 throw new Exception ("Should never be called");
9339 /// The base indexer operator
9341 public class BaseIndexerAccess : IndexerAccess {
9342 public BaseIndexerAccess (ArrayList args, Location loc)
9343 : base (null, true, loc)
9345 arguments = new ArrayList ();
9346 foreach (Expression tmp in args)
9347 arguments.Add (new Argument (tmp, Argument.AType.Expression));
9350 protected override bool CommonResolve (EmitContext ec)
9352 instance_expr = ec.GetThis (loc);
9354 current_type = ec.ContainerType.BaseType;
9355 indexer_type = current_type;
9357 foreach (Argument a in arguments){
9358 if (!a.Resolve (ec, loc))
9367 /// This class exists solely to pass the Type around and to be a dummy
9368 /// that can be passed to the conversion functions (this is used by
9369 /// foreach implementation to typecast the object return value from
9370 /// get_Current into the proper type. All code has been generated and
9371 /// we only care about the side effect conversions to be performed
9373 /// This is also now used as a placeholder where a no-action expression
9374 /// is needed (the `New' class).
9376 public class EmptyExpression : Expression {
9377 public static readonly EmptyExpression Null = new EmptyExpression ();
9379 // TODO: should be protected
9380 public EmptyExpression ()
9382 type = TypeManager.object_type;
9383 eclass = ExprClass.Value;
9384 loc = Location.Null;
9387 public EmptyExpression (Type t)
9390 eclass = ExprClass.Value;
9391 loc = Location.Null;
9394 public override Expression DoResolve (EmitContext ec)
9399 public override void Emit (EmitContext ec)
9401 // nothing, as we only exist to not do anything.
9405 // This is just because we might want to reuse this bad boy
9406 // instead of creating gazillions of EmptyExpressions.
9407 // (CanImplicitConversion uses it)
9409 public void SetType (Type t)
9415 public class UserCast : Expression {
9419 public UserCast (MethodInfo method, Expression source, Location l)
9421 this.method = method;
9422 this.source = source;
9423 type = method.ReturnType;
9424 eclass = ExprClass.Value;
9428 public Expression Source {
9434 public override Expression DoResolve (EmitContext ec)
9437 // We are born fully resolved
9442 public override void Emit (EmitContext ec)
9444 ILGenerator ig = ec.ig;
9448 if (method is MethodInfo)
9449 ig.Emit (OpCodes.Call, (MethodInfo) method);
9451 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
9457 // This class is used to "construct" the type during a typecast
9458 // operation. Since the Type.GetType class in .NET can parse
9459 // the type specification, we just use this to construct the type
9460 // one bit at a time.
9462 public class ComposedCast : TypeExpr {
9466 public ComposedCast (Expression left, string dim, Location l)
9473 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
9475 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec);
9479 Type ltype = lexpr.Type;
9481 if ((ltype == TypeManager.void_type) && (dim != "*")) {
9482 Report.Error (1547, Location,
9483 "Keyword 'void' cannot be used in this context");
9487 if ((dim.Length > 0) && (dim [0] == '?')) {
9488 TypeExpr nullable = new NullableType (left, loc);
9490 nullable = new ComposedCast (nullable, dim.Substring (1), loc);
9491 return nullable.ResolveAsTypeTerminal (ec);
9495 while ((pos < dim.Length) && (dim [pos] == '[')) {
9498 if (dim [pos] == ']') {
9499 ltype = ltype.MakeArrayType ();
9502 if (pos < dim.Length)
9506 eclass = ExprClass.Type;
9511 while (dim [pos] == ',') {
9515 if ((dim [pos] != ']') || (pos != dim.Length-1))
9518 type = ltype.MakeArrayType (rank + 1);
9519 eclass = ExprClass.Type;
9525 // ltype.Fullname is already fully qualified, so we can skip
9526 // a lot of probes, and go directly to TypeManager.LookupType
9528 string fname = ltype.FullName != null ? ltype.FullName : ltype.Name;
9529 string cname = fname + dim;
9530 type = TypeManager.LookupTypeDirect (cname);
9533 // For arrays of enumerations we are having a problem
9534 // with the direct lookup. Need to investigate.
9536 // For now, fall back to the full lookup in that case.
9538 FullNamedExpression e = ec.DeclSpace.LookupType (cname, false, loc);
9540 type = ((TypeExpr) e).ResolveType (ec);
9548 if (!ec.InUnsafe && type.IsPointer){
9553 if (type.IsArray && (type.GetElementType () == TypeManager.arg_iterator_type ||
9554 type.GetElementType () == TypeManager.typed_reference_type)) {
9555 Report.Error (611, loc, "Array elements cannot be of type '{0}'", TypeManager.CSharpName (type.GetElementType ()));
9559 eclass = ExprClass.Type;
9563 public override string Name {
9569 public override string FullName {
9571 return type.FullName;
9577 // This class is used to represent the address of an array, used
9578 // only by the Fixed statement, this is like the C "&a [0]" construct.
9580 public class ArrayPtr : Expression {
9583 public ArrayPtr (Expression array, Location l)
9585 Type array_type = TypeManager.GetElementType (array.Type);
9589 type = TypeManager.GetPointerType (array_type);
9590 eclass = ExprClass.Value;
9594 public override void Emit (EmitContext ec)
9596 ILGenerator ig = ec.ig;
9599 IntLiteral.EmitInt (ig, 0);
9600 ig.Emit (OpCodes.Ldelema, TypeManager.GetElementType (array.Type));
9603 public override Expression DoResolve (EmitContext ec)
9606 // We are born fully resolved
9613 // Used by the fixed statement
9615 public class StringPtr : Expression {
9618 public StringPtr (LocalBuilder b, Location l)
9621 eclass = ExprClass.Value;
9622 type = TypeManager.char_ptr_type;
9626 public override Expression DoResolve (EmitContext ec)
9628 // This should never be invoked, we are born in fully
9629 // initialized state.
9634 public override void Emit (EmitContext ec)
9636 ILGenerator ig = ec.ig;
9638 ig.Emit (OpCodes.Ldloc, b);
9639 ig.Emit (OpCodes.Conv_I);
9640 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
9641 ig.Emit (OpCodes.Add);
9646 // Implements the `stackalloc' keyword
9648 public class StackAlloc : Expression {
9653 public StackAlloc (Expression type, Expression count, Location l)
9660 public override Expression DoResolve (EmitContext ec)
9662 count = count.Resolve (ec);
9666 if (count.Type != TypeManager.int32_type){
9667 count = Convert.WideningConversionRequired (ec, count, TypeManager.int32_type, loc);
9672 Constant c = count as Constant;
9673 if (c != null && c.IsNegative) {
9674 Report.Error (247, loc, "Cannot use a negative size with stackalloc");
9678 if (ec.CurrentBranching.InCatch () ||
9679 ec.CurrentBranching.InFinally (true)) {
9681 "stackalloc can not be used in a catch or finally block");
9685 TypeExpr texpr = t.ResolveAsTypeTerminal (ec);
9691 if (!TypeManager.VerifyUnManaged (otype, loc))
9694 type = TypeManager.GetPointerType (otype);
9695 eclass = ExprClass.Value;
9700 public override void Emit (EmitContext ec)
9702 int size = GetTypeSize (otype);
9703 ILGenerator ig = ec.ig;
9706 ig.Emit (OpCodes.Sizeof, otype);
9708 IntConstant.EmitInt (ig, size);
9710 ig.Emit (OpCodes.Mul);
9711 ig.Emit (OpCodes.Localloc);