2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // (C) 2001, 2002, 2003 Ximian, Inc.
9 // (C) 2003, 2004 Novell, Inc.
13 namespace Mono.CSharp {
15 using System.Collections;
16 using System.Reflection;
17 using System.Reflection.Emit;
21 /// This is just a helper class, it is generated by Unary, UnaryMutator
22 /// when an overloaded method has been found. It just emits the code for a
25 public class StaticCallExpr : ExpressionStatement {
29 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)
100 public override Expression DoResolve (EmitContext ec)
102 Expr = Expr.Resolve (ec);
106 public override void Emit (EmitContext ec)
108 throw new Exception ("Should not happen");
111 public override Location Location
114 return Expr.Location;
120 /// Unary expressions.
124 /// Unary implements unary expressions. It derives from
125 /// ExpressionStatement becuase the pre/post increment/decrement
126 /// operators can be used in a statement context.
128 public class Unary : Expression {
129 public enum Operator : byte {
130 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
131 Indirection, AddressOf, TOP
134 public Operator Oper;
135 public Expression Expr;
137 public Unary (Operator op, Expression expr, Location loc)
145 /// Returns a stringified representation of the Operator
147 static public string OperName (Operator oper)
150 case Operator.UnaryPlus:
152 case Operator.UnaryNegation:
154 case Operator.LogicalNot:
156 case Operator.OnesComplement:
158 case Operator.AddressOf:
160 case Operator.Indirection:
164 return oper.ToString ();
167 public static readonly string [] oper_names;
171 oper_names = new string [(int)Operator.TOP];
173 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
174 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
175 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
176 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
177 oper_names [(int) Operator.Indirection] = "op_Indirection";
178 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
181 void Error23 (Type t)
183 Report.Error (23, loc, "Operator `{0}' cannot be applied to operand of type `{1}'",
184 OperName (Oper), TypeManager.CSharpName (t));
188 /// The result has been already resolved:
190 /// FIXME: a minus constant -128 sbyte cant be turned into a
193 static Expression TryReduceNegative (Constant expr)
197 if (expr is IntConstant)
198 e = new IntConstant (-((IntConstant) expr).Value, expr.Location);
199 else if (expr is UIntConstant){
200 uint value = ((UIntConstant) expr).Value;
202 if (value < 2147483649)
203 return new IntConstant (-(int)value, expr.Location);
205 e = new LongConstant (-value, expr.Location);
207 else if (expr is LongConstant)
208 e = new LongConstant (-((LongConstant) expr).Value, expr.Location);
209 else if (expr is ULongConstant){
210 ulong value = ((ULongConstant) expr).Value;
212 if (value < 9223372036854775809)
213 return new LongConstant(-(long)value, expr.Location);
215 else if (expr is FloatConstant)
216 e = new FloatConstant (-((FloatConstant) expr).Value, expr.Location);
217 else if (expr is DoubleConstant)
218 e = new DoubleConstant (-((DoubleConstant) expr).Value, expr.Location);
219 else if (expr is DecimalConstant)
220 e = new DecimalConstant (-((DecimalConstant) expr).Value, expr.Location);
221 else if (expr is ShortConstant)
222 e = new IntConstant (-((ShortConstant) expr).Value, expr.Location);
223 else if (expr is UShortConstant)
224 e = new IntConstant (-((UShortConstant) expr).Value, expr.Location);
225 else if (expr is SByteConstant)
226 e = new IntConstant (-((SByteConstant) expr).Value, expr.Location);
227 else if (expr is ByteConstant)
228 e = new IntConstant (-((ByteConstant) expr).Value, expr.Location);
233 // This routine will attempt to simplify the unary expression when the
234 // argument is a constant. The result is returned in `result' and the
235 // function returns true or false depending on whether a reduction
236 // was performed or not
238 bool Reduce (EmitContext ec, Constant e, out Expression result)
240 Type expr_type = e.Type;
243 case Operator.UnaryPlus:
244 if (expr_type == TypeManager.bool_type){
253 case Operator.UnaryNegation:
254 result = TryReduceNegative (e);
255 return result != null;
257 case Operator.LogicalNot:
258 if (expr_type != TypeManager.bool_type) {
264 BoolConstant b = (BoolConstant) e;
265 result = new BoolConstant (!(b.Value), b.Location);
268 case Operator.OnesComplement:
269 if (!((expr_type == TypeManager.int32_type) ||
270 (expr_type == TypeManager.uint32_type) ||
271 (expr_type == TypeManager.int64_type) ||
272 (expr_type == TypeManager.uint64_type) ||
273 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
276 if (Convert.ImplicitConversionExists (ec, e, TypeManager.int32_type)){
277 result = new Cast (new TypeExpression (TypeManager.int32_type, loc), e, loc);
278 result = result.Resolve (ec);
279 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint32_type)){
280 result = new Cast (new TypeExpression (TypeManager.uint32_type, loc), e, loc);
281 result = result.Resolve (ec);
282 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.int64_type)){
283 result = new Cast (new TypeExpression (TypeManager.int64_type, loc), e, loc);
284 result = result.Resolve (ec);
285 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint64_type)){
286 result = new Cast (new TypeExpression (TypeManager.uint64_type, loc), e, loc);
287 result = result.Resolve (ec);
290 if (result == null || !(result is Constant)){
296 expr_type = result.Type;
297 e = (Constant) result;
300 if (e is EnumConstant){
301 EnumConstant enum_constant = (EnumConstant) e;
304 if (Reduce (ec, enum_constant.Child, out reduced)){
305 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
313 if (expr_type == TypeManager.int32_type){
314 result = new IntConstant (~ ((IntConstant) e).Value, e.Location);
315 } else if (expr_type == TypeManager.uint32_type){
316 result = new UIntConstant (~ ((UIntConstant) e).Value, e.Location);
317 } else if (expr_type == TypeManager.int64_type){
318 result = new LongConstant (~ ((LongConstant) e).Value, e.Location);
319 } else if (expr_type == TypeManager.uint64_type){
320 result = new ULongConstant (~ ((ULongConstant) e).Value, e.Location);
328 case Operator.AddressOf:
332 case Operator.Indirection:
336 throw new Exception ("Can not constant fold: " + Oper.ToString());
339 Expression ResolveOperator (EmitContext ec)
342 // Step 1: Default operations on CLI native types.
345 // Attempt to use a constant folding operation.
346 if (Expr is Constant){
349 if (Reduce (ec, (Constant) Expr, out result))
354 // Step 2: Perform Operator Overload location
356 Type expr_type = Expr.Type;
360 op_name = oper_names [(int) Oper];
362 mg = MemberLookup (ec.ContainerType, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
365 Expression e = StaticCallExpr.MakeSimpleCall (
366 ec, (MethodGroupExpr) mg, Expr, loc);
376 // Only perform numeric promotions on:
379 if (expr_type == null)
383 case Operator.LogicalNot:
384 if (expr_type != TypeManager.bool_type) {
385 Expr = ResolveBoolean (ec, Expr, loc);
392 type = TypeManager.bool_type;
395 case Operator.OnesComplement:
396 if (!((expr_type == TypeManager.int32_type) ||
397 (expr_type == TypeManager.uint32_type) ||
398 (expr_type == TypeManager.int64_type) ||
399 (expr_type == TypeManager.uint64_type) ||
400 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
403 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
406 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint32_type, loc);
409 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
412 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint64_type, loc);
425 case Operator.AddressOf:
431 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
435 IVariable variable = Expr as IVariable;
436 bool is_fixed = variable != null && variable.VerifyFixed ();
438 if (!ec.InFixedInitializer && !is_fixed) {
439 Error (212, "You can only take the address of unfixed expression inside " +
440 "of a fixed statement initializer");
444 if (ec.InFixedInitializer && is_fixed) {
445 Error (213, "You cannot use the fixed statement to take the address of an already fixed expression");
449 LocalVariableReference lr = Expr as LocalVariableReference;
451 if (lr.local_info.IsCaptured){
452 AnonymousMethod.Error_AddressOfCapturedVar (lr.Name, loc);
455 lr.local_info.AddressTaken = true;
456 lr.local_info.Used = true;
459 // According to the specs, a variable is considered definitely assigned if you take
461 if ((variable != null) && (variable.VariableInfo != null)){
462 variable.VariableInfo.SetAssigned (ec);
465 type = TypeManager.GetPointerType (Expr.Type);
468 case Operator.Indirection:
474 if (!expr_type.IsPointer){
475 Error (193, "The * or -> operator must be applied to a pointer");
480 // We create an Indirection expression, because
481 // it can implement the IMemoryLocation.
483 return new Indirection (Expr, loc);
485 case Operator.UnaryPlus:
487 // A plus in front of something is just a no-op, so return the child.
491 case Operator.UnaryNegation:
493 // Deals with -literals
494 // int operator- (int x)
495 // long operator- (long x)
496 // float operator- (float f)
497 // double operator- (double d)
498 // decimal operator- (decimal d)
500 Expression expr = null;
503 // transform - - expr into expr
506 Unary unary = (Unary) Expr;
508 if (unary.Oper == Operator.UnaryNegation)
513 // perform numeric promotions to int,
517 // The following is inneficient, because we call
518 // ImplicitConversion too many times.
520 // It is also not clear if we should convert to Float
521 // or Double initially.
523 if (expr_type == TypeManager.uint32_type){
525 // FIXME: handle exception to this rule that
526 // permits the int value -2147483648 (-2^31) to
527 // bt wrote as a decimal interger literal
529 type = TypeManager.int64_type;
530 Expr = Convert.ImplicitConversion (ec, Expr, type, loc);
534 if (expr_type == TypeManager.uint64_type){
536 // FIXME: Handle exception of `long value'
537 // -92233720368547758087 (-2^63) to be wrote as
538 // decimal integer literal.
544 if (expr_type == TypeManager.float_type){
549 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
556 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
563 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.double_type, loc);
574 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
575 TypeManager.CSharpName (expr_type) + "'");
579 public override Expression DoResolve (EmitContext ec)
581 if (Oper == Operator.AddressOf) {
582 Expr = Expr.DoResolveLValue (ec, new EmptyExpression ());
584 if (Expr == null || Expr.eclass != ExprClass.Variable){
585 Error (211, "Cannot take the address of the given expression");
590 Expr = Expr.Resolve (ec);
595 eclass = ExprClass.Value;
596 return ResolveOperator (ec);
599 public override Expression DoResolveLValue (EmitContext ec, Expression right)
601 if (Oper == Operator.Indirection)
602 return DoResolve (ec);
607 public override void Emit (EmitContext ec)
609 ILGenerator ig = ec.ig;
612 case Operator.UnaryPlus:
613 throw new Exception ("This should be caught by Resolve");
615 case Operator.UnaryNegation:
616 if (ec.CheckState && type != TypeManager.float_type && type != TypeManager.double_type) {
617 ig.Emit (OpCodes.Ldc_I4_0);
618 if (type == TypeManager.int64_type)
619 ig.Emit (OpCodes.Conv_U8);
621 ig.Emit (OpCodes.Sub_Ovf);
624 ig.Emit (OpCodes.Neg);
629 case Operator.LogicalNot:
631 ig.Emit (OpCodes.Ldc_I4_0);
632 ig.Emit (OpCodes.Ceq);
635 case Operator.OnesComplement:
637 ig.Emit (OpCodes.Not);
640 case Operator.AddressOf:
641 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
645 throw new Exception ("This should not happen: Operator = "
650 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
652 if (Oper == Operator.LogicalNot)
653 Expr.EmitBranchable (ec, target, !onTrue);
655 base.EmitBranchable (ec, target, onTrue);
658 public override string ToString ()
660 return "Unary (" + Oper + ", " + Expr + ")";
666 // Unary operators are turned into Indirection expressions
667 // after semantic analysis (this is so we can take the address
668 // of an indirection).
670 public class Indirection : Expression, IMemoryLocation, IAssignMethod, IVariable {
672 LocalTemporary temporary;
675 public Indirection (Expression expr, Location l)
678 type = TypeManager.HasElementType (expr.Type) ? TypeManager.GetElementType (expr.Type) : expr.Type;
679 eclass = ExprClass.Variable;
683 public override void Emit (EmitContext ec)
688 LoadFromPtr (ec.ig, Type);
691 public void Emit (EmitContext ec, bool leave_copy)
695 ec.ig.Emit (OpCodes.Dup);
696 temporary = new LocalTemporary (expr.Type);
697 temporary.Store (ec);
701 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
703 prepared = prepare_for_load;
707 if (prepare_for_load)
708 ec.ig.Emit (OpCodes.Dup);
712 ec.ig.Emit (OpCodes.Dup);
713 temporary = new LocalTemporary (expr.Type);
714 temporary.Store (ec);
717 StoreFromPtr (ec.ig, type);
719 if (temporary != null)
723 public void AddressOf (EmitContext ec, AddressOp Mode)
728 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
730 return DoResolve (ec);
733 public override Expression DoResolve (EmitContext ec)
736 // Born fully resolved
741 public override string ToString ()
743 return "*(" + expr + ")";
746 #region IVariable Members
748 public VariableInfo VariableInfo {
754 public bool VerifyFixed ()
756 // A pointer-indirection is always fixed.
764 /// Unary Mutator expressions (pre and post ++ and --)
768 /// UnaryMutator implements ++ and -- expressions. It derives from
769 /// ExpressionStatement becuase the pre/post increment/decrement
770 /// operators can be used in a statement context.
772 /// FIXME: Idea, we could split this up in two classes, one simpler
773 /// for the common case, and one with the extra fields for more complex
774 /// classes (indexers require temporary access; overloaded require method)
777 public class UnaryMutator : ExpressionStatement {
779 public enum Mode : byte {
786 PreDecrement = IsDecrement,
787 PostIncrement = IsPost,
788 PostDecrement = IsPost | IsDecrement
792 bool is_expr = false;
793 bool recurse = false;
798 // This is expensive for the simplest case.
800 StaticCallExpr method;
802 public UnaryMutator (Mode m, Expression e, Location l)
809 static string OperName (Mode mode)
811 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
816 /// Returns whether an object of type `t' can be incremented
817 /// or decremented with add/sub (ie, basically whether we can
818 /// use pre-post incr-decr operations on it, but it is not a
819 /// System.Decimal, which we require operator overloading to catch)
821 static bool IsIncrementableNumber (Type t)
823 return (t == TypeManager.sbyte_type) ||
824 (t == TypeManager.byte_type) ||
825 (t == TypeManager.short_type) ||
826 (t == TypeManager.ushort_type) ||
827 (t == TypeManager.int32_type) ||
828 (t == TypeManager.uint32_type) ||
829 (t == TypeManager.int64_type) ||
830 (t == TypeManager.uint64_type) ||
831 (t == TypeManager.char_type) ||
832 (t.IsSubclassOf (TypeManager.enum_type)) ||
833 (t == TypeManager.float_type) ||
834 (t == TypeManager.double_type) ||
835 (t.IsPointer && t != TypeManager.void_ptr_type);
838 Expression ResolveOperator (EmitContext ec)
840 Type expr_type = expr.Type;
843 // Step 1: Perform Operator Overload location
848 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
849 op_name = "op_Increment";
851 op_name = "op_Decrement";
853 mg = MemberLookup (ec.ContainerType, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
856 method = StaticCallExpr.MakeSimpleCall (
857 ec, (MethodGroupExpr) mg, expr, loc);
860 } else if (!IsIncrementableNumber (expr_type)) {
861 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
862 TypeManager.CSharpName (expr_type) + "'");
867 // The operand of the prefix/postfix increment decrement operators
868 // should be an expression that is classified as a variable,
869 // a property access or an indexer access
872 if (expr.eclass == ExprClass.Variable){
873 LocalVariableReference var = expr as LocalVariableReference;
874 if ((var != null) && var.IsReadOnly) {
875 Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
878 } else if (expr.eclass == ExprClass.IndexerAccess || expr.eclass == ExprClass.PropertyAccess){
879 expr = expr.ResolveLValue (ec, this, Location);
883 expr.Error_UnexpectedKind (ec.DeclContainer, "variable, indexer or property access", loc);
890 public override Expression DoResolve (EmitContext ec)
892 expr = expr.Resolve (ec);
897 eclass = ExprClass.Value;
898 return ResolveOperator (ec);
901 static int PtrTypeSize (Type t)
903 return GetTypeSize (TypeManager.GetElementType (t));
907 // Loads the proper "1" into the stack based on the type, then it emits the
908 // opcode for the operation requested
910 void LoadOneAndEmitOp (EmitContext ec, Type t)
913 // Measure if getting the typecode and using that is more/less efficient
914 // that comparing types. t.GetTypeCode() is an internal call.
916 ILGenerator ig = ec.ig;
918 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
919 LongConstant.EmitLong (ig, 1);
920 else if (t == TypeManager.double_type)
921 ig.Emit (OpCodes.Ldc_R8, 1.0);
922 else if (t == TypeManager.float_type)
923 ig.Emit (OpCodes.Ldc_R4, 1.0F);
924 else if (t.IsPointer){
925 int n = PtrTypeSize (t);
928 ig.Emit (OpCodes.Sizeof, t);
930 IntConstant.EmitInt (ig, n);
932 ig.Emit (OpCodes.Ldc_I4_1);
935 // Now emit the operation
938 if (t == TypeManager.int32_type ||
939 t == TypeManager.int64_type){
940 if ((mode & Mode.IsDecrement) != 0)
941 ig.Emit (OpCodes.Sub_Ovf);
943 ig.Emit (OpCodes.Add_Ovf);
944 } else if (t == TypeManager.uint32_type ||
945 t == TypeManager.uint64_type){
946 if ((mode & Mode.IsDecrement) != 0)
947 ig.Emit (OpCodes.Sub_Ovf_Un);
949 ig.Emit (OpCodes.Add_Ovf_Un);
951 if ((mode & Mode.IsDecrement) != 0)
952 ig.Emit (OpCodes.Sub_Ovf);
954 ig.Emit (OpCodes.Add_Ovf);
957 if ((mode & Mode.IsDecrement) != 0)
958 ig.Emit (OpCodes.Sub);
960 ig.Emit (OpCodes.Add);
963 if (t == TypeManager.sbyte_type){
965 ig.Emit (OpCodes.Conv_Ovf_I1);
967 ig.Emit (OpCodes.Conv_I1);
968 } else if (t == TypeManager.byte_type){
970 ig.Emit (OpCodes.Conv_Ovf_U1);
972 ig.Emit (OpCodes.Conv_U1);
973 } else if (t == TypeManager.short_type){
975 ig.Emit (OpCodes.Conv_Ovf_I2);
977 ig.Emit (OpCodes.Conv_I2);
978 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
980 ig.Emit (OpCodes.Conv_Ovf_U2);
982 ig.Emit (OpCodes.Conv_U2);
987 void EmitCode (EmitContext ec, bool is_expr)
990 this.is_expr = is_expr;
991 ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
994 public override void Emit (EmitContext ec)
997 // We use recurse to allow ourselfs to be the source
998 // of an assignment. This little hack prevents us from
999 // having to allocate another expression
1002 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
1004 LoadOneAndEmitOp (ec, expr.Type);
1006 ec.ig.Emit (OpCodes.Call, method.Method);
1011 EmitCode (ec, true);
1014 public override void EmitStatement (EmitContext ec)
1016 EmitCode (ec, false);
1021 /// Base class for the `Is' and `As' classes.
1025 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1028 public abstract class Probe : Expression {
1029 public Expression ProbeType;
1030 protected Expression expr;
1031 protected Type probe_type;
1033 public Probe (Expression expr, Expression probe_type, Location l)
1035 ProbeType = probe_type;
1040 public Expression Expr {
1046 public override Expression DoResolve (EmitContext ec)
1048 TypeExpr texpr = ProbeType.ResolveAsTypeTerminal (ec, false);
1052 probe_type = texpr.Type;
1054 expr = expr.Resolve (ec);
1058 if (expr.Type.IsPointer) {
1059 Report.Error (244, loc, "\"is\" or \"as\" are not valid on pointer types");
1067 /// Implementation of the `is' operator.
1069 public class Is : Probe {
1070 public Is (Expression expr, Expression probe_type, Location l)
1071 : base (expr, probe_type, l)
1076 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1081 public override void Emit (EmitContext ec)
1083 ILGenerator ig = ec.ig;
1088 case Action.AlwaysFalse:
1089 ig.Emit (OpCodes.Pop);
1090 IntConstant.EmitInt (ig, 0);
1092 case Action.AlwaysTrue:
1093 ig.Emit (OpCodes.Pop);
1094 IntConstant.EmitInt (ig, 1);
1096 case Action.LeaveOnStack:
1097 // the `e != null' rule.
1098 ig.Emit (OpCodes.Ldnull);
1099 ig.Emit (OpCodes.Ceq);
1100 ig.Emit (OpCodes.Ldc_I4_0);
1101 ig.Emit (OpCodes.Ceq);
1104 ig.Emit (OpCodes.Isinst, probe_type);
1105 ig.Emit (OpCodes.Ldnull);
1106 ig.Emit (OpCodes.Cgt_Un);
1109 throw new Exception ("never reached");
1112 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
1114 ILGenerator ig = ec.ig;
1117 case Action.AlwaysFalse:
1119 ig.Emit (OpCodes.Br, target);
1122 case Action.AlwaysTrue:
1124 ig.Emit (OpCodes.Br, target);
1127 case Action.LeaveOnStack:
1128 // the `e != null' rule.
1130 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1134 ig.Emit (OpCodes.Isinst, probe_type);
1135 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1138 throw new Exception ("never reached");
1141 public override Expression DoResolve (EmitContext ec)
1143 Expression e = base.DoResolve (ec);
1145 if ((e == null) || (expr == null))
1148 Type etype = expr.Type;
1149 bool warning_always_matches = false;
1150 bool warning_never_matches = false;
1152 type = TypeManager.bool_type;
1153 eclass = ExprClass.Value;
1156 // First case, if at compile time, there is an implicit conversion
1157 // then e != null (objects) or true (value types)
1159 e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1160 if (e != null && !(e is NullCast)){
1162 if (etype.IsValueType)
1163 action = Action.AlwaysTrue;
1165 action = Action.LeaveOnStack;
1167 warning_always_matches = true;
1168 } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1170 // Second case: explicit reference convresion
1172 if (expr is NullLiteral)
1173 action = Action.AlwaysFalse;
1175 action = Action.Probe;
1177 action = Action.AlwaysFalse;
1178 warning_never_matches = true;
1181 if (warning_always_matches)
1182 Report.Warning (183, 1, loc, "The given expression is always of the provided (`{0}') type", TypeManager.CSharpName (probe_type));
1183 else if (warning_never_matches){
1184 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1185 Report.Warning (184, 1, loc, "The given expression is never of the provided (`{0}') type", TypeManager.CSharpName (probe_type));
1193 /// Implementation of the `as' operator.
1195 public class As : Probe {
1196 public As (Expression expr, Expression probe_type, Location l)
1197 : base (expr, probe_type, l)
1201 bool do_isinst = false;
1202 Expression resolved_type;
1204 public override void Emit (EmitContext ec)
1206 ILGenerator ig = ec.ig;
1211 ig.Emit (OpCodes.Isinst, probe_type);
1214 static void Error_CannotConvertType (Type source, Type target, Location loc)
1216 Report.Error (39, loc, "Cannot convert type `{0}' to `{1}' via a built-in conversion",
1217 TypeManager.CSharpName (source),
1218 TypeManager.CSharpName (target));
1221 public override Expression DoResolve (EmitContext ec)
1223 if (resolved_type == null) {
1224 resolved_type = base.DoResolve (ec);
1226 if (resolved_type == null)
1231 eclass = ExprClass.Value;
1232 Type etype = expr.Type;
1234 if (TypeManager.IsValueType (probe_type)){
1235 Report.Error (77, loc, "The as operator must be used with a reference type (`" +
1236 TypeManager.CSharpName (probe_type) + "' is a value type)");
1241 Expression e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1248 if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1253 Error_CannotConvertType (etype, probe_type, loc);
1257 public override bool GetAttributableValue (Type valueType, out object value)
1259 return expr.GetAttributableValue (valueType, out value);
1264 /// This represents a typecast in the source language.
1266 /// FIXME: Cast expressions have an unusual set of parsing
1267 /// rules, we need to figure those out.
1269 public class Cast : Expression {
1270 Expression target_type;
1273 public Cast (Expression cast_type, Expression expr)
1274 : this (cast_type, expr, cast_type.Location)
1278 public Cast (Expression cast_type, Expression expr, Location loc)
1280 this.target_type = cast_type;
1284 if (target_type == TypeManager.system_void_expr) {
1285 Report.Error (1547, loc, "Keyword `void' cannot be used in this context");
1289 public Expression TargetType {
1295 public Expression Expr {
1304 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1306 expr = expr.DoResolveLValue (ec, right_side);
1310 return ResolveRest (ec);
1313 public override Expression DoResolve (EmitContext ec)
1315 expr = expr.Resolve (ec);
1319 return ResolveRest (ec);
1322 Expression ResolveRest (EmitContext ec)
1324 TypeExpr target = target_type.ResolveAsTypeTerminal (ec, false);
1330 if (type.IsAbstract && type.IsSealed) {
1331 Report.Error (716, loc, "Cannot convert to static type `{0}'", TypeManager.CSharpName (type));
1335 eclass = ExprClass.Value;
1337 Constant c = expr as Constant;
1340 c = c.TryReduce (ec, type, loc);
1344 catch (OverflowException) {
1349 if (type.IsPointer && !ec.InUnsafe) {
1353 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1357 public override void Emit (EmitContext ec)
1360 // This one will never happen
1362 throw new Exception ("Should not happen");
1367 /// Binary operators
1369 public class Binary : Expression {
1370 public enum Operator : byte {
1371 Multiply, Division, Modulus,
1372 Addition, Subtraction,
1373 LeftShift, RightShift,
1374 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1375 Equality, Inequality,
1385 Expression left, right;
1387 // This must be kept in sync with Operator!!!
1388 public static readonly string [] oper_names;
1392 oper_names = new string [(int) Operator.TOP];
1394 oper_names [(int) Operator.Multiply] = "op_Multiply";
1395 oper_names [(int) Operator.Division] = "op_Division";
1396 oper_names [(int) Operator.Modulus] = "op_Modulus";
1397 oper_names [(int) Operator.Addition] = "op_Addition";
1398 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1399 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1400 oper_names [(int) Operator.RightShift] = "op_RightShift";
1401 oper_names [(int) Operator.LessThan] = "op_LessThan";
1402 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1403 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1404 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1405 oper_names [(int) Operator.Equality] = "op_Equality";
1406 oper_names [(int) Operator.Inequality] = "op_Inequality";
1407 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1408 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1409 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1410 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1411 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1414 public Binary (Operator oper, Expression left, Expression right)
1419 this.loc = left.Location;
1422 public Operator Oper {
1431 public Expression Left {
1440 public Expression Right {
1451 /// Returns a stringified representation of the Operator
1453 public static string OperName (Operator oper)
1456 case Operator.Multiply:
1458 case Operator.Division:
1460 case Operator.Modulus:
1462 case Operator.Addition:
1464 case Operator.Subtraction:
1466 case Operator.LeftShift:
1468 case Operator.RightShift:
1470 case Operator.LessThan:
1472 case Operator.GreaterThan:
1474 case Operator.LessThanOrEqual:
1476 case Operator.GreaterThanOrEqual:
1478 case Operator.Equality:
1480 case Operator.Inequality:
1482 case Operator.BitwiseAnd:
1484 case Operator.BitwiseOr:
1486 case Operator.ExclusiveOr:
1488 case Operator.LogicalOr:
1490 case Operator.LogicalAnd:
1494 return oper.ToString ();
1497 public override string ToString ()
1499 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1500 right.ToString () + ")";
1503 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1505 if (expr.Type == target_type)
1508 return Convert.ImplicitConversion (ec, expr, target_type, loc);
1511 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1514 34, loc, "Operator `" + OperName (oper)
1515 + "' is ambiguous on operands of type `"
1516 + TypeManager.CSharpName (l) + "' "
1517 + "and `" + TypeManager.CSharpName (r)
1521 static bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
1523 if ((l == t) || (r == t))
1526 if (!check_user_conversions)
1529 if (Convert.ImplicitUserConversionExists (ec, l, t))
1531 else if (Convert.ImplicitUserConversionExists (ec, r, t))
1538 // Note that handling the case l == Decimal || r == Decimal
1539 // is taken care of by the Step 1 Operator Overload resolution.
1541 // If `check_user_conv' is true, we also check whether a user-defined conversion
1542 // exists. Note that we only need to do this if both arguments are of a user-defined
1543 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
1544 // so we don't explicitly check for performance reasons.
1546 bool DoNumericPromotions (EmitContext ec, Type l, Type r, Expression lexpr, Expression rexpr, bool check_user_conv)
1548 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
1550 // If either operand is of type double, the other operand is
1551 // conveted to type double.
1553 if (r != TypeManager.double_type)
1554 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
1555 if (l != TypeManager.double_type)
1556 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
1558 type = TypeManager.double_type;
1559 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
1561 // if either operand is of type float, the other operand is
1562 // converted to type float.
1564 if (r != TypeManager.double_type)
1565 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
1566 if (l != TypeManager.double_type)
1567 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
1568 type = TypeManager.float_type;
1569 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
1573 // If either operand is of type ulong, the other operand is
1574 // converted to type ulong. or an error ocurrs if the other
1575 // operand is of type sbyte, short, int or long
1577 if (l == TypeManager.uint64_type){
1578 if (r != TypeManager.uint64_type){
1579 if (right is IntConstant){
1580 IntConstant ic = (IntConstant) right;
1582 e = Convert.TryImplicitIntConversion (l, ic);
1585 } else if (right is LongConstant){
1586 long ll = ((LongConstant) right).Value;
1589 right = new ULongConstant ((ulong) ll, right.Location);
1591 e = Convert.ImplicitNumericConversion (right, l);
1598 if (left is IntConstant){
1599 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
1602 } else if (left is LongConstant){
1603 long ll = ((LongConstant) left).Value;
1606 left = new ULongConstant ((ulong) ll, right.Location);
1608 e = Convert.ImplicitNumericConversion (left, r);
1615 if ((other == TypeManager.sbyte_type) ||
1616 (other == TypeManager.short_type) ||
1617 (other == TypeManager.int32_type) ||
1618 (other == TypeManager.int64_type))
1619 Error_OperatorAmbiguous (loc, oper, l, r);
1621 left = ForceConversion (ec, left, TypeManager.uint64_type);
1622 right = ForceConversion (ec, right, TypeManager.uint64_type);
1624 type = TypeManager.uint64_type;
1625 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
1627 // If either operand is of type long, the other operand is converted
1630 if (l != TypeManager.int64_type)
1631 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
1632 if (r != TypeManager.int64_type)
1633 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
1635 type = TypeManager.int64_type;
1636 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
1638 // If either operand is of type uint, and the other
1639 // operand is of type sbyte, short or int, othe operands are
1640 // converted to type long (unless we have an int constant).
1644 if (l == TypeManager.uint32_type){
1645 if (right is IntConstant){
1646 IntConstant ic = (IntConstant) right;
1650 right = new UIntConstant ((uint) val, ic.Location);
1657 } else if (r == TypeManager.uint32_type){
1658 if (left is IntConstant){
1659 IntConstant ic = (IntConstant) left;
1663 left = new UIntConstant ((uint) val, ic.Location);
1672 if ((other == TypeManager.sbyte_type) ||
1673 (other == TypeManager.short_type) ||
1674 (other == TypeManager.int32_type)){
1675 left = ForceConversion (ec, left, TypeManager.int64_type);
1676 right = ForceConversion (ec, right, TypeManager.int64_type);
1677 type = TypeManager.int64_type;
1680 // if either operand is of type uint, the other
1681 // operand is converd to type uint
1683 left = ForceConversion (ec, left, TypeManager.uint32_type);
1684 right = ForceConversion (ec, right, TypeManager.uint32_type);
1685 type = TypeManager.uint32_type;
1687 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1688 if (l != TypeManager.decimal_type)
1689 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
1691 if (r != TypeManager.decimal_type)
1692 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
1693 type = TypeManager.decimal_type;
1695 left = ForceConversion (ec, left, TypeManager.int32_type);
1696 right = ForceConversion (ec, right, TypeManager.int32_type);
1699 Convert.ImplicitConversionExists (ec, lexpr, TypeManager.string_type) &&
1700 Convert.ImplicitConversionExists (ec, rexpr, TypeManager.string_type);
1701 if (strConv && left != null && right != null)
1702 Error_OperatorAmbiguous (loc, oper, l, r);
1704 type = TypeManager.int32_type;
1707 return (left != null) && (right != null);
1710 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
1712 Error_OperatorCannotBeApplied (loc, name, TypeManager.CSharpName (l), TypeManager.CSharpName (r));
1715 public static void Error_OperatorCannotBeApplied (Location loc, string name, string left, string right)
1717 Report.Error (19, loc, "Operator `{0}' cannot be applied to operands of type `{1}' and `{2}'",
1721 void Error_OperatorCannotBeApplied ()
1723 Error_OperatorCannotBeApplied (Location, OperName (oper), left.GetSignatureForError (), right.GetSignatureForError ());
1726 static bool is_unsigned (Type t)
1728 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
1729 t == TypeManager.short_type || t == TypeManager.byte_type);
1732 static bool is_user_defined (Type t)
1734 if (t.IsSubclassOf (TypeManager.value_type) &&
1735 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
1741 Expression Make32or64 (EmitContext ec, Expression e)
1745 if (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
1746 t == TypeManager.int64_type || t == TypeManager.uint64_type)
1748 Expression ee = Convert.ImplicitConversion (ec, e, TypeManager.int32_type, loc);
1751 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint32_type, loc);
1754 ee = Convert.ImplicitConversion (ec, e, TypeManager.int64_type, loc);
1757 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint64_type, loc);
1763 Expression CheckShiftArguments (EmitContext ec)
1767 e = ForceConversion (ec, right, TypeManager.int32_type);
1769 Error_OperatorCannotBeApplied ();
1774 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
1775 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
1776 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
1777 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
1781 if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
1782 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntConstant (31, loc));
1783 right = right.DoResolve (ec);
1785 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntConstant (63, loc));
1786 right = right.DoResolve (ec);
1791 Error_OperatorCannotBeApplied ();
1796 // This is used to check if a test 'x == null' can be optimized to a reference equals,
1797 // i.e., not invoke op_Equality.
1799 static bool EqualsNullIsReferenceEquals (Type t)
1801 return t == TypeManager.object_type || t == TypeManager.string_type ||
1802 t == TypeManager.delegate_type || t.IsSubclassOf (TypeManager.delegate_type);
1805 static void Warning_UnintendedReferenceComparison (Location loc, string side, Type type)
1807 Report.Warning ((side == "left" ? 252 : 253), 2, loc,
1808 "Possible unintended reference comparison; to get a value comparison, " +
1809 "cast the {0} hand side to type `{1}'.", side, TypeManager.CSharpName (type));
1812 Expression ResolveOperator (EmitContext ec)
1815 Type r = right.Type;
1817 if (oper == Operator.Equality || oper == Operator.Inequality){
1819 // Optimize out call to op_Equality in a few cases.
1821 if ((l == TypeManager.null_type && EqualsNullIsReferenceEquals (r)) ||
1822 (r == TypeManager.null_type && EqualsNullIsReferenceEquals (l))) {
1824 Type = TypeManager.bool_type;
1830 if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
1831 Type = TypeManager.bool_type;
1838 // Do not perform operator overload resolution when both sides are
1841 Expression left_operators = null, right_operators = null;
1842 if (!(TypeManager.IsPrimitiveType (l) && TypeManager.IsPrimitiveType (r))){
1844 // Step 1: Perform Operator Overload location
1846 string op = oper_names [(int) oper];
1848 MethodGroupExpr union;
1849 left_operators = MemberLookup (ec.ContainerType, l, op, MemberTypes.Method, AllBindingFlags, loc);
1851 right_operators = MemberLookup (
1852 ec.ContainerType, r, op, MemberTypes.Method, AllBindingFlags, loc);
1853 union = Invocation.MakeUnionSet (left_operators, right_operators, loc);
1855 union = (MethodGroupExpr) left_operators;
1857 if (union != null) {
1858 ArrayList args = new ArrayList (2);
1859 args.Add (new Argument (left, Argument.AType.Expression));
1860 args.Add (new Argument (right, Argument.AType.Expression));
1862 MethodBase method = Invocation.OverloadResolve (
1863 ec, union, args, true, Location.Null);
1865 if (method != null) {
1866 MethodInfo mi = (MethodInfo) method;
1868 return new BinaryMethod (mi.ReturnType, method, args);
1874 // Step 0: String concatenation (because overloading will get this wrong)
1876 if (oper == Operator.Addition){
1878 // If any of the arguments is a string, cast to string
1881 // Simple constant folding
1882 if (left is StringConstant && right is StringConstant)
1883 return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value, left.Location);
1885 if (l == TypeManager.string_type || r == TypeManager.string_type) {
1887 if (r == TypeManager.void_type || l == TypeManager.void_type) {
1888 Error_OperatorCannotBeApplied ();
1892 // try to fold it in on the left
1893 if (left is StringConcat) {
1896 // We have to test here for not-null, since we can be doubly-resolved
1897 // take care of not appending twice
1900 type = TypeManager.string_type;
1901 ((StringConcat) left).Append (ec, right);
1902 return left.Resolve (ec);
1908 // Otherwise, start a new concat expression
1909 return new StringConcat (ec, loc, left, right).Resolve (ec);
1913 // Transform a + ( - b) into a - b
1915 if (right is Unary){
1916 Unary right_unary = (Unary) right;
1918 if (right_unary.Oper == Unary.Operator.UnaryNegation){
1919 oper = Operator.Subtraction;
1920 right = right_unary.Expr;
1926 if (oper == Operator.Equality || oper == Operator.Inequality){
1927 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1928 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1929 Error_OperatorCannotBeApplied ();
1933 type = TypeManager.bool_type;
1937 if (l.IsPointer || r.IsPointer) {
1938 if (l.IsPointer && r.IsPointer) {
1939 type = TypeManager.bool_type;
1943 if (l.IsPointer && r == TypeManager.null_type) {
1944 right = new EmptyCast (NullPointer.Null, l);
1945 type = TypeManager.bool_type;
1949 if (r.IsPointer && l == TypeManager.null_type) {
1950 left = new EmptyCast (NullPointer.Null, r);
1951 type = TypeManager.bool_type;
1957 // operator != (object a, object b)
1958 // operator == (object a, object b)
1960 // For this to be used, both arguments have to be reference-types.
1961 // Read the rationale on the spec (14.9.6)
1963 if (!(l.IsValueType || r.IsValueType)){
1964 type = TypeManager.bool_type;
1970 // Also, a standard conversion must exist from either one
1972 bool left_to_right =
1973 Convert.ImplicitStandardConversionExists (left, r);
1974 bool right_to_left = !left_to_right &&
1975 Convert.ImplicitStandardConversionExists (right, l);
1977 if (!left_to_right && !right_to_left) {
1978 Error_OperatorCannotBeApplied ();
1982 if (left_to_right && left_operators != null &&
1983 RootContext.WarningLevel >= 2) {
1984 ArrayList args = new ArrayList (2);
1985 args.Add (new Argument (left, Argument.AType.Expression));
1986 args.Add (new Argument (left, Argument.AType.Expression));
1987 MethodBase method = Invocation.OverloadResolve (
1988 ec, (MethodGroupExpr) left_operators, args, true, Location.Null);
1990 Warning_UnintendedReferenceComparison (loc, "right", l);
1993 if (right_to_left && right_operators != null &&
1994 RootContext.WarningLevel >= 2) {
1995 ArrayList args = new ArrayList (2);
1996 args.Add (new Argument (right, Argument.AType.Expression));
1997 args.Add (new Argument (right, Argument.AType.Expression));
1998 MethodBase method = Invocation.OverloadResolve (
1999 ec, (MethodGroupExpr) right_operators, args, true, Location.Null);
2001 Warning_UnintendedReferenceComparison (loc, "left", r);
2005 // We are going to have to convert to an object to compare
2007 if (l != TypeManager.object_type)
2008 left = new EmptyCast (left, TypeManager.object_type);
2009 if (r != TypeManager.object_type)
2010 right = new EmptyCast (right, TypeManager.object_type);
2013 // FIXME: CSC here catches errors cs254 and cs252
2019 // One of them is a valuetype, but the other one is not.
2021 if (!l.IsValueType || !r.IsValueType) {
2022 Error_OperatorCannotBeApplied ();
2027 // Only perform numeric promotions on:
2028 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2030 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2031 if (TypeManager.IsDelegateType (l)){
2032 if (((right.eclass == ExprClass.MethodGroup) ||
2033 (r == TypeManager.anonymous_method_type))){
2034 if ((RootContext.Version != LanguageVersion.ISO_1)){
2035 Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2043 if (TypeManager.IsDelegateType (r)){
2045 ArrayList args = new ArrayList (2);
2047 args = new ArrayList (2);
2048 args.Add (new Argument (left, Argument.AType.Expression));
2049 args.Add (new Argument (right, Argument.AType.Expression));
2051 if (oper == Operator.Addition)
2052 method = TypeManager.delegate_combine_delegate_delegate;
2054 method = TypeManager.delegate_remove_delegate_delegate;
2057 Error_OperatorCannotBeApplied ();
2061 return new BinaryDelegate (l, method, args);
2066 // Pointer arithmetic:
2068 // T* operator + (T* x, int y);
2069 // T* operator + (T* x, uint y);
2070 // T* operator + (T* x, long y);
2071 // T* operator + (T* x, ulong y);
2073 // T* operator + (int y, T* x);
2074 // T* operator + (uint y, T *x);
2075 // T* operator + (long y, T *x);
2076 // T* operator + (ulong y, T *x);
2078 // T* operator - (T* x, int y);
2079 // T* operator - (T* x, uint y);
2080 // T* operator - (T* x, long y);
2081 // T* operator - (T* x, ulong y);
2083 // long operator - (T* x, T *y)
2086 if (r.IsPointer && oper == Operator.Subtraction){
2088 return new PointerArithmetic (
2089 false, left, right, TypeManager.int64_type,
2092 Expression t = Make32or64 (ec, right);
2094 return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc).Resolve (ec);
2096 } else if (r.IsPointer && oper == Operator.Addition){
2097 Expression t = Make32or64 (ec, left);
2099 return new PointerArithmetic (true, right, t, r, loc).Resolve (ec);
2104 // Enumeration operators
2106 bool lie = TypeManager.IsEnumType (l);
2107 bool rie = TypeManager.IsEnumType (r);
2111 // U operator - (E e, E f)
2113 if (oper == Operator.Subtraction){
2115 type = TypeManager.EnumToUnderlying (l);
2118 Error_OperatorCannotBeApplied ();
2124 // operator + (E e, U x)
2125 // operator - (E e, U x)
2127 if (oper == Operator.Addition || oper == Operator.Subtraction){
2128 Type enum_type = lie ? l : r;
2129 Type other_type = lie ? r : l;
2130 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2132 if (underlying_type != other_type){
2133 temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
2143 Error_OperatorCannotBeApplied ();
2152 temp = Convert.ImplicitConversion (ec, right, l, loc);
2156 Error_OperatorCannotBeApplied ();
2160 temp = Convert.ImplicitConversion (ec, left, r, loc);
2165 Error_OperatorCannotBeApplied ();
2170 if (oper == Operator.Equality || oper == Operator.Inequality ||
2171 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2172 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2173 if (left.Type != right.Type){
2174 Error_OperatorCannotBeApplied ();
2177 type = TypeManager.bool_type;
2181 if (oper == Operator.BitwiseAnd ||
2182 oper == Operator.BitwiseOr ||
2183 oper == Operator.ExclusiveOr){
2184 if (left.Type != right.Type){
2185 Error_OperatorCannotBeApplied ();
2191 Error_OperatorCannotBeApplied ();
2195 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2196 return CheckShiftArguments (ec);
2198 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2199 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2200 type = TypeManager.bool_type;
2205 Error_OperatorCannotBeApplied ();
2209 Expression e = new ConditionalLogicalOperator (
2210 oper == Operator.LogicalAnd, left, right, l, loc);
2211 return e.Resolve (ec);
2215 // operator & (bool x, bool y)
2216 // operator | (bool x, bool y)
2217 // operator ^ (bool x, bool y)
2219 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2220 if (oper == Operator.BitwiseAnd ||
2221 oper == Operator.BitwiseOr ||
2222 oper == Operator.ExclusiveOr){
2229 // Pointer comparison
2231 if (l.IsPointer && r.IsPointer){
2232 if (oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2233 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2234 type = TypeManager.bool_type;
2240 // This will leave left or right set to null if there is an error
2242 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2243 DoNumericPromotions (ec, l, r, left, right, check_user_conv);
2244 if (left == null || right == null){
2245 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2250 // reload our cached types if required
2255 if (oper == Operator.BitwiseAnd ||
2256 oper == Operator.BitwiseOr ||
2257 oper == Operator.ExclusiveOr){
2259 if (((l == TypeManager.int32_type) ||
2260 (l == TypeManager.uint32_type) ||
2261 (l == TypeManager.short_type) ||
2262 (l == TypeManager.ushort_type) ||
2263 (l == TypeManager.int64_type) ||
2264 (l == TypeManager.uint64_type))){
2267 Error_OperatorCannotBeApplied ();
2271 Error_OperatorCannotBeApplied ();
2276 if (oper == Operator.Equality ||
2277 oper == Operator.Inequality ||
2278 oper == Operator.LessThanOrEqual ||
2279 oper == Operator.LessThan ||
2280 oper == Operator.GreaterThanOrEqual ||
2281 oper == Operator.GreaterThan){
2282 type = TypeManager.bool_type;
2288 Constant EnumLiftUp (Constant left, Constant right)
2291 case Operator.BitwiseOr:
2292 case Operator.BitwiseAnd:
2293 case Operator.ExclusiveOr:
2294 case Operator.Equality:
2295 case Operator.Inequality:
2296 case Operator.LessThan:
2297 case Operator.LessThanOrEqual:
2298 case Operator.GreaterThan:
2299 case Operator.GreaterThanOrEqual:
2300 if (left is EnumConstant)
2303 if (left.IsZeroInteger)
2304 return new EnumConstant (left, right.Type);
2308 case Operator.Addition:
2309 case Operator.Subtraction:
2312 case Operator.Multiply:
2313 case Operator.Division:
2314 case Operator.Modulus:
2315 case Operator.LeftShift:
2316 case Operator.RightShift:
2317 if (right is EnumConstant || left is EnumConstant)
2321 Error_OperatorCannotBeApplied (loc, Binary.OperName (oper), left.Type, right.Type);
2325 public override Expression DoResolve (EmitContext ec)
2330 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2331 left = ((ParenthesizedExpression) left).Expr;
2332 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2336 if (left.eclass == ExprClass.Type) {
2337 Report.Error (75, loc, "To cast a negative value, you must enclose the value in parentheses");
2341 left = left.Resolve (ec);
2346 Constant lc = left as Constant;
2347 if (lc != null && lc.Type == TypeManager.bool_type &&
2348 ((oper == Operator.LogicalAnd && (bool)lc.GetValue () == false) ||
2349 (oper == Operator.LogicalOr && (bool)lc.GetValue () == true))) {
2351 // TODO: make a sense to resolve unreachable expression as we do for statement
2352 Report.Warning (429, 4, loc, "Unreachable expression code detected");
2356 right = right.Resolve (ec);
2360 eclass = ExprClass.Value;
2361 Constant rc = right as Constant;
2363 // The conversion rules are ignored in enum context but why
2364 if (!ec.InEnumContext && lc != null && rc != null && (TypeManager.IsEnumType (left.Type) || TypeManager.IsEnumType (right.Type))) {
2365 left = lc = EnumLiftUp (lc, rc);
2369 right = rc = EnumLiftUp (rc, lc);
2374 if (oper == Operator.BitwiseAnd) {
2375 if (rc != null && rc.IsZeroInteger) {
2376 return lc is EnumConstant ?
2377 new EnumConstant (rc, lc.Type):
2381 if (lc != null && lc.IsZeroInteger) {
2382 return rc is EnumConstant ?
2383 new EnumConstant (lc, rc.Type):
2387 else if (oper == Operator.BitwiseOr) {
2388 if (lc is EnumConstant &&
2389 rc != null && rc.IsZeroInteger)
2391 if (rc is EnumConstant &&
2392 lc != null && lc.IsZeroInteger)
2394 } else if (oper == Operator.LogicalAnd) {
2395 if (rc != null && rc.IsDefaultValue && rc.Type == TypeManager.bool_type)
2397 if (lc != null && lc.IsDefaultValue && lc.Type == TypeManager.bool_type)
2401 if (rc != null && lc != null){
2402 int prev_e = Report.Errors;
2403 Expression e = ConstantFold.BinaryFold (
2404 ec, oper, lc, rc, loc);
2405 if (e != null || Report.Errors != prev_e)
2409 // Comparison warnings
2410 if (oper == Operator.Equality || oper == Operator.Inequality ||
2411 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2412 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2413 if (left.Equals (right)) {
2414 Report.Warning (1718, 3, loc, "Comparison made to same variable; did you mean to compare something else?");
2416 CheckUselessComparison (lc, right.Type);
2417 CheckUselessComparison (rc, left.Type);
2420 return ResolveOperator (ec);
2423 public override TypeExpr ResolveAsTypeTerminal (IResolveContext ec, bool silent)
2428 private void CheckUselessComparison (Constant c, Type type)
2430 if (c == null || !IsTypeIntegral (type)
2431 || c is StringConstant
2432 || c is BoolConstant
2433 || c is CharConstant
2434 || c is FloatConstant
2435 || c is DoubleConstant
2436 || c is DecimalConstant
2442 if (c is ULongConstant) {
2443 ulong uvalue = ((ULongConstant) c).Value;
2444 if (uvalue > long.MaxValue) {
2445 if (type == TypeManager.byte_type ||
2446 type == TypeManager.sbyte_type ||
2447 type == TypeManager.short_type ||
2448 type == TypeManager.ushort_type ||
2449 type == TypeManager.int32_type ||
2450 type == TypeManager.uint32_type ||
2451 type == TypeManager.int64_type)
2452 WarnUselessComparison (type);
2455 value = (long) uvalue;
2457 else if (c is ByteConstant)
2458 value = ((ByteConstant) c).Value;
2459 else if (c is SByteConstant)
2460 value = ((SByteConstant) c).Value;
2461 else if (c is ShortConstant)
2462 value = ((ShortConstant) c).Value;
2463 else if (c is UShortConstant)
2464 value = ((UShortConstant) c).Value;
2465 else if (c is IntConstant)
2466 value = ((IntConstant) c).Value;
2467 else if (c is UIntConstant)
2468 value = ((UIntConstant) c).Value;
2469 else if (c is LongConstant)
2470 value = ((LongConstant) c).Value;
2473 if (IsValueOutOfRange (value, type))
2474 WarnUselessComparison (type);
2479 private bool IsValueOutOfRange (long value, Type type)
2481 if (IsTypeUnsigned (type) && value < 0)
2483 return type == TypeManager.sbyte_type && (value >= 0x80 || value < -0x80) ||
2484 type == TypeManager.byte_type && value >= 0x100 ||
2485 type == TypeManager.short_type && (value >= 0x8000 || value < -0x8000) ||
2486 type == TypeManager.ushort_type && value >= 0x10000 ||
2487 type == TypeManager.int32_type && (value >= 0x80000000 || value < -0x80000000) ||
2488 type == TypeManager.uint32_type && value >= 0x100000000;
2491 private static bool IsTypeIntegral (Type type)
2493 return type == TypeManager.uint64_type ||
2494 type == TypeManager.int64_type ||
2495 type == TypeManager.uint32_type ||
2496 type == TypeManager.int32_type ||
2497 type == TypeManager.ushort_type ||
2498 type == TypeManager.short_type ||
2499 type == TypeManager.sbyte_type ||
2500 type == TypeManager.byte_type;
2503 private static bool IsTypeUnsigned (Type type)
2505 return type == TypeManager.uint64_type ||
2506 type == TypeManager.uint32_type ||
2507 type == TypeManager.ushort_type ||
2508 type == TypeManager.byte_type;
2511 private void WarnUselessComparison (Type type)
2513 Report.Warning (652, 2, loc, "Comparison to integral constant is useless; the constant is outside the range of type `{0}'",
2514 TypeManager.CSharpName (type));
2518 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2519 /// context of a conditional bool expression. This function will return
2520 /// false if it is was possible to use EmitBranchable, or true if it was.
2522 /// The expression's code is generated, and we will generate a branch to `target'
2523 /// if the resulting expression value is equal to isTrue
2525 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2527 ILGenerator ig = ec.ig;
2530 // This is more complicated than it looks, but its just to avoid
2531 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2532 // but on top of that we want for == and != to use a special path
2533 // if we are comparing against null
2535 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
2536 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2539 // put the constant on the rhs, for simplicity
2541 if (left is Constant) {
2542 Expression swap = right;
2547 if (((Constant) right).IsZeroInteger) {
2550 ig.Emit (OpCodes.Brtrue, target);
2552 ig.Emit (OpCodes.Brfalse, target);
2555 } else if (right is BoolConstant) {
2557 if (my_on_true != ((BoolConstant) right).Value)
2558 ig.Emit (OpCodes.Brtrue, target);
2560 ig.Emit (OpCodes.Brfalse, target);
2565 } else if (oper == Operator.LogicalAnd) {
2568 Label tests_end = ig.DefineLabel ();
2570 left.EmitBranchable (ec, tests_end, false);
2571 right.EmitBranchable (ec, target, true);
2572 ig.MarkLabel (tests_end);
2574 left.EmitBranchable (ec, target, false);
2575 right.EmitBranchable (ec, target, false);
2580 } else if (oper == Operator.LogicalOr){
2582 left.EmitBranchable (ec, target, true);
2583 right.EmitBranchable (ec, target, true);
2586 Label tests_end = ig.DefineLabel ();
2587 left.EmitBranchable (ec, tests_end, true);
2588 right.EmitBranchable (ec, target, false);
2589 ig.MarkLabel (tests_end);
2594 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2595 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2596 oper == Operator.Equality || oper == Operator.Inequality)) {
2597 base.EmitBranchable (ec, target, onTrue);
2605 bool isUnsigned = is_unsigned (t) || t == TypeManager.double_type || t == TypeManager.float_type;
2608 case Operator.Equality:
2610 ig.Emit (OpCodes.Beq, target);
2612 ig.Emit (OpCodes.Bne_Un, target);
2615 case Operator.Inequality:
2617 ig.Emit (OpCodes.Bne_Un, target);
2619 ig.Emit (OpCodes.Beq, target);
2622 case Operator.LessThan:
2625 ig.Emit (OpCodes.Blt_Un, target);
2627 ig.Emit (OpCodes.Blt, target);
2630 ig.Emit (OpCodes.Bge_Un, target);
2632 ig.Emit (OpCodes.Bge, target);
2635 case Operator.GreaterThan:
2638 ig.Emit (OpCodes.Bgt_Un, target);
2640 ig.Emit (OpCodes.Bgt, target);
2643 ig.Emit (OpCodes.Ble_Un, target);
2645 ig.Emit (OpCodes.Ble, target);
2648 case Operator.LessThanOrEqual:
2651 ig.Emit (OpCodes.Ble_Un, target);
2653 ig.Emit (OpCodes.Ble, target);
2656 ig.Emit (OpCodes.Bgt_Un, target);
2658 ig.Emit (OpCodes.Bgt, target);
2662 case Operator.GreaterThanOrEqual:
2665 ig.Emit (OpCodes.Bge_Un, target);
2667 ig.Emit (OpCodes.Bge, target);
2670 ig.Emit (OpCodes.Blt_Un, target);
2672 ig.Emit (OpCodes.Blt, target);
2675 Console.WriteLine (oper);
2676 throw new Exception ("what is THAT");
2680 public override void Emit (EmitContext ec)
2682 ILGenerator ig = ec.ig;
2687 // Handle short-circuit operators differently
2690 if (oper == Operator.LogicalAnd) {
2691 Label load_zero = ig.DefineLabel ();
2692 Label end = ig.DefineLabel ();
2694 left.EmitBranchable (ec, load_zero, false);
2696 ig.Emit (OpCodes.Br, end);
2698 ig.MarkLabel (load_zero);
2699 ig.Emit (OpCodes.Ldc_I4_0);
2702 } else if (oper == Operator.LogicalOr) {
2703 Label load_one = ig.DefineLabel ();
2704 Label end = ig.DefineLabel ();
2706 left.EmitBranchable (ec, load_one, true);
2708 ig.Emit (OpCodes.Br, end);
2710 ig.MarkLabel (load_one);
2711 ig.Emit (OpCodes.Ldc_I4_1);
2719 bool isUnsigned = is_unsigned (left.Type);
2722 case Operator.Multiply:
2724 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2725 opcode = OpCodes.Mul_Ovf;
2726 else if (isUnsigned)
2727 opcode = OpCodes.Mul_Ovf_Un;
2729 opcode = OpCodes.Mul;
2731 opcode = OpCodes.Mul;
2735 case Operator.Division:
2737 opcode = OpCodes.Div_Un;
2739 opcode = OpCodes.Div;
2742 case Operator.Modulus:
2744 opcode = OpCodes.Rem_Un;
2746 opcode = OpCodes.Rem;
2749 case Operator.Addition:
2751 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2752 opcode = OpCodes.Add_Ovf;
2753 else if (isUnsigned)
2754 opcode = OpCodes.Add_Ovf_Un;
2756 opcode = OpCodes.Add;
2758 opcode = OpCodes.Add;
2761 case Operator.Subtraction:
2763 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2764 opcode = OpCodes.Sub_Ovf;
2765 else if (isUnsigned)
2766 opcode = OpCodes.Sub_Ovf_Un;
2768 opcode = OpCodes.Sub;
2770 opcode = OpCodes.Sub;
2773 case Operator.RightShift:
2775 opcode = OpCodes.Shr_Un;
2777 opcode = OpCodes.Shr;
2780 case Operator.LeftShift:
2781 opcode = OpCodes.Shl;
2784 case Operator.Equality:
2785 opcode = OpCodes.Ceq;
2788 case Operator.Inequality:
2789 ig.Emit (OpCodes.Ceq);
2790 ig.Emit (OpCodes.Ldc_I4_0);
2792 opcode = OpCodes.Ceq;
2795 case Operator.LessThan:
2797 opcode = OpCodes.Clt_Un;
2799 opcode = OpCodes.Clt;
2802 case Operator.GreaterThan:
2804 opcode = OpCodes.Cgt_Un;
2806 opcode = OpCodes.Cgt;
2809 case Operator.LessThanOrEqual:
2810 Type lt = left.Type;
2812 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
2813 ig.Emit (OpCodes.Cgt_Un);
2815 ig.Emit (OpCodes.Cgt);
2816 ig.Emit (OpCodes.Ldc_I4_0);
2818 opcode = OpCodes.Ceq;
2821 case Operator.GreaterThanOrEqual:
2822 Type le = left.Type;
2824 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
2825 ig.Emit (OpCodes.Clt_Un);
2827 ig.Emit (OpCodes.Clt);
2829 ig.Emit (OpCodes.Ldc_I4_0);
2831 opcode = OpCodes.Ceq;
2834 case Operator.BitwiseOr:
2835 opcode = OpCodes.Or;
2838 case Operator.BitwiseAnd:
2839 opcode = OpCodes.And;
2842 case Operator.ExclusiveOr:
2843 opcode = OpCodes.Xor;
2847 throw new Exception ("This should not happen: Operator = "
2848 + oper.ToString ());
2856 // Object created by Binary when the binary operator uses an method instead of being
2857 // a binary operation that maps to a CIL binary operation.
2859 public class BinaryMethod : Expression {
2860 public MethodBase method;
2861 public ArrayList Arguments;
2863 public BinaryMethod (Type t, MethodBase m, ArrayList args)
2868 eclass = ExprClass.Value;
2871 public override Expression DoResolve (EmitContext ec)
2876 public override void Emit (EmitContext ec)
2878 ILGenerator ig = ec.ig;
2880 if (Arguments != null)
2881 Invocation.EmitArguments (ec, method, Arguments, false, null);
2883 if (method is MethodInfo)
2884 ig.Emit (OpCodes.Call, (MethodInfo) method);
2886 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2891 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
2892 // b, c, d... may be strings or objects.
2894 public class StringConcat : Expression {
2896 bool invalid = false;
2897 bool emit_conv_done = false;
2899 // Are we also concating objects?
2901 bool is_strings_only = true;
2903 public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
2906 type = TypeManager.string_type;
2907 eclass = ExprClass.Value;
2909 operands = new ArrayList (2);
2914 public override Expression DoResolve (EmitContext ec)
2922 public void Append (EmitContext ec, Expression operand)
2927 StringConstant sc = operand as StringConstant;
2929 // TODO: it will be better to do this silently as an optimalization
2931 // string s = "" + i;
2932 // because this code has poor performace
2933 // if (sc.Value.Length == 0)
2934 // Report.Warning (-300, 3, Location, "Appending an empty string has no effect. Did you intend to append a space string?");
2936 if (operands.Count != 0) {
2937 StringConstant last_operand = operands [operands.Count - 1] as StringConstant;
2938 if (last_operand != null) {
2939 operands [operands.Count - 1] = new StringConstant (last_operand.Value + ((StringConstant) operand).Value, last_operand.Location);
2946 // Conversion to object
2948 if (operand.Type != TypeManager.string_type) {
2949 Expression no = Convert.ImplicitConversion (ec, operand, TypeManager.object_type, loc);
2952 Binary.Error_OperatorCannotBeApplied (loc, "+", TypeManager.string_type, operand.Type);
2958 operands.Add (operand);
2961 public override void Emit (EmitContext ec)
2963 MethodInfo concat_method = null;
2966 // Do conversion to arguments; check for strings only
2969 // This can get called multiple times, so we have to deal with that.
2970 if (!emit_conv_done) {
2971 emit_conv_done = true;
2972 for (int i = 0; i < operands.Count; i ++) {
2973 Expression e = (Expression) operands [i];
2974 is_strings_only &= e.Type == TypeManager.string_type;
2977 for (int i = 0; i < operands.Count; i ++) {
2978 Expression e = (Expression) operands [i];
2980 if (! is_strings_only && e.Type == TypeManager.string_type) {
2981 // need to make sure this is an object, because the EmitParams
2982 // method might look at the type of this expression, see it is a
2983 // string and emit a string [] when we want an object [];
2985 e = new EmptyCast (e, TypeManager.object_type);
2987 operands [i] = new Argument (e, Argument.AType.Expression);
2992 // Find the right method
2994 switch (operands.Count) {
2997 // This should not be possible, because simple constant folding
2998 // is taken care of in the Binary code.
3000 throw new Exception ("how did you get here?");
3003 concat_method = is_strings_only ?
3004 TypeManager.string_concat_string_string :
3005 TypeManager.string_concat_object_object ;
3008 concat_method = is_strings_only ?
3009 TypeManager.string_concat_string_string_string :
3010 TypeManager.string_concat_object_object_object ;
3014 // There is not a 4 param overlaod for object (the one that there is
3015 // is actually a varargs methods, and is only in corlib because it was
3016 // introduced there before.).
3018 if (!is_strings_only)
3021 concat_method = TypeManager.string_concat_string_string_string_string;
3024 concat_method = is_strings_only ?
3025 TypeManager.string_concat_string_dot_dot_dot :
3026 TypeManager.string_concat_object_dot_dot_dot ;
3030 Invocation.EmitArguments (ec, concat_method, operands, false, null);
3031 ec.ig.Emit (OpCodes.Call, concat_method);
3036 // Object created with +/= on delegates
3038 public class BinaryDelegate : Expression {
3042 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3047 eclass = ExprClass.Value;
3050 public override Expression DoResolve (EmitContext ec)
3055 public override void Emit (EmitContext ec)
3057 ILGenerator ig = ec.ig;
3059 Invocation.EmitArguments (ec, method, args, false, null);
3061 ig.Emit (OpCodes.Call, (MethodInfo) method);
3062 ig.Emit (OpCodes.Castclass, type);
3065 public Expression Right {
3067 Argument arg = (Argument) args [1];
3072 public bool IsAddition {
3074 return method == TypeManager.delegate_combine_delegate_delegate;
3080 // User-defined conditional logical operator
3081 public class ConditionalLogicalOperator : Expression {
3082 Expression left, right;
3085 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3088 eclass = ExprClass.Value;
3092 this.is_and = is_and;
3095 protected void Error19 ()
3097 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", left.GetSignatureForError (), right.GetSignatureForError ());
3100 protected void Error218 ()
3102 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3103 "declarations of operator true and operator false");
3106 Expression op_true, op_false, op;
3107 LocalTemporary left_temp;
3109 public override Expression DoResolve (EmitContext ec)
3112 Expression operator_group;
3114 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3115 if (operator_group == null) {
3120 left_temp = new LocalTemporary (type);
3122 ArrayList arguments = new ArrayList ();
3123 arguments.Add (new Argument (left_temp, Argument.AType.Expression));
3124 arguments.Add (new Argument (right, Argument.AType.Expression));
3125 method = Invocation.OverloadResolve (
3126 ec, (MethodGroupExpr) operator_group, arguments, false, loc)
3128 if (method == null) {
3133 if (method.ReturnType != type) {
3134 Report.Error (217, loc, "In order to be applicable as a short circuit operator a user-defined logical operator `{0}' " +
3135 "must have the same return type as the type of its 2 parameters", TypeManager.CSharpSignature (method));
3139 op = new StaticCallExpr (method, arguments, loc);
3141 op_true = GetOperatorTrue (ec, left_temp, loc);
3142 op_false = GetOperatorFalse (ec, left_temp, loc);
3143 if ((op_true == null) || (op_false == null)) {
3151 public override void Emit (EmitContext ec)
3153 ILGenerator ig = ec.ig;
3154 Label false_target = ig.DefineLabel ();
3155 Label end_target = ig.DefineLabel ();
3158 left_temp.Store (ec);
3160 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
3161 left_temp.Emit (ec);
3162 ig.Emit (OpCodes.Br, end_target);
3163 ig.MarkLabel (false_target);
3165 ig.MarkLabel (end_target);
3169 public class PointerArithmetic : Expression {
3170 Expression left, right;
3174 // We assume that `l' is always a pointer
3176 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3182 is_add = is_addition;
3185 public override Expression DoResolve (EmitContext ec)
3187 eclass = ExprClass.Variable;
3189 if (left.Type == TypeManager.void_ptr_type) {
3190 Error (242, "The operation in question is undefined on void pointers");
3197 public override void Emit (EmitContext ec)
3199 Type op_type = left.Type;
3200 ILGenerator ig = ec.ig;
3202 // It must be either array or fixed buffer
3203 Type element = TypeManager.HasElementType (op_type) ?
3204 element = TypeManager.GetElementType (op_type) :
3205 element = AttributeTester.GetFixedBuffer (((FieldExpr)left).FieldInfo).ElementType;
3207 int size = GetTypeSize (element);
3208 Type rtype = right.Type;
3210 if (rtype.IsPointer){
3212 // handle (pointer - pointer)
3216 ig.Emit (OpCodes.Sub);
3220 ig.Emit (OpCodes.Sizeof, element);
3222 IntLiteral.EmitInt (ig, size);
3223 ig.Emit (OpCodes.Div);
3225 ig.Emit (OpCodes.Conv_I8);
3228 // handle + and - on (pointer op int)
3231 ig.Emit (OpCodes.Conv_I);
3233 Constant right_const = right as Constant;
3234 if (right_const != null && size != 0) {
3235 Expression ex = ConstantFold.BinaryFold (ec, Binary.Operator.Multiply, new IntConstant (size, right.Location), right_const, loc);
3243 ig.Emit (OpCodes.Sizeof, element);
3245 IntLiteral.EmitInt (ig, size);
3246 if (rtype == TypeManager.int64_type)
3247 ig.Emit (OpCodes.Conv_I8);
3248 else if (rtype == TypeManager.uint64_type)
3249 ig.Emit (OpCodes.Conv_U8);
3250 ig.Emit (OpCodes.Mul);
3254 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
3255 ig.Emit (OpCodes.Conv_I);
3258 ig.Emit (OpCodes.Add);
3260 ig.Emit (OpCodes.Sub);
3266 /// Implements the ternary conditional operator (?:)
3268 public class Conditional : Expression {
3269 Expression expr, trueExpr, falseExpr;
3271 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr)
3274 this.trueExpr = trueExpr;
3275 this.falseExpr = falseExpr;
3276 this.loc = expr.Location;
3279 public Expression Expr {
3285 public Expression TrueExpr {
3291 public Expression FalseExpr {
3297 public override Expression DoResolve (EmitContext ec)
3299 expr = expr.Resolve (ec);
3304 if (expr.Type != TypeManager.bool_type){
3305 expr = Expression.ResolveBoolean (
3312 Assign ass = expr as Assign;
3313 if (ass != null && ass.Source is Constant) {
3314 Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
3317 trueExpr = trueExpr.Resolve (ec);
3318 falseExpr = falseExpr.Resolve (ec);
3320 if (trueExpr == null || falseExpr == null)
3323 eclass = ExprClass.Value;
3324 if (trueExpr.Type == falseExpr.Type)
3325 type = trueExpr.Type;
3328 Type true_type = trueExpr.Type;
3329 Type false_type = falseExpr.Type;
3332 // First, if an implicit conversion exists from trueExpr
3333 // to falseExpr, then the result type is of type falseExpr.Type
3335 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3338 // Check if both can convert implicitl to each other's type
3340 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3342 "Can not compute type of conditional expression " +
3343 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3344 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3345 "' convert implicitly to each other");
3350 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3354 Report.Error (173, loc, "Type of conditional expression cannot be determined because there is no implicit conversion between `{0}' and `{1}'",
3355 trueExpr.GetSignatureForError (), falseExpr.GetSignatureForError ());
3360 // Dead code optimalization
3361 if (expr is BoolConstant){
3362 BoolConstant bc = (BoolConstant) expr;
3364 Report.Warning (429, 4, bc.Value ? falseExpr.Location : trueExpr.Location, "Unreachable expression code detected");
3365 return bc.Value ? trueExpr : falseExpr;
3371 public override TypeExpr ResolveAsTypeTerminal (IResolveContext ec, bool silent)
3376 public override void Emit (EmitContext ec)
3378 ILGenerator ig = ec.ig;
3379 Label false_target = ig.DefineLabel ();
3380 Label end_target = ig.DefineLabel ();
3382 expr.EmitBranchable (ec, false_target, false);
3384 ig.Emit (OpCodes.Br, end_target);
3385 ig.MarkLabel (false_target);
3386 falseExpr.Emit (ec);
3387 ig.MarkLabel (end_target);
3395 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3396 public readonly string Name;
3397 public readonly Block Block;
3398 public LocalInfo local_info;
3401 LocalTemporary temp;
3403 public LocalVariableReference (Block block, string name, Location l)
3408 eclass = ExprClass.Variable;
3412 // Setting `is_readonly' to false will allow you to create a writable
3413 // reference to a read-only variable. This is used by foreach and using.
3415 public LocalVariableReference (Block block, string name, Location l,
3416 LocalInfo local_info, bool is_readonly)
3417 : this (block, name, l)
3419 this.local_info = local_info;
3420 this.is_readonly = is_readonly;
3423 public VariableInfo VariableInfo {
3425 return local_info.VariableInfo;
3429 public bool IsReadOnly {
3435 public bool VerifyAssigned (EmitContext ec)
3437 VariableInfo variable_info = local_info.VariableInfo;
3438 return variable_info == null || variable_info.IsAssigned (ec, loc);
3441 protected Expression DoResolveBase (EmitContext ec, Expression lvalue_right_side)
3443 if (local_info == null) {
3444 local_info = Block.GetLocalInfo (Name);
3447 if (lvalue_right_side == EmptyExpression.OutAccess)
3448 local_info.Used = true;
3450 is_readonly = local_info.ReadOnly;
3453 type = local_info.VariableType;
3455 VariableInfo variable_info = local_info.VariableInfo;
3456 if (lvalue_right_side != null){
3458 if (lvalue_right_side is LocalVariableReference || lvalue_right_side == EmptyExpression.OutAccess)
3459 Report.Error (1657, loc, "Cannot pass `{0}' as a ref or out argument because it is a `{1}'",
3460 Name, local_info.GetReadOnlyContext ());
3461 else if (lvalue_right_side == EmptyExpression.LValueMemberAccess)
3462 Report.Error (1654, loc, "Cannot assign to members of `{0}' because it is a `{1}'",
3463 Name, local_info.GetReadOnlyContext ());
3465 Report.Error (1656, loc, "Cannot assign to `{0}' because it is a `{1}'",
3466 Name, local_info.GetReadOnlyContext ());
3470 if (variable_info != null)
3471 variable_info.SetAssigned (ec);
3474 Expression e = Block.GetConstantExpression (Name);
3476 local_info.Used = true;
3477 eclass = ExprClass.Value;
3478 return e.Resolve (ec);
3481 if (!VerifyAssigned (ec))
3484 if (lvalue_right_side == null)
3485 local_info.Used = true;
3487 if (ec.CurrentAnonymousMethod != null){
3489 // If we are referencing a variable from the external block
3490 // flag it for capturing
3492 if ((local_info.Block.Toplevel != ec.CurrentBlock.Toplevel) ||
3493 ec.CurrentAnonymousMethod.IsIterator)
3495 if (local_info.AddressTaken){
3496 AnonymousMethod.Error_AddressOfCapturedVar (local_info.Name, loc);
3499 ec.CaptureVariable (local_info);
3506 public override Expression DoResolve (EmitContext ec)
3508 return DoResolveBase (ec, null);
3511 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3513 return DoResolveBase (ec, right_side);
3516 public bool VerifyFixed ()
3518 // A local Variable is always fixed.
3522 public override int GetHashCode()
3524 return Name.GetHashCode ();
3527 public override bool Equals (object obj)
3529 LocalVariableReference lvr = obj as LocalVariableReference;
3533 return Name == lvr.Name && Block == lvr.Block;
3536 public override void Emit (EmitContext ec)
3538 ILGenerator ig = ec.ig;
3540 if (local_info.FieldBuilder == null){
3542 // A local variable on the local CLR stack
3544 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3547 // A local variable captured by anonymous methods.
3550 ec.EmitCapturedVariableInstance (local_info);
3552 ig.Emit (OpCodes.Ldfld, local_info.FieldBuilder);
3556 public void Emit (EmitContext ec, bool leave_copy)
3560 ec.ig.Emit (OpCodes.Dup);
3561 if (local_info.FieldBuilder != null){
3562 temp = new LocalTemporary (Type);
3568 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3570 ILGenerator ig = ec.ig;
3571 prepared = prepare_for_load;
3573 if (local_info.FieldBuilder == null){
3575 // A local variable on the local CLR stack
3577 if (local_info.LocalBuilder == null)
3578 throw new Exception ("This should not happen: both Field and Local are null");
3582 ec.ig.Emit (OpCodes.Dup);
3583 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3586 // A local variable captured by anonymous methods or itereators.
3588 ec.EmitCapturedVariableInstance (local_info);
3590 if (prepare_for_load)
3591 ig.Emit (OpCodes.Dup);
3594 ig.Emit (OpCodes.Dup);
3595 temp = new LocalTemporary (Type);
3598 ig.Emit (OpCodes.Stfld, local_info.FieldBuilder);
3604 public void AddressOf (EmitContext ec, AddressOp mode)
3606 ILGenerator ig = ec.ig;
3608 if (local_info.FieldBuilder == null){
3610 // A local variable on the local CLR stack
3612 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3615 // A local variable captured by anonymous methods or iterators
3617 ec.EmitCapturedVariableInstance (local_info);
3618 ig.Emit (OpCodes.Ldflda, local_info.FieldBuilder);
3622 public override string ToString ()
3624 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3629 /// This represents a reference to a parameter in the intermediate
3632 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3638 public bool is_ref, is_out, prepared;
3652 LocalTemporary temp;
3654 public ParameterReference (Parameter par, Block block, int idx, Location loc)
3657 this.name = par.Name;
3661 eclass = ExprClass.Variable;
3664 public VariableInfo VariableInfo {
3668 public bool VerifyFixed ()
3670 // A parameter is fixed if it's a value parameter (i.e., no modifier like out, ref, param).
3671 return par.ModFlags == Parameter.Modifier.NONE;
3674 public bool IsAssigned (EmitContext ec, Location loc)
3676 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsAssigned (vi))
3679 Report.Error (269, loc,
3680 "Use of unassigned out parameter `{0}'", par.Name);
3684 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3686 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3689 Report.Error (170, loc,
3690 "Use of possibly unassigned field `" + field_name + "'");
3694 public void SetAssigned (EmitContext ec)
3696 if (is_out && ec.DoFlowAnalysis)
3697 ec.CurrentBranching.SetAssigned (vi);
3700 public void SetFieldAssigned (EmitContext ec, string field_name)
3702 if (is_out && ec.DoFlowAnalysis)
3703 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3706 protected bool DoResolveBase (EmitContext ec)
3708 if (!par.Resolve (ec)) {
3712 type = par.ParameterType;
3713 Parameter.Modifier mod = par.ModFlags;
3714 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3715 is_out = (mod & Parameter.Modifier.OUT) == Parameter.Modifier.OUT;
3716 eclass = ExprClass.Variable;
3719 vi = block.ParameterMap [idx];
3721 if (ec.CurrentAnonymousMethod != null){
3722 if (is_ref && !block.Toplevel.IsLocalParameter (name)){
3723 Report.Error (1628, Location, "Cannot use ref or out parameter `{0}' inside an anonymous method block",
3729 // If we are referencing the parameter from the external block
3730 // flag it for capturing
3732 //Console.WriteLine ("Is parameter `{0}' local? {1}", name, block.IsLocalParameter (name));
3733 if (!block.Toplevel.IsLocalParameter (name)){
3734 ec.CaptureParameter (name, type, idx);
3741 public override int GetHashCode()
3743 return name.GetHashCode ();
3746 public override bool Equals (object obj)
3748 ParameterReference pr = obj as ParameterReference;
3752 return name == pr.name && block == pr.block;
3756 // Notice that for ref/out parameters, the type exposed is not the
3757 // same type exposed externally.
3760 // externally we expose "int&"
3761 // here we expose "int".
3763 // We record this in "is_ref". This means that the type system can treat
3764 // the type as it is expected, but when we generate the code, we generate
3765 // the alternate kind of code.
3767 public override Expression DoResolve (EmitContext ec)
3769 if (!DoResolveBase (ec))
3772 if (is_out && ec.DoFlowAnalysis && (!ec.OmitStructFlowAnalysis || !vi.TypeInfo.IsStruct) && !IsAssigned (ec, loc))
3778 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3780 if (!DoResolveBase (ec))
3788 static public void EmitLdArg (ILGenerator ig, int x)
3792 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3793 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3794 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3795 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3796 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3799 ig.Emit (OpCodes.Ldarg, x);
3803 // This method is used by parameters that are references, that are
3804 // being passed as references: we only want to pass the pointer (that
3805 // is already stored in the parameter, not the address of the pointer,
3806 // and not the value of the variable).
3808 public void EmitLoad (EmitContext ec)
3810 ILGenerator ig = ec.ig;
3813 if (!ec.MethodIsStatic)
3816 EmitLdArg (ig, arg_idx);
3819 // FIXME: Review for anonymous methods
3823 public override void Emit (EmitContext ec)
3828 public void Emit (EmitContext ec, bool leave_copy)
3830 ILGenerator ig = ec.ig;
3833 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
3834 ec.EmitParameter (name, leave_copy, prepared, ref temp);
3838 if (!ec.MethodIsStatic)
3841 EmitLdArg (ig, arg_idx);
3845 ec.ig.Emit (OpCodes.Dup);
3848 // If we are a reference, we loaded on the stack a pointer
3849 // Now lets load the real value
3851 LoadFromPtr (ig, type);
3855 ec.ig.Emit (OpCodes.Dup);
3858 temp = new LocalTemporary (type);
3864 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3866 prepared = prepare_for_load;
3867 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
3868 ec.EmitAssignParameter (name, source, leave_copy, prepare_for_load, ref temp);
3872 ILGenerator ig = ec.ig;
3877 if (!ec.MethodIsStatic)
3880 if (is_ref && !prepared)
3881 EmitLdArg (ig, arg_idx);
3886 ec.ig.Emit (OpCodes.Dup);
3890 temp = new LocalTemporary (type);
3894 StoreFromPtr (ig, type);
3900 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
3902 ig.Emit (OpCodes.Starg, arg_idx);
3906 public void AddressOf (EmitContext ec, AddressOp mode)
3908 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
3909 ec.EmitAddressOfParameter (name);
3915 if (!ec.MethodIsStatic)
3920 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
3922 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
3925 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
3927 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
3931 public override string ToString ()
3933 return "ParameterReference[" + name + "]";
3938 /// Used for arguments to New(), Invocation()
3940 public class Argument {
3941 public enum AType : byte {
3948 public readonly AType ArgType;
3949 public Expression Expr;
3951 public Argument (Expression expr, AType type)
3954 this.ArgType = type;
3957 public Argument (Expression expr)
3960 this.ArgType = AType.Expression;
3965 if (ArgType == AType.Ref || ArgType == AType.Out)
3966 return TypeManager.GetReferenceType (Expr.Type);
3972 public Parameter.Modifier Modifier
3977 return Parameter.Modifier.OUT;
3980 return Parameter.Modifier.REF;
3983 return Parameter.Modifier.NONE;
3988 public static string FullDesc (Argument a)
3990 if (a.ArgType == AType.ArgList)
3993 return (a.ArgType == AType.Ref ? "ref " :
3994 (a.ArgType == AType.Out ? "out " : "")) +
3995 TypeManager.CSharpName (a.Expr.Type);
3998 public bool ResolveMethodGroup (EmitContext ec)
4000 // FIXME: csc doesn't report any error if you try to use `ref' or
4001 // `out' in a delegate creation expression.
4002 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4009 void Error_LValueRequired (Location loc)
4011 Report.Error (1510, loc, "A ref or out argument must be an assignable variable");
4014 public bool Resolve (EmitContext ec, Location loc)
4016 bool old_do_flow_analysis = ec.DoFlowAnalysis;
4017 ec.DoFlowAnalysis = true;
4019 if (ArgType == AType.Ref) {
4020 ec.InRefOutArgumentResolving = true;
4021 Expr = Expr.Resolve (ec);
4022 ec.InRefOutArgumentResolving = false;
4024 ec.DoFlowAnalysis = old_do_flow_analysis;
4028 int errors = Report.Errors;
4029 Expr = Expr.DoResolveLValue (ec, Expr);
4030 if (Expr == null && errors == Report.Errors)
4031 Error_LValueRequired (loc);
4032 } else if (ArgType == AType.Out) {
4033 int errors = Report.Errors;
4034 ec.InRefOutArgumentResolving = true;
4035 Expr = Expr.DoResolveLValue (ec, EmptyExpression.OutAccess);
4036 ec.InRefOutArgumentResolving = false;
4038 if (Expr == null && errors == Report.Errors)
4039 Error_LValueRequired (loc);
4042 Expr = Expr.Resolve (ec);
4044 ec.DoFlowAnalysis = old_do_flow_analysis;
4049 if (ArgType == AType.Expression)
4053 // Catch errors where fields of a MarshalByRefObject are passed as ref or out
4054 // This is only allowed for `this'
4056 FieldExpr fe = Expr as FieldExpr;
4057 if (fe != null && !fe.IsStatic){
4058 Expression instance = fe.InstanceExpression;
4060 if (instance.GetType () != typeof (This)){
4061 if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
4062 Report.SymbolRelatedToPreviousError (fe.InstanceExpression.Type);
4063 Report.Warning (197, 1, loc,
4064 "Passing `{0}' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class",
4065 fe.GetSignatureForError ());
4075 public void Emit (EmitContext ec)
4078 // Ref and Out parameters need to have their addresses taken.
4080 // ParameterReferences might already be references, so we want
4081 // to pass just the value
4083 if (ArgType == AType.Ref || ArgType == AType.Out){
4084 AddressOp mode = AddressOp.Store;
4086 if (ArgType == AType.Ref)
4087 mode |= AddressOp.Load;
4089 if (Expr is ParameterReference){
4090 ParameterReference pr = (ParameterReference) Expr;
4096 pr.AddressOf (ec, mode);
4099 if (Expr is IMemoryLocation)
4100 ((IMemoryLocation) Expr).AddressOf (ec, mode);
4102 Error_LValueRequired (Expr.Location);
4112 /// Invocation of methods or delegates.
4114 public class Invocation : ExpressionStatement {
4115 public readonly ArrayList Arguments;
4118 MethodBase method = null;
4121 // arguments is an ArrayList, but we do not want to typecast,
4122 // as it might be null.
4124 // FIXME: only allow expr to be a method invocation or a
4125 // delegate invocation (7.5.5)
4127 public Invocation (Expression expr, ArrayList arguments)
4130 Arguments = arguments;
4131 loc = expr.Location;
4134 public Expression Expr {
4141 /// Determines "better conversion" as specified in 14.4.2.3
4143 /// Returns : p if a->p is better,
4144 /// q if a->q is better,
4145 /// null if neither is better
4147 static Type BetterConversion (EmitContext ec, Argument a, Type p, Type q)
4149 Type argument_type = a.Type;
4150 Expression argument_expr = a.Expr;
4152 if (argument_type == null)
4153 throw new Exception ("Expression of type " + a.Expr +
4154 " does not resolve its type");
4156 if (p == null || q == null)
4157 throw new InternalErrorException ("BetterConversion Got a null conversion");
4162 if (argument_expr is NullLiteral) {
4164 // If the argument is null and one of the types to compare is 'object' and
4165 // the other is a reference type, we prefer the other.
4167 // This follows from the usual rules:
4168 // * There is an implicit conversion from 'null' to type 'object'
4169 // * There is an implicit conversion from 'null' to any reference type
4170 // * There is an implicit conversion from any reference type to type 'object'
4171 // * There is no implicit conversion from type 'object' to other reference types
4172 // => Conversion of 'null' to a reference type is better than conversion to 'object'
4174 // FIXME: This probably isn't necessary, since the type of a NullLiteral is the
4175 // null type. I think it used to be 'object' and thus needed a special
4176 // case to avoid the immediately following two checks.
4178 if (!p.IsValueType && q == TypeManager.object_type)
4180 if (!q.IsValueType && p == TypeManager.object_type)
4184 if (argument_type == p)
4187 if (argument_type == q)
4190 Expression p_tmp = new EmptyExpression (p);
4191 Expression q_tmp = new EmptyExpression (q);
4193 bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
4194 bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
4196 if (p_to_q && !q_to_p)
4199 if (q_to_p && !p_to_q)
4202 if (p == TypeManager.sbyte_type)
4203 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4204 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4206 if (q == TypeManager.sbyte_type)
4207 if (p == TypeManager.byte_type || p == TypeManager.ushort_type ||
4208 p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4211 if (p == TypeManager.short_type)
4212 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4213 q == TypeManager.uint64_type)
4215 if (q == TypeManager.short_type)
4216 if (p == TypeManager.ushort_type || p == TypeManager.uint32_type ||
4217 p == TypeManager.uint64_type)
4220 if (p == TypeManager.int32_type)
4221 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4223 if (q == TypeManager.int32_type)
4224 if (p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4227 if (p == TypeManager.int64_type)
4228 if (q == TypeManager.uint64_type)
4230 if (q == TypeManager.int64_type)
4231 if (p == TypeManager.uint64_type)
4238 /// Determines "Better function" between candidate
4239 /// and the current best match
4242 /// Returns a boolean indicating :
4243 /// false if candidate ain't better
4244 /// true if candidate is better than the current best match
4246 static bool BetterFunction (EmitContext ec, ArrayList args, int argument_count,
4247 MethodBase candidate, bool candidate_params,
4248 MethodBase best, bool best_params)
4250 ParameterData candidate_pd = TypeManager.GetParameterData (candidate);
4251 ParameterData best_pd = TypeManager.GetParameterData (best);
4253 bool better_at_least_one = false;
4255 for (int j = 0; j < argument_count; ++j) {
4256 Argument a = (Argument) args [j];
4258 Type ct = TypeManager.TypeToCoreType (candidate_pd.ParameterType (j));
4259 Type bt = TypeManager.TypeToCoreType (best_pd.ParameterType (j));
4261 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4262 if (candidate_params)
4263 ct = TypeManager.GetElementType (ct);
4265 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4267 bt = TypeManager.GetElementType (bt);
4273 Type better = BetterConversion (ec, a, ct, bt);
4275 // for each argument, the conversion to 'ct' should be no worse than
4276 // the conversion to 'bt'.
4280 // for at least one argument, the conversion to 'ct' should be better than
4281 // the conversion to 'bt'.
4283 better_at_least_one = true;
4286 if (better_at_least_one)
4290 // This handles the case
4292 // Add (float f1, float f2, float f3);
4293 // Add (params decimal [] foo);
4295 // The call Add (3, 4, 5) should be ambiguous. Without this check, the
4296 // first candidate would've chosen as better.
4302 // This handles the following cases:
4304 // Trim () is better than Trim (params char[] chars)
4305 // Concat (string s1, string s2, string s3) is better than
4306 // Concat (string s1, params string [] srest)
4308 return !candidate_params && best_params;
4311 internal static bool IsOverride (MethodBase cand_method, MethodBase base_method)
4313 if (!IsAncestralType (base_method.DeclaringType, cand_method.DeclaringType))
4316 ParameterData cand_pd = TypeManager.GetParameterData (cand_method);
4317 ParameterData base_pd = TypeManager.GetParameterData (base_method);
4319 if (cand_pd.Count != base_pd.Count)
4322 for (int j = 0; j < cand_pd.Count; ++j) {
4323 Parameter.Modifier cm = cand_pd.ParameterModifier (j);
4324 Parameter.Modifier bm = base_pd.ParameterModifier (j);
4325 Type ct = TypeManager.TypeToCoreType (cand_pd.ParameterType (j));
4326 Type bt = TypeManager.TypeToCoreType (base_pd.ParameterType (j));
4328 if (cm != bm || ct != bt)
4335 public static string FullMethodDesc (MethodBase mb)
4341 if (mb is MethodInfo) {
4342 sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
4346 sb = new StringBuilder ();
4348 sb.Append (TypeManager.CSharpSignature (mb));
4349 return sb.ToString ();
4352 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4354 MemberInfo [] miset;
4355 MethodGroupExpr union;
4360 return (MethodGroupExpr) mg2;
4363 return (MethodGroupExpr) mg1;
4366 MethodGroupExpr left_set = null, right_set = null;
4367 int length1 = 0, length2 = 0;
4369 left_set = (MethodGroupExpr) mg1;
4370 length1 = left_set.Methods.Length;
4372 right_set = (MethodGroupExpr) mg2;
4373 length2 = right_set.Methods.Length;
4375 ArrayList common = new ArrayList ();
4377 foreach (MethodBase r in right_set.Methods){
4378 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
4382 miset = new MemberInfo [length1 + length2 - common.Count];
4383 left_set.Methods.CopyTo (miset, 0);
4387 foreach (MethodBase r in right_set.Methods) {
4388 if (!common.Contains (r))
4392 union = new MethodGroupExpr (miset, loc);
4397 public static bool IsParamsMethodApplicable (EmitContext ec,
4398 ArrayList arguments, int arg_count,
4399 MethodBase candidate)
4401 return IsParamsMethodApplicable (
4402 ec, arguments, arg_count, candidate, false) ||
4403 IsParamsMethodApplicable (
4404 ec, arguments, arg_count, candidate, true);
4410 /// Determines if the candidate method, if a params method, is applicable
4411 /// in its expanded form to the given set of arguments
4413 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
4414 int arg_count, MethodBase candidate,
4417 ParameterData pd = TypeManager.GetParameterData (candidate);
4419 int pd_count = pd.Count;
4423 int count = pd_count - 1;
4425 if (pd.ParameterModifier (count) != Parameter.Modifier.ARGLIST)
4427 if (pd_count != arg_count)
4434 if (count > arg_count)
4437 if (pd_count == 1 && arg_count == 0)
4441 // If we have come this far, the case which
4442 // remains is when the number of parameters is
4443 // less than or equal to the argument count.
4445 for (int i = 0; i < count; ++i) {
4447 Argument a = (Argument) arguments [i];
4449 Parameter.Modifier a_mod = a.Modifier &
4450 (unchecked (~(Parameter.Modifier.OUTMASK | Parameter.Modifier.REFMASK)));
4451 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4452 (unchecked (~(Parameter.Modifier.OUTMASK | Parameter.Modifier.REFMASK)));
4454 if (a_mod == p_mod) {
4456 if (a_mod == Parameter.Modifier.NONE)
4457 if (!Convert.ImplicitConversionExists (ec,
4459 pd.ParameterType (i)))
4462 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4463 Type pt = pd.ParameterType (i);
4466 pt = TypeManager.GetReferenceType (pt);
4477 Argument a = (Argument) arguments [count];
4478 if (!(a.Expr is Arglist))
4484 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4486 for (int i = pd_count - 1; i < arg_count; i++) {
4487 Argument a = (Argument) arguments [i];
4489 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4497 /// Determines if the candidate method is applicable (section 14.4.2.1)
4498 /// to the given set of arguments
4500 public static bool IsApplicable (EmitContext ec, ArrayList arguments, int arg_count,
4501 MethodBase candidate)
4503 ParameterData pd = TypeManager.GetParameterData (candidate);
4505 if (arg_count != pd.Count)
4508 for (int i = arg_count; i > 0; ) {
4511 Argument a = (Argument) arguments [i];
4513 Parameter.Modifier a_mod = a.Modifier &
4514 ~(Parameter.Modifier.OUTMASK | Parameter.Modifier.REFMASK);
4516 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4517 ~(Parameter.Modifier.OUTMASK | Parameter.Modifier.REFMASK | Parameter.Modifier.PARAMS);
4519 if (a_mod == p_mod) {
4520 Type pt = pd.ParameterType (i);
4522 if (a_mod == Parameter.Modifier.NONE) {
4523 if (!Convert.ImplicitConversionExists (ec, a.Expr, pt))
4537 static internal bool IsAncestralType (Type first_type, Type second_type)
4539 return first_type != second_type &&
4540 (TypeManager.IsSubclassOf (second_type, first_type) ||
4541 TypeManager.ImplementsInterface (second_type, first_type));
4545 /// Find the Applicable Function Members (7.4.2.1)
4547 /// me: Method Group expression with the members to select.
4548 /// it might contain constructors or methods (or anything
4549 /// that maps to a method).
4551 /// Arguments: ArrayList containing resolved Argument objects.
4553 /// loc: The location if we want an error to be reported, or a Null
4554 /// location for "probing" purposes.
4556 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4557 /// that is the best match of me on Arguments.
4560 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4561 ArrayList Arguments, bool may_fail,
4564 MethodBase method = null;
4565 bool method_params = false;
4566 Type applicable_type = null;
4568 ArrayList candidates = new ArrayList (2);
4569 ArrayList candidate_overrides = null;
4572 // Used to keep a map between the candidate
4573 // and whether it is being considered in its
4574 // normal or expanded form
4576 // false is normal form, true is expanded form
4578 Hashtable candidate_to_form = null;
4580 if (Arguments != null)
4581 arg_count = Arguments.Count;
4583 if ((me.Name == "Invoke") &&
4584 TypeManager.IsDelegateType (me.DeclaringType)) {
4585 Error_InvokeOnDelegate (loc);
4589 MethodBase[] methods = me.Methods;
4591 int nmethods = methods.Length;
4595 // Methods marked 'override' don't take part in 'applicable_type'
4596 // computation, nor in the actual overload resolution.
4597 // However, they still need to be emitted instead of a base virtual method.
4598 // So, we salt them away into the 'candidate_overrides' array.
4600 // In case of reflected methods, we replace each overriding method with
4601 // its corresponding base virtual method. This is to improve compatibility
4602 // with non-C# libraries which change the visibility of overrides (#75636)
4605 for (int i = 0; i < methods.Length; ++i) {
4606 MethodBase m = methods [i];
4607 if (TypeManager.IsOverride (m)) {
4608 if (candidate_overrides == null)
4609 candidate_overrides = new ArrayList ();
4610 candidate_overrides.Add (m);
4611 m = TypeManager.TryGetBaseDefinition (m);
4619 int applicable_errors = Report.Errors;
4622 // First we construct the set of applicable methods
4624 bool is_sorted = true;
4625 for (int i = 0; i < nmethods; i++){
4626 Type decl_type = methods [i].DeclaringType;
4629 // If we have already found an applicable method
4630 // we eliminate all base types (Section 14.5.5.1)
4632 if (applicable_type != null && IsAncestralType (decl_type, applicable_type))
4636 // Check if candidate is applicable (section 14.4.2.1)
4637 // Is candidate applicable in normal form?
4639 bool is_applicable = IsApplicable (ec, Arguments, arg_count, methods [i]);
4641 if (!is_applicable && IsParamsMethodApplicable (ec, Arguments, arg_count, methods [i])) {
4642 MethodBase candidate = methods [i];
4643 if (candidate_to_form == null)
4644 candidate_to_form = new PtrHashtable ();
4645 candidate_to_form [candidate] = candidate;
4646 // Candidate is applicable in expanded form
4647 is_applicable = true;
4653 candidates.Add (methods [i]);
4655 if (applicable_type == null)
4656 applicable_type = decl_type;
4657 else if (applicable_type != decl_type) {
4659 if (IsAncestralType (applicable_type, decl_type))
4660 applicable_type = decl_type;
4664 if (applicable_errors != Report.Errors)
4667 int candidate_top = candidates.Count;
4669 if (applicable_type == null) {
4671 // Okay so we have failed to find anything so we
4672 // return by providing info about the closest match
4674 int errors = Report.Errors;
4675 for (int i = 0; i < nmethods; ++i) {
4676 MethodBase c = (MethodBase) methods [i];
4677 ParameterData pd = TypeManager.GetParameterData (c);
4679 if (pd.Count != arg_count)
4682 VerifyArgumentsCompat (ec, Arguments, arg_count,
4683 c, false, null, may_fail, loc);
4685 if (!may_fail && errors == Report.Errors)
4686 throw new InternalErrorException (
4687 "VerifyArgumentsCompat and IsApplicable do not agree; " +
4688 "likely reason: ImplicitConversion and ImplicitConversionExists have gone out of sync");
4693 if (!may_fail && errors == Report.Errors) {
4694 string report_name = me.Name;
4695 if (report_name == ".ctor")
4696 report_name = me.DeclaringType.ToString ();
4697 Error_WrongNumArguments (loc, report_name, arg_count);
4705 // At this point, applicable_type is _one_ of the most derived types
4706 // in the set of types containing the methods in this MethodGroup.
4707 // Filter the candidates so that they only contain methods from the
4708 // most derived types.
4711 int finalized = 0; // Number of finalized candidates
4714 // Invariant: applicable_type is a most derived type
4716 // We'll try to complete Section 14.5.5.1 for 'applicable_type' by
4717 // eliminating all it's base types. At the same time, we'll also move
4718 // every unrelated type to the end of the array, and pick the next
4719 // 'applicable_type'.
4721 Type next_applicable_type = null;
4722 int j = finalized; // where to put the next finalized candidate
4723 int k = finalized; // where to put the next undiscarded candidate
4724 for (int i = finalized; i < candidate_top; ++i) {
4725 MethodBase candidate = (MethodBase) candidates [i];
4726 Type decl_type = candidate.DeclaringType;
4728 if (decl_type == applicable_type) {
4729 candidates [k++] = candidates [j];
4730 candidates [j++] = candidates [i];
4734 if (IsAncestralType (decl_type, applicable_type))
4737 if (next_applicable_type != null &&
4738 IsAncestralType (decl_type, next_applicable_type))
4741 candidates [k++] = candidates [i];
4743 if (next_applicable_type == null ||
4744 IsAncestralType (next_applicable_type, decl_type))
4745 next_applicable_type = decl_type;
4748 applicable_type = next_applicable_type;
4751 } while (applicable_type != null);
4755 // Now we actually find the best method
4758 method = (MethodBase) candidates [0];
4759 method_params = candidate_to_form != null && candidate_to_form.Contains (method);
4760 for (int ix = 1; ix < candidate_top; ix++){
4761 MethodBase candidate = (MethodBase) candidates [ix];
4763 if (candidate == method)
4766 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4768 if (BetterFunction (ec, Arguments, arg_count,
4769 candidate, cand_params,
4770 method, method_params)) {
4772 method_params = cand_params;
4776 // Now check that there are no ambiguities i.e the selected method
4777 // should be better than all the others
4779 MethodBase ambiguous = null;
4780 for (int ix = 0; ix < candidate_top; ix++){
4781 MethodBase candidate = (MethodBase) candidates [ix];
4783 if (candidate == method)
4786 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4787 if (!BetterFunction (ec, Arguments, arg_count,
4788 method, method_params,
4789 candidate, cand_params)) {
4790 Report.SymbolRelatedToPreviousError (candidate);
4791 ambiguous = candidate;
4795 if (ambiguous != null) {
4796 Report.SymbolRelatedToPreviousError (method);
4797 Report.Error (121, loc, "The call is ambiguous between the following methods or properties: `{0}' and `{1}'",
4798 TypeManager.CSharpSignature (ambiguous), TypeManager.CSharpSignature (method));
4803 // If the method is a virtual function, pick an override closer to the LHS type.
4805 if (!me.IsBase && method.IsVirtual) {
4806 if (TypeManager.IsOverride (method))
4807 throw new InternalErrorException (
4808 "Should not happen. An 'override' method took part in overload resolution: " + method);
4810 if (candidate_overrides != null)
4811 foreach (MethodBase candidate in candidate_overrides) {
4812 if (IsOverride (candidate, method))
4818 // And now check if the arguments are all
4819 // compatible, perform conversions if
4820 // necessary etc. and return if everything is
4823 if (!VerifyArgumentsCompat (ec, Arguments, arg_count, method,
4824 method_params, null, may_fail, loc))
4830 IMethodData data = TypeManager.GetMethod (method);
4832 data.SetMemberIsUsed ();
4837 public static void Error_WrongNumArguments (Location loc, String name, int arg_count)
4839 Report.Error (1501, loc, "No overload for method `{0}' takes `{1}' arguments",
4840 name, arg_count.ToString ());
4843 static void Error_InvokeOnDelegate (Location loc)
4845 Report.Error (1533, loc,
4846 "Invoke cannot be called directly on a delegate");
4849 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
4850 Type delegate_type, Argument a, ParameterData expected_par)
4852 if (delegate_type == null)
4853 Report.Error (1502, loc, "The best overloaded method match for `{0}' has some invalid arguments",
4854 TypeManager.CSharpSignature (method));
4856 Report.Error (1594, loc, "Delegate `{0}' has some invalid arguments",
4857 TypeManager.CSharpName (delegate_type));
4859 Parameter.Modifier mod = expected_par.ParameterModifier (idx);
4861 string index = (idx + 1).ToString ();
4862 if (mod != Parameter.Modifier.ARGLIST && mod != a.Modifier) {
4863 if ((mod & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) == 0)
4864 Report.Error (1615, loc, "Argument `{0}' should not be passed with the `{1}' keyword",
4865 index, Parameter.GetModifierSignature (a.Modifier));
4867 Report.Error (1620, loc, "Argument `{0}' must be passed with the `{1}' keyword",
4868 index, Parameter.GetModifierSignature (mod));
4870 Report.Error (1503, loc, "Argument {0}: Cannot convert from `{1}' to `{2}'",
4871 index, Argument.FullDesc (a), expected_par.ParameterDesc (idx));
4875 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
4876 int arg_count, MethodBase method,
4877 bool chose_params_expanded,
4878 Type delegate_type, bool may_fail,
4881 ParameterData pd = TypeManager.GetParameterData (method);
4882 int pd_count = pd.Count;
4884 for (int j = 0; j < arg_count; j++) {
4885 Argument a = (Argument) Arguments [j];
4886 Expression a_expr = a.Expr;
4887 Type parameter_type = pd.ParameterType (j);
4888 Parameter.Modifier pm = pd.ParameterModifier (j);
4890 if (pm == Parameter.Modifier.PARAMS){
4891 if ((pm & ~Parameter.Modifier.PARAMS) != a.Modifier) {
4893 Error_InvalidArguments (loc, j, method, delegate_type, a, pd);
4897 if (chose_params_expanded)
4898 parameter_type = TypeManager.GetElementType (parameter_type);
4899 } else if (pm == Parameter.Modifier.ARGLIST) {
4900 if (!(a.Expr is Arglist)) {
4902 Error_InvalidArguments (loc, j, method, delegate_type, a, pd);
4910 if (pd.ParameterModifier (j) != a.Modifier){
4912 Error_InvalidArguments (loc, j, method, delegate_type, a, pd);
4920 if (!a.Type.Equals (parameter_type)){
4923 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
4927 Error_InvalidArguments (loc, j, method, delegate_type, a, pd);
4932 // Update the argument with the implicit conversion
4938 if (parameter_type.IsPointer){
4945 Parameter.Modifier a_mod = a.Modifier &
4946 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4947 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
4948 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4950 if (a_mod != p_mod &&
4951 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
4953 Invocation.Error_InvalidArguments (loc, j, method, null, a, pd);
4963 private bool resolved = false;
4964 public override Expression DoResolve (EmitContext ec)
4967 return this.method == null ? null : this;
4971 // First, resolve the expression that is used to
4972 // trigger the invocation
4974 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4978 if (!(expr is MethodGroupExpr)) {
4979 Type expr_type = expr.Type;
4981 if (expr_type != null){
4982 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
4984 return (new DelegateInvocation (
4985 this.expr, Arguments, loc)).Resolve (ec);
4989 if (!(expr is MethodGroupExpr)){
4990 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup, loc);
4995 // Next, evaluate all the expressions in the argument list
4997 if (Arguments != null){
4998 foreach (Argument a in Arguments){
4999 if (!a.Resolve (ec, loc))
5004 MethodGroupExpr mg = (MethodGroupExpr) expr;
5005 MethodBase method = OverloadResolve (ec, mg, Arguments, false, loc);
5010 MethodInfo mi = method as MethodInfo;
5012 type = TypeManager.TypeToCoreType (mi.ReturnType);
5013 Expression iexpr = mg.InstanceExpression;
5015 if (iexpr == null ||
5016 iexpr is This || iexpr is EmptyExpression ||
5017 mg.IdenticalTypeName) {
5018 mg.InstanceExpression = null;
5020 MemberExpr.error176 (loc, TypeManager.CSharpSignature (mi));
5024 if (iexpr == null || iexpr is EmptyExpression) {
5025 SimpleName.Error_ObjectRefRequired (ec, loc, TypeManager.CSharpSignature (mi));
5031 if (type.IsPointer){
5039 // Only base will allow this invocation to happen.
5041 if (mg.IsBase && method.IsAbstract){
5042 Error_CannotCallAbstractBase (TypeManager.CSharpSignature (method));
5046 if (Arguments == null && method.Name == "Finalize") {
5048 Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
5050 Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
5054 if ((method.Attributes & MethodAttributes.SpecialName) != 0 && IsSpecialMethodInvocation (method)) {
5058 if (mg.InstanceExpression != null)
5059 mg.InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
5061 eclass = ExprClass.Value;
5062 this.method = method;
5066 bool IsSpecialMethodInvocation (MethodBase method)
5068 IMethodData md = TypeManager.GetMethod (method);
5070 if (!(md is AbstractPropertyEventMethod) && !(md is Operator))
5073 if (!TypeManager.IsSpecialMethod (method))
5076 int args = TypeManager.GetParameterData (method).Count;
5077 if (method.Name.StartsWith ("get_") && args > 0)
5079 else if (method.Name.StartsWith ("set_") && args > 2)
5082 // TODO: check operators and events as well ?
5085 Report.SymbolRelatedToPreviousError (method);
5086 Report.Error (571, loc, "`{0}': cannot explicitly call operator or accessor",
5087 TypeManager.CSharpSignature (method, true));
5093 // Emits the list of arguments as an array
5095 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
5097 ILGenerator ig = ec.ig;
5098 int count = arguments.Count - idx;
5099 Argument a = (Argument) arguments [idx];
5100 Type t = a.Expr.Type;
5102 IntConstant.EmitInt (ig, count);
5103 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
5105 int top = arguments.Count;
5106 for (int j = idx; j < top; j++){
5107 a = (Argument) arguments [j];
5109 ig.Emit (OpCodes.Dup);
5110 IntConstant.EmitInt (ig, j - idx);
5113 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj);
5115 ig.Emit (OpCodes.Ldelema, t);
5120 ig.Emit (OpCodes.Stobj, t);
5127 /// Emits a list of resolved Arguments that are in the arguments
5130 /// The MethodBase argument might be null if the
5131 /// emission of the arguments is known not to contain
5132 /// a `params' field (for example in constructors or other routines
5133 /// that keep their arguments in this structure)
5135 /// if `dup_args' is true, a copy of the arguments will be left
5136 /// on the stack. If `dup_args' is true, you can specify `this_arg'
5137 /// which will be duplicated before any other args. Only EmitCall
5138 /// should be using this interface.
5140 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments, bool dup_args, LocalTemporary this_arg)
5142 ParameterData pd = mb == null ? null : TypeManager.GetParameterData (mb);
5143 int top = arguments == null ? 0 : arguments.Count;
5144 LocalTemporary [] temps = null;
5146 if (dup_args && top != 0)
5147 temps = new LocalTemporary [top];
5149 for (int i = 0; i < top; i++){
5150 Argument a = (Argument) arguments [i];
5153 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
5155 // Special case if we are passing the same data as the
5156 // params argument, do not put it in an array.
5158 if (pd.ParameterType (i) == a.Type)
5161 EmitParams (ec, i, arguments);
5168 ec.ig.Emit (OpCodes.Dup);
5169 (temps [i] = new LocalTemporary (a.Type)).Store (ec);
5174 if (this_arg != null)
5177 for (int i = 0; i < top; i ++)
5178 temps [i].Emit (ec);
5181 if (pd != null && pd.Count > top &&
5182 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
5183 ILGenerator ig = ec.ig;
5185 IntConstant.EmitInt (ig, 0);
5186 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
5190 static Type[] GetVarargsTypes (MethodBase mb, ArrayList arguments)
5192 ParameterData pd = TypeManager.GetParameterData (mb);
5194 if (arguments == null)
5195 return new Type [0];
5197 Argument a = (Argument) arguments [pd.Count - 1];
5198 Arglist list = (Arglist) a.Expr;
5200 return list.ArgumentTypes;
5204 /// This checks the ConditionalAttribute on the method
5206 static bool IsMethodExcluded (MethodBase method)
5208 if (method.IsConstructor)
5211 IMethodData md = TypeManager.GetMethod (method);
5213 return md.IsExcluded ();
5215 // For some methods (generated by delegate class) GetMethod returns null
5216 // because they are not included in builder_to_method table
5217 if (method.DeclaringType is TypeBuilder)
5220 return AttributeTester.IsConditionalMethodExcluded (method);
5224 /// is_base tells whether we want to force the use of the `call'
5225 /// opcode instead of using callvirt. Call is required to call
5226 /// a specific method, while callvirt will always use the most
5227 /// recent method in the vtable.
5229 /// is_static tells whether this is an invocation on a static method
5231 /// instance_expr is an expression that represents the instance
5232 /// it must be non-null if is_static is false.
5234 /// method is the method to invoke.
5236 /// Arguments is the list of arguments to pass to the method or constructor.
5238 public static void EmitCall (EmitContext ec, bool is_base,
5239 bool is_static, Expression instance_expr,
5240 MethodBase method, ArrayList Arguments, Location loc)
5242 EmitCall (ec, is_base, is_static, instance_expr, method, Arguments, loc, false, false);
5245 // `dup_args' leaves an extra copy of the arguments on the stack
5246 // `omit_args' does not leave any arguments at all.
5247 // So, basically, you could make one call with `dup_args' set to true,
5248 // and then another with `omit_args' set to true, and the two calls
5249 // would have the same set of arguments. However, each argument would
5250 // only have been evaluated once.
5251 public static void EmitCall (EmitContext ec, bool is_base,
5252 bool is_static, Expression instance_expr,
5253 MethodBase method, ArrayList Arguments, Location loc,
5254 bool dup_args, bool omit_args)
5256 ILGenerator ig = ec.ig;
5257 bool struct_call = false;
5258 bool this_call = false;
5259 LocalTemporary this_arg = null;
5261 Type decl_type = method.DeclaringType;
5263 if (!RootContext.StdLib) {
5264 // Replace any calls to the system's System.Array type with calls to
5265 // the newly created one.
5266 if (method == TypeManager.system_int_array_get_length)
5267 method = TypeManager.int_array_get_length;
5268 else if (method == TypeManager.system_int_array_get_rank)
5269 method = TypeManager.int_array_get_rank;
5270 else if (method == TypeManager.system_object_array_clone)
5271 method = TypeManager.object_array_clone;
5272 else if (method == TypeManager.system_int_array_get_length_int)
5273 method = TypeManager.int_array_get_length_int;
5274 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5275 method = TypeManager.int_array_get_lower_bound_int;
5276 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5277 method = TypeManager.int_array_get_upper_bound_int;
5278 else if (method == TypeManager.system_void_array_copyto_array_int)
5279 method = TypeManager.void_array_copyto_array_int;
5282 if (!ec.IsInObsoleteScope) {
5284 // This checks ObsoleteAttribute on the method and on the declaring type
5286 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
5288 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
5290 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
5292 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
5296 if (IsMethodExcluded (method))
5300 if (instance_expr == EmptyExpression.Null) {
5301 SimpleName.Error_ObjectRefRequired (ec, loc, TypeManager.CSharpSignature (method));
5305 this_call = instance_expr is This;
5306 if (decl_type.IsValueType || (!this_call && instance_expr.Type.IsValueType))
5310 // If this is ourselves, push "this"
5315 // Push the instance expression
5317 if (TypeManager.IsValueType (instance_expr.Type)) {
5319 // Special case: calls to a function declared in a
5320 // reference-type with a value-type argument need
5321 // to have their value boxed.
5322 if (decl_type.IsValueType) {
5324 // If the expression implements IMemoryLocation, then
5325 // we can optimize and use AddressOf on the
5328 // If not we have to use some temporary storage for
5330 if (instance_expr is IMemoryLocation) {
5331 ((IMemoryLocation)instance_expr).
5332 AddressOf (ec, AddressOp.LoadStore);
5334 LocalTemporary temp = new LocalTemporary (instance_expr.Type);
5335 instance_expr.Emit (ec);
5337 temp.AddressOf (ec, AddressOp.Load);
5340 // avoid the overhead of doing this all the time.
5342 t = TypeManager.GetReferenceType (instance_expr.Type);
5344 instance_expr.Emit (ec);
5345 ig.Emit (OpCodes.Box, instance_expr.Type);
5346 t = TypeManager.object_type;
5349 instance_expr.Emit (ec);
5350 t = instance_expr.Type;
5354 ig.Emit (OpCodes.Dup);
5355 if (Arguments != null && Arguments.Count != 0) {
5356 this_arg = new LocalTemporary (t);
5357 this_arg.Store (ec);
5364 EmitArguments (ec, method, Arguments, dup_args, this_arg);
5367 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
5368 call_op = OpCodes.Call;
5370 call_op = OpCodes.Callvirt;
5372 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
5373 Type[] varargs_types = GetVarargsTypes (method, Arguments);
5374 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
5381 // and DoFoo is not virtual, you can omit the callvirt,
5382 // because you don't need the null checking behavior.
5384 if (method is MethodInfo)
5385 ig.Emit (call_op, (MethodInfo) method);
5387 ig.Emit (call_op, (ConstructorInfo) method);
5390 public override void Emit (EmitContext ec)
5392 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5394 EmitCall (ec, mg.IsBase, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5397 public override void EmitStatement (EmitContext ec)
5402 // Pop the return value if there is one
5404 if (method is MethodInfo){
5405 Type ret = ((MethodInfo)method).ReturnType;
5406 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5407 ec.ig.Emit (OpCodes.Pop);
5412 public class InvocationOrCast : ExpressionStatement
5415 Expression argument;
5417 public InvocationOrCast (Expression expr, Expression argument)
5420 this.argument = argument;
5421 this.loc = expr.Location;
5424 public override Expression DoResolve (EmitContext ec)
5427 // First try to resolve it as a cast.
5429 TypeExpr te = expr.ResolveAsTypeTerminal (ec, true);
5431 Cast cast = new Cast (te, argument, loc);
5432 return cast.Resolve (ec);
5436 // This can either be a type or a delegate invocation.
5437 // Let's just resolve it and see what we'll get.
5439 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5444 // Ok, so it's a Cast.
5446 if (expr.eclass == ExprClass.Type) {
5447 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
5448 return cast.Resolve (ec);
5452 // It's a delegate invocation.
5454 if (!TypeManager.IsDelegateType (expr.Type)) {
5455 Error (149, "Method name expected");
5459 ArrayList args = new ArrayList ();
5460 args.Add (new Argument (argument, Argument.AType.Expression));
5461 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5462 return invocation.Resolve (ec);
5467 Error (201, "Only assignment, call, increment, decrement and new object " +
5468 "expressions can be used as a statement");
5471 public override ExpressionStatement ResolveStatement (EmitContext ec)
5474 // First try to resolve it as a cast.
5476 TypeExpr te = expr.ResolveAsTypeTerminal (ec, true);
5483 // This can either be a type or a delegate invocation.
5484 // Let's just resolve it and see what we'll get.
5486 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5487 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5493 // It's a delegate invocation.
5495 if (!TypeManager.IsDelegateType (expr.Type)) {
5496 Error (149, "Method name expected");
5500 ArrayList args = new ArrayList ();
5501 args.Add (new Argument (argument, Argument.AType.Expression));
5502 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5503 return invocation.ResolveStatement (ec);
5506 public override void Emit (EmitContext ec)
5508 throw new Exception ("Cannot happen");
5511 public override void EmitStatement (EmitContext ec)
5513 throw new Exception ("Cannot happen");
5518 // This class is used to "disable" the code generation for the
5519 // temporary variable when initializing value types.
5521 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5522 public void AddressOf (EmitContext ec, AddressOp Mode)
5529 /// Implements the new expression
5531 public class New : ExpressionStatement, IMemoryLocation {
5532 public readonly ArrayList Arguments;
5535 // During bootstrap, it contains the RequestedType,
5536 // but if `type' is not null, it *might* contain a NewDelegate
5537 // (because of field multi-initialization)
5539 public Expression RequestedType;
5541 MethodBase method = null;
5544 // If set, the new expression is for a value_target, and
5545 // we will not leave anything on the stack.
5547 Expression value_target;
5548 bool value_target_set = false;
5550 public New (Expression requested_type, ArrayList arguments, Location l)
5552 RequestedType = requested_type;
5553 Arguments = arguments;
5557 public bool SetValueTypeVariable (Expression value)
5559 value_target = value;
5560 value_target_set = true;
5561 if (!(value_target is IMemoryLocation)){
5562 Error_UnexpectedKind (null, "variable", loc);
5569 // This function is used to disable the following code sequence for
5570 // value type initialization:
5572 // AddressOf (temporary)
5576 // Instead the provide will have provided us with the address on the
5577 // stack to store the results.
5579 static Expression MyEmptyExpression;
5581 public void DisableTemporaryValueType ()
5583 if (MyEmptyExpression == null)
5584 MyEmptyExpression = new EmptyAddressOf ();
5587 // To enable this, look into:
5588 // test-34 and test-89 and self bootstrapping.
5590 // For instance, we can avoid a copy by using `newobj'
5591 // instead of Call + Push-temp on value types.
5592 // value_target = MyEmptyExpression;
5597 /// Converts complex core type syntax like 'new int ()' to simple constant
5599 public static Constant Constantify (Type t)
5601 if (t == TypeManager.int32_type)
5602 return new IntConstant (0, Location.Null);
5603 if (t == TypeManager.uint32_type)
5604 return new UIntConstant (0, Location.Null);
5605 if (t == TypeManager.int64_type)
5606 return new LongConstant (0, Location.Null);
5607 if (t == TypeManager.uint64_type)
5608 return new ULongConstant (0, Location.Null);
5609 if (t == TypeManager.float_type)
5610 return new FloatConstant (0, Location.Null);
5611 if (t == TypeManager.double_type)
5612 return new DoubleConstant (0, Location.Null);
5613 if (t == TypeManager.short_type)
5614 return new ShortConstant (0, Location.Null);
5615 if (t == TypeManager.ushort_type)
5616 return new UShortConstant (0, Location.Null);
5617 if (t == TypeManager.sbyte_type)
5618 return new SByteConstant (0, Location.Null);
5619 if (t == TypeManager.byte_type)
5620 return new ByteConstant (0, Location.Null);
5621 if (t == TypeManager.char_type)
5622 return new CharConstant ('\0', Location.Null);
5623 if (t == TypeManager.bool_type)
5624 return new BoolConstant (false, Location.Null);
5625 if (t == TypeManager.decimal_type)
5626 return new DecimalConstant (0, Location.Null);
5632 // Checks whether the type is an interface that has the
5633 // [ComImport, CoClass] attributes and must be treated
5636 public Expression CheckComImport (EmitContext ec)
5638 if (!type.IsInterface)
5642 // Turn the call into:
5643 // (the-interface-stated) (new class-referenced-in-coclassattribute ())
5645 Type real_class = AttributeTester.GetCoClassAttribute (type);
5646 if (real_class == null)
5649 New proxy = new New (new TypeExpression (real_class, loc), Arguments, loc);
5650 Cast cast = new Cast (new TypeExpression (type, loc), proxy, loc);
5651 return cast.Resolve (ec);
5654 public override Expression DoResolve (EmitContext ec)
5657 // The New DoResolve might be called twice when initializing field
5658 // expressions (see EmitFieldInitializers, the call to
5659 // GetInitializerExpression will perform a resolve on the expression,
5660 // and later the assign will trigger another resolution
5662 // This leads to bugs (#37014)
5665 if (RequestedType is NewDelegate)
5666 return RequestedType;
5670 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec, false);
5676 if (Arguments == null) {
5677 Expression c = Constantify (type);
5682 if (TypeManager.IsDelegateType (type)) {
5683 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5684 if (RequestedType != null)
5685 if (!(RequestedType is DelegateCreation))
5686 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
5687 return RequestedType;
5690 if (type.IsAbstract && type.IsSealed) {
5691 Report.SymbolRelatedToPreviousError (type);
5692 Report.Error (712, loc, "Cannot create an instance of the static class `{0}'", TypeManager.CSharpName (type));
5696 if (type.IsInterface || type.IsAbstract){
5697 RequestedType = CheckComImport (ec);
5698 if (RequestedType != null)
5699 return RequestedType;
5701 Report.SymbolRelatedToPreviousError (type);
5702 Report.Error (144, loc, "Cannot create an instance of the abstract class or interface `{0}'", TypeManager.CSharpName (type));
5706 bool is_struct = type.IsValueType;
5707 eclass = ExprClass.Value;
5710 // SRE returns a match for .ctor () on structs (the object constructor),
5711 // so we have to manually ignore it.
5713 if (is_struct && Arguments == null)
5716 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
5717 Expression ml = MemberLookupFinal (ec, type, type, ".ctor",
5718 MemberTypes.Constructor, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5723 MethodGroupExpr mg = ml as MethodGroupExpr;
5726 ml.Error_UnexpectedKind (ec.DeclContainer, "method group", loc);
5730 if (Arguments != null){
5731 foreach (Argument a in Arguments){
5732 if (!a.Resolve (ec, loc))
5737 method = Invocation.OverloadResolve (ec, mg, Arguments, false, loc);
5738 if (method == null) {
5739 if (almostMatchedMembers.Count != 0)
5740 MemberLookupFailed (ec.ContainerType, type, type, ".ctor", null, true, loc);
5748 // This DoEmit can be invoked in two contexts:
5749 // * As a mechanism that will leave a value on the stack (new object)
5750 // * As one that wont (init struct)
5752 // You can control whether a value is required on the stack by passing
5753 // need_value_on_stack. The code *might* leave a value on the stack
5754 // so it must be popped manually
5756 // If we are dealing with a ValueType, we have a few
5757 // situations to deal with:
5759 // * The target is a ValueType, and we have been provided
5760 // the instance (this is easy, we are being assigned).
5762 // * The target of New is being passed as an argument,
5763 // to a boxing operation or a function that takes a
5766 // In this case, we need to create a temporary variable
5767 // that is the argument of New.
5769 // Returns whether a value is left on the stack
5771 bool DoEmit (EmitContext ec, bool need_value_on_stack)
5773 bool is_value_type = TypeManager.IsValueType (type);
5774 ILGenerator ig = ec.ig;
5779 // Allow DoEmit() to be called multiple times.
5780 // We need to create a new LocalTemporary each time since
5781 // you can't share LocalBuilders among ILGeneators.
5782 if (!value_target_set)
5783 value_target = new LocalTemporary (type);
5785 ml = (IMemoryLocation) value_target;
5786 ml.AddressOf (ec, AddressOp.Store);
5790 Invocation.EmitArguments (ec, method, Arguments, false, null);
5794 ig.Emit (OpCodes.Initobj, type);
5796 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5797 if (need_value_on_stack){
5798 value_target.Emit (ec);
5803 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
5808 public override void Emit (EmitContext ec)
5813 public override void EmitStatement (EmitContext ec)
5815 if (DoEmit (ec, false))
5816 ec.ig.Emit (OpCodes.Pop);
5819 public void AddressOf (EmitContext ec, AddressOp Mode)
5821 if (!type.IsValueType){
5823 // We throw an exception. So far, I believe we only need to support
5825 // foreach (int j in new StructType ())
5828 throw new Exception ("AddressOf should not be used for classes");
5831 if (!value_target_set)
5832 value_target = new LocalTemporary (type);
5834 IMemoryLocation ml = (IMemoryLocation) value_target;
5835 ml.AddressOf (ec, AddressOp.Store);
5837 Invocation.EmitArguments (ec, method, Arguments, false, null);
5840 ec.ig.Emit (OpCodes.Initobj, type);
5842 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5844 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
5849 /// 14.5.10.2: Represents an array creation expression.
5853 /// There are two possible scenarios here: one is an array creation
5854 /// expression that specifies the dimensions and optionally the
5855 /// initialization data and the other which does not need dimensions
5856 /// specified but where initialization data is mandatory.
5858 public class ArrayCreation : Expression {
5859 Expression requested_base_type;
5860 ArrayList initializers;
5863 // The list of Argument types.
5864 // This is used to construct the `newarray' or constructor signature
5866 ArrayList arguments;
5869 // Method used to create the array object.
5871 MethodBase new_method = null;
5873 Type array_element_type;
5874 Type underlying_type;
5875 bool is_one_dimensional = false;
5876 bool is_builtin_type = false;
5877 bool expect_initializers = false;
5878 int num_arguments = 0;
5882 ArrayList array_data;
5886 // The number of constants in array initializers
5887 int const_initializers_count;
5889 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
5891 this.requested_base_type = requested_base_type;
5892 this.initializers = initializers;
5896 arguments = new ArrayList ();
5898 foreach (Expression e in exprs) {
5899 arguments.Add (new Argument (e, Argument.AType.Expression));
5904 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
5906 this.requested_base_type = requested_base_type;
5907 this.initializers = initializers;
5911 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
5913 //string tmp = rank.Substring (rank.LastIndexOf ('['));
5915 //dimensions = tmp.Length - 1;
5916 expect_initializers = true;
5919 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
5921 StringBuilder sb = new StringBuilder (rank);
5924 for (int i = 1; i < idx_count; i++)
5929 return new ComposedCast (base_type, sb.ToString (), loc);
5932 void Error_IncorrectArrayInitializer ()
5934 Error (178, "Invalid rank specifier: expected `,' or `]'");
5937 bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
5939 if (specified_dims) {
5940 Argument a = (Argument) arguments [idx];
5942 if (!a.Resolve (ec, loc))
5945 Constant c = a.Expr as Constant;
5947 c = c.ToType (TypeManager.int32_type, a.Expr.Location);
5951 Report.Error (150, a.Expr.Location, "A constant value is expected");
5955 int value = (int) c.GetValue ();
5957 if (value != probe.Count) {
5958 Error_IncorrectArrayInitializer ();
5962 bounds [idx] = value;
5965 int child_bounds = -1;
5966 for (int i = 0; i < probe.Count; ++i) {
5967 object o = probe [i];
5968 if (o is ArrayList) {
5969 ArrayList sub_probe = o as ArrayList;
5970 int current_bounds = sub_probe.Count;
5972 if (child_bounds == -1)
5973 child_bounds = current_bounds;
5975 else if (child_bounds != current_bounds){
5976 Error_IncorrectArrayInitializer ();
5979 if (idx + 1 >= dimensions){
5980 Error (623, "Array initializers can only be used in a variable or field initializer. Try using a new expression instead");
5984 bool ret = CheckIndices (ec, sub_probe, idx + 1, specified_dims);
5988 if (child_bounds != -1){
5989 Error_IncorrectArrayInitializer ();
5993 Expression tmp = (Expression) o;
5994 tmp = tmp.Resolve (ec);
5998 Expression conv = Convert.ImplicitConversionRequired (
5999 ec, tmp, underlying_type, loc);
6004 // Initializers with the default values can be ignored
6005 Constant c = tmp as Constant;
6007 if (c.IsDefaultInitializer (array_element_type)) {
6011 ++const_initializers_count;
6014 // Used to invalidate static initializer
6015 const_initializers_count = int.MinValue;
6018 array_data.Add (conv);
6025 public void UpdateIndices ()
6028 for (ArrayList probe = initializers; probe != null;) {
6029 if (probe.Count > 0 && probe [0] is ArrayList) {
6030 Expression e = new IntConstant (probe.Count, Location.Null);
6031 arguments.Add (new Argument (e, Argument.AType.Expression));
6033 bounds [i++] = probe.Count;
6035 probe = (ArrayList) probe [0];
6038 Expression e = new IntConstant (probe.Count, Location.Null);
6039 arguments.Add (new Argument (e, Argument.AType.Expression));
6041 bounds [i++] = probe.Count;
6048 bool ResolveInitializers (EmitContext ec)
6050 if (initializers == null) {
6051 return !expect_initializers;
6054 if (underlying_type == null)
6058 // We use this to store all the date values in the order in which we
6059 // will need to store them in the byte blob later
6061 array_data = new ArrayList ();
6062 bounds = new System.Collections.Specialized.HybridDictionary ();
6064 if (arguments != null)
6065 return CheckIndices (ec, initializers, 0, true);
6067 arguments = new ArrayList ();
6069 if (!CheckIndices (ec, initializers, 0, false))
6074 if (arguments.Count != dimensions) {
6075 Error_IncorrectArrayInitializer ();
6083 // Creates the type of the array
6085 bool LookupType (EmitContext ec)
6087 StringBuilder array_qualifier = new StringBuilder (rank);
6090 // `In the first form allocates an array instace of the type that results
6091 // from deleting each of the individual expression from the expression list'
6093 if (num_arguments > 0) {
6094 array_qualifier.Append ("[");
6095 for (int i = num_arguments-1; i > 0; i--)
6096 array_qualifier.Append (",");
6097 array_qualifier.Append ("]");
6103 TypeExpr array_type_expr;
6104 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
6105 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec, false);
6106 if (array_type_expr == null)
6109 type = array_type_expr.Type;
6110 underlying_type = TypeManager.GetElementType (type);
6111 dimensions = type.GetArrayRank ();
6116 public override Expression DoResolve (EmitContext ec)
6121 if (!LookupType (ec))
6124 array_element_type = TypeManager.GetElementType (type);
6125 if (array_element_type.IsAbstract && array_element_type.IsSealed) {
6126 Report.Error (719, loc, "`{0}': array elements cannot be of static type", TypeManager.CSharpName (array_element_type));
6131 // First step is to validate the initializers and fill
6132 // in any missing bits
6134 if (!ResolveInitializers (ec))
6138 if (arguments == null)
6141 arg_count = arguments.Count;
6142 foreach (Argument a in arguments){
6143 if (!a.Resolve (ec, loc))
6146 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
6147 if (real_arg == null)
6154 if (arg_count == 1) {
6155 is_one_dimensional = true;
6156 eclass = ExprClass.Value;
6160 is_builtin_type = TypeManager.IsBuiltinType (type);
6162 if (is_builtin_type) {
6165 ml = MemberLookup (ec.ContainerType, type, ".ctor", MemberTypes.Constructor,
6166 AllBindingFlags, loc);
6168 if (!(ml is MethodGroupExpr)) {
6169 ml.Error_UnexpectedKind (ec.DeclContainer, "method group", loc);
6174 Error (-6, "New invocation: Can not find a constructor for " +
6175 "this argument list");
6179 new_method = Invocation.OverloadResolve (
6180 ec, (MethodGroupExpr) ml, arguments, false, loc);
6182 if (new_method == null) {
6183 Error (-6, "New invocation: Can not find a constructor for " +
6184 "this argument list");
6188 eclass = ExprClass.Value;
6191 ModuleBuilder mb = CodeGen.Module.Builder;
6192 ArrayList args = new ArrayList ();
6194 if (arguments != null) {
6195 for (int i = 0; i < arg_count; i++)
6196 args.Add (TypeManager.int32_type);
6199 Type [] arg_types = null;
6202 arg_types = new Type [args.Count];
6204 args.CopyTo (arg_types, 0);
6206 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
6209 if (new_method == null) {
6210 Error (-6, "New invocation: Can not find a constructor for " +
6211 "this argument list");
6215 eclass = ExprClass.Value;
6220 byte [] MakeByteBlob ()
6225 int count = array_data.Count;
6227 if (underlying_type.IsEnum)
6228 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
6230 factor = GetTypeSize (underlying_type);
6232 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
6234 data = new byte [(count * factor + 4) & ~3];
6237 for (int i = 0; i < count; ++i) {
6238 object v = array_data [i];
6240 if (v is EnumConstant)
6241 v = ((EnumConstant) v).Child;
6243 if (v is Constant && !(v is StringConstant))
6244 v = ((Constant) v).GetValue ();
6250 if (underlying_type == TypeManager.int64_type){
6251 if (!(v is Expression)){
6252 long val = (long) v;
6254 for (int j = 0; j < factor; ++j) {
6255 data [idx + j] = (byte) (val & 0xFF);
6259 } else if (underlying_type == TypeManager.uint64_type){
6260 if (!(v is Expression)){
6261 ulong val = (ulong) v;
6263 for (int j = 0; j < factor; ++j) {
6264 data [idx + j] = (byte) (val & 0xFF);
6268 } else if (underlying_type == TypeManager.float_type) {
6269 if (!(v is Expression)){
6270 element = BitConverter.GetBytes ((float) v);
6272 for (int j = 0; j < factor; ++j)
6273 data [idx + j] = element [j];
6275 } else if (underlying_type == TypeManager.double_type) {
6276 if (!(v is Expression)){
6277 element = BitConverter.GetBytes ((double) v);
6279 for (int j = 0; j < factor; ++j)
6280 data [idx + j] = element [j];
6282 } else if (underlying_type == TypeManager.char_type){
6283 if (!(v is Expression)){
6284 int val = (int) ((char) v);
6286 data [idx] = (byte) (val & 0xff);
6287 data [idx+1] = (byte) (val >> 8);
6289 } else if (underlying_type == TypeManager.short_type){
6290 if (!(v is Expression)){
6291 int val = (int) ((short) v);
6293 data [idx] = (byte) (val & 0xff);
6294 data [idx+1] = (byte) (val >> 8);
6296 } else if (underlying_type == TypeManager.ushort_type){
6297 if (!(v is Expression)){
6298 int val = (int) ((ushort) v);
6300 data [idx] = (byte) (val & 0xff);
6301 data [idx+1] = (byte) (val >> 8);
6303 } else if (underlying_type == TypeManager.int32_type) {
6304 if (!(v is Expression)){
6307 data [idx] = (byte) (val & 0xff);
6308 data [idx+1] = (byte) ((val >> 8) & 0xff);
6309 data [idx+2] = (byte) ((val >> 16) & 0xff);
6310 data [idx+3] = (byte) (val >> 24);
6312 } else if (underlying_type == TypeManager.uint32_type) {
6313 if (!(v is Expression)){
6314 uint val = (uint) v;
6316 data [idx] = (byte) (val & 0xff);
6317 data [idx+1] = (byte) ((val >> 8) & 0xff);
6318 data [idx+2] = (byte) ((val >> 16) & 0xff);
6319 data [idx+3] = (byte) (val >> 24);
6321 } else if (underlying_type == TypeManager.sbyte_type) {
6322 if (!(v is Expression)){
6323 sbyte val = (sbyte) v;
6324 data [idx] = (byte) val;
6326 } else if (underlying_type == TypeManager.byte_type) {
6327 if (!(v is Expression)){
6328 byte val = (byte) v;
6329 data [idx] = (byte) val;
6331 } else if (underlying_type == TypeManager.bool_type) {
6332 if (!(v is Expression)){
6333 bool val = (bool) v;
6334 data [idx] = (byte) (val ? 1 : 0);
6336 } else if (underlying_type == TypeManager.decimal_type){
6337 if (!(v is Expression)){
6338 int [] bits = Decimal.GetBits ((decimal) v);
6341 // FIXME: For some reason, this doesn't work on the MS runtime.
6342 int [] nbits = new int [4];
6343 nbits [0] = bits [3];
6344 nbits [1] = bits [2];
6345 nbits [2] = bits [0];
6346 nbits [3] = bits [1];
6348 for (int j = 0; j < 4; j++){
6349 data [p++] = (byte) (nbits [j] & 0xff);
6350 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6351 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6352 data [p++] = (byte) (nbits [j] >> 24);
6356 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6365 // Emits the initializers for the array
6367 void EmitStaticInitializers (EmitContext ec)
6370 // First, the static data
6373 ILGenerator ig = ec.ig;
6375 byte [] data = MakeByteBlob ();
6377 fb = RootContext.MakeStaticData (data);
6379 ig.Emit (OpCodes.Dup);
6380 ig.Emit (OpCodes.Ldtoken, fb);
6381 ig.Emit (OpCodes.Call,
6382 TypeManager.void_initializearray_array_fieldhandle);
6386 // Emits pieces of the array that can not be computed at compile
6387 // time (variables and string locations).
6389 // This always expect the top value on the stack to be the array
6391 void EmitDynamicInitializers (EmitContext ec)
6393 ILGenerator ig = ec.ig;
6394 int dims = bounds.Count;
6395 int [] current_pos = new int [dims];
6397 MethodInfo set = null;
6400 Type [] args = new Type [dims + 1];
6402 for (int j = 0; j < dims; j++)
6403 args [j] = TypeManager.int32_type;
6404 args [dims] = array_element_type;
6406 set = CodeGen.Module.Builder.GetArrayMethod (
6408 CallingConventions.HasThis | CallingConventions.Standard,
6409 TypeManager.void_type, args);
6412 for (int i = 0; i < array_data.Count; i++){
6414 Expression e = (Expression)array_data [i];
6417 Type etype = e.Type;
6419 ig.Emit (OpCodes.Dup);
6421 for (int idx = 0; idx < dims; idx++)
6422 IntConstant.EmitInt (ig, current_pos [idx]);
6425 // If we are dealing with a struct, get the
6426 // address of it, so we can store it.
6429 TypeManager.IsValueType (etype) &&
6430 (!TypeManager.IsBuiltinOrEnum (etype) ||
6431 etype == TypeManager.decimal_type)) {
6436 // Let new know that we are providing
6437 // the address where to store the results
6439 n.DisableTemporaryValueType ();
6442 ig.Emit (OpCodes.Ldelema, etype);
6449 OpCode op = ArrayAccess.GetStoreOpcode (etype, out is_stobj);
6451 ig.Emit (OpCodes.Stobj, etype);
6455 ig.Emit (OpCodes.Call, set);
6462 for (int j = dims - 1; j >= 0; j--){
6464 if (current_pos [j] < (int) bounds [j])
6466 current_pos [j] = 0;
6471 void EmitArrayArguments (EmitContext ec)
6473 ILGenerator ig = ec.ig;
6475 foreach (Argument a in arguments) {
6476 Type atype = a.Type;
6479 if (atype == TypeManager.uint64_type)
6480 ig.Emit (OpCodes.Conv_Ovf_U4);
6481 else if (atype == TypeManager.int64_type)
6482 ig.Emit (OpCodes.Conv_Ovf_I4);
6486 public override void Emit (EmitContext ec)
6488 ILGenerator ig = ec.ig;
6490 EmitArrayArguments (ec);
6491 if (is_one_dimensional)
6492 ig.Emit (OpCodes.Newarr, array_element_type);
6494 if (is_builtin_type)
6495 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6497 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6500 if (initializers == null)
6503 // This is a treshold for static initializers
6504 // I tried to make more accurate but it seems to me that Array.Initialize is
6505 // always slower (managed -> unmanaged switch?)
6506 const int max_automatic_initializers = 200;
6508 if (const_initializers_count > max_automatic_initializers && TypeManager.IsPrimitiveType (array_element_type)) {
6509 EmitStaticInitializers (ec);
6513 EmitDynamicInitializers (ec);
6516 public override bool GetAttributableValue (Type valueType, out object value)
6518 if (!is_one_dimensional){
6519 // Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6520 return base.GetAttributableValue (null, out value);
6523 if (array_data == null) {
6524 Constant c = (Constant)((Argument)arguments [0]).Expr;
6525 if (c.IsDefaultValue) {
6526 value = Array.CreateInstance (array_element_type, 0);
6529 // Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6530 return base.GetAttributableValue (null, out value);
6533 Array ret = Array.CreateInstance (array_element_type, array_data.Count);
6534 object element_value;
6535 for (int i = 0; i < ret.Length; ++i)
6537 Expression e = (Expression)array_data [i];
6538 if (e == null) // Is null when initializer is optimized away
6539 e = (Expression)initializers [i];
6541 if (!e.GetAttributableValue (array_element_type, out element_value)) {
6545 ret.SetValue (element_value, i);
6552 public sealed class CompilerGeneratedThis : This
6554 public static This Instance = new CompilerGeneratedThis ();
6556 private CompilerGeneratedThis ()
6557 : base (Location.Null)
6561 public override Expression DoResolve (EmitContext ec)
6563 eclass = ExprClass.Variable;
6564 type = ec.ContainerType;
6570 /// Represents the `this' construct
6572 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6575 VariableInfo variable_info;
6577 public This (Block block, Location loc)
6583 public This (Location loc)
6588 public VariableInfo VariableInfo {
6589 get { return variable_info; }
6592 public bool VerifyFixed ()
6594 return !TypeManager.IsValueType (Type);
6597 public bool ResolveBase (EmitContext ec)
6599 eclass = ExprClass.Variable;
6600 type = ec.ContainerType;
6603 Error (26, "Keyword `this' is not valid in a static property, static method, or static field initializer");
6607 if (block != null && block.Toplevel.ThisVariable != null)
6608 variable_info = block.Toplevel.ThisVariable.VariableInfo;
6610 if (ec.CurrentAnonymousMethod != null)
6616 public override Expression DoResolve (EmitContext ec)
6618 if (!ResolveBase (ec))
6621 if ((variable_info != null) && !(type.IsValueType && ec.OmitStructFlowAnalysis) && !variable_info.IsAssigned (ec)) {
6622 Error (188, "The `this' object cannot be used before all of its fields are assigned to");
6623 variable_info.SetAssigned (ec);
6627 if (ec.IsFieldInitializer) {
6628 Error (27, "Keyword `this' is not available in the current context");
6635 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6637 if (!ResolveBase (ec))
6640 if (variable_info != null)
6641 variable_info.SetAssigned (ec);
6643 if (ec.TypeContainer is Class){
6644 Error (1604, "Cannot assign to 'this' because it is read-only");
6651 public void Emit (EmitContext ec, bool leave_copy)
6655 ec.ig.Emit (OpCodes.Dup);
6658 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
6660 ILGenerator ig = ec.ig;
6662 if (ec.TypeContainer is Struct){
6663 ec.EmitThis (false);
6666 LocalTemporary t = null;
6668 t = new LocalTemporary (type);
6669 ec.ig.Emit (OpCodes.Dup);
6673 ig.Emit (OpCodes.Stobj, type);
6678 throw new Exception ("how did you get here");
6682 public override void Emit (EmitContext ec)
6684 ILGenerator ig = ec.ig;
6686 ec.EmitThis (false);
6687 if (ec.TypeContainer is Struct)
6688 ig.Emit (OpCodes.Ldobj, type);
6691 public override int GetHashCode()
6693 return block.GetHashCode ();
6696 public override bool Equals (object obj)
6698 This t = obj as This;
6702 return block == t.block;
6705 public void AddressOf (EmitContext ec, AddressOp mode)
6710 // FIGURE OUT WHY LDARG_S does not work
6712 // consider: struct X { int val; int P { set { val = value; }}}
6714 // Yes, this looks very bad. Look at `NOTAS' for
6716 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
6721 /// Represents the `__arglist' construct
6723 public class ArglistAccess : Expression
6725 public ArglistAccess (Location loc)
6730 public override Expression DoResolve (EmitContext ec)
6732 eclass = ExprClass.Variable;
6733 type = TypeManager.runtime_argument_handle_type;
6735 if (ec.IsFieldInitializer || !ec.CurrentBlock.Toplevel.HasVarargs)
6737 Error (190, "The __arglist construct is valid only within " +
6738 "a variable argument method.");
6745 public override void Emit (EmitContext ec)
6747 ec.ig.Emit (OpCodes.Arglist);
6752 /// Represents the `__arglist (....)' construct
6754 public class Arglist : Expression
6756 public readonly Argument[] Arguments;
6758 public Arglist (Argument[] args, Location l)
6764 public Type[] ArgumentTypes {
6766 Type[] retval = new Type [Arguments.Length];
6767 for (int i = 0; i < Arguments.Length; i++)
6768 retval [i] = Arguments [i].Type;
6773 public override Expression DoResolve (EmitContext ec)
6775 eclass = ExprClass.Variable;
6776 type = TypeManager.runtime_argument_handle_type;
6778 foreach (Argument arg in Arguments) {
6779 if (!arg.Resolve (ec, loc))
6786 public override void Emit (EmitContext ec)
6788 foreach (Argument arg in Arguments)
6794 // This produces the value that renders an instance, used by the iterators code
6796 public class ProxyInstance : Expression, IMemoryLocation {
6797 public override Expression DoResolve (EmitContext ec)
6799 eclass = ExprClass.Variable;
6800 type = ec.ContainerType;
6804 public override void Emit (EmitContext ec)
6806 ec.ig.Emit (OpCodes.Ldarg_0);
6810 public void AddressOf (EmitContext ec, AddressOp mode)
6812 ec.ig.Emit (OpCodes.Ldarg_0);
6817 /// Implements the typeof operator
6819 public class TypeOf : Expression {
6820 readonly Expression QueriedType;
6821 protected Type typearg;
6823 public TypeOf (Expression queried_type, Location l)
6825 QueriedType = queried_type;
6829 public override Expression DoResolve (EmitContext ec)
6831 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
6835 typearg = texpr.Type;
6837 if (typearg == TypeManager.void_type) {
6838 Error (673, "System.Void cannot be used from C#. Use typeof (void) to get the void type object");
6842 if (typearg.IsPointer && !ec.InUnsafe){
6847 type = TypeManager.type_type;
6848 // Even though what is returned is a type object, it's treated as a value by the compiler.
6849 // In particular, 'typeof (Foo).X' is something totally different from 'Foo.X'.
6850 eclass = ExprClass.Value;
6854 public override void Emit (EmitContext ec)
6856 ec.ig.Emit (OpCodes.Ldtoken, typearg);
6857 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6860 public override bool GetAttributableValue (Type valueType, out object value)
6862 if (valueType == TypeManager.object_type) {
6863 value = (object)typearg;
6872 /// Implements the `typeof (void)' operator
6874 public class TypeOfVoid : TypeOf {
6875 public TypeOfVoid (Location l) : base (null, l)
6880 public override Expression DoResolve (EmitContext ec)
6882 type = TypeManager.type_type;
6883 typearg = TypeManager.void_type;
6884 // See description in TypeOf.
6885 eclass = ExprClass.Value;
6891 /// Implements the sizeof expression
6893 public class SizeOf : Expression {
6894 public Expression QueriedType;
6897 public SizeOf (Expression queried_type, Location l)
6899 this.QueriedType = queried_type;
6903 public override Expression DoResolve (EmitContext ec)
6905 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
6909 type_queried = texpr.Type;
6911 int size_of = GetTypeSize (type_queried);
6913 return new IntConstant (size_of, loc);
6917 Report.Error (233, loc, "`{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)",
6918 TypeManager.CSharpName (type_queried));
6922 if (!TypeManager.VerifyUnManaged (type_queried, loc)){
6926 type = TypeManager.int32_type;
6927 eclass = ExprClass.Value;
6931 public override void Emit (EmitContext ec)
6933 int size = GetTypeSize (type_queried);
6936 ec.ig.Emit (OpCodes.Sizeof, type_queried);
6938 IntConstant.EmitInt (ec.ig, size);
6943 /// Implements the qualified-alias-member (::) expression.
6945 public class QualifiedAliasMember : Expression
6947 string alias, identifier;
6949 public QualifiedAliasMember (string alias, string identifier, Location l)
6952 this.identifier = identifier;
6956 public override FullNamedExpression ResolveAsTypeStep (IResolveContext ec, bool silent)
6958 if (alias == "global")
6959 return new MemberAccess (RootNamespace.Global, identifier).ResolveAsTypeStep (ec, silent);
6961 int errors = Report.Errors;
6962 FullNamedExpression fne = ec.DeclContainer.NamespaceEntry.LookupAlias (alias);
6964 if (errors == Report.Errors)
6965 Report.Error (432, loc, "Alias `{0}' not found", alias);
6968 if (fne.eclass != ExprClass.Namespace) {
6970 Report.Error (431, loc, "`{0}' cannot be used with '::' since it denotes a type", alias);
6973 return new MemberAccess (fne, identifier).ResolveAsTypeStep (ec, silent);
6976 public override Expression DoResolve (EmitContext ec)
6978 FullNamedExpression fne;
6979 if (alias == "global") {
6980 fne = RootNamespace.Global;
6982 int errors = Report.Errors;
6983 fne = ec.DeclContainer.NamespaceEntry.LookupAlias (alias);
6985 if (errors == Report.Errors)
6986 Report.Error (432, loc, "Alias `{0}' not found", alias);
6991 Expression retval = new MemberAccess (fne, identifier).DoResolve (ec);
6995 if (!(retval is FullNamedExpression)) {
6996 Report.Error (687, loc, "The expression `{0}::{1}' did not resolve to a namespace or a type", alias, identifier);
7000 // We defer this check till the end to match the behaviour of CSC
7001 if (fne.eclass != ExprClass.Namespace) {
7002 Report.Error (431, loc, "`{0}' cannot be used with '::' since it denotes a type", alias);
7008 public override void Emit (EmitContext ec)
7010 throw new InternalErrorException ("QualifiedAliasMember found in resolved tree");
7014 public override string ToString ()
7016 return alias + "::" + identifier;
7019 public override string GetSignatureForError ()
7026 /// Implements the member access expression
7028 public class MemberAccess : Expression {
7029 public readonly string Identifier;
7032 public MemberAccess (Expression expr, string id)
7036 loc = expr.Location;
7039 public Expression Expr {
7040 get { return expr; }
7043 // TODO: this method has very poor performace for Enum fields and
7044 // probably for other constants as well
7045 Expression DoResolve (EmitContext ec, Expression right_side)
7048 throw new Exception ();
7051 // Resolve the expression with flow analysis turned off, we'll do the definite
7052 // assignment checks later. This is because we don't know yet what the expression
7053 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7054 // definite assignment check on the actual field and not on the whole struct.
7057 SimpleName original = expr as SimpleName;
7058 Expression new_expr = expr.Resolve (ec,
7059 ResolveFlags.VariableOrValue | ResolveFlags.Type |
7060 ResolveFlags.Intermediate | ResolveFlags.DisableStructFlowAnalysis);
7062 if (new_expr == null)
7065 if (new_expr is Namespace) {
7066 Namespace ns = (Namespace) new_expr;
7067 FullNamedExpression retval = ns.Lookup (ec.DeclContainer, Identifier, loc);
7069 Report.Error (234, loc, "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
7070 Identifier, ns.FullName);
7074 Type expr_type = new_expr.Type;
7075 if (expr_type.IsPointer){
7076 Error (23, "The `.' operator can not be applied to pointer operands (" +
7077 TypeManager.CSharpName (expr_type) + ")");
7079 } else if (expr_type == TypeManager.void_type) {
7080 Error (23, "The `.' operator can not be applied to operands of type 'void'");
7082 } else if (expr_type == TypeManager.anonymous_method_type){
7083 Error (23, "The `.' operator can not be applied to anonymous methods");
7087 Expression member_lookup;
7088 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
7089 if (member_lookup == null)
7092 if (member_lookup is TypeExpr) {
7093 if (!(new_expr is TypeExpr) &&
7094 (original == null || !original.IdenticalNameAndTypeName (ec, new_expr, loc))) {
7095 Report.Error (572, loc, "`{0}': cannot reference a type through an expression; try `{1}' instead",
7096 Identifier, member_lookup.GetSignatureForError ());
7100 return member_lookup;
7103 MemberExpr me = (MemberExpr) member_lookup;
7104 member_lookup = me.ResolveMemberAccess (ec, new_expr, loc, original);
7105 if (member_lookup == null)
7108 if (original != null && !TypeManager.IsValueType (expr_type)) {
7109 me = member_lookup as MemberExpr;
7110 if (me != null && me.IsInstance) {
7111 LocalVariableReference var = new_expr as LocalVariableReference;
7112 if (var != null && !var.VerifyAssigned (ec))
7117 // The following DoResolve/DoResolveLValue will do the definite assignment
7120 if (right_side != null)
7121 return member_lookup.DoResolveLValue (ec, right_side);
7123 return member_lookup.DoResolve (ec);
7126 public override Expression DoResolve (EmitContext ec)
7128 return DoResolve (ec, null);
7131 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7133 return DoResolve (ec, right_side);
7136 public override FullNamedExpression ResolveAsTypeStep (IResolveContext ec, bool silent)
7138 return ResolveNamespaceOrType (ec, silent);
7141 public FullNamedExpression ResolveNamespaceOrType (IResolveContext rc, bool silent)
7143 FullNamedExpression new_expr = expr.ResolveAsTypeStep (rc, silent);
7145 if (new_expr == null)
7148 if (new_expr is Namespace) {
7149 Namespace ns = (Namespace) new_expr;
7150 FullNamedExpression retval = ns.Lookup (rc.DeclContainer, Identifier, loc);
7151 if (!silent && retval == null)
7152 Report.Error (234, loc, "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
7153 Identifier, ns.FullName);
7157 Type expr_type = new_expr.Type;
7159 if (expr_type.IsPointer){
7160 Error (23, "The `.' operator can not be applied to pointer operands (" +
7161 TypeManager.CSharpName (expr_type) + ")");
7165 Expression member_lookup = MemberLookup (rc.DeclContainer.TypeBuilder, expr_type, expr_type, Identifier, loc);
7166 if (member_lookup == null) {
7167 int errors = Report.Errors;
7168 MemberLookupFailed (rc.DeclContainer.TypeBuilder, expr_type, expr_type, Identifier, null, false, loc);
7170 if (!silent && errors == Report.Errors) {
7171 Report.Error (426, loc, "The nested type `{0}' does not exist in the type `{1}'",
7172 Identifier, new_expr.GetSignatureForError ());
7177 if (!(member_lookup is TypeExpr)) {
7178 new_expr.Error_UnexpectedKind (rc.DeclContainer, "type", loc);
7182 return member_lookup.ResolveAsTypeTerminal (rc, silent);
7185 public override void Emit (EmitContext ec)
7187 throw new Exception ("Should not happen");
7190 public override string ToString ()
7192 return expr + "." + Identifier;
7195 public override string GetSignatureForError ()
7197 return expr.GetSignatureForError () + "." + Identifier;
7202 /// Implements checked expressions
7204 public class CheckedExpr : Expression {
7206 public Expression Expr;
7208 public CheckedExpr (Expression e, Location l)
7214 public override Expression DoResolve (EmitContext ec)
7216 bool last_check = ec.CheckState;
7217 bool last_const_check = ec.ConstantCheckState;
7219 ec.CheckState = true;
7220 ec.ConstantCheckState = true;
7221 Expr = Expr.Resolve (ec);
7222 ec.CheckState = last_check;
7223 ec.ConstantCheckState = last_const_check;
7228 if (Expr is Constant)
7231 eclass = Expr.eclass;
7236 public override void Emit (EmitContext ec)
7238 bool last_check = ec.CheckState;
7239 bool last_const_check = ec.ConstantCheckState;
7241 ec.CheckState = true;
7242 ec.ConstantCheckState = true;
7244 ec.CheckState = last_check;
7245 ec.ConstantCheckState = last_const_check;
7251 /// Implements the unchecked expression
7253 public class UnCheckedExpr : Expression {
7255 public Expression Expr;
7257 public UnCheckedExpr (Expression e, Location l)
7263 public override Expression DoResolve (EmitContext ec)
7265 bool last_check = ec.CheckState;
7266 bool last_const_check = ec.ConstantCheckState;
7268 ec.CheckState = false;
7269 ec.ConstantCheckState = false;
7270 Expr = Expr.Resolve (ec);
7271 ec.CheckState = last_check;
7272 ec.ConstantCheckState = last_const_check;
7277 if (Expr is Constant)
7280 eclass = Expr.eclass;
7285 public override void Emit (EmitContext ec)
7287 bool last_check = ec.CheckState;
7288 bool last_const_check = ec.ConstantCheckState;
7290 ec.CheckState = false;
7291 ec.ConstantCheckState = false;
7293 ec.CheckState = last_check;
7294 ec.ConstantCheckState = last_const_check;
7300 /// An Element Access expression.
7302 /// During semantic analysis these are transformed into
7303 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7305 public class ElementAccess : Expression {
7306 public ArrayList Arguments;
7307 public Expression Expr;
7309 public ElementAccess (Expression e, ArrayList e_list)
7318 Arguments = new ArrayList ();
7319 foreach (Expression tmp in e_list)
7320 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7324 bool CommonResolve (EmitContext ec)
7326 Expr = Expr.Resolve (ec);
7331 if (Arguments == null)
7334 foreach (Argument a in Arguments){
7335 if (!a.Resolve (ec, loc))
7342 Expression MakePointerAccess (EmitContext ec, Type t)
7344 if (t == TypeManager.void_ptr_type){
7345 Error (242, "The array index operation is not valid on void pointers");
7348 if (Arguments.Count != 1){
7349 Error (196, "A pointer must be indexed by only one value");
7354 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc).Resolve (ec);
7357 return new Indirection (p, loc).Resolve (ec);
7360 public override Expression DoResolve (EmitContext ec)
7362 if (!CommonResolve (ec))
7366 // We perform some simple tests, and then to "split" the emit and store
7367 // code we create an instance of a different class, and return that.
7369 // I am experimenting with this pattern.
7373 if (t == TypeManager.array_type){
7374 Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `System.Array'");
7379 return (new ArrayAccess (this, loc)).Resolve (ec);
7381 return MakePointerAccess (ec, Expr.Type);
7383 FieldExpr fe = Expr as FieldExpr;
7385 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
7387 return MakePointerAccess (ec, ff.ElementType);
7390 return (new IndexerAccess (this, loc)).Resolve (ec);
7393 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7395 if (!CommonResolve (ec))
7400 return (new ArrayAccess (this, loc)).DoResolveLValue (ec, right_side);
7403 return MakePointerAccess (ec, Expr.Type);
7405 FieldExpr fe = Expr as FieldExpr;
7407 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
7409 if (!(fe.InstanceExpression is LocalVariableReference) &&
7410 !(fe.InstanceExpression is This)) {
7411 Report.Error (1708, loc, "Fixed size buffers can only be accessed through locals or fields");
7414 if (!ec.InFixedInitializer && ec.ContainerType.IsValueType) {
7415 Error (1666, "You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement");
7418 return MakePointerAccess (ec, ff.ElementType);
7421 return (new IndexerAccess (this, loc)).DoResolveLValue (ec, right_side);
7424 public override void Emit (EmitContext ec)
7426 throw new Exception ("Should never be reached");
7431 /// Implements array access
7433 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7435 // Points to our "data" repository
7439 LocalTemporary temp;
7442 public ArrayAccess (ElementAccess ea_data, Location l)
7445 eclass = ExprClass.Variable;
7449 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7451 return DoResolve (ec);
7454 public override Expression DoResolve (EmitContext ec)
7457 ExprClass eclass = ea.Expr.eclass;
7459 // As long as the type is valid
7460 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7461 eclass == ExprClass.Value)) {
7462 ea.Expr.Error_UnexpectedKind ("variable or value");
7467 Type t = ea.Expr.Type;
7468 if (t.GetArrayRank () != ea.Arguments.Count){
7469 Report.Error (22, ea.Location, "Wrong number of indexes `{0}' inside [], expected `{1}'",
7470 ea.Arguments.Count.ToString (), t.GetArrayRank ().ToString ());
7474 type = TypeManager.GetElementType (t);
7475 if (type.IsPointer && !ec.InUnsafe){
7476 UnsafeError (ea.Location);
7480 foreach (Argument a in ea.Arguments){
7481 Type argtype = a.Type;
7483 if (argtype == TypeManager.int32_type ||
7484 argtype == TypeManager.uint32_type ||
7485 argtype == TypeManager.int64_type ||
7486 argtype == TypeManager.uint64_type) {
7487 Constant c = a.Expr as Constant;
7488 if (c != null && c.IsNegative) {
7489 Report.Warning (251, 2, ea.Location, "Indexing an array with a negative index (array indices always start at zero)");
7495 // Mhm. This is strage, because the Argument.Type is not the same as
7496 // Argument.Expr.Type: the value changes depending on the ref/out setting.
7498 // Wonder if I will run into trouble for this.
7500 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
7505 eclass = ExprClass.Variable;
7511 /// Emits the right opcode to load an object of Type `t'
7512 /// from an array of T
7514 static public void EmitLoadOpcode (ILGenerator ig, Type type)
7516 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7517 ig.Emit (OpCodes.Ldelem_U1);
7518 else if (type == TypeManager.sbyte_type)
7519 ig.Emit (OpCodes.Ldelem_I1);
7520 else if (type == TypeManager.short_type)
7521 ig.Emit (OpCodes.Ldelem_I2);
7522 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7523 ig.Emit (OpCodes.Ldelem_U2);
7524 else if (type == TypeManager.int32_type)
7525 ig.Emit (OpCodes.Ldelem_I4);
7526 else if (type == TypeManager.uint32_type)
7527 ig.Emit (OpCodes.Ldelem_U4);
7528 else if (type == TypeManager.uint64_type)
7529 ig.Emit (OpCodes.Ldelem_I8);
7530 else if (type == TypeManager.int64_type)
7531 ig.Emit (OpCodes.Ldelem_I8);
7532 else if (type == TypeManager.float_type)
7533 ig.Emit (OpCodes.Ldelem_R4);
7534 else if (type == TypeManager.double_type)
7535 ig.Emit (OpCodes.Ldelem_R8);
7536 else if (type == TypeManager.intptr_type)
7537 ig.Emit (OpCodes.Ldelem_I);
7538 else if (TypeManager.IsEnumType (type)){
7539 EmitLoadOpcode (ig, TypeManager.EnumToUnderlying (type));
7540 } else if (type.IsValueType){
7541 ig.Emit (OpCodes.Ldelema, type);
7542 ig.Emit (OpCodes.Ldobj, type);
7543 } else if (type.IsPointer)
7544 ig.Emit (OpCodes.Ldelem_I);
7546 ig.Emit (OpCodes.Ldelem_Ref);
7550 /// Returns the right opcode to store an object of Type `t'
7551 /// from an array of T.
7553 static public OpCode GetStoreOpcode (Type t, out bool is_stobj)
7555 //Console.WriteLine (new System.Diagnostics.StackTrace ());
7557 t = TypeManager.TypeToCoreType (t);
7558 if (TypeManager.IsEnumType (t))
7559 t = TypeManager.EnumToUnderlying (t);
7560 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
7561 t == TypeManager.bool_type)
7562 return OpCodes.Stelem_I1;
7563 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
7564 t == TypeManager.char_type)
7565 return OpCodes.Stelem_I2;
7566 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
7567 return OpCodes.Stelem_I4;
7568 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
7569 return OpCodes.Stelem_I8;
7570 else if (t == TypeManager.float_type)
7571 return OpCodes.Stelem_R4;
7572 else if (t == TypeManager.double_type)
7573 return OpCodes.Stelem_R8;
7574 else if (t == TypeManager.intptr_type) {
7576 return OpCodes.Stobj;
7577 } else if (t.IsValueType) {
7579 return OpCodes.Stobj;
7580 } else if (t.IsPointer)
7581 return OpCodes.Stelem_I;
7583 return OpCodes.Stelem_Ref;
7586 MethodInfo FetchGetMethod ()
7588 ModuleBuilder mb = CodeGen.Module.Builder;
7589 int arg_count = ea.Arguments.Count;
7590 Type [] args = new Type [arg_count];
7593 for (int i = 0; i < arg_count; i++){
7594 //args [i++] = a.Type;
7595 args [i] = TypeManager.int32_type;
7598 get = mb.GetArrayMethod (
7599 ea.Expr.Type, "Get",
7600 CallingConventions.HasThis |
7601 CallingConventions.Standard,
7607 MethodInfo FetchAddressMethod ()
7609 ModuleBuilder mb = CodeGen.Module.Builder;
7610 int arg_count = ea.Arguments.Count;
7611 Type [] args = new Type [arg_count];
7615 ret_type = TypeManager.GetReferenceType (type);
7617 for (int i = 0; i < arg_count; i++){
7618 //args [i++] = a.Type;
7619 args [i] = TypeManager.int32_type;
7622 address = mb.GetArrayMethod (
7623 ea.Expr.Type, "Address",
7624 CallingConventions.HasThis |
7625 CallingConventions.Standard,
7632 // Load the array arguments into the stack.
7634 // If we have been requested to cache the values (cached_locations array
7635 // initialized), then load the arguments the first time and store them
7636 // in locals. otherwise load from local variables.
7638 void LoadArrayAndArguments (EmitContext ec)
7640 ILGenerator ig = ec.ig;
7643 foreach (Argument a in ea.Arguments){
7644 Type argtype = a.Expr.Type;
7648 if (argtype == TypeManager.int64_type)
7649 ig.Emit (OpCodes.Conv_Ovf_I);
7650 else if (argtype == TypeManager.uint64_type)
7651 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7655 public void Emit (EmitContext ec, bool leave_copy)
7657 int rank = ea.Expr.Type.GetArrayRank ();
7658 ILGenerator ig = ec.ig;
7661 LoadArrayAndArguments (ec);
7664 EmitLoadOpcode (ig, type);
7668 method = FetchGetMethod ();
7669 ig.Emit (OpCodes.Call, method);
7672 LoadFromPtr (ec.ig, this.type);
7675 ec.ig.Emit (OpCodes.Dup);
7676 temp = new LocalTemporary (this.type);
7681 public override void Emit (EmitContext ec)
7686 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
7688 int rank = ea.Expr.Type.GetArrayRank ();
7689 ILGenerator ig = ec.ig;
7690 Type t = source.Type;
7691 prepared = prepare_for_load;
7693 if (prepare_for_load) {
7694 AddressOf (ec, AddressOp.LoadStore);
7695 ec.ig.Emit (OpCodes.Dup);
7698 ec.ig.Emit (OpCodes.Dup);
7699 temp = new LocalTemporary (this.type);
7702 StoreFromPtr (ec.ig, t);
7710 LoadArrayAndArguments (ec);
7714 OpCode op = GetStoreOpcode (t, out is_stobj);
7716 // The stobj opcode used by value types will need
7717 // an address on the stack, not really an array/array
7721 ig.Emit (OpCodes.Ldelema, t);
7725 ec.ig.Emit (OpCodes.Dup);
7726 temp = new LocalTemporary (this.type);
7731 ig.Emit (OpCodes.Stobj, t);
7735 ModuleBuilder mb = CodeGen.Module.Builder;
7736 int arg_count = ea.Arguments.Count;
7737 Type [] args = new Type [arg_count + 1];
7742 ec.ig.Emit (OpCodes.Dup);
7743 temp = new LocalTemporary (this.type);
7747 for (int i = 0; i < arg_count; i++){
7748 //args [i++] = a.Type;
7749 args [i] = TypeManager.int32_type;
7752 args [arg_count] = type;
7754 set = mb.GetArrayMethod (
7755 ea.Expr.Type, "Set",
7756 CallingConventions.HasThis |
7757 CallingConventions.Standard,
7758 TypeManager.void_type, args);
7760 ig.Emit (OpCodes.Call, set);
7767 public void AddressOf (EmitContext ec, AddressOp mode)
7769 int rank = ea.Expr.Type.GetArrayRank ();
7770 ILGenerator ig = ec.ig;
7772 LoadArrayAndArguments (ec);
7775 ig.Emit (OpCodes.Ldelema, type);
7777 MethodInfo address = FetchAddressMethod ();
7778 ig.Emit (OpCodes.Call, address);
7782 public void EmitGetLength (EmitContext ec, int dim)
7784 int rank = ea.Expr.Type.GetArrayRank ();
7785 ILGenerator ig = ec.ig;
7789 ig.Emit (OpCodes.Ldlen);
7790 ig.Emit (OpCodes.Conv_I4);
7792 IntLiteral.EmitInt (ig, dim);
7793 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
7799 // note that the ArrayList itself in mutable. We just can't assign to 'Properties' again.
7800 public readonly ArrayList Properties;
7801 static Indexers empty;
7803 public struct Indexer {
7804 public readonly PropertyInfo PropertyInfo;
7805 public readonly MethodInfo Getter, Setter;
7807 public Indexer (PropertyInfo property_info, MethodInfo get, MethodInfo set)
7809 this.PropertyInfo = property_info;
7817 empty = new Indexers (null);
7820 Indexers (ArrayList array)
7825 static void Append (ref Indexers ix, Type caller_type, MemberInfo [] mi)
7830 foreach (PropertyInfo property in mi){
7831 MethodInfo get, set;
7833 get = property.GetGetMethod (true);
7834 set = property.GetSetMethod (true);
7835 if (get != null && !Expression.IsAccessorAccessible (caller_type, get, out dummy))
7837 if (set != null && !Expression.IsAccessorAccessible (caller_type, set, out dummy))
7839 if (get != null || set != null) {
7841 ix = new Indexers (new ArrayList ());
7842 ix.Properties.Add (new Indexer (property, get, set));
7847 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
7849 string p_name = TypeManager.IndexerPropertyName (lookup_type);
7851 return TypeManager.MemberLookup (
7852 caller_type, caller_type, lookup_type, MemberTypes.Property,
7853 BindingFlags.Public | BindingFlags.Instance |
7854 BindingFlags.DeclaredOnly, p_name, null);
7857 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type)
7859 Indexers ix = empty;
7861 Type copy = lookup_type;
7862 while (copy != TypeManager.object_type && copy != null){
7863 Append (ref ix, caller_type, GetIndexersForTypeOrInterface (caller_type, copy));
7864 copy = copy.BaseType;
7867 if (lookup_type.IsInterface) {
7868 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
7869 if (ifaces != null) {
7870 foreach (Type itype in ifaces)
7871 Append (ref ix, caller_type, GetIndexersForTypeOrInterface (caller_type, itype));
7880 /// Expressions that represent an indexer call.
7882 public class IndexerAccess : Expression, IAssignMethod {
7884 // Points to our "data" repository
7886 MethodInfo get, set;
7887 ArrayList set_arguments;
7888 bool is_base_indexer;
7890 protected Type indexer_type;
7891 protected Type current_type;
7892 protected Expression instance_expr;
7893 protected ArrayList arguments;
7895 public IndexerAccess (ElementAccess ea, Location loc)
7896 : this (ea.Expr, false, loc)
7898 this.arguments = ea.Arguments;
7901 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
7904 this.instance_expr = instance_expr;
7905 this.is_base_indexer = is_base_indexer;
7906 this.eclass = ExprClass.Value;
7910 protected virtual bool CommonResolve (EmitContext ec)
7912 indexer_type = instance_expr.Type;
7913 current_type = ec.ContainerType;
7918 public override Expression DoResolve (EmitContext ec)
7920 ArrayList AllGetters = new ArrayList();
7921 if (!CommonResolve (ec))
7925 // Step 1: Query for all `Item' *properties*. Notice
7926 // that the actual methods are pointed from here.
7928 // This is a group of properties, piles of them.
7930 bool found_any = false, found_any_getters = false;
7931 Type lookup_type = indexer_type;
7933 Indexers ilist = Indexers.GetIndexersForType (current_type, lookup_type);
7934 if (ilist.Properties != null) {
7936 foreach (Indexers.Indexer ix in ilist.Properties) {
7937 if (ix.Getter != null)
7938 AllGetters.Add (ix.Getter);
7942 if (AllGetters.Count > 0) {
7943 found_any_getters = true;
7944 get = (MethodInfo) Invocation.OverloadResolve (
7945 ec, new MethodGroupExpr (AllGetters, loc),
7946 arguments, false, loc);
7950 Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
7951 TypeManager.CSharpName (indexer_type));
7955 if (!found_any_getters) {
7956 Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
7962 Invocation.Error_WrongNumArguments (loc, "this", arguments.Count);
7967 // Only base will allow this invocation to happen.
7969 if (get.IsAbstract && this is BaseIndexerAccess){
7970 Error_CannotCallAbstractBase (TypeManager.CSharpSignature (get));
7974 type = get.ReturnType;
7975 if (type.IsPointer && !ec.InUnsafe){
7980 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
7982 eclass = ExprClass.IndexerAccess;
7986 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7988 if (right_side == EmptyExpression.OutAccess) {
7989 Report.Error (206, loc, "A property or indexer `{0}' may not be passed as an out or ref parameter",
7990 GetSignatureForError ());
7994 // if the indexer returns a value type, and we try to set a field in it
7995 if (right_side == EmptyExpression.LValueMemberAccess) {
7996 Report.Error (1612, loc, "Cannot modify the return value of `{0}' because it is not a variable",
7997 GetSignatureForError ());
8001 ArrayList AllSetters = new ArrayList();
8002 if (!CommonResolve (ec))
8005 bool found_any = false, found_any_setters = false;
8007 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type);
8008 if (ilist.Properties != null) {
8010 foreach (Indexers.Indexer ix in ilist.Properties) {
8011 if (ix.Setter != null)
8012 AllSetters.Add (ix.Setter);
8015 if (AllSetters.Count > 0) {
8016 found_any_setters = true;
8017 set_arguments = (ArrayList) arguments.Clone ();
8018 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
8019 set = (MethodInfo) Invocation.OverloadResolve (
8020 ec, new MethodGroupExpr (AllSetters, loc),
8021 set_arguments, false, loc);
8025 Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
8026 TypeManager.CSharpName (indexer_type));
8030 if (!found_any_setters) {
8031 Error (154, "indexer can not be used in this context, because " +
8032 "it lacks a `set' accessor");
8037 Invocation.Error_WrongNumArguments (loc, "this", arguments.Count);
8042 // Only base will allow this invocation to happen.
8044 if (set.IsAbstract && this is BaseIndexerAccess){
8045 Error_CannotCallAbstractBase (TypeManager.CSharpSignature (set));
8050 // Now look for the actual match in the list of indexers to set our "return" type
8052 type = TypeManager.void_type; // default value
8053 foreach (Indexers.Indexer ix in ilist.Properties){
8054 if (ix.Setter == set){
8055 type = ix.PropertyInfo.PropertyType;
8060 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8062 eclass = ExprClass.IndexerAccess;
8066 bool prepared = false;
8067 LocalTemporary temp;
8069 public void Emit (EmitContext ec, bool leave_copy)
8071 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc, prepared, false);
8073 ec.ig.Emit (OpCodes.Dup);
8074 temp = new LocalTemporary (Type);
8080 // source is ignored, because we already have a copy of it from the
8081 // LValue resolution and we have already constructed a pre-cached
8082 // version of the arguments (ea.set_arguments);
8084 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8086 prepared = prepare_for_load;
8087 Argument a = (Argument) set_arguments [set_arguments.Count - 1];
8092 ec.ig.Emit (OpCodes.Dup);
8093 temp = new LocalTemporary (Type);
8096 } else if (leave_copy) {
8097 temp = new LocalTemporary (Type);
8103 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc, false, prepared);
8110 public override void Emit (EmitContext ec)
8115 public override string GetSignatureForError ()
8117 // FIXME: print the argument list of the indexer
8118 return instance_expr.GetSignatureForError () + ".this[...]";
8123 /// The base operator for method names
8125 public class BaseAccess : Expression {
8128 public BaseAccess (string member, Location l)
8130 this.member = member;
8134 public override Expression DoResolve (EmitContext ec)
8136 Expression c = CommonResolve (ec);
8142 // MethodGroups use this opportunity to flag an error on lacking ()
8144 if (!(c is MethodGroupExpr))
8145 return c.Resolve (ec);
8149 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8151 Expression c = CommonResolve (ec);
8157 // MethodGroups use this opportunity to flag an error on lacking ()
8159 if (! (c is MethodGroupExpr))
8160 return c.DoResolveLValue (ec, right_side);
8165 Expression CommonResolve (EmitContext ec)
8167 Expression member_lookup;
8168 Type current_type = ec.ContainerType;
8169 Type base_type = current_type.BaseType;
8172 Error (1511, "Keyword `base' is not available in a static method");
8176 if (ec.IsFieldInitializer){
8177 Error (1512, "Keyword `base' is not available in the current context");
8181 member_lookup = MemberLookup (ec.ContainerType, null, base_type, member,
8182 AllMemberTypes, AllBindingFlags, loc);
8183 if (member_lookup == null) {
8184 MemberLookupFailed (ec.ContainerType, base_type, base_type, member, null, true, loc);
8191 left = new TypeExpression (base_type, loc);
8193 left = ec.GetThis (loc);
8195 MemberExpr me = (MemberExpr) member_lookup;
8197 Expression e = me.ResolveMemberAccess (ec, left, loc, null);
8199 if (e is PropertyExpr) {
8200 PropertyExpr pe = (PropertyExpr) e;
8205 if (e is MethodGroupExpr)
8206 ((MethodGroupExpr) e).IsBase = true;
8211 public override void Emit (EmitContext ec)
8213 throw new Exception ("Should never be called");
8218 /// The base indexer operator
8220 public class BaseIndexerAccess : IndexerAccess {
8221 public BaseIndexerAccess (ArrayList args, Location loc)
8222 : base (null, true, loc)
8224 arguments = new ArrayList ();
8225 foreach (Expression tmp in args)
8226 arguments.Add (new Argument (tmp, Argument.AType.Expression));
8229 protected override bool CommonResolve (EmitContext ec)
8231 instance_expr = ec.GetThis (loc);
8233 current_type = ec.ContainerType.BaseType;
8234 indexer_type = current_type;
8236 foreach (Argument a in arguments){
8237 if (!a.Resolve (ec, loc))
8246 /// This class exists solely to pass the Type around and to be a dummy
8247 /// that can be passed to the conversion functions (this is used by
8248 /// foreach implementation to typecast the object return value from
8249 /// get_Current into the proper type. All code has been generated and
8250 /// we only care about the side effect conversions to be performed
8252 /// This is also now used as a placeholder where a no-action expression
8253 /// is needed (the `New' class).
8255 public class EmptyExpression : Expression {
8256 public static readonly EmptyExpression Null = new EmptyExpression ();
8258 public static readonly EmptyExpression OutAccess = new EmptyExpression ();
8259 public static readonly EmptyExpression LValueMemberAccess = new EmptyExpression ();
8261 static EmptyExpression temp = new EmptyExpression ();
8262 public static EmptyExpression Grab ()
8265 throw new InternalErrorException ("Nested Grab");
8266 EmptyExpression retval = temp;
8271 public static void Release (EmptyExpression e)
8274 throw new InternalErrorException ("Already released");
8278 // TODO: should be protected
8279 public EmptyExpression ()
8281 type = TypeManager.object_type;
8282 eclass = ExprClass.Value;
8283 loc = Location.Null;
8286 public EmptyExpression (Type t)
8289 eclass = ExprClass.Value;
8290 loc = Location.Null;
8293 public override Expression DoResolve (EmitContext ec)
8298 public override void Emit (EmitContext ec)
8300 // nothing, as we only exist to not do anything.
8304 // This is just because we might want to reuse this bad boy
8305 // instead of creating gazillions of EmptyExpressions.
8306 // (CanImplicitConversion uses it)
8308 public void SetType (Type t)
8314 public class UserCast : Expression {
8318 public UserCast (MethodInfo method, Expression source, Location l)
8320 this.method = method;
8321 this.source = source;
8322 type = method.ReturnType;
8323 eclass = ExprClass.Value;
8327 public Expression Source {
8333 public override Expression DoResolve (EmitContext ec)
8336 // We are born fully resolved
8341 public override void Emit (EmitContext ec)
8343 ILGenerator ig = ec.ig;
8347 if (method is MethodInfo)
8348 ig.Emit (OpCodes.Call, (MethodInfo) method);
8350 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
8356 // This class is used to "construct" the type during a typecast
8357 // operation. Since the Type.GetType class in .NET can parse
8358 // the type specification, we just use this to construct the type
8359 // one bit at a time.
8361 public class ComposedCast : TypeExpr {
8365 public ComposedCast (Expression left, string dim)
8366 : this (left, dim, left.Location)
8370 public ComposedCast (Expression left, string dim, Location l)
8377 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
8379 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec, false);
8383 Type ltype = lexpr.Type;
8384 if ((ltype == TypeManager.void_type) && (dim != "*")) {
8385 Report.Error (1547, Location,
8386 "Keyword 'void' cannot be used in this context");
8390 if (dim == "*" && !TypeManager.VerifyUnManaged (ltype, loc)) {
8394 type = TypeManager.GetConstructedType (ltype, dim);
8396 throw new InternalErrorException ("Couldn't create computed type " + ltype + dim);
8399 if (type.IsPointer && !ec.IsInUnsafeScope){
8404 if (type.IsArray && (type.GetElementType () == TypeManager.arg_iterator_type ||
8405 type.GetElementType () == TypeManager.typed_reference_type)) {
8406 Report.Error (611, loc, "Array elements cannot be of type `{0}'", TypeManager.CSharpName (type.GetElementType ()));
8410 eclass = ExprClass.Type;
8414 public override string Name {
8415 get { return left + dim; }
8418 public override string FullName {
8419 get { return type.FullName; }
8422 public override string GetSignatureForError ()
8424 return left.GetSignatureForError () + dim;
8428 public class FixedBufferPtr : Expression {
8431 public FixedBufferPtr (Expression array, Type array_type, Location l)
8436 type = TypeManager.GetPointerType (array_type);
8437 eclass = ExprClass.Value;
8440 public override void Emit(EmitContext ec)
8445 public override Expression DoResolve (EmitContext ec)
8448 // We are born fully resolved
8456 // This class is used to represent the address of an array, used
8457 // only by the Fixed statement, this generates "&a [0]" construct
8458 // for fixed (char *pa = a)
8460 public class ArrayPtr : FixedBufferPtr {
8463 public ArrayPtr (Expression array, Type array_type, Location l):
8464 base (array, array_type, l)
8466 this.array_type = array_type;
8469 public override void Emit (EmitContext ec)
8473 ILGenerator ig = ec.ig;
8474 IntLiteral.EmitInt (ig, 0);
8475 ig.Emit (OpCodes.Ldelema, array_type);
8480 // Used by the fixed statement
8482 public class StringPtr : Expression {
8485 public StringPtr (LocalBuilder b, Location l)
8488 eclass = ExprClass.Value;
8489 type = TypeManager.char_ptr_type;
8493 public override Expression DoResolve (EmitContext ec)
8495 // This should never be invoked, we are born in fully
8496 // initialized state.
8501 public override void Emit (EmitContext ec)
8503 ILGenerator ig = ec.ig;
8505 ig.Emit (OpCodes.Ldloc, b);
8506 ig.Emit (OpCodes.Conv_I);
8507 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
8508 ig.Emit (OpCodes.Add);
8513 // Implements the `stackalloc' keyword
8515 public class StackAlloc : Expression {
8520 public StackAlloc (Expression type, Expression count, Location l)
8527 public override Expression DoResolve (EmitContext ec)
8529 count = count.Resolve (ec);
8533 if (count.Type != TypeManager.int32_type){
8534 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8539 Constant c = count as Constant;
8540 if (c != null && c.IsNegative) {
8541 Report.Error (247, loc, "Cannot use a negative size with stackalloc");
8545 if (ec.InCatch || ec.InFinally) {
8546 Error (255, "Cannot use stackalloc in finally or catch");
8550 TypeExpr texpr = t.ResolveAsTypeTerminal (ec, false);
8556 if (!TypeManager.VerifyUnManaged (otype, loc))
8559 type = TypeManager.GetPointerType (otype);
8560 eclass = ExprClass.Value;
8565 public override void Emit (EmitContext ec)
8567 int size = GetTypeSize (otype);
8568 ILGenerator ig = ec.ig;
8571 ig.Emit (OpCodes.Sizeof, otype);
8573 IntConstant.EmitInt (ig, size);
8575 ig.Emit (OpCodes.Mul);
8576 ig.Emit (OpCodes.Localloc);