2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
8 // (C) 2003, 2004 Novell, Inc.
12 namespace Mono.CSharp {
14 using System.Collections;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// This is just a helper class, it is generated by Unary, UnaryMutator
21 /// when an overloaded method has been found. It just emits the code for a
24 public class StaticCallExpr : ExpressionStatement {
28 public StaticCallExpr (MethodInfo m, ArrayList a, Location l)
34 eclass = ExprClass.Value;
38 public override Expression DoResolve (EmitContext ec)
41 // We are born fully resolved
46 public override void Emit (EmitContext ec)
49 Invocation.EmitArguments (ec, mi, args, false, null);
51 ec.ig.Emit (OpCodes.Call, mi);
55 static public StaticCallExpr MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
56 Expression e, Location loc)
61 args = new ArrayList (1);
62 Argument a = new Argument (e, Argument.AType.Expression);
64 // We need to resolve the arguments before sending them in !
65 if (!a.Resolve (ec, loc))
69 method = Invocation.OverloadResolve (
70 ec, (MethodGroupExpr) mg, args, false, loc);
75 return new StaticCallExpr ((MethodInfo) method, args, loc);
78 public override void EmitStatement (EmitContext ec)
81 if (TypeManager.TypeToCoreType (type) != TypeManager.void_type)
82 ec.ig.Emit (OpCodes.Pop);
85 public MethodInfo Method {
90 public class ParenthesizedExpression : Expression
92 public Expression Expr;
94 public ParenthesizedExpression (Expression expr)
99 public override Expression DoResolve (EmitContext ec)
101 Expr = Expr.Resolve (ec);
105 public override void Emit (EmitContext ec)
107 throw new Exception ("Should not happen");
110 public override Location Location
113 return Expr.Location;
119 /// Unary expressions.
123 /// Unary implements unary expressions. It derives from
124 /// ExpressionStatement becuase the pre/post increment/decrement
125 /// operators can be used in a statement context.
127 public class Unary : Expression {
128 public enum Operator : byte {
129 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
130 Indirection, AddressOf, TOP
133 public Operator Oper;
134 public Expression Expr;
136 public Unary (Operator op, Expression expr, Location loc)
144 /// Returns a stringified representation of the Operator
146 static public string OperName (Operator oper)
149 case Operator.UnaryPlus:
151 case Operator.UnaryNegation:
153 case Operator.LogicalNot:
155 case Operator.OnesComplement:
157 case Operator.AddressOf:
159 case Operator.Indirection:
163 return oper.ToString ();
166 public static readonly string [] oper_names;
170 oper_names = new string [(int)Operator.TOP];
172 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
173 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
174 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
175 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
176 oper_names [(int) Operator.Indirection] = "op_Indirection";
177 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
180 void Error23 (Type t)
182 Report.Error (23, loc, "Operator `{0}' cannot be applied to operand of type `{1}'",
183 OperName (Oper), TypeManager.CSharpName (t));
187 /// The result has been already resolved:
189 /// FIXME: a minus constant -128 sbyte cant be turned into a
192 static Expression TryReduceNegative (Constant expr)
196 if (expr is IntConstant)
197 e = new IntConstant (-((IntConstant) expr).Value, expr.Location);
198 else if (expr is UIntConstant){
199 uint value = ((UIntConstant) expr).Value;
201 if (value < 2147483649)
202 return new IntConstant (-(int)value, expr.Location);
204 e = new LongConstant (-value, expr.Location);
206 else if (expr is LongConstant)
207 e = new LongConstant (-((LongConstant) expr).Value, expr.Location);
208 else if (expr is ULongConstant){
209 ulong value = ((ULongConstant) expr).Value;
211 if (value < 9223372036854775809)
212 return new LongConstant(-(long)value, expr.Location);
214 else if (expr is FloatConstant)
215 e = new FloatConstant (-((FloatConstant) expr).Value, expr.Location);
216 else if (expr is DoubleConstant)
217 e = new DoubleConstant (-((DoubleConstant) expr).Value, expr.Location);
218 else if (expr is DecimalConstant)
219 e = new DecimalConstant (-((DecimalConstant) expr).Value, expr.Location);
220 else if (expr is ShortConstant)
221 e = new IntConstant (-((ShortConstant) expr).Value, expr.Location);
222 else if (expr is UShortConstant)
223 e = new IntConstant (-((UShortConstant) expr).Value, expr.Location);
224 else if (expr is SByteConstant)
225 e = new IntConstant (-((SByteConstant) expr).Value, expr.Location);
226 else if (expr is ByteConstant)
227 e = new IntConstant (-((ByteConstant) expr).Value, expr.Location);
232 // This routine will attempt to simplify the unary expression when the
233 // argument is a constant. The result is returned in `result' and the
234 // function returns true or false depending on whether a reduction
235 // was performed or not
237 bool Reduce (EmitContext ec, Constant e, out Expression result)
239 Type expr_type = e.Type;
242 case Operator.UnaryPlus:
243 if (expr_type == TypeManager.bool_type){
252 case Operator.UnaryNegation:
253 result = TryReduceNegative (e);
254 return result != null;
256 case Operator.LogicalNot:
257 if (expr_type != TypeManager.bool_type) {
263 BoolConstant b = (BoolConstant) e;
264 result = new BoolConstant (!(b.Value), b.Location);
267 case Operator.OnesComplement:
268 if (!((expr_type == TypeManager.int32_type) ||
269 (expr_type == TypeManager.uint32_type) ||
270 (expr_type == TypeManager.int64_type) ||
271 (expr_type == TypeManager.uint64_type) ||
272 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
275 if (Convert.ImplicitConversionExists (ec, e, TypeManager.int32_type)){
276 result = new Cast (new TypeExpression (TypeManager.int32_type, loc), e, loc);
277 result = result.Resolve (ec);
278 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint32_type)){
279 result = new Cast (new TypeExpression (TypeManager.uint32_type, loc), e, loc);
280 result = result.Resolve (ec);
281 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.int64_type)){
282 result = new Cast (new TypeExpression (TypeManager.int64_type, loc), e, loc);
283 result = result.Resolve (ec);
284 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint64_type)){
285 result = new Cast (new TypeExpression (TypeManager.uint64_type, loc), e, loc);
286 result = result.Resolve (ec);
289 if (result == null || !(result is Constant)){
295 expr_type = result.Type;
296 e = (Constant) result;
299 if (e is EnumConstant){
300 EnumConstant enum_constant = (EnumConstant) e;
303 if (Reduce (ec, enum_constant.Child, out reduced)){
304 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
312 if (expr_type == TypeManager.int32_type){
313 result = new IntConstant (~ ((IntConstant) e).Value, e.Location);
314 } else if (expr_type == TypeManager.uint32_type){
315 result = new UIntConstant (~ ((UIntConstant) e).Value, e.Location);
316 } else if (expr_type == TypeManager.int64_type){
317 result = new LongConstant (~ ((LongConstant) e).Value, e.Location);
318 } else if (expr_type == TypeManager.uint64_type){
319 result = new ULongConstant (~ ((ULongConstant) e).Value, e.Location);
327 case Operator.AddressOf:
331 case Operator.Indirection:
335 throw new Exception ("Can not constant fold: " + Oper.ToString());
338 Expression ResolveOperator (EmitContext ec)
341 // Step 1: Default operations on CLI native types.
344 // Attempt to use a constant folding operation.
345 if (Expr is Constant){
348 if (Reduce (ec, (Constant) Expr, out result))
353 // Step 2: Perform Operator Overload location
355 Type expr_type = Expr.Type;
359 op_name = oper_names [(int) Oper];
361 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
364 Expression e = StaticCallExpr.MakeSimpleCall (
365 ec, (MethodGroupExpr) mg, Expr, loc);
375 // Only perform numeric promotions on:
378 if (expr_type == null)
382 case Operator.LogicalNot:
383 if (expr_type != TypeManager.bool_type) {
384 Expr = ResolveBoolean (ec, Expr, loc);
391 type = TypeManager.bool_type;
394 case Operator.OnesComplement:
395 if (!((expr_type == TypeManager.int32_type) ||
396 (expr_type == TypeManager.uint32_type) ||
397 (expr_type == TypeManager.int64_type) ||
398 (expr_type == TypeManager.uint64_type) ||
399 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
402 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
405 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint32_type, loc);
408 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
411 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint64_type, loc);
424 case Operator.AddressOf:
430 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
434 IVariable variable = Expr as IVariable;
435 bool is_fixed = variable != null && variable.VerifyFixed ();
437 if (!ec.InFixedInitializer && !is_fixed) {
438 Error (212, "You can only take the address of unfixed expression inside " +
439 "of a fixed statement initializer");
443 if (ec.InFixedInitializer && is_fixed) {
444 Error (213, "You cannot use the fixed statement to take the address of an already fixed expression");
448 LocalVariableReference lr = Expr as LocalVariableReference;
450 if (lr.local_info.IsCaptured){
451 AnonymousMethod.Error_AddressOfCapturedVar (lr.Name, loc);
454 lr.local_info.AddressTaken = true;
455 lr.local_info.Used = true;
458 // According to the specs, a variable is considered definitely assigned if you take
460 if ((variable != null) && (variable.VariableInfo != null)){
461 variable.VariableInfo.SetAssigned (ec);
464 type = TypeManager.GetPointerType (Expr.Type);
467 case Operator.Indirection:
473 if (!expr_type.IsPointer){
474 Error (193, "The * or -> operator must be applied to a pointer");
479 // We create an Indirection expression, because
480 // it can implement the IMemoryLocation.
482 return new Indirection (Expr, loc);
484 case Operator.UnaryPlus:
486 // A plus in front of something is just a no-op, so return the child.
490 case Operator.UnaryNegation:
492 // Deals with -literals
493 // int operator- (int x)
494 // long operator- (long x)
495 // float operator- (float f)
496 // double operator- (double d)
497 // decimal operator- (decimal d)
499 Expression expr = null;
502 // transform - - expr into expr
505 Unary unary = (Unary) Expr;
507 if (unary.Oper == Operator.UnaryNegation)
512 // perform numeric promotions to int,
516 // The following is inneficient, because we call
517 // ImplicitConversion too many times.
519 // It is also not clear if we should convert to Float
520 // or Double initially.
522 if (expr_type == TypeManager.uint32_type){
524 // FIXME: handle exception to this rule that
525 // permits the int value -2147483648 (-2^31) to
526 // bt wrote as a decimal interger literal
528 type = TypeManager.int64_type;
529 Expr = Convert.ImplicitConversion (ec, Expr, type, loc);
533 if (expr_type == TypeManager.uint64_type){
535 // FIXME: Handle exception of `long value'
536 // -92233720368547758087 (-2^63) to be wrote as
537 // decimal integer literal.
543 if (expr_type == TypeManager.float_type){
548 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
555 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
562 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.double_type, loc);
573 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
574 TypeManager.CSharpName (expr_type) + "'");
578 public override Expression DoResolve (EmitContext ec)
580 if (Oper == Operator.AddressOf) {
581 Expr = Expr.DoResolveLValue (ec, new EmptyExpression ());
583 if (Expr == null || Expr.eclass != ExprClass.Variable){
584 Error (211, "Cannot take the address of the given expression");
589 Expr = Expr.Resolve (ec);
594 eclass = ExprClass.Value;
595 return ResolveOperator (ec);
598 public override Expression DoResolveLValue (EmitContext ec, Expression right)
600 if (Oper == Operator.Indirection)
601 return DoResolve (ec);
606 public override void Emit (EmitContext ec)
608 ILGenerator ig = ec.ig;
611 case Operator.UnaryPlus:
612 throw new Exception ("This should be caught by Resolve");
614 case Operator.UnaryNegation:
616 ig.Emit (OpCodes.Ldc_I4_0);
617 if (type == TypeManager.int64_type)
618 ig.Emit (OpCodes.Conv_U8);
620 ig.Emit (OpCodes.Sub_Ovf);
623 ig.Emit (OpCodes.Neg);
628 case Operator.LogicalNot:
630 ig.Emit (OpCodes.Ldc_I4_0);
631 ig.Emit (OpCodes.Ceq);
634 case Operator.OnesComplement:
636 ig.Emit (OpCodes.Not);
639 case Operator.AddressOf:
640 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
644 throw new Exception ("This should not happen: Operator = "
649 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
651 if (Oper == Operator.LogicalNot)
652 Expr.EmitBranchable (ec, target, !onTrue);
654 base.EmitBranchable (ec, target, onTrue);
657 public override string ToString ()
659 return "Unary (" + Oper + ", " + Expr + ")";
665 // Unary operators are turned into Indirection expressions
666 // after semantic analysis (this is so we can take the address
667 // of an indirection).
669 public class Indirection : Expression, IMemoryLocation, IAssignMethod, IVariable {
671 LocalTemporary temporary;
674 public Indirection (Expression expr, Location l)
677 type = TypeManager.HasElementType (expr.Type) ? TypeManager.GetElementType (expr.Type) : expr.Type;
678 eclass = ExprClass.Variable;
682 public override void Emit (EmitContext ec)
687 LoadFromPtr (ec.ig, Type);
690 public void Emit (EmitContext ec, bool leave_copy)
694 ec.ig.Emit (OpCodes.Dup);
695 temporary = new LocalTemporary (ec, expr.Type);
696 temporary.Store (ec);
700 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
702 prepared = prepare_for_load;
706 if (prepare_for_load)
707 ec.ig.Emit (OpCodes.Dup);
711 ec.ig.Emit (OpCodes.Dup);
712 temporary = new LocalTemporary (ec, expr.Type);
713 temporary.Store (ec);
716 StoreFromPtr (ec.ig, type);
718 if (temporary != null)
722 public void AddressOf (EmitContext ec, AddressOp Mode)
727 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
729 return DoResolve (ec);
732 public override Expression DoResolve (EmitContext ec)
735 // Born fully resolved
740 public override string ToString ()
742 return "*(" + expr + ")";
745 #region IVariable Members
747 public VariableInfo VariableInfo {
753 public bool VerifyFixed ()
755 // A pointer-indirection is always fixed.
763 /// Unary Mutator expressions (pre and post ++ and --)
767 /// UnaryMutator implements ++ and -- expressions. It derives from
768 /// ExpressionStatement becuase the pre/post increment/decrement
769 /// operators can be used in a statement context.
771 /// FIXME: Idea, we could split this up in two classes, one simpler
772 /// for the common case, and one with the extra fields for more complex
773 /// classes (indexers require temporary access; overloaded require method)
776 public class UnaryMutator : ExpressionStatement {
778 public enum Mode : byte {
785 PreDecrement = IsDecrement,
786 PostIncrement = IsPost,
787 PostDecrement = IsPost | IsDecrement
791 bool is_expr = false;
792 bool recurse = false;
797 // This is expensive for the simplest case.
799 StaticCallExpr method;
801 public UnaryMutator (Mode m, Expression e, Location l)
808 static string OperName (Mode mode)
810 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
815 /// Returns whether an object of type `t' can be incremented
816 /// or decremented with add/sub (ie, basically whether we can
817 /// use pre-post incr-decr operations on it, but it is not a
818 /// System.Decimal, which we require operator overloading to catch)
820 static bool IsIncrementableNumber (Type t)
822 return (t == TypeManager.sbyte_type) ||
823 (t == TypeManager.byte_type) ||
824 (t == TypeManager.short_type) ||
825 (t == TypeManager.ushort_type) ||
826 (t == TypeManager.int32_type) ||
827 (t == TypeManager.uint32_type) ||
828 (t == TypeManager.int64_type) ||
829 (t == TypeManager.uint64_type) ||
830 (t == TypeManager.char_type) ||
831 (t.IsSubclassOf (TypeManager.enum_type)) ||
832 (t == TypeManager.float_type) ||
833 (t == TypeManager.double_type) ||
834 (t.IsPointer && t != TypeManager.void_ptr_type);
837 Expression ResolveOperator (EmitContext ec)
839 Type expr_type = expr.Type;
842 // Step 1: Perform Operator Overload location
847 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
848 op_name = "op_Increment";
850 op_name = "op_Decrement";
852 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
855 method = StaticCallExpr.MakeSimpleCall (
856 ec, (MethodGroupExpr) mg, expr, loc);
859 } else if (!IsIncrementableNumber (expr_type)) {
860 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
861 TypeManager.CSharpName (expr_type) + "'");
866 // The operand of the prefix/postfix increment decrement operators
867 // should be an expression that is classified as a variable,
868 // a property access or an indexer access
871 if (expr.eclass == ExprClass.Variable){
872 LocalVariableReference var = expr as LocalVariableReference;
873 if ((var != null) && var.IsReadOnly) {
874 Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
877 } else if (expr.eclass == ExprClass.IndexerAccess || expr.eclass == ExprClass.PropertyAccess){
878 expr = expr.ResolveLValue (ec, this, Location);
882 expr.Error_UnexpectedKind (ec, "variable, indexer or property access", loc);
889 public override Expression DoResolve (EmitContext ec)
891 expr = expr.Resolve (ec);
896 eclass = ExprClass.Value;
897 return ResolveOperator (ec);
900 static int PtrTypeSize (Type t)
902 return GetTypeSize (TypeManager.GetElementType (t));
906 // Loads the proper "1" into the stack based on the type, then it emits the
907 // opcode for the operation requested
909 void LoadOneAndEmitOp (EmitContext ec, Type t)
912 // Measure if getting the typecode and using that is more/less efficient
913 // that comparing types. t.GetTypeCode() is an internal call.
915 ILGenerator ig = ec.ig;
917 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
918 LongConstant.EmitLong (ig, 1);
919 else if (t == TypeManager.double_type)
920 ig.Emit (OpCodes.Ldc_R8, 1.0);
921 else if (t == TypeManager.float_type)
922 ig.Emit (OpCodes.Ldc_R4, 1.0F);
923 else if (t.IsPointer){
924 int n = PtrTypeSize (t);
927 ig.Emit (OpCodes.Sizeof, t);
929 IntConstant.EmitInt (ig, n);
931 ig.Emit (OpCodes.Ldc_I4_1);
934 // Now emit the operation
937 if (t == TypeManager.int32_type ||
938 t == TypeManager.int64_type){
939 if ((mode & Mode.IsDecrement) != 0)
940 ig.Emit (OpCodes.Sub_Ovf);
942 ig.Emit (OpCodes.Add_Ovf);
943 } else if (t == TypeManager.uint32_type ||
944 t == TypeManager.uint64_type){
945 if ((mode & Mode.IsDecrement) != 0)
946 ig.Emit (OpCodes.Sub_Ovf_Un);
948 ig.Emit (OpCodes.Add_Ovf_Un);
950 if ((mode & Mode.IsDecrement) != 0)
951 ig.Emit (OpCodes.Sub_Ovf);
953 ig.Emit (OpCodes.Add_Ovf);
956 if ((mode & Mode.IsDecrement) != 0)
957 ig.Emit (OpCodes.Sub);
959 ig.Emit (OpCodes.Add);
962 if (t == TypeManager.sbyte_type){
964 ig.Emit (OpCodes.Conv_Ovf_I1);
966 ig.Emit (OpCodes.Conv_I1);
967 } else if (t == TypeManager.byte_type){
969 ig.Emit (OpCodes.Conv_Ovf_U1);
971 ig.Emit (OpCodes.Conv_U1);
972 } else if (t == TypeManager.short_type){
974 ig.Emit (OpCodes.Conv_Ovf_I2);
976 ig.Emit (OpCodes.Conv_I2);
977 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
979 ig.Emit (OpCodes.Conv_Ovf_U2);
981 ig.Emit (OpCodes.Conv_U2);
986 void EmitCode (EmitContext ec, bool is_expr)
989 this.is_expr = is_expr;
990 ((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);
1051 probe_type = texpr.ResolveType (ec);
1053 expr = expr.Resolve (ec);
1057 if (expr.Type.IsPointer) {
1058 Report.Error (244, loc, "\"is\" or \"as\" are not valid on pointer types");
1066 /// Implementation of the `is' operator.
1068 public class Is : Probe {
1069 public Is (Expression expr, Expression probe_type, Location l)
1070 : base (expr, probe_type, l)
1075 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1080 public override void Emit (EmitContext ec)
1082 ILGenerator ig = ec.ig;
1087 case Action.AlwaysFalse:
1088 ig.Emit (OpCodes.Pop);
1089 IntConstant.EmitInt (ig, 0);
1091 case Action.AlwaysTrue:
1092 ig.Emit (OpCodes.Pop);
1093 IntConstant.EmitInt (ig, 1);
1095 case Action.LeaveOnStack:
1096 // the `e != null' rule.
1097 ig.Emit (OpCodes.Ldnull);
1098 ig.Emit (OpCodes.Ceq);
1099 ig.Emit (OpCodes.Ldc_I4_0);
1100 ig.Emit (OpCodes.Ceq);
1103 ig.Emit (OpCodes.Isinst, probe_type);
1104 ig.Emit (OpCodes.Ldnull);
1105 ig.Emit (OpCodes.Cgt_Un);
1108 throw new Exception ("never reached");
1111 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
1113 ILGenerator ig = ec.ig;
1116 case Action.AlwaysFalse:
1118 ig.Emit (OpCodes.Br, target);
1121 case Action.AlwaysTrue:
1123 ig.Emit (OpCodes.Br, target);
1126 case Action.LeaveOnStack:
1127 // the `e != null' rule.
1129 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1133 ig.Emit (OpCodes.Isinst, probe_type);
1134 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1137 throw new Exception ("never reached");
1140 public override Expression DoResolve (EmitContext ec)
1142 Expression e = base.DoResolve (ec);
1144 if ((e == null) || (expr == null))
1147 Type etype = expr.Type;
1148 bool warning_always_matches = false;
1149 bool warning_never_matches = false;
1151 type = TypeManager.bool_type;
1152 eclass = ExprClass.Value;
1155 // First case, if at compile time, there is an implicit conversion
1156 // then e != null (objects) or true (value types)
1158 e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1159 if (e != null && !(e is NullCast)){
1161 if (etype.IsValueType)
1162 action = Action.AlwaysTrue;
1164 action = Action.LeaveOnStack;
1166 warning_always_matches = true;
1167 } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1169 // Second case: explicit reference convresion
1171 if (expr is NullLiteral)
1172 action = Action.AlwaysFalse;
1174 action = Action.Probe;
1176 action = Action.AlwaysFalse;
1177 warning_never_matches = true;
1180 if (warning_always_matches)
1181 Report.Warning (183, 1, loc, "The given expression is always of the provided (`{0}') type", TypeManager.CSharpName (probe_type));
1182 else if (warning_never_matches){
1183 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1184 Report.Warning (184, 1, loc, "The given expression is never of the provided (`{0}') type", TypeManager.CSharpName (probe_type));
1192 /// Implementation of the `as' operator.
1194 public class As : Probe {
1195 public As (Expression expr, Expression probe_type, Location l)
1196 : base (expr, probe_type, l)
1200 bool do_isinst = false;
1201 Expression resolved_type;
1203 public override void Emit (EmitContext ec)
1205 ILGenerator ig = ec.ig;
1210 ig.Emit (OpCodes.Isinst, probe_type);
1213 static void Error_CannotConvertType (Type source, Type target, Location loc)
1215 Report.Error (39, loc, "Cannot convert type `{0}' to `{1}' via a built-in conversion",
1216 TypeManager.CSharpName (source),
1217 TypeManager.CSharpName (target));
1220 public override Expression DoResolve (EmitContext ec)
1222 if (resolved_type == null) {
1223 resolved_type = base.DoResolve (ec);
1225 if (resolved_type == null)
1230 eclass = ExprClass.Value;
1231 Type etype = expr.Type;
1233 if (TypeManager.IsValueType (probe_type)){
1234 Report.Error (77, loc, "The as operator must be used with a reference type (`" +
1235 TypeManager.CSharpName (probe_type) + "' is a value type)");
1240 Expression e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1247 if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1252 Error_CannotConvertType (etype, probe_type, loc);
1258 /// This represents a typecast in the source language.
1260 /// FIXME: Cast expressions have an unusual set of parsing
1261 /// rules, we need to figure those out.
1263 public class Cast : Expression {
1264 Expression target_type;
1267 public Cast (Expression cast_type, Expression expr)
1268 : this (cast_type, expr, cast_type.Location)
1272 public Cast (Expression cast_type, Expression expr, Location loc)
1274 this.target_type = cast_type;
1279 public Expression TargetType {
1285 public Expression Expr {
1294 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1296 expr = expr.DoResolveLValue (ec, right_side);
1300 return ResolveRest (ec);
1303 public override Expression DoResolve (EmitContext ec)
1305 expr = expr.Resolve (ec);
1309 return ResolveRest (ec);
1312 Expression ResolveRest (EmitContext ec)
1314 TypeExpr target = target_type.ResolveAsTypeTerminal (ec, false);
1318 type = target.ResolveType (ec);
1320 if (type.IsAbstract && type.IsSealed) {
1321 Report.Error (716, loc, "Cannot convert to static type `{0}'", TypeManager.CSharpName (type));
1325 eclass = ExprClass.Value;
1327 Constant c = expr as Constant;
1329 c = c.TryReduce (ec, type, loc);
1334 if (type.IsPointer && !ec.InUnsafe) {
1338 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1342 public override void Emit (EmitContext ec)
1345 // This one will never happen
1347 throw new Exception ("Should not happen");
1352 /// Binary operators
1354 public class Binary : Expression {
1355 public enum Operator : byte {
1356 Multiply, Division, Modulus,
1357 Addition, Subtraction,
1358 LeftShift, RightShift,
1359 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1360 Equality, Inequality,
1370 Expression left, right;
1372 // This must be kept in sync with Operator!!!
1373 public static readonly string [] oper_names;
1377 oper_names = new string [(int) Operator.TOP];
1379 oper_names [(int) Operator.Multiply] = "op_Multiply";
1380 oper_names [(int) Operator.Division] = "op_Division";
1381 oper_names [(int) Operator.Modulus] = "op_Modulus";
1382 oper_names [(int) Operator.Addition] = "op_Addition";
1383 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1384 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1385 oper_names [(int) Operator.RightShift] = "op_RightShift";
1386 oper_names [(int) Operator.LessThan] = "op_LessThan";
1387 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1388 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1389 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1390 oper_names [(int) Operator.Equality] = "op_Equality";
1391 oper_names [(int) Operator.Inequality] = "op_Inequality";
1392 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1393 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1394 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1395 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1396 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1399 public Binary (Operator oper, Expression left, Expression right)
1404 this.loc = left.Location;
1407 public Operator Oper {
1416 public Expression Left {
1425 public Expression Right {
1436 /// Returns a stringified representation of the Operator
1438 public static string OperName (Operator oper)
1441 case Operator.Multiply:
1443 case Operator.Division:
1445 case Operator.Modulus:
1447 case Operator.Addition:
1449 case Operator.Subtraction:
1451 case Operator.LeftShift:
1453 case Operator.RightShift:
1455 case Operator.LessThan:
1457 case Operator.GreaterThan:
1459 case Operator.LessThanOrEqual:
1461 case Operator.GreaterThanOrEqual:
1463 case Operator.Equality:
1465 case Operator.Inequality:
1467 case Operator.BitwiseAnd:
1469 case Operator.BitwiseOr:
1471 case Operator.ExclusiveOr:
1473 case Operator.LogicalOr:
1475 case Operator.LogicalAnd:
1479 return oper.ToString ();
1482 public override string ToString ()
1484 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1485 right.ToString () + ")";
1488 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1490 if (expr.Type == target_type)
1493 return Convert.ImplicitConversion (ec, expr, target_type, loc);
1496 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1499 34, loc, "Operator `" + OperName (oper)
1500 + "' is ambiguous on operands of type `"
1501 + TypeManager.CSharpName (l) + "' "
1502 + "and `" + TypeManager.CSharpName (r)
1506 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
1508 if ((l == t) || (r == t))
1511 if (!check_user_conversions)
1514 if (Convert.ImplicitUserConversionExists (ec, l, t))
1516 else if (Convert.ImplicitUserConversionExists (ec, r, t))
1523 // Note that handling the case l == Decimal || r == Decimal
1524 // is taken care of by the Step 1 Operator Overload resolution.
1526 // If `check_user_conv' is true, we also check whether a user-defined conversion
1527 // exists. Note that we only need to do this if both arguments are of a user-defined
1528 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
1529 // so we don't explicitly check for performance reasons.
1531 bool DoNumericPromotions (EmitContext ec, Type l, Type r, Expression lexpr, Expression rexpr, bool check_user_conv)
1533 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
1535 // If either operand is of type double, the other operand is
1536 // conveted to type double.
1538 if (r != TypeManager.double_type)
1539 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
1540 if (l != TypeManager.double_type)
1541 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
1543 type = TypeManager.double_type;
1544 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
1546 // if either operand is of type float, the other operand is
1547 // converted to type float.
1549 if (r != TypeManager.double_type)
1550 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
1551 if (l != TypeManager.double_type)
1552 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
1553 type = TypeManager.float_type;
1554 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
1558 // If either operand is of type ulong, the other operand is
1559 // converted to type ulong. or an error ocurrs if the other
1560 // operand is of type sbyte, short, int or long
1562 if (l == TypeManager.uint64_type){
1563 if (r != TypeManager.uint64_type){
1564 if (right is IntConstant){
1565 IntConstant ic = (IntConstant) right;
1567 e = Convert.TryImplicitIntConversion (l, ic);
1570 } else if (right is LongConstant){
1571 long ll = ((LongConstant) right).Value;
1574 right = new ULongConstant ((ulong) ll, right.Location);
1576 e = Convert.ImplicitNumericConversion (ec, right, l);
1583 if (left is IntConstant){
1584 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
1587 } else if (left is LongConstant){
1588 long ll = ((LongConstant) left).Value;
1591 left = new ULongConstant ((ulong) ll, right.Location);
1593 e = Convert.ImplicitNumericConversion (ec, left, r);
1600 if ((other == TypeManager.sbyte_type) ||
1601 (other == TypeManager.short_type) ||
1602 (other == TypeManager.int32_type) ||
1603 (other == TypeManager.int64_type))
1604 Error_OperatorAmbiguous (loc, oper, l, r);
1606 left = ForceConversion (ec, left, TypeManager.uint64_type);
1607 right = ForceConversion (ec, right, TypeManager.uint64_type);
1609 type = TypeManager.uint64_type;
1610 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
1612 // If either operand is of type long, the other operand is converted
1615 if (l != TypeManager.int64_type)
1616 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
1617 if (r != TypeManager.int64_type)
1618 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
1620 type = TypeManager.int64_type;
1621 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
1623 // If either operand is of type uint, and the other
1624 // operand is of type sbyte, short or int, othe operands are
1625 // converted to type long (unless we have an int constant).
1629 if (l == TypeManager.uint32_type){
1630 if (right is IntConstant){
1631 IntConstant ic = (IntConstant) right;
1635 right = new UIntConstant ((uint) val, ic.Location);
1642 } else if (r == TypeManager.uint32_type){
1643 if (left is IntConstant){
1644 IntConstant ic = (IntConstant) left;
1648 left = new UIntConstant ((uint) val, ic.Location);
1657 if ((other == TypeManager.sbyte_type) ||
1658 (other == TypeManager.short_type) ||
1659 (other == TypeManager.int32_type)){
1660 left = ForceConversion (ec, left, TypeManager.int64_type);
1661 right = ForceConversion (ec, right, TypeManager.int64_type);
1662 type = TypeManager.int64_type;
1665 // if either operand is of type uint, the other
1666 // operand is converd to type uint
1668 left = ForceConversion (ec, left, TypeManager.uint32_type);
1669 right = ForceConversion (ec, right, TypeManager.uint32_type);
1670 type = TypeManager.uint32_type;
1672 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1673 if (l != TypeManager.decimal_type)
1674 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
1676 if (r != TypeManager.decimal_type)
1677 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
1678 type = TypeManager.decimal_type;
1680 left = ForceConversion (ec, left, TypeManager.int32_type);
1681 right = ForceConversion (ec, right, TypeManager.int32_type);
1684 Convert.ImplicitConversionExists (ec, lexpr, TypeManager.string_type) &&
1685 Convert.ImplicitConversionExists (ec, rexpr, TypeManager.string_type);
1686 if (strConv && left != null && right != null)
1687 Error_OperatorAmbiguous (loc, oper, l, r);
1689 type = TypeManager.int32_type;
1692 return (left != null) && (right != null);
1695 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
1697 Error_OperatorCannotBeApplied (loc, name, TypeManager.CSharpName (l), TypeManager.CSharpName (r));
1700 public static void Error_OperatorCannotBeApplied (Location loc, string name, string left, string right)
1702 Report.Error (19, loc, "Operator `{0}' cannot be applied to operands of type `{1}' and `{2}'",
1706 void Error_OperatorCannotBeApplied ()
1708 Error_OperatorCannotBeApplied (Location, OperName (oper), left.GetSignatureForError (), right.GetSignatureForError ());
1711 static bool is_unsigned (Type t)
1713 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
1714 t == TypeManager.short_type || t == TypeManager.byte_type);
1717 static bool is_user_defined (Type t)
1719 if (t.IsSubclassOf (TypeManager.value_type) &&
1720 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
1726 Expression Make32or64 (EmitContext ec, Expression e)
1730 if (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
1731 t == TypeManager.int64_type || t == TypeManager.uint64_type)
1733 Expression ee = Convert.ImplicitConversion (ec, e, TypeManager.int32_type, loc);
1736 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint32_type, loc);
1739 ee = Convert.ImplicitConversion (ec, e, TypeManager.int64_type, loc);
1742 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint64_type, loc);
1748 Expression CheckShiftArguments (EmitContext ec)
1752 e = ForceConversion (ec, right, TypeManager.int32_type);
1754 Error_OperatorCannotBeApplied ();
1759 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
1760 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
1761 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
1762 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
1766 if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
1767 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntConstant (31, loc));
1768 right = right.DoResolve (ec);
1770 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntConstant (63, loc));
1771 right = right.DoResolve (ec);
1776 Error_OperatorCannotBeApplied ();
1781 // This is used to check if a test 'x == null' can be optimized to a reference equals,
1782 // i.e., not invoke op_Equality.
1784 static bool EqualsNullIsReferenceEquals (Type t)
1786 return t == TypeManager.object_type || t == TypeManager.string_type ||
1787 t == TypeManager.delegate_type || t.IsSubclassOf (TypeManager.delegate_type);
1790 static void Warning_UnintendedReferenceComparison (Location loc, string side, Type type)
1792 Report.Warning ((side == "left" ? 252 : 253), 2, loc,
1793 "Possible unintended reference comparison; to get a value comparison, " +
1794 "cast the {0} hand side to type `{1}'.", side, TypeManager.CSharpName (type));
1797 Expression ResolveOperator (EmitContext ec)
1800 Type r = right.Type;
1802 if (oper == Operator.Equality || oper == Operator.Inequality){
1804 // Optimize out call to op_Equality in a few cases.
1806 if ((l == TypeManager.null_type && EqualsNullIsReferenceEquals (r)) ||
1807 (r == TypeManager.null_type && EqualsNullIsReferenceEquals (l))) {
1809 Type = TypeManager.bool_type;
1815 if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
1816 Type = TypeManager.bool_type;
1823 // Do not perform operator overload resolution when both sides are
1826 Expression left_operators = null, right_operators = null;
1827 if (!(TypeManager.IsPrimitiveType (l) && TypeManager.IsPrimitiveType (r))){
1829 // Step 1: Perform Operator Overload location
1831 string op = oper_names [(int) oper];
1833 MethodGroupExpr union;
1834 left_operators = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
1836 right_operators = MemberLookup (
1837 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
1838 union = Invocation.MakeUnionSet (left_operators, right_operators, loc);
1840 union = (MethodGroupExpr) left_operators;
1842 if (union != null) {
1843 ArrayList args = new ArrayList (2);
1844 args.Add (new Argument (left, Argument.AType.Expression));
1845 args.Add (new Argument (right, Argument.AType.Expression));
1847 MethodBase method = Invocation.OverloadResolve (
1848 ec, union, args, true, Location.Null);
1850 if (method != null) {
1851 MethodInfo mi = (MethodInfo) method;
1853 return new BinaryMethod (mi.ReturnType, method, args);
1859 // Step 0: String concatenation (because overloading will get this wrong)
1861 if (oper == Operator.Addition){
1863 // If any of the arguments is a string, cast to string
1866 // Simple constant folding
1867 if (left is StringConstant && right is StringConstant)
1868 return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value, left.Location);
1870 if (l == TypeManager.string_type || r == TypeManager.string_type) {
1872 if (r == TypeManager.void_type || l == TypeManager.void_type) {
1873 Error_OperatorCannotBeApplied ();
1877 // try to fold it in on the left
1878 if (left is StringConcat) {
1881 // We have to test here for not-null, since we can be doubly-resolved
1882 // take care of not appending twice
1885 type = TypeManager.string_type;
1886 ((StringConcat) left).Append (ec, right);
1887 return left.Resolve (ec);
1893 // Otherwise, start a new concat expression
1894 return new StringConcat (ec, loc, left, right).Resolve (ec);
1898 // Transform a + ( - b) into a - b
1900 if (right is Unary){
1901 Unary right_unary = (Unary) right;
1903 if (right_unary.Oper == Unary.Operator.UnaryNegation){
1904 oper = Operator.Subtraction;
1905 right = right_unary.Expr;
1911 if (oper == Operator.Equality || oper == Operator.Inequality){
1912 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1913 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1914 Error_OperatorCannotBeApplied ();
1918 type = TypeManager.bool_type;
1922 if (l.IsPointer || r.IsPointer) {
1923 if (l.IsPointer && r.IsPointer) {
1924 type = TypeManager.bool_type;
1928 if (l.IsPointer && r == TypeManager.null_type) {
1929 right = new EmptyCast (NullPointer.Null, l);
1930 type = TypeManager.bool_type;
1934 if (r.IsPointer && l == TypeManager.null_type) {
1935 left = new EmptyCast (NullPointer.Null, r);
1936 type = TypeManager.bool_type;
1942 // operator != (object a, object b)
1943 // operator == (object a, object b)
1945 // For this to be used, both arguments have to be reference-types.
1946 // Read the rationale on the spec (14.9.6)
1948 if (!(l.IsValueType || r.IsValueType)){
1949 type = TypeManager.bool_type;
1955 // Also, a standard conversion must exist from either one
1957 bool left_to_right =
1958 Convert.ImplicitStandardConversionExists (ec, left, r);
1959 bool right_to_left = !left_to_right &&
1960 Convert.ImplicitStandardConversionExists (ec, right, l);
1962 if (!left_to_right && !right_to_left) {
1963 Error_OperatorCannotBeApplied ();
1967 if (left_to_right && left_operators != null &&
1968 RootContext.WarningLevel >= 2) {
1969 ArrayList args = new ArrayList (2);
1970 args.Add (new Argument (left, Argument.AType.Expression));
1971 args.Add (new Argument (left, Argument.AType.Expression));
1972 MethodBase method = Invocation.OverloadResolve (
1973 ec, (MethodGroupExpr) left_operators, args, true, Location.Null);
1975 Warning_UnintendedReferenceComparison (loc, "right", l);
1978 if (right_to_left && right_operators != null &&
1979 RootContext.WarningLevel >= 2) {
1980 ArrayList args = new ArrayList (2);
1981 args.Add (new Argument (right, Argument.AType.Expression));
1982 args.Add (new Argument (right, Argument.AType.Expression));
1983 MethodBase method = Invocation.OverloadResolve (
1984 ec, (MethodGroupExpr) right_operators, args, true, Location.Null);
1986 Warning_UnintendedReferenceComparison (loc, "left", r);
1990 // We are going to have to convert to an object to compare
1992 if (l != TypeManager.object_type)
1993 left = new EmptyCast (left, TypeManager.object_type);
1994 if (r != TypeManager.object_type)
1995 right = new EmptyCast (right, TypeManager.object_type);
1998 // FIXME: CSC here catches errors cs254 and cs252
2004 // One of them is a valuetype, but the other one is not.
2006 if (!l.IsValueType || !r.IsValueType) {
2007 Error_OperatorCannotBeApplied ();
2012 // Only perform numeric promotions on:
2013 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2015 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2016 if (l.IsSubclassOf (TypeManager.delegate_type)){
2017 if (((right.eclass == ExprClass.MethodGroup) ||
2018 (r == TypeManager.anonymous_method_type))){
2019 if ((RootContext.Version != LanguageVersion.ISO_1)){
2020 Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2028 if (r.IsSubclassOf (TypeManager.delegate_type)){
2030 ArrayList args = new ArrayList (2);
2032 args = new ArrayList (2);
2033 args.Add (new Argument (left, Argument.AType.Expression));
2034 args.Add (new Argument (right, Argument.AType.Expression));
2036 if (oper == Operator.Addition)
2037 method = TypeManager.delegate_combine_delegate_delegate;
2039 method = TypeManager.delegate_remove_delegate_delegate;
2042 Error_OperatorCannotBeApplied ();
2046 return new BinaryDelegate (l, method, args);
2051 // Pointer arithmetic:
2053 // T* operator + (T* x, int y);
2054 // T* operator + (T* x, uint y);
2055 // T* operator + (T* x, long y);
2056 // T* operator + (T* x, ulong y);
2058 // T* operator + (int y, T* x);
2059 // T* operator + (uint y, T *x);
2060 // T* operator + (long y, T *x);
2061 // T* operator + (ulong y, T *x);
2063 // T* operator - (T* x, int y);
2064 // T* operator - (T* x, uint y);
2065 // T* operator - (T* x, long y);
2066 // T* operator - (T* x, ulong y);
2068 // long operator - (T* x, T *y)
2071 if (r.IsPointer && oper == Operator.Subtraction){
2073 return new PointerArithmetic (
2074 false, left, right, TypeManager.int64_type,
2077 Expression t = Make32or64 (ec, right);
2079 return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc).Resolve (ec);
2081 } else if (r.IsPointer && oper == Operator.Addition){
2082 Expression t = Make32or64 (ec, left);
2084 return new PointerArithmetic (true, right, t, r, loc).Resolve (ec);
2089 // Enumeration operators
2091 bool lie = TypeManager.IsEnumType (l);
2092 bool rie = TypeManager.IsEnumType (r);
2096 // U operator - (E e, E f)
2098 if (oper == Operator.Subtraction){
2100 type = TypeManager.EnumToUnderlying (l);
2103 Error_OperatorCannotBeApplied ();
2109 // operator + (E e, U x)
2110 // operator - (E e, U x)
2112 if (oper == Operator.Addition || oper == Operator.Subtraction){
2113 Type enum_type = lie ? l : r;
2114 Type other_type = lie ? r : l;
2115 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2117 if (underlying_type != other_type){
2118 temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
2128 Error_OperatorCannotBeApplied ();
2137 temp = Convert.ImplicitConversion (ec, right, l, loc);
2141 Error_OperatorCannotBeApplied ();
2145 temp = Convert.ImplicitConversion (ec, left, r, loc);
2150 Error_OperatorCannotBeApplied ();
2155 if (oper == Operator.Equality || oper == Operator.Inequality ||
2156 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2157 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2158 if (left.Type != right.Type){
2159 Error_OperatorCannotBeApplied ();
2162 type = TypeManager.bool_type;
2166 if (oper == Operator.BitwiseAnd ||
2167 oper == Operator.BitwiseOr ||
2168 oper == Operator.ExclusiveOr){
2169 if (left.Type != right.Type){
2170 Error_OperatorCannotBeApplied ();
2176 Error_OperatorCannotBeApplied ();
2180 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2181 return CheckShiftArguments (ec);
2183 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2184 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2185 type = TypeManager.bool_type;
2190 Error_OperatorCannotBeApplied ();
2194 Expression e = new ConditionalLogicalOperator (
2195 oper == Operator.LogicalAnd, left, right, l, loc);
2196 return e.Resolve (ec);
2200 // operator & (bool x, bool y)
2201 // operator | (bool x, bool y)
2202 // operator ^ (bool x, bool y)
2204 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2205 if (oper == Operator.BitwiseAnd ||
2206 oper == Operator.BitwiseOr ||
2207 oper == Operator.ExclusiveOr){
2214 // Pointer comparison
2216 if (l.IsPointer && r.IsPointer){
2217 if (oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2218 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2219 type = TypeManager.bool_type;
2225 // This will leave left or right set to null if there is an error
2227 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2228 DoNumericPromotions (ec, l, r, left, right, check_user_conv);
2229 if (left == null || right == null){
2230 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2235 // reload our cached types if required
2240 if (oper == Operator.BitwiseAnd ||
2241 oper == Operator.BitwiseOr ||
2242 oper == Operator.ExclusiveOr){
2244 if (((l == TypeManager.int32_type) ||
2245 (l == TypeManager.uint32_type) ||
2246 (l == TypeManager.short_type) ||
2247 (l == TypeManager.ushort_type) ||
2248 (l == TypeManager.int64_type) ||
2249 (l == TypeManager.uint64_type))){
2252 Error_OperatorCannotBeApplied ();
2256 Error_OperatorCannotBeApplied ();
2261 if (oper == Operator.Equality ||
2262 oper == Operator.Inequality ||
2263 oper == Operator.LessThanOrEqual ||
2264 oper == Operator.LessThan ||
2265 oper == Operator.GreaterThanOrEqual ||
2266 oper == Operator.GreaterThan){
2267 type = TypeManager.bool_type;
2273 Constant EnumLiftUp (EmitContext ec, Constant left, Constant right)
2276 case Operator.BitwiseOr:
2277 case Operator.BitwiseAnd:
2278 case Operator.ExclusiveOr:
2279 case Operator.Equality:
2280 case Operator.Inequality:
2281 case Operator.LessThan:
2282 case Operator.LessThanOrEqual:
2283 case Operator.GreaterThan:
2284 case Operator.GreaterThanOrEqual:
2285 if (left is EnumConstant)
2288 if (left.IsZeroInteger)
2289 return new EnumConstant (left, right.Type);
2293 case Operator.Addition:
2294 case Operator.Subtraction:
2297 case Operator.Multiply:
2298 case Operator.Division:
2299 case Operator.Modulus:
2300 case Operator.LeftShift:
2301 case Operator.RightShift:
2302 if (right is EnumConstant || left is EnumConstant)
2306 Error_OperatorCannotBeApplied (loc, Binary.OperName (oper), left.Type, right.Type);
2310 public override Expression DoResolve (EmitContext ec)
2312 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2313 left = ((ParenthesizedExpression) left).Expr;
2314 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2318 if (left.eclass == ExprClass.Type) {
2319 Report.Error (75, loc, "To cast a negative value, you must enclose the value in parentheses");
2323 left = left.Resolve (ec);
2328 Constant lc = left as Constant;
2329 if (lc != null && lc.Type == TypeManager.bool_type &&
2330 ((oper == Operator.LogicalAnd && (bool)lc.GetValue () == false) ||
2331 (oper == Operator.LogicalOr && (bool)lc.GetValue () == true))) {
2333 // TODO: make a sense to resolve unreachable expression as we do for statement
2334 Report.Warning (429, 4, loc, "Unreachable expression code detected");
2338 right = right.Resolve (ec);
2342 eclass = ExprClass.Value;
2343 Constant rc = right as Constant;
2345 // The conversion rules are ignored in enum context but why
2346 if (!ec.InEnumContext && lc != null && rc != null && (TypeManager.IsEnumType (left.Type) || TypeManager.IsEnumType (right.Type))) {
2347 left = lc = EnumLiftUp (ec, lc, rc);
2351 right = rc = EnumLiftUp (ec, rc, lc);
2356 if (oper == Operator.BitwiseAnd) {
2357 if (rc != null && rc.IsZeroInteger) {
2358 return lc is EnumConstant ?
2359 new EnumConstant (rc, lc.Type):
2363 if (lc != null && lc.IsZeroInteger) {
2364 return rc is EnumConstant ?
2365 new EnumConstant (lc, rc.Type):
2369 else if (oper == Operator.BitwiseOr) {
2370 if (lc is EnumConstant &&
2371 rc != null && rc.IsZeroInteger)
2373 if (rc is EnumConstant &&
2374 lc != null && lc.IsZeroInteger)
2378 if (rc != null && lc != null){
2379 int prev_e = Report.Errors;
2380 Expression e = ConstantFold.BinaryFold (
2381 ec, oper, lc, rc, loc);
2382 if (e != null || Report.Errors != prev_e)
2386 // Comparison warnings
2387 if (oper == Operator.Equality || oper == Operator.Inequality ||
2388 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2389 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2390 if (left.Equals (right)) {
2391 Report.Warning (1718, 3, loc, "Comparison made to same variable; did you mean to compare something else?");
2393 CheckUselessComparison (lc, right.Type);
2394 CheckUselessComparison (rc, left.Type);
2397 return ResolveOperator (ec);
2400 private void CheckUselessComparison (Constant c, Type type)
2402 if (c == null || !IsTypeIntegral (type)
2403 || c is StringConstant
2404 || c is BoolConstant
2405 || c is CharConstant
2406 || c is FloatConstant
2407 || c is DoubleConstant
2408 || c is DecimalConstant
2414 if (c is ULongConstant) {
2415 ulong uvalue = ((ULongConstant) c).Value;
2416 if (uvalue > long.MaxValue) {
2417 if (type == TypeManager.byte_type ||
2418 type == TypeManager.sbyte_type ||
2419 type == TypeManager.short_type ||
2420 type == TypeManager.ushort_type ||
2421 type == TypeManager.int32_type ||
2422 type == TypeManager.uint32_type ||
2423 type == TypeManager.int64_type)
2424 WarnUselessComparison (type);
2427 value = (long) uvalue;
2429 else if (c is ByteConstant)
2430 value = ((ByteConstant) c).Value;
2431 else if (c is SByteConstant)
2432 value = ((SByteConstant) c).Value;
2433 else if (c is ShortConstant)
2434 value = ((ShortConstant) c).Value;
2435 else if (c is UShortConstant)
2436 value = ((UShortConstant) c).Value;
2437 else if (c is IntConstant)
2438 value = ((IntConstant) c).Value;
2439 else if (c is UIntConstant)
2440 value = ((UIntConstant) c).Value;
2441 else if (c is LongConstant)
2442 value = ((LongConstant) c).Value;
2445 if (IsValueOutOfRange (value, type))
2446 WarnUselessComparison (type);
2451 private bool IsValueOutOfRange (long value, Type type)
2453 if (IsTypeUnsigned (type) && value < 0)
2455 return type == TypeManager.sbyte_type && (value >= 0x80 || value < -0x80) ||
2456 type == TypeManager.byte_type && value >= 0x100 ||
2457 type == TypeManager.short_type && (value >= 0x8000 || value < -0x8000) ||
2458 type == TypeManager.ushort_type && value >= 0x10000 ||
2459 type == TypeManager.int32_type && (value >= 0x80000000 || value < -0x80000000) ||
2460 type == TypeManager.uint32_type && value >= 0x100000000;
2463 private static bool IsTypeIntegral (Type type)
2465 return type == TypeManager.uint64_type ||
2466 type == TypeManager.int64_type ||
2467 type == TypeManager.uint32_type ||
2468 type == TypeManager.int32_type ||
2469 type == TypeManager.ushort_type ||
2470 type == TypeManager.short_type ||
2471 type == TypeManager.sbyte_type ||
2472 type == TypeManager.byte_type;
2475 private static bool IsTypeUnsigned (Type type)
2477 return type == TypeManager.uint64_type ||
2478 type == TypeManager.uint32_type ||
2479 type == TypeManager.ushort_type ||
2480 type == TypeManager.byte_type;
2483 private void WarnUselessComparison (Type type)
2485 Report.Warning (652, 2, loc, "Comparison to integral constant is useless; the constant is outside the range of type `{0}'",
2486 TypeManager.CSharpName (type));
2490 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2491 /// context of a conditional bool expression. This function will return
2492 /// false if it is was possible to use EmitBranchable, or true if it was.
2494 /// The expression's code is generated, and we will generate a branch to `target'
2495 /// if the resulting expression value is equal to isTrue
2497 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2499 ILGenerator ig = ec.ig;
2502 // This is more complicated than it looks, but its just to avoid
2503 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2504 // but on top of that we want for == and != to use a special path
2505 // if we are comparing against null
2507 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
2508 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2511 // put the constant on the rhs, for simplicity
2513 if (left is Constant) {
2514 Expression swap = right;
2519 if (((Constant) right).IsZeroInteger) {
2522 ig.Emit (OpCodes.Brtrue, target);
2524 ig.Emit (OpCodes.Brfalse, target);
2527 } else if (right is BoolConstant) {
2529 if (my_on_true != ((BoolConstant) right).Value)
2530 ig.Emit (OpCodes.Brtrue, target);
2532 ig.Emit (OpCodes.Brfalse, target);
2537 } else if (oper == Operator.LogicalAnd) {
2540 Label tests_end = ig.DefineLabel ();
2542 left.EmitBranchable (ec, tests_end, false);
2543 right.EmitBranchable (ec, target, true);
2544 ig.MarkLabel (tests_end);
2546 left.EmitBranchable (ec, target, false);
2547 right.EmitBranchable (ec, target, false);
2552 } else if (oper == Operator.LogicalOr){
2554 left.EmitBranchable (ec, target, true);
2555 right.EmitBranchable (ec, target, true);
2558 Label tests_end = ig.DefineLabel ();
2559 left.EmitBranchable (ec, tests_end, true);
2560 right.EmitBranchable (ec, target, false);
2561 ig.MarkLabel (tests_end);
2566 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2567 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2568 oper == Operator.Equality || oper == Operator.Inequality)) {
2569 base.EmitBranchable (ec, target, onTrue);
2577 bool isUnsigned = is_unsigned (t) || t == TypeManager.double_type || t == TypeManager.float_type;
2580 case Operator.Equality:
2582 ig.Emit (OpCodes.Beq, target);
2584 ig.Emit (OpCodes.Bne_Un, target);
2587 case Operator.Inequality:
2589 ig.Emit (OpCodes.Bne_Un, target);
2591 ig.Emit (OpCodes.Beq, target);
2594 case Operator.LessThan:
2597 ig.Emit (OpCodes.Blt_Un, target);
2599 ig.Emit (OpCodes.Blt, target);
2602 ig.Emit (OpCodes.Bge_Un, target);
2604 ig.Emit (OpCodes.Bge, target);
2607 case Operator.GreaterThan:
2610 ig.Emit (OpCodes.Bgt_Un, target);
2612 ig.Emit (OpCodes.Bgt, target);
2615 ig.Emit (OpCodes.Ble_Un, target);
2617 ig.Emit (OpCodes.Ble, target);
2620 case Operator.LessThanOrEqual:
2623 ig.Emit (OpCodes.Ble_Un, target);
2625 ig.Emit (OpCodes.Ble, target);
2628 ig.Emit (OpCodes.Bgt_Un, target);
2630 ig.Emit (OpCodes.Bgt, target);
2634 case Operator.GreaterThanOrEqual:
2637 ig.Emit (OpCodes.Bge_Un, target);
2639 ig.Emit (OpCodes.Bge, target);
2642 ig.Emit (OpCodes.Blt_Un, target);
2644 ig.Emit (OpCodes.Blt, target);
2647 Console.WriteLine (oper);
2648 throw new Exception ("what is THAT");
2652 public override void Emit (EmitContext ec)
2654 ILGenerator ig = ec.ig;
2659 // Handle short-circuit operators differently
2662 if (oper == Operator.LogicalAnd) {
2663 Label load_zero = ig.DefineLabel ();
2664 Label end = ig.DefineLabel ();
2666 left.EmitBranchable (ec, load_zero, false);
2668 ig.Emit (OpCodes.Br, end);
2670 ig.MarkLabel (load_zero);
2671 ig.Emit (OpCodes.Ldc_I4_0);
2674 } else if (oper == Operator.LogicalOr) {
2675 Label load_one = ig.DefineLabel ();
2676 Label end = ig.DefineLabel ();
2678 left.EmitBranchable (ec, load_one, true);
2680 ig.Emit (OpCodes.Br, end);
2682 ig.MarkLabel (load_one);
2683 ig.Emit (OpCodes.Ldc_I4_1);
2691 bool isUnsigned = is_unsigned (left.Type);
2694 case Operator.Multiply:
2696 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2697 opcode = OpCodes.Mul_Ovf;
2698 else if (isUnsigned)
2699 opcode = OpCodes.Mul_Ovf_Un;
2701 opcode = OpCodes.Mul;
2703 opcode = OpCodes.Mul;
2707 case Operator.Division:
2709 opcode = OpCodes.Div_Un;
2711 opcode = OpCodes.Div;
2714 case Operator.Modulus:
2716 opcode = OpCodes.Rem_Un;
2718 opcode = OpCodes.Rem;
2721 case Operator.Addition:
2723 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2724 opcode = OpCodes.Add_Ovf;
2725 else if (isUnsigned)
2726 opcode = OpCodes.Add_Ovf_Un;
2728 opcode = OpCodes.Add;
2730 opcode = OpCodes.Add;
2733 case Operator.Subtraction:
2735 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2736 opcode = OpCodes.Sub_Ovf;
2737 else if (isUnsigned)
2738 opcode = OpCodes.Sub_Ovf_Un;
2740 opcode = OpCodes.Sub;
2742 opcode = OpCodes.Sub;
2745 case Operator.RightShift:
2747 opcode = OpCodes.Shr_Un;
2749 opcode = OpCodes.Shr;
2752 case Operator.LeftShift:
2753 opcode = OpCodes.Shl;
2756 case Operator.Equality:
2757 opcode = OpCodes.Ceq;
2760 case Operator.Inequality:
2761 ig.Emit (OpCodes.Ceq);
2762 ig.Emit (OpCodes.Ldc_I4_0);
2764 opcode = OpCodes.Ceq;
2767 case Operator.LessThan:
2769 opcode = OpCodes.Clt_Un;
2771 opcode = OpCodes.Clt;
2774 case Operator.GreaterThan:
2776 opcode = OpCodes.Cgt_Un;
2778 opcode = OpCodes.Cgt;
2781 case Operator.LessThanOrEqual:
2782 Type lt = left.Type;
2784 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
2785 ig.Emit (OpCodes.Cgt_Un);
2787 ig.Emit (OpCodes.Cgt);
2788 ig.Emit (OpCodes.Ldc_I4_0);
2790 opcode = OpCodes.Ceq;
2793 case Operator.GreaterThanOrEqual:
2794 Type le = left.Type;
2796 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
2797 ig.Emit (OpCodes.Clt_Un);
2799 ig.Emit (OpCodes.Clt);
2801 ig.Emit (OpCodes.Ldc_I4_0);
2803 opcode = OpCodes.Ceq;
2806 case Operator.BitwiseOr:
2807 opcode = OpCodes.Or;
2810 case Operator.BitwiseAnd:
2811 opcode = OpCodes.And;
2814 case Operator.ExclusiveOr:
2815 opcode = OpCodes.Xor;
2819 throw new Exception ("This should not happen: Operator = "
2820 + oper.ToString ());
2828 // Object created by Binary when the binary operator uses an method instead of being
2829 // a binary operation that maps to a CIL binary operation.
2831 public class BinaryMethod : Expression {
2832 public MethodBase method;
2833 public ArrayList Arguments;
2835 public BinaryMethod (Type t, MethodBase m, ArrayList args)
2840 eclass = ExprClass.Value;
2843 public override Expression DoResolve (EmitContext ec)
2848 public override void Emit (EmitContext ec)
2850 ILGenerator ig = ec.ig;
2852 if (Arguments != null)
2853 Invocation.EmitArguments (ec, method, Arguments, false, null);
2855 if (method is MethodInfo)
2856 ig.Emit (OpCodes.Call, (MethodInfo) method);
2858 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2863 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
2864 // b, c, d... may be strings or objects.
2866 public class StringConcat : Expression {
2868 bool invalid = false;
2869 bool emit_conv_done = false;
2871 // Are we also concating objects?
2873 bool is_strings_only = true;
2875 public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
2878 type = TypeManager.string_type;
2879 eclass = ExprClass.Value;
2881 operands = new ArrayList (2);
2886 public override Expression DoResolve (EmitContext ec)
2894 public void Append (EmitContext ec, Expression operand)
2899 if (operand is StringConstant && operands.Count != 0) {
2900 StringConstant last_operand = operands [operands.Count - 1] as StringConstant;
2901 if (last_operand != null) {
2902 operands [operands.Count - 1] = new StringConstant (last_operand.Value + ((StringConstant) operand).Value, last_operand.Location);
2908 // Conversion to object
2910 if (operand.Type != TypeManager.string_type) {
2911 Expression no = Convert.ImplicitConversion (ec, operand, TypeManager.object_type, loc);
2914 Binary.Error_OperatorCannotBeApplied (loc, "+", TypeManager.string_type, operand.Type);
2920 operands.Add (operand);
2923 public override void Emit (EmitContext ec)
2925 MethodInfo concat_method = null;
2928 // Do conversion to arguments; check for strings only
2931 // This can get called multiple times, so we have to deal with that.
2932 if (!emit_conv_done) {
2933 emit_conv_done = true;
2934 for (int i = 0; i < operands.Count; i ++) {
2935 Expression e = (Expression) operands [i];
2936 is_strings_only &= e.Type == TypeManager.string_type;
2939 for (int i = 0; i < operands.Count; i ++) {
2940 Expression e = (Expression) operands [i];
2942 if (! is_strings_only && e.Type == TypeManager.string_type) {
2943 // need to make sure this is an object, because the EmitParams
2944 // method might look at the type of this expression, see it is a
2945 // string and emit a string [] when we want an object [];
2947 e = new EmptyCast (e, TypeManager.object_type);
2949 operands [i] = new Argument (e, Argument.AType.Expression);
2954 // Find the right method
2956 switch (operands.Count) {
2959 // This should not be possible, because simple constant folding
2960 // is taken care of in the Binary code.
2962 throw new Exception ("how did you get here?");
2965 concat_method = is_strings_only ?
2966 TypeManager.string_concat_string_string :
2967 TypeManager.string_concat_object_object ;
2970 concat_method = is_strings_only ?
2971 TypeManager.string_concat_string_string_string :
2972 TypeManager.string_concat_object_object_object ;
2976 // There is not a 4 param overlaod for object (the one that there is
2977 // is actually a varargs methods, and is only in corlib because it was
2978 // introduced there before.).
2980 if (!is_strings_only)
2983 concat_method = TypeManager.string_concat_string_string_string_string;
2986 concat_method = is_strings_only ?
2987 TypeManager.string_concat_string_dot_dot_dot :
2988 TypeManager.string_concat_object_dot_dot_dot ;
2992 Invocation.EmitArguments (ec, concat_method, operands, false, null);
2993 ec.ig.Emit (OpCodes.Call, concat_method);
2998 // Object created with +/= on delegates
3000 public class BinaryDelegate : Expression {
3004 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3009 eclass = ExprClass.Value;
3012 public override Expression DoResolve (EmitContext ec)
3017 public override void Emit (EmitContext ec)
3019 ILGenerator ig = ec.ig;
3021 Invocation.EmitArguments (ec, method, args, false, null);
3023 ig.Emit (OpCodes.Call, (MethodInfo) method);
3024 ig.Emit (OpCodes.Castclass, type);
3027 public Expression Right {
3029 Argument arg = (Argument) args [1];
3034 public bool IsAddition {
3036 return method == TypeManager.delegate_combine_delegate_delegate;
3042 // User-defined conditional logical operator
3043 public class ConditionalLogicalOperator : Expression {
3044 Expression left, right;
3047 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3050 eclass = ExprClass.Value;
3054 this.is_and = is_and;
3057 protected void Error19 ()
3059 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", left.GetSignatureForError (), right.GetSignatureForError ());
3062 protected void Error218 ()
3064 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3065 "declarations of operator true and operator false");
3068 Expression op_true, op_false, op;
3069 LocalTemporary left_temp;
3071 public override Expression DoResolve (EmitContext ec)
3074 Expression operator_group;
3076 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3077 if (operator_group == null) {
3082 left_temp = new LocalTemporary (ec, type);
3084 ArrayList arguments = new ArrayList ();
3085 arguments.Add (new Argument (left_temp, Argument.AType.Expression));
3086 arguments.Add (new Argument (right, Argument.AType.Expression));
3087 method = Invocation.OverloadResolve (
3088 ec, (MethodGroupExpr) operator_group, arguments, false, loc)
3090 if (method == null) {
3095 if (method.ReturnType != type) {
3096 Report.Error (217, loc, "In order to be applicable as a short circuit operator a user-defined logical operator `{0}' " +
3097 "must have the same return type as the type of its 2 parameters", TypeManager.CSharpSignature (method));
3101 op = new StaticCallExpr (method, arguments, loc);
3103 op_true = GetOperatorTrue (ec, left_temp, loc);
3104 op_false = GetOperatorFalse (ec, left_temp, loc);
3105 if ((op_true == null) || (op_false == null)) {
3113 public override void Emit (EmitContext ec)
3115 ILGenerator ig = ec.ig;
3116 Label false_target = ig.DefineLabel ();
3117 Label end_target = ig.DefineLabel ();
3120 left_temp.Store (ec);
3122 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
3123 left_temp.Emit (ec);
3124 ig.Emit (OpCodes.Br, end_target);
3125 ig.MarkLabel (false_target);
3127 ig.MarkLabel (end_target);
3131 public class PointerArithmetic : Expression {
3132 Expression left, right;
3136 // We assume that `l' is always a pointer
3138 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3144 is_add = is_addition;
3147 public override Expression DoResolve (EmitContext ec)
3149 eclass = ExprClass.Variable;
3151 if (left.Type == TypeManager.void_ptr_type) {
3152 Error (242, "The operation in question is undefined on void pointers");
3159 public override void Emit (EmitContext ec)
3161 Type op_type = left.Type;
3162 ILGenerator ig = ec.ig;
3164 // It must be either array or fixed buffer
3165 Type element = TypeManager.HasElementType (op_type) ?
3166 element = TypeManager.GetElementType (op_type) :
3167 element = AttributeTester.GetFixedBuffer (((FieldExpr)left).FieldInfo).ElementType;
3169 int size = GetTypeSize (element);
3170 Type rtype = right.Type;
3172 if (rtype.IsPointer){
3174 // handle (pointer - pointer)
3178 ig.Emit (OpCodes.Sub);
3182 ig.Emit (OpCodes.Sizeof, element);
3184 IntLiteral.EmitInt (ig, size);
3185 ig.Emit (OpCodes.Div);
3187 ig.Emit (OpCodes.Conv_I8);
3190 // handle + and - on (pointer op int)
3193 ig.Emit (OpCodes.Conv_I);
3195 Constant right_const = right as Constant;
3196 if (right_const != null && size != 0) {
3197 Expression ex = ConstantFold.BinaryFold (ec, Binary.Operator.Multiply, new IntConstant (size, right.Location), right_const, loc);
3205 ig.Emit (OpCodes.Sizeof, element);
3207 IntLiteral.EmitInt (ig, size);
3208 if (rtype == TypeManager.int64_type)
3209 ig.Emit (OpCodes.Conv_I8);
3210 else if (rtype == TypeManager.uint64_type)
3211 ig.Emit (OpCodes.Conv_U8);
3212 ig.Emit (OpCodes.Mul);
3216 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
3217 ig.Emit (OpCodes.Conv_I);
3220 ig.Emit (OpCodes.Add);
3222 ig.Emit (OpCodes.Sub);
3228 /// Implements the ternary conditional operator (?:)
3230 public class Conditional : Expression {
3231 Expression expr, trueExpr, falseExpr;
3233 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr)
3236 this.trueExpr = trueExpr;
3237 this.falseExpr = falseExpr;
3238 this.loc = expr.Location;
3241 public Expression Expr {
3247 public Expression TrueExpr {
3253 public Expression FalseExpr {
3259 public override Expression DoResolve (EmitContext ec)
3261 expr = expr.Resolve (ec);
3266 if (expr.Type != TypeManager.bool_type){
3267 expr = Expression.ResolveBoolean (
3274 Assign ass = expr as Assign;
3275 if (ass != null && ass.Source is Constant) {
3276 Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
3279 trueExpr = trueExpr.Resolve (ec);
3280 falseExpr = falseExpr.Resolve (ec);
3282 if (trueExpr == null || falseExpr == null)
3285 eclass = ExprClass.Value;
3286 if (trueExpr.Type == falseExpr.Type)
3287 type = trueExpr.Type;
3290 Type true_type = trueExpr.Type;
3291 Type false_type = falseExpr.Type;
3294 // First, if an implicit conversion exists from trueExpr
3295 // to falseExpr, then the result type is of type falseExpr.Type
3297 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3300 // Check if both can convert implicitl to each other's type
3302 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3304 "Can not compute type of conditional expression " +
3305 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3306 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3307 "' convert implicitly to each other");
3312 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3316 Report.Error (173, loc, "Type of conditional expression cannot be determined because there is no implicit conversion between `{0}' and `{1}'",
3317 trueExpr.GetSignatureForError (), falseExpr.GetSignatureForError ());
3322 // Dead code optimalization
3323 if (expr is BoolConstant){
3324 BoolConstant bc = (BoolConstant) expr;
3326 Report.Warning (429, 4, bc.Value ? falseExpr.Location : trueExpr.Location, "Unreachable expression code detected");
3327 return bc.Value ? trueExpr : falseExpr;
3333 public override void Emit (EmitContext ec)
3335 ILGenerator ig = ec.ig;
3336 Label false_target = ig.DefineLabel ();
3337 Label end_target = ig.DefineLabel ();
3339 expr.EmitBranchable (ec, false_target, false);
3341 ig.Emit (OpCodes.Br, end_target);
3342 ig.MarkLabel (false_target);
3343 falseExpr.Emit (ec);
3344 ig.MarkLabel (end_target);
3352 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3353 public readonly string Name;
3354 public readonly Block Block;
3355 public LocalInfo local_info;
3358 LocalTemporary temp;
3360 public LocalVariableReference (Block block, string name, Location l)
3365 eclass = ExprClass.Variable;
3369 // Setting `is_readonly' to false will allow you to create a writable
3370 // reference to a read-only variable. This is used by foreach and using.
3372 public LocalVariableReference (Block block, string name, Location l,
3373 LocalInfo local_info, bool is_readonly)
3374 : this (block, name, l)
3376 this.local_info = local_info;
3377 this.is_readonly = is_readonly;
3380 public VariableInfo VariableInfo {
3382 return local_info.VariableInfo;
3386 public bool IsReadOnly {
3392 public bool VerifyAssigned (EmitContext ec)
3394 VariableInfo variable_info = local_info.VariableInfo;
3395 return variable_info == null || variable_info.IsAssigned (ec, loc);
3398 protected Expression DoResolveBase (EmitContext ec, Expression lvalue_right_side)
3400 if (local_info == null) {
3401 local_info = Block.GetLocalInfo (Name);
3404 if (lvalue_right_side == EmptyExpression.Null)
3405 local_info.Used = true;
3407 is_readonly = local_info.ReadOnly;
3410 type = local_info.VariableType;
3412 VariableInfo variable_info = local_info.VariableInfo;
3413 if (lvalue_right_side != null){
3415 if (lvalue_right_side is LocalVariableReference || lvalue_right_side == EmptyExpression.Null)
3416 Report.Error (1657, loc, "Cannot pass `{0}' as a ref or out argument because it is a `{1}'",
3417 Name, local_info.GetReadOnlyContext ());
3419 Report.Error (1656, loc, "Cannot assign to `{0}' because it is a `{1}'",
3420 Name, local_info.GetReadOnlyContext ());
3424 if (variable_info != null)
3425 variable_info.SetAssigned (ec);
3428 Expression e = Block.GetConstantExpression (Name);
3430 local_info.Used = true;
3431 eclass = ExprClass.Value;
3432 return e.Resolve (ec);
3435 if (!VerifyAssigned (ec))
3438 if (lvalue_right_side == null)
3439 local_info.Used = true;
3441 if (ec.CurrentAnonymousMethod != null){
3443 // If we are referencing a variable from the external block
3444 // flag it for capturing
3446 if ((local_info.Block.Toplevel != ec.CurrentBlock.Toplevel) ||
3447 ec.CurrentAnonymousMethod.IsIterator)
3449 if (local_info.AddressTaken){
3450 AnonymousMethod.Error_AddressOfCapturedVar (local_info.Name, loc);
3453 ec.CaptureVariable (local_info);
3460 public override Expression DoResolve (EmitContext ec)
3462 return DoResolveBase (ec, null);
3465 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3467 return DoResolveBase (ec, right_side);
3470 public bool VerifyFixed ()
3472 // A local Variable is always fixed.
3476 public override int GetHashCode()
3478 return Name.GetHashCode ();
3481 public override bool Equals (object obj)
3483 LocalVariableReference lvr = obj as LocalVariableReference;
3487 return Name == lvr.Name && Block == lvr.Block;
3490 public override void Emit (EmitContext ec)
3492 ILGenerator ig = ec.ig;
3494 if (local_info.FieldBuilder == null){
3496 // A local variable on the local CLR stack
3498 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3501 // A local variable captured by anonymous methods.
3504 ec.EmitCapturedVariableInstance (local_info);
3506 ig.Emit (OpCodes.Ldfld, local_info.FieldBuilder);
3510 public void Emit (EmitContext ec, bool leave_copy)
3514 ec.ig.Emit (OpCodes.Dup);
3515 if (local_info.FieldBuilder != null){
3516 temp = new LocalTemporary (ec, Type);
3522 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3524 ILGenerator ig = ec.ig;
3525 prepared = prepare_for_load;
3527 if (local_info.FieldBuilder == null){
3529 // A local variable on the local CLR stack
3531 if (local_info.LocalBuilder == null)
3532 throw new Exception ("This should not happen: both Field and Local are null");
3536 ec.ig.Emit (OpCodes.Dup);
3537 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3540 // A local variable captured by anonymous methods or itereators.
3542 ec.EmitCapturedVariableInstance (local_info);
3544 if (prepare_for_load)
3545 ig.Emit (OpCodes.Dup);
3548 ig.Emit (OpCodes.Dup);
3549 temp = new LocalTemporary (ec, Type);
3552 ig.Emit (OpCodes.Stfld, local_info.FieldBuilder);
3558 public void AddressOf (EmitContext ec, AddressOp mode)
3560 ILGenerator ig = ec.ig;
3562 if (local_info.FieldBuilder == null){
3564 // A local variable on the local CLR stack
3566 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3569 // A local variable captured by anonymous methods or iterators
3571 ec.EmitCapturedVariableInstance (local_info);
3572 ig.Emit (OpCodes.Ldflda, local_info.FieldBuilder);
3576 public override string ToString ()
3578 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3583 /// This represents a reference to a parameter in the intermediate
3586 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3592 public Parameter.Modifier mod;
3593 public bool is_ref, is_out, prepared;
3607 LocalTemporary temp;
3609 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3616 eclass = ExprClass.Variable;
3619 public ParameterReference (InternalParameters pars, Block block, int idx, Location loc)
3620 : this (pars.Parameters, block, idx, pars.ParameterName (idx), loc)
3623 public VariableInfo VariableInfo {
3627 public bool VerifyFixed ()
3629 // A parameter is fixed if it's a value parameter (i.e., no modifier like out, ref, param).
3630 return mod == Parameter.Modifier.NONE;
3633 public bool IsAssigned (EmitContext ec, Location loc)
3635 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsAssigned (vi))
3638 Report.Error (269, loc,
3639 "Use of unassigned out parameter `{0}'", name);
3643 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3645 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3648 Report.Error (170, loc,
3649 "Use of possibly unassigned field `" + field_name + "'");
3653 public void SetAssigned (EmitContext ec)
3655 if (is_out && ec.DoFlowAnalysis)
3656 ec.CurrentBranching.SetAssigned (vi);
3659 public void SetFieldAssigned (EmitContext ec, string field_name)
3661 if (is_out && ec.DoFlowAnalysis)
3662 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3665 protected void DoResolveBase (EmitContext ec)
3667 type = pars.GetParameterInfo (ec, idx, out mod);
3668 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3669 is_out = (mod & Parameter.Modifier.OUT) != 0;
3670 eclass = ExprClass.Variable;
3673 vi = block.ParameterMap [idx];
3675 if (ec.CurrentAnonymousMethod != null){
3677 Report.Error (1628, Location, "Cannot use ref or out parameter `{0}' inside an anonymous method block",
3683 // If we are referencing the parameter from the external block
3684 // flag it for capturing
3686 //Console.WriteLine ("Is parameter `{0}' local? {1}", name, block.IsLocalParameter (name));
3687 if (!block.Toplevel.IsLocalParameter (name)){
3688 ec.CaptureParameter (name, type, idx);
3693 public override int GetHashCode()
3695 return name.GetHashCode ();
3698 public override bool Equals (object obj)
3700 ParameterReference pr = obj as ParameterReference;
3704 return name == pr.name && block == pr.block;
3708 // Notice that for ref/out parameters, the type exposed is not the
3709 // same type exposed externally.
3712 // externally we expose "int&"
3713 // here we expose "int".
3715 // We record this in "is_ref". This means that the type system can treat
3716 // the type as it is expected, but when we generate the code, we generate
3717 // the alternate kind of code.
3719 public override Expression DoResolve (EmitContext ec)
3723 if (is_out && ec.DoFlowAnalysis && (!ec.OmitStructFlowAnalysis || !vi.TypeInfo.IsStruct) && !IsAssigned (ec, loc))
3729 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3738 static public void EmitLdArg (ILGenerator ig, int x)
3742 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3743 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3744 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3745 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3746 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3749 ig.Emit (OpCodes.Ldarg, x);
3753 // This method is used by parameters that are references, that are
3754 // being passed as references: we only want to pass the pointer (that
3755 // is already stored in the parameter, not the address of the pointer,
3756 // and not the value of the variable).
3758 public void EmitLoad (EmitContext ec)
3760 ILGenerator ig = ec.ig;
3763 if (!ec.MethodIsStatic)
3766 EmitLdArg (ig, arg_idx);
3769 // FIXME: Review for anonymous methods
3773 public override void Emit (EmitContext ec)
3778 public void Emit (EmitContext ec, bool leave_copy)
3780 ILGenerator ig = ec.ig;
3783 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
3785 throw new InternalErrorException ();
3787 ec.EmitParameter (name);
3791 if (!ec.MethodIsStatic)
3794 EmitLdArg (ig, arg_idx);
3798 ec.ig.Emit (OpCodes.Dup);
3801 // If we are a reference, we loaded on the stack a pointer
3802 // Now lets load the real value
3804 LoadFromPtr (ig, type);
3808 ec.ig.Emit (OpCodes.Dup);
3811 temp = new LocalTemporary (ec, type);
3817 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3819 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
3820 ec.EmitAssignParameter (name, source, leave_copy, prepare_for_load);
3824 ILGenerator ig = ec.ig;
3827 prepared = prepare_for_load;
3829 if (!ec.MethodIsStatic)
3832 if (is_ref && !prepared)
3833 EmitLdArg (ig, arg_idx);
3838 ec.ig.Emit (OpCodes.Dup);
3842 temp = new LocalTemporary (ec, type);
3846 StoreFromPtr (ig, type);
3852 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
3854 ig.Emit (OpCodes.Starg, arg_idx);
3858 public void AddressOf (EmitContext ec, AddressOp mode)
3860 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
3861 ec.EmitAddressOfParameter (name);
3867 if (!ec.MethodIsStatic)
3872 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
3874 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
3877 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
3879 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
3886 /// Used for arguments to New(), Invocation()
3888 public class Argument {
3889 public enum AType : byte {
3896 public readonly AType ArgType;
3897 public Expression Expr;
3899 public Argument (Expression expr, AType type)
3902 this.ArgType = type;
3905 public Argument (Expression expr)
3908 this.ArgType = AType.Expression;
3913 if (ArgType == AType.Ref || ArgType == AType.Out)
3914 return TypeManager.GetReferenceType (Expr.Type);
3920 public Parameter.Modifier Modifier
3925 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
3928 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
3931 return Parameter.Modifier.NONE;
3936 public static string FullDesc (Argument a)
3938 if (a.ArgType == AType.ArgList)
3941 return (a.ArgType == AType.Ref ? "ref " :
3942 (a.ArgType == AType.Out ? "out " : "")) +
3943 TypeManager.CSharpName (a.Expr.Type);
3946 public bool ResolveMethodGroup (EmitContext ec, Location loc)
3948 // FIXME: csc doesn't report any error if you try to use `ref' or
3949 // `out' in a delegate creation expression.
3950 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
3957 void Error_LValueRequired (Location loc)
3959 Report.Error (1510, loc, "A ref or out argument must be an assignable variable");
3962 public bool Resolve (EmitContext ec, Location loc)
3964 bool old_do_flow_analysis = ec.DoFlowAnalysis;
3965 ec.DoFlowAnalysis = true;
3967 if (ArgType == AType.Ref) {
3968 ec.InRefOutArgumentResolving = true;
3969 Expr = Expr.Resolve (ec);
3970 ec.InRefOutArgumentResolving = false;
3972 ec.DoFlowAnalysis = old_do_flow_analysis;
3976 Expr = Expr.DoResolveLValue (ec, Expr);
3978 Error_LValueRequired (loc);
3979 } else if (ArgType == AType.Out) {
3980 ec.InRefOutArgumentResolving = true;
3981 Expr = Expr.DoResolveLValue (ec, EmptyExpression.Null);
3982 ec.InRefOutArgumentResolving = false;
3985 Error_LValueRequired (loc);
3988 Expr = Expr.Resolve (ec);
3990 ec.DoFlowAnalysis = old_do_flow_analysis;
3995 if (ArgType == AType.Expression)
3999 // Catch errors where fields of a MarshalByRefObject are passed as ref or out
4000 // This is only allowed for `this'
4002 FieldExpr fe = Expr as FieldExpr;
4003 if (fe != null && !fe.IsStatic){
4004 Expression instance = fe.InstanceExpression;
4006 if (instance.GetType () != typeof (This)){
4007 if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
4008 Report.SymbolRelatedToPreviousError (fe.InstanceExpression.Type);
4009 Report.Warning (197, 1, loc,
4010 "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",
4011 fe.GetSignatureForError ());
4018 if (Expr.eclass != ExprClass.Variable){
4020 // We just probe to match the CSC output
4022 if (Expr.eclass == ExprClass.PropertyAccess ||
4023 Expr.eclass == ExprClass.IndexerAccess){
4024 Report.Error (206, loc, "A property or indexer `{0}' may not be passed as an out or ref parameter",
4025 Expr.GetSignatureForError ());
4027 Error_LValueRequired (loc);
4035 public void Emit (EmitContext ec)
4038 // Ref and Out parameters need to have their addresses taken.
4040 // ParameterReferences might already be references, so we want
4041 // to pass just the value
4043 if (ArgType == AType.Ref || ArgType == AType.Out){
4044 AddressOp mode = AddressOp.Store;
4046 if (ArgType == AType.Ref)
4047 mode |= AddressOp.Load;
4049 if (Expr is ParameterReference){
4050 ParameterReference pr = (ParameterReference) Expr;
4056 pr.AddressOf (ec, mode);
4059 if (Expr is IMemoryLocation)
4060 ((IMemoryLocation) Expr).AddressOf (ec, mode);
4062 Error_LValueRequired (Expr.Location);
4072 /// Invocation of methods or delegates.
4074 public class Invocation : ExpressionStatement {
4075 public readonly ArrayList Arguments;
4078 MethodBase method = null;
4081 // arguments is an ArrayList, but we do not want to typecast,
4082 // as it might be null.
4084 // FIXME: only allow expr to be a method invocation or a
4085 // delegate invocation (7.5.5)
4087 public Invocation (Expression expr, ArrayList arguments)
4090 Arguments = arguments;
4091 loc = expr.Location;
4094 public Expression Expr {
4101 /// Determines "better conversion" as specified in 14.4.2.3
4103 /// Returns : p if a->p is better,
4104 /// q if a->q is better,
4105 /// null if neither is better
4107 static Type BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
4109 Type argument_type = a.Type;
4110 Expression argument_expr = a.Expr;
4112 if (argument_type == null)
4113 throw new Exception ("Expression of type " + a.Expr +
4114 " does not resolve its type");
4116 if (p == null || q == null)
4117 throw new InternalErrorException ("BetterConversion Got a null conversion");
4122 if (argument_expr is NullLiteral) {
4124 // If the argument is null and one of the types to compare is 'object' and
4125 // the other is a reference type, we prefer the other.
4127 // This follows from the usual rules:
4128 // * There is an implicit conversion from 'null' to type 'object'
4129 // * There is an implicit conversion from 'null' to any reference type
4130 // * There is an implicit conversion from any reference type to type 'object'
4131 // * There is no implicit conversion from type 'object' to other reference types
4132 // => Conversion of 'null' to a reference type is better than conversion to 'object'
4134 // FIXME: This probably isn't necessary, since the type of a NullLiteral is the
4135 // null type. I think it used to be 'object' and thus needed a special
4136 // case to avoid the immediately following two checks.
4138 if (!p.IsValueType && q == TypeManager.object_type)
4140 if (!q.IsValueType && p == TypeManager.object_type)
4144 if (argument_type == p)
4147 if (argument_type == q)
4150 Expression p_tmp = new EmptyExpression (p);
4151 Expression q_tmp = new EmptyExpression (q);
4153 bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
4154 bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
4156 if (p_to_q && !q_to_p)
4159 if (q_to_p && !p_to_q)
4162 if (p == TypeManager.sbyte_type)
4163 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4164 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4166 if (q == TypeManager.sbyte_type)
4167 if (p == TypeManager.byte_type || p == TypeManager.ushort_type ||
4168 p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4171 if (p == TypeManager.short_type)
4172 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4173 q == TypeManager.uint64_type)
4175 if (q == TypeManager.short_type)
4176 if (p == TypeManager.ushort_type || p == TypeManager.uint32_type ||
4177 p == TypeManager.uint64_type)
4180 if (p == TypeManager.int32_type)
4181 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4183 if (q == TypeManager.int32_type)
4184 if (p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4187 if (p == TypeManager.int64_type)
4188 if (q == TypeManager.uint64_type)
4190 if (q == TypeManager.int64_type)
4191 if (p == TypeManager.uint64_type)
4198 /// Determines "Better function" between candidate
4199 /// and the current best match
4202 /// Returns an integer indicating :
4203 /// false if candidate ain't better
4204 /// true if candidate is better than the current best match
4206 static bool BetterFunction (EmitContext ec, ArrayList args, int argument_count,
4207 MethodBase candidate, bool candidate_params,
4208 MethodBase best, bool best_params, Location loc)
4210 ParameterData candidate_pd = TypeManager.GetParameterData (candidate);
4211 ParameterData best_pd = TypeManager.GetParameterData (best);
4213 bool better_at_least_one = false;
4215 for (int j = 0; j < argument_count; ++j) {
4216 Argument a = (Argument) args [j];
4218 Type ct = TypeManager.TypeToCoreType (candidate_pd.ParameterType (j));
4219 Type bt = TypeManager.TypeToCoreType (best_pd.ParameterType (j));
4221 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4222 if (candidate_params)
4223 ct = TypeManager.GetElementType (ct);
4225 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4227 bt = TypeManager.GetElementType (bt);
4233 Type better = BetterConversion (ec, a, ct, bt, loc);
4235 // for each argument, the conversion to 'ct' should be no worse than
4236 // the conversion to 'bt'.
4240 // for at least one argument, the conversion to 'ct' should be better than
4241 // the conversion to 'bt'.
4243 better_at_least_one = true;
4246 if (better_at_least_one)
4250 // This handles the case
4252 // Add (float f1, float f2, float f3);
4253 // Add (params decimal [] foo);
4255 // The call Add (3, 4, 5) should be ambiguous. Without this check, the
4256 // first candidate would've chosen as better.
4262 // This handles the following cases:
4264 // Trim () is better than Trim (params char[] chars)
4265 // Concat (string s1, string s2, string s3) is better than
4266 // Concat (string s1, params string [] srest)
4268 return !candidate_params && best_params;
4271 static bool IsOverride (MethodBase cand_method, MethodBase base_method)
4273 if (!IsAncestralType (base_method.DeclaringType, cand_method.DeclaringType))
4276 ParameterData cand_pd = TypeManager.GetParameterData (cand_method);
4277 ParameterData base_pd = TypeManager.GetParameterData (base_method);
4279 if (cand_pd.Count != base_pd.Count)
4282 for (int j = 0; j < cand_pd.Count; ++j) {
4283 Parameter.Modifier cm = cand_pd.ParameterModifier (j);
4284 Parameter.Modifier bm = base_pd.ParameterModifier (j);
4285 Type ct = TypeManager.TypeToCoreType (cand_pd.ParameterType (j));
4286 Type bt = TypeManager.TypeToCoreType (base_pd.ParameterType (j));
4288 if (cm != bm || ct != bt)
4295 public static string FullMethodDesc (MethodBase mb)
4301 if (mb is MethodInfo) {
4302 sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
4306 sb = new StringBuilder ();
4308 sb.Append (TypeManager.CSharpSignature (mb));
4309 return sb.ToString ();
4312 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4314 MemberInfo [] miset;
4315 MethodGroupExpr union;
4320 return (MethodGroupExpr) mg2;
4323 return (MethodGroupExpr) mg1;
4326 MethodGroupExpr left_set = null, right_set = null;
4327 int length1 = 0, length2 = 0;
4329 left_set = (MethodGroupExpr) mg1;
4330 length1 = left_set.Methods.Length;
4332 right_set = (MethodGroupExpr) mg2;
4333 length2 = right_set.Methods.Length;
4335 ArrayList common = new ArrayList ();
4337 foreach (MethodBase r in right_set.Methods){
4338 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
4342 miset = new MemberInfo [length1 + length2 - common.Count];
4343 left_set.Methods.CopyTo (miset, 0);
4347 foreach (MethodBase r in right_set.Methods) {
4348 if (!common.Contains (r))
4352 union = new MethodGroupExpr (miset, loc);
4357 public static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4358 ArrayList arguments, int arg_count,
4359 ref MethodBase candidate)
4361 return IsParamsMethodApplicable (
4362 ec, me, arguments, arg_count, false, ref candidate) ||
4363 IsParamsMethodApplicable (
4364 ec, me, arguments, arg_count, true, ref candidate);
4369 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4370 ArrayList arguments, int arg_count,
4371 bool do_varargs, ref MethodBase candidate)
4373 return IsParamsMethodApplicable (
4374 ec, arguments, arg_count, candidate, do_varargs);
4378 /// Determines if the candidate method, if a params method, is applicable
4379 /// in its expanded form to the given set of arguments
4381 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
4382 int arg_count, MethodBase candidate,
4385 ParameterData pd = TypeManager.GetParameterData (candidate);
4387 int pd_count = pd.Count;
4391 int count = pd_count - 1;
4393 if (pd.ParameterModifier (count) != Parameter.Modifier.ARGLIST)
4395 if (pd_count != arg_count)
4398 if (pd.ParameterModifier (count) != Parameter.Modifier.PARAMS)
4402 if (count > arg_count)
4405 if (pd_count == 1 && arg_count == 0)
4409 // If we have come this far, the case which
4410 // remains is when the number of parameters is
4411 // less than or equal to the argument count.
4413 for (int i = 0; i < count; ++i) {
4415 Argument a = (Argument) arguments [i];
4417 Parameter.Modifier a_mod = a.Modifier &
4418 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4419 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4420 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4422 if (a_mod == p_mod) {
4424 if (a_mod == Parameter.Modifier.NONE)
4425 if (!Convert.ImplicitConversionExists (ec,
4427 pd.ParameterType (i)))
4430 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4431 Type pt = pd.ParameterType (i);
4434 pt = TypeManager.GetReferenceType (pt);
4445 Argument a = (Argument) arguments [count];
4446 if (!(a.Expr is Arglist))
4452 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4454 for (int i = pd_count - 1; i < arg_count; i++) {
4455 Argument a = (Argument) arguments [i];
4457 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4464 public static bool IsApplicable (EmitContext ec, MethodGroupExpr me,
4465 ArrayList arguments, int arg_count,
4466 ref MethodBase candidate)
4468 return IsApplicable (ec, arguments, arg_count, candidate);
4472 /// Determines if the candidate method is applicable (section 14.4.2.1)
4473 /// to the given set of arguments
4475 static bool IsApplicable (EmitContext ec, ArrayList arguments, int arg_count,
4476 MethodBase candidate)
4478 ParameterData pd = TypeManager.GetParameterData (candidate);
4480 if (arg_count != pd.Count)
4483 for (int i = arg_count; i > 0; ) {
4486 Argument a = (Argument) arguments [i];
4488 Parameter.Modifier a_mod = a.Modifier &
4489 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4490 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4491 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4493 if (a_mod == p_mod ||
4494 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4495 if (a_mod == Parameter.Modifier.NONE) {
4496 if (!Convert.ImplicitConversionExists (ec,
4498 pd.ParameterType (i)))
4502 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4503 Type pt = pd.ParameterType (i);
4506 pt = TypeManager.GetReferenceType (pt);
4518 static private bool IsAncestralType (Type first_type, Type second_type)
4520 return first_type != second_type &&
4521 (second_type.IsSubclassOf (first_type) ||
4522 TypeManager.ImplementsInterface (second_type, first_type));
4526 /// Find the Applicable Function Members (7.4.2.1)
4528 /// me: Method Group expression with the members to select.
4529 /// it might contain constructors or methods (or anything
4530 /// that maps to a method).
4532 /// Arguments: ArrayList containing resolved Argument objects.
4534 /// loc: The location if we want an error to be reported, or a Null
4535 /// location for "probing" purposes.
4537 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4538 /// that is the best match of me on Arguments.
4541 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4542 ArrayList Arguments, bool may_fail,
4545 MethodBase method = null;
4546 bool method_params = false;
4547 Type applicable_type = null;
4549 ArrayList candidates = new ArrayList (2);
4550 ArrayList candidate_overrides = null;
4553 // Used to keep a map between the candidate
4554 // and whether it is being considered in its
4555 // normal or expanded form
4557 // false is normal form, true is expanded form
4559 Hashtable candidate_to_form = null;
4561 if (Arguments != null)
4562 arg_count = Arguments.Count;
4564 if ((me.Name == "Invoke") &&
4565 TypeManager.IsDelegateType (me.DeclaringType)) {
4566 Error_InvokeOnDelegate (loc);
4570 MethodBase[] methods = me.Methods;
4573 // First we construct the set of applicable methods
4575 bool is_sorted = true;
4576 for (int i = 0; i < methods.Length; i++){
4577 Type decl_type = methods [i].DeclaringType;
4580 // If we have already found an applicable method
4581 // we eliminate all base types (Section 14.5.5.1)
4583 if ((applicable_type != null) &&
4584 IsAncestralType (decl_type, applicable_type))
4588 // Methods marked 'override' don't take part in 'applicable_type'
4589 // computation, nor in the actual overload resolution.
4590 // However, they still need to be emitted instead of a base virtual method.
4591 // We avoid doing the 'applicable' test here, since it'll anyway be applied
4592 // to the base virtual function, and IsOverride is much faster than IsApplicable.
4594 if (!me.IsBase && TypeManager.IsOverride (methods [i])) {
4595 if (candidate_overrides == null)
4596 candidate_overrides = new ArrayList ();
4597 candidate_overrides.Add (methods [i]);
4602 // Check if candidate is applicable (section 14.4.2.1)
4603 // Is candidate applicable in normal form?
4605 bool is_applicable = IsApplicable (
4606 ec, me, Arguments, arg_count, ref methods [i]);
4608 if (!is_applicable &&
4609 (IsParamsMethodApplicable (
4610 ec, me, Arguments, arg_count, ref methods [i]))) {
4611 MethodBase candidate = methods [i];
4612 if (candidate_to_form == null)
4613 candidate_to_form = new PtrHashtable ();
4614 candidate_to_form [candidate] = candidate;
4615 // Candidate is applicable in expanded form
4616 is_applicable = true;
4622 candidates.Add (methods [i]);
4624 if (applicable_type == null)
4625 applicable_type = decl_type;
4626 else if (applicable_type != decl_type) {
4628 if (IsAncestralType (applicable_type, decl_type))
4629 applicable_type = decl_type;
4633 int candidate_top = candidates.Count;
4635 if (applicable_type == null) {
4637 // Okay so we have failed to find anything so we
4638 // return by providing info about the closest match
4640 int errors = Report.Errors;
4641 for (int i = 0; i < methods.Length; ++i) {
4642 MethodBase c = (MethodBase) methods [i];
4643 ParameterData pd = TypeManager.GetParameterData (c);
4645 if (pd.Count != arg_count)
4648 VerifyArgumentsCompat (ec, Arguments, arg_count,
4649 c, false, null, may_fail, loc);
4651 if (!may_fail && errors == Report.Errors)
4652 throw new InternalErrorException (
4653 "VerifyArgumentsCompat and IsApplicable do not agree; " +
4654 "likely reason: ImplicitConversion and ImplicitConversionExists have gone out of sync");
4659 if (!may_fail && errors == Report.Errors) {
4660 string report_name = me.Name;
4661 if (report_name == ".ctor")
4662 report_name = me.DeclaringType.ToString ();
4663 Error_WrongNumArguments (loc, report_name, arg_count);
4671 // At this point, applicable_type is _one_ of the most derived types
4672 // in the set of types containing the methods in this MethodGroup.
4673 // Filter the candidates so that they only contain methods from the
4674 // most derived types.
4677 int finalized = 0; // Number of finalized candidates
4680 // Invariant: applicable_type is a most derived type
4682 // We'll try to complete Section 14.5.5.1 for 'applicable_type' by
4683 // eliminating all it's base types. At the same time, we'll also move
4684 // every unrelated type to the end of the array, and pick the next
4685 // 'applicable_type'.
4687 Type next_applicable_type = null;
4688 int j = finalized; // where to put the next finalized candidate
4689 int k = finalized; // where to put the next undiscarded candidate
4690 for (int i = finalized; i < candidate_top; ++i) {
4691 MethodBase candidate = (MethodBase) candidates [i];
4692 Type decl_type = candidate.DeclaringType;
4694 if (decl_type == applicable_type) {
4695 candidates [k++] = candidates [j];
4696 candidates [j++] = candidates [i];
4700 if (IsAncestralType (decl_type, applicable_type))
4703 if (next_applicable_type != null &&
4704 IsAncestralType (decl_type, next_applicable_type))
4707 candidates [k++] = candidates [i];
4709 if (next_applicable_type == null ||
4710 IsAncestralType (next_applicable_type, decl_type))
4711 next_applicable_type = decl_type;
4714 applicable_type = next_applicable_type;
4717 } while (applicable_type != null);
4721 // Now we actually find the best method
4724 method = (MethodBase) candidates [0];
4725 method_params = candidate_to_form != null && candidate_to_form.Contains (method);
4726 for (int ix = 1; ix < candidate_top; ix++){
4727 MethodBase candidate = (MethodBase) candidates [ix];
4729 if (candidate == method)
4732 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4734 if (BetterFunction (ec, Arguments, arg_count,
4735 candidate, cand_params,
4736 method, method_params, loc)) {
4738 method_params = cand_params;
4742 // Now check that there are no ambiguities i.e the selected method
4743 // should be better than all the others
4745 MethodBase ambiguous = null;
4746 for (int ix = 0; ix < candidate_top; ix++){
4747 MethodBase candidate = (MethodBase) candidates [ix];
4749 if (candidate == method)
4752 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4753 if (!BetterFunction (ec, Arguments, arg_count,
4754 method, method_params,
4755 candidate, cand_params,
4757 Report.SymbolRelatedToPreviousError (candidate);
4758 ambiguous = candidate;
4762 if (ambiguous != null) {
4763 Report.SymbolRelatedToPreviousError (method);
4764 Report.Error (121, loc, "The call is ambiguous between the following methods or properties: `{0}' and `{1}'",
4765 TypeManager.CSharpSignature (ambiguous), TypeManager.CSharpSignature (method));
4770 // If the method is a virtual function, pick an override closer to the LHS type.
4772 if (!me.IsBase && method.IsVirtual) {
4773 if (TypeManager.IsOverride (method))
4774 throw new InternalErrorException (
4775 "Should not happen. An 'override' method took part in overload resolution: " + method);
4777 if (candidate_overrides != null)
4778 foreach (MethodBase candidate in candidate_overrides) {
4779 if (IsOverride (candidate, method))
4785 // And now check if the arguments are all
4786 // compatible, perform conversions if
4787 // necessary etc. and return if everything is
4790 if (!VerifyArgumentsCompat (ec, Arguments, arg_count, method,
4791 method_params, null, may_fail, loc))
4794 if (method != null) {
4795 IMethodData data = TypeManager.GetMethod (method);
4797 data.SetMemberIsUsed ();
4802 public static void Error_WrongNumArguments (Location loc, String name, int arg_count)
4804 Report.Error (1501, loc, "No overload for method `{0}' takes `{1}' arguments",
4808 static void Error_InvokeOnDelegate (Location loc)
4810 Report.Error (1533, loc,
4811 "Invoke cannot be called directly on a delegate");
4814 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
4815 Type delegate_type, Argument a, ParameterData expected_par)
4817 if (delegate_type == null)
4818 Report.Error (1502, loc, "The best overloaded method match for `{0}' has some invalid arguments",
4819 TypeManager.CSharpSignature (method));
4821 Report.Error (1594, loc, "Delegate `{0}' has some invalid arguments",
4822 TypeManager.CSharpName (delegate_type));
4824 string par_desc = expected_par.ParameterDesc (idx);
4826 if (a.Modifier != expected_par.ParameterModifier (idx)) {
4827 if ((expected_par.ParameterModifier (idx) & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) == 0)
4828 Report.Error (1615, loc, "Argument `{0}' should not be passed with the `{1}' keyword",
4829 idx + 1, Parameter.GetModifierSignature (a.Modifier));
4831 Report.Error (1620, loc, "Argument `{0}' must be passed with the `{1}' keyword",
4832 idx + 1, Parameter.GetModifierSignature (expected_par.ParameterModifier (idx)));
4836 Report.Error (1503, loc,
4837 String.Format ("Argument {0}: Cannot convert from `{1}' to `{2}'",
4838 idx + 1, Argument.FullDesc (a), par_desc));
4841 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
4842 int arg_count, MethodBase method,
4843 bool chose_params_expanded,
4844 Type delegate_type, bool may_fail,
4847 ParameterData pd = TypeManager.GetParameterData (method);
4848 int pd_count = pd.Count;
4850 for (int j = 0; j < arg_count; j++) {
4851 Argument a = (Argument) Arguments [j];
4852 Expression a_expr = a.Expr;
4853 Type parameter_type = pd.ParameterType (j);
4854 Parameter.Modifier pm = pd.ParameterModifier (j);
4856 if (pm == Parameter.Modifier.PARAMS){
4857 if ((pm & ~Parameter.Modifier.PARAMS) != a.Modifier) {
4859 Error_InvalidArguments (
4860 loc, j, method, delegate_type,
4865 if (chose_params_expanded)
4866 parameter_type = TypeManager.GetElementType (parameter_type);
4867 } else if (pm == Parameter.Modifier.ARGLIST){
4873 if (pd.ParameterModifier (j) != a.Modifier){
4875 Error_InvalidArguments (
4876 loc, j, method, delegate_type,
4885 if (!a.Type.Equals (parameter_type)){
4888 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
4892 Error_InvalidArguments (loc, j, method, delegate_type, a, pd);
4897 // Update the argument with the implicit conversion
4903 if (parameter_type.IsPointer){
4910 Parameter.Modifier a_mod = a.Modifier &
4911 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4912 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
4913 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4915 if (a_mod != p_mod &&
4916 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
4918 Invocation.Error_InvalidArguments (loc, j, method, null, a, pd);
4928 public override Expression DoResolve (EmitContext ec)
4931 // First, resolve the expression that is used to
4932 // trigger the invocation
4934 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4938 if (!(expr is MethodGroupExpr)) {
4939 Type expr_type = expr.Type;
4941 if (expr_type != null){
4942 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
4944 return (new DelegateInvocation (
4945 this.expr, Arguments, loc)).Resolve (ec);
4949 if (!(expr is MethodGroupExpr)){
4950 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup, loc);
4955 // Next, evaluate all the expressions in the argument list
4957 if (Arguments != null){
4958 foreach (Argument a in Arguments){
4959 if (!a.Resolve (ec, loc))
4964 MethodGroupExpr mg = (MethodGroupExpr) expr;
4965 method = OverloadResolve (ec, mg, Arguments, false, loc);
4970 MethodInfo mi = method as MethodInfo;
4972 type = TypeManager.TypeToCoreType (mi.ReturnType);
4973 Expression iexpr = mg.InstanceExpression;
4975 if (iexpr == null ||
4976 iexpr is This || iexpr is EmptyExpression ||
4977 mg.IdenticalTypeName) {
4978 mg.InstanceExpression = null;
4980 MemberExpr.error176 (loc, TypeManager.CSharpSignature (mi));
4984 if (iexpr == null || iexpr is EmptyExpression) {
4985 SimpleName.Error_ObjectRefRequired (ec, loc, TypeManager.CSharpSignature (mi));
4991 if (type.IsPointer){
4999 // Only base will allow this invocation to happen.
5001 if (mg.IsBase && method.IsAbstract){
5002 Error_CannotCallAbstractBase (TypeManager.CSharpSignature (method));
5006 if (Arguments == null && method.Name == "Finalize") {
5008 Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
5010 Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
5014 if ((method.Attributes & MethodAttributes.SpecialName) != 0 && IsSpecialMethodInvocation (method)) {
5018 if (mg.InstanceExpression != null)
5019 mg.InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
5021 eclass = ExprClass.Value;
5025 bool IsSpecialMethodInvocation (MethodBase method)
5027 IMethodData md = TypeManager.GetMethod (method);
5029 if (!(md is AbstractPropertyEventMethod) && !(md is Operator))
5032 if (!TypeManager.IsSpecialMethod (method))
5035 int args = TypeManager.GetParameterData (method).Count;
5036 if (method.Name.StartsWith ("get_") && args > 0)
5038 else if (method.Name.StartsWith ("set_") && args > 2)
5041 // TODO: check operators and events as well ?
5044 Report.SymbolRelatedToPreviousError (method);
5045 Report.Error (571, loc, "`{0}': cannot explicitly call operator or accessor",
5046 TypeManager.CSharpSignature (method, true));
5052 // Emits the list of arguments as an array
5054 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
5056 ILGenerator ig = ec.ig;
5057 int count = arguments.Count - idx;
5058 Argument a = (Argument) arguments [idx];
5059 Type t = a.Expr.Type;
5061 IntConstant.EmitInt (ig, count);
5062 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
5064 int top = arguments.Count;
5065 for (int j = idx; j < top; j++){
5066 a = (Argument) arguments [j];
5068 ig.Emit (OpCodes.Dup);
5069 IntConstant.EmitInt (ig, j - idx);
5072 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj);
5074 ig.Emit (OpCodes.Ldelema, t);
5079 ig.Emit (OpCodes.Stobj, t);
5086 /// Emits a list of resolved Arguments that are in the arguments
5089 /// The MethodBase argument might be null if the
5090 /// emission of the arguments is known not to contain
5091 /// a `params' field (for example in constructors or other routines
5092 /// that keep their arguments in this structure)
5094 /// if `dup_args' is true, a copy of the arguments will be left
5095 /// on the stack. If `dup_args' is true, you can specify `this_arg'
5096 /// which will be duplicated before any other args. Only EmitCall
5097 /// should be using this interface.
5099 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments, bool dup_args, LocalTemporary this_arg)
5101 ParameterData pd = mb == null ? null : TypeManager.GetParameterData (mb);
5102 int top = arguments == null ? 0 : arguments.Count;
5103 LocalTemporary [] temps = null;
5105 if (dup_args && top != 0)
5106 temps = new LocalTemporary [top];
5108 for (int i = 0; i < top; i++){
5109 Argument a = (Argument) arguments [i];
5112 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
5114 // Special case if we are passing the same data as the
5115 // params argument, do not put it in an array.
5117 if (pd.ParameterType (i) == a.Type)
5120 EmitParams (ec, i, arguments);
5127 ec.ig.Emit (OpCodes.Dup);
5128 (temps [i] = new LocalTemporary (ec, a.Type)).Store (ec);
5133 if (this_arg != null)
5136 for (int i = 0; i < top; i ++)
5137 temps [i].Emit (ec);
5140 if (pd != null && pd.Count > top &&
5141 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
5142 ILGenerator ig = ec.ig;
5144 IntConstant.EmitInt (ig, 0);
5145 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
5149 static Type[] GetVarargsTypes (EmitContext ec, MethodBase mb,
5150 ArrayList arguments)
5152 ParameterData pd = TypeManager.GetParameterData (mb);
5154 if (arguments == null)
5155 return new Type [0];
5157 Argument a = (Argument) arguments [pd.Count - 1];
5158 Arglist list = (Arglist) a.Expr;
5160 return list.ArgumentTypes;
5164 /// This checks the ConditionalAttribute on the method
5166 static bool IsMethodExcluded (MethodBase method, EmitContext ec)
5168 if (method.IsConstructor)
5171 IMethodData md = TypeManager.GetMethod (method);
5173 return md.IsExcluded (ec);
5175 // For some methods (generated by delegate class) GetMethod returns null
5176 // because they are not included in builder_to_method table
5177 if (method.DeclaringType is TypeBuilder)
5180 return AttributeTester.IsConditionalMethodExcluded (method);
5184 /// is_base tells whether we want to force the use of the `call'
5185 /// opcode instead of using callvirt. Call is required to call
5186 /// a specific method, while callvirt will always use the most
5187 /// recent method in the vtable.
5189 /// is_static tells whether this is an invocation on a static method
5191 /// instance_expr is an expression that represents the instance
5192 /// it must be non-null if is_static is false.
5194 /// method is the method to invoke.
5196 /// Arguments is the list of arguments to pass to the method or constructor.
5198 public static void EmitCall (EmitContext ec, bool is_base,
5199 bool is_static, Expression instance_expr,
5200 MethodBase method, ArrayList Arguments, Location loc)
5202 EmitCall (ec, is_base, is_static, instance_expr, method, Arguments, loc, false, false);
5205 // `dup_args' leaves an extra copy of the arguments on the stack
5206 // `omit_args' does not leave any arguments at all.
5207 // So, basically, you could make one call with `dup_args' set to true,
5208 // and then another with `omit_args' set to true, and the two calls
5209 // would have the same set of arguments. However, each argument would
5210 // only have been evaluated once.
5211 public static void EmitCall (EmitContext ec, bool is_base,
5212 bool is_static, Expression instance_expr,
5213 MethodBase method, ArrayList Arguments, Location loc,
5214 bool dup_args, bool omit_args)
5216 ILGenerator ig = ec.ig;
5217 bool struct_call = false;
5218 bool this_call = false;
5219 LocalTemporary this_arg = null;
5221 Type decl_type = method.DeclaringType;
5223 if (!RootContext.StdLib) {
5224 // Replace any calls to the system's System.Array type with calls to
5225 // the newly created one.
5226 if (method == TypeManager.system_int_array_get_length)
5227 method = TypeManager.int_array_get_length;
5228 else if (method == TypeManager.system_int_array_get_rank)
5229 method = TypeManager.int_array_get_rank;
5230 else if (method == TypeManager.system_object_array_clone)
5231 method = TypeManager.object_array_clone;
5232 else if (method == TypeManager.system_int_array_get_length_int)
5233 method = TypeManager.int_array_get_length_int;
5234 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5235 method = TypeManager.int_array_get_lower_bound_int;
5236 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5237 method = TypeManager.int_array_get_upper_bound_int;
5238 else if (method == TypeManager.system_void_array_copyto_array_int)
5239 method = TypeManager.void_array_copyto_array_int;
5242 if (ec.TestObsoleteMethodUsage) {
5244 // This checks ObsoleteAttribute on the method and on the declaring type
5246 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
5248 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
5251 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
5253 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
5257 if (IsMethodExcluded (method, ec))
5261 if (instance_expr == EmptyExpression.Null) {
5262 SimpleName.Error_ObjectRefRequired (ec, loc, TypeManager.CSharpSignature (method));
5266 this_call = instance_expr is This;
5267 if (decl_type.IsValueType || (!this_call && instance_expr.Type.IsValueType))
5273 // Push the instance expression
5275 if (instance_expr.Type.IsValueType) {
5277 // Special case: calls to a function declared in a
5278 // reference-type with a value-type argument need
5279 // to have their value boxed.
5280 if (decl_type.IsValueType) {
5282 // If the expression implements IMemoryLocation, then
5283 // we can optimize and use AddressOf on the
5286 // If not we have to use some temporary storage for
5288 if (instance_expr is IMemoryLocation) {
5289 ((IMemoryLocation)instance_expr).
5290 AddressOf (ec, AddressOp.LoadStore);
5292 LocalTemporary temp = new LocalTemporary (ec, instance_expr.Type);
5293 instance_expr.Emit (ec);
5295 temp.AddressOf (ec, AddressOp.Load);
5298 // avoid the overhead of doing this all the time.
5300 t = TypeManager.GetReferenceType (instance_expr.Type);
5302 instance_expr.Emit (ec);
5303 ig.Emit (OpCodes.Box, instance_expr.Type);
5304 t = TypeManager.object_type;
5307 instance_expr.Emit (ec);
5308 t = instance_expr.Type;
5312 ig.Emit (OpCodes.Dup);
5313 if (Arguments != null && Arguments.Count != 0) {
5314 this_arg = new LocalTemporary (ec, t);
5315 this_arg.Store (ec);
5322 EmitArguments (ec, method, Arguments, dup_args, this_arg);
5325 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
5326 call_op = OpCodes.Call;
5328 call_op = OpCodes.Callvirt;
5330 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
5331 Type[] varargs_types = GetVarargsTypes (ec, method, Arguments);
5332 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
5339 // and DoFoo is not virtual, you can omit the callvirt,
5340 // because you don't need the null checking behavior.
5342 if (method is MethodInfo)
5343 ig.Emit (call_op, (MethodInfo) method);
5345 ig.Emit (call_op, (ConstructorInfo) method);
5348 public override void Emit (EmitContext ec)
5350 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5352 EmitCall (ec, mg.IsBase, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5355 public override void EmitStatement (EmitContext ec)
5360 // Pop the return value if there is one
5362 if (method is MethodInfo){
5363 Type ret = ((MethodInfo)method).ReturnType;
5364 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5365 ec.ig.Emit (OpCodes.Pop);
5370 public class InvocationOrCast : ExpressionStatement
5373 Expression argument;
5375 public InvocationOrCast (Expression expr, Expression argument)
5378 this.argument = argument;
5379 this.loc = expr.Location;
5382 public override Expression DoResolve (EmitContext ec)
5385 // First try to resolve it as a cast.
5387 TypeExpr te = expr.ResolveAsTypeTerminal (ec, true);
5389 Cast cast = new Cast (te, argument, loc);
5390 return cast.Resolve (ec);
5394 // This can either be a type or a delegate invocation.
5395 // Let's just resolve it and see what we'll get.
5397 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5402 // Ok, so it's a Cast.
5404 if (expr.eclass == ExprClass.Type) {
5405 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
5406 return cast.Resolve (ec);
5410 // It's a delegate invocation.
5412 if (!TypeManager.IsDelegateType (expr.Type)) {
5413 Error (149, "Method name expected");
5417 ArrayList args = new ArrayList ();
5418 args.Add (new Argument (argument, Argument.AType.Expression));
5419 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5420 return invocation.Resolve (ec);
5425 Error (201, "Only assignment, call, increment, decrement and new object " +
5426 "expressions can be used as a statement");
5429 public override ExpressionStatement ResolveStatement (EmitContext ec)
5432 // First try to resolve it as a cast.
5434 TypeExpr te = expr.ResolveAsTypeTerminal (ec, true);
5441 // This can either be a type or a delegate invocation.
5442 // Let's just resolve it and see what we'll get.
5444 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5445 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5451 // It's a delegate invocation.
5453 if (!TypeManager.IsDelegateType (expr.Type)) {
5454 Error (149, "Method name expected");
5458 ArrayList args = new ArrayList ();
5459 args.Add (new Argument (argument, Argument.AType.Expression));
5460 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5461 return invocation.ResolveStatement (ec);
5464 public override void Emit (EmitContext ec)
5466 throw new Exception ("Cannot happen");
5469 public override void EmitStatement (EmitContext ec)
5471 throw new Exception ("Cannot happen");
5476 // This class is used to "disable" the code generation for the
5477 // temporary variable when initializing value types.
5479 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5480 public void AddressOf (EmitContext ec, AddressOp Mode)
5487 /// Implements the new expression
5489 public class New : ExpressionStatement, IMemoryLocation {
5490 public readonly ArrayList Arguments;
5493 // During bootstrap, it contains the RequestedType,
5494 // but if `type' is not null, it *might* contain a NewDelegate
5495 // (because of field multi-initialization)
5497 public Expression RequestedType;
5499 MethodBase method = null;
5502 // If set, the new expression is for a value_target, and
5503 // we will not leave anything on the stack.
5505 Expression value_target;
5506 bool value_target_set = false;
5508 public New (Expression requested_type, ArrayList arguments, Location l)
5510 RequestedType = requested_type;
5511 Arguments = arguments;
5515 public bool SetValueTypeVariable (Expression value)
5517 value_target = value;
5518 value_target_set = true;
5519 if (!(value_target is IMemoryLocation)){
5520 Error_UnexpectedKind (null, "variable", loc);
5527 // This function is used to disable the following code sequence for
5528 // value type initialization:
5530 // AddressOf (temporary)
5534 // Instead the provide will have provided us with the address on the
5535 // stack to store the results.
5537 static Expression MyEmptyExpression;
5539 public void DisableTemporaryValueType ()
5541 if (MyEmptyExpression == null)
5542 MyEmptyExpression = new EmptyAddressOf ();
5545 // To enable this, look into:
5546 // test-34 and test-89 and self bootstrapping.
5548 // For instance, we can avoid a copy by using `newobj'
5549 // instead of Call + Push-temp on value types.
5550 // value_target = MyEmptyExpression;
5555 /// Converts complex core type syntax like 'new int ()' to simple constant
5557 public static Constant Constantify (Type t)
5559 if (t == TypeManager.int32_type)
5560 return new IntConstant (0, Location.Null);
5561 if (t == TypeManager.uint32_type)
5562 return new UIntConstant (0, Location.Null);
5563 if (t == TypeManager.int64_type)
5564 return new LongConstant (0, Location.Null);
5565 if (t == TypeManager.uint64_type)
5566 return new ULongConstant (0, Location.Null);
5567 if (t == TypeManager.float_type)
5568 return new FloatConstant (0, Location.Null);
5569 if (t == TypeManager.double_type)
5570 return new DoubleConstant (0, Location.Null);
5571 if (t == TypeManager.short_type)
5572 return new ShortConstant (0, Location.Null);
5573 if (t == TypeManager.ushort_type)
5574 return new UShortConstant (0, Location.Null);
5575 if (t == TypeManager.sbyte_type)
5576 return new SByteConstant (0, Location.Null);
5577 if (t == TypeManager.byte_type)
5578 return new ByteConstant (0, Location.Null);
5579 if (t == TypeManager.char_type)
5580 return new CharConstant ('\0', Location.Null);
5581 if (t == TypeManager.bool_type)
5582 return new BoolConstant (false, Location.Null);
5583 if (t == TypeManager.decimal_type)
5584 return new DecimalConstant (0, Location.Null);
5589 public override Expression DoResolve (EmitContext ec)
5592 // The New DoResolve might be called twice when initializing field
5593 // expressions (see EmitFieldInitializers, the call to
5594 // GetInitializerExpression will perform a resolve on the expression,
5595 // and later the assign will trigger another resolution
5597 // This leads to bugs (#37014)
5600 if (RequestedType is NewDelegate)
5601 return RequestedType;
5605 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec, false);
5609 type = texpr.ResolveType (ec);
5611 if (Arguments == null) {
5612 Expression c = Constantify (type);
5617 if (TypeManager.IsDelegateType (type)) {
5618 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5619 if (RequestedType != null)
5620 if (!(RequestedType is DelegateCreation))
5621 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
5622 return RequestedType;
5625 if (type.IsAbstract && type.IsSealed) {
5626 Report.SymbolRelatedToPreviousError (type);
5627 Report.Error (712, loc, "Cannot create an instance of the static class `{0}'", TypeManager.CSharpName (type));
5631 if (type.IsInterface || type.IsAbstract){
5632 Report.SymbolRelatedToPreviousError (type);
5633 Report.Error (144, loc, "Cannot create an instance of the abstract class or interface `{0}'", TypeManager.CSharpName (type));
5637 bool is_struct = type.IsValueType;
5638 eclass = ExprClass.Value;
5641 // SRE returns a match for .ctor () on structs (the object constructor),
5642 // so we have to manually ignore it.
5644 if (is_struct && Arguments == null)
5647 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
5648 Expression ml = MemberLookupFinal (ec, type, type, ".ctor",
5649 MemberTypes.Constructor, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5654 MethodGroupExpr mg = ml as MethodGroupExpr;
5657 ml.Error_UnexpectedKind (ec, "method group", loc);
5661 if (Arguments != null){
5662 foreach (Argument a in Arguments){
5663 if (!a.Resolve (ec, loc))
5668 method = Invocation.OverloadResolve (ec, mg, Arguments, false, loc);
5669 if (method == null) {
5670 if (almostMatchedMembers.Count != 0)
5671 MemberLookupFailed (ec, type, type, ".ctor", null, true, loc);
5679 // This DoEmit can be invoked in two contexts:
5680 // * As a mechanism that will leave a value on the stack (new object)
5681 // * As one that wont (init struct)
5683 // You can control whether a value is required on the stack by passing
5684 // need_value_on_stack. The code *might* leave a value on the stack
5685 // so it must be popped manually
5687 // If we are dealing with a ValueType, we have a few
5688 // situations to deal with:
5690 // * The target is a ValueType, and we have been provided
5691 // the instance (this is easy, we are being assigned).
5693 // * The target of New is being passed as an argument,
5694 // to a boxing operation or a function that takes a
5697 // In this case, we need to create a temporary variable
5698 // that is the argument of New.
5700 // Returns whether a value is left on the stack
5702 bool DoEmit (EmitContext ec, bool need_value_on_stack)
5704 bool is_value_type = type.IsValueType;
5705 ILGenerator ig = ec.ig;
5710 // Allow DoEmit() to be called multiple times.
5711 // We need to create a new LocalTemporary each time since
5712 // you can't share LocalBuilders among ILGeneators.
5713 if (!value_target_set)
5714 value_target = new LocalTemporary (ec, type);
5716 ml = (IMemoryLocation) value_target;
5717 ml.AddressOf (ec, AddressOp.Store);
5721 Invocation.EmitArguments (ec, method, Arguments, false, null);
5725 ig.Emit (OpCodes.Initobj, type);
5727 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5728 if (need_value_on_stack){
5729 value_target.Emit (ec);
5734 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
5739 public override void Emit (EmitContext ec)
5744 public override void EmitStatement (EmitContext ec)
5746 if (DoEmit (ec, false))
5747 ec.ig.Emit (OpCodes.Pop);
5750 public void AddressOf (EmitContext ec, AddressOp Mode)
5752 if (!type.IsValueType){
5754 // We throw an exception. So far, I believe we only need to support
5756 // foreach (int j in new StructType ())
5759 throw new Exception ("AddressOf should not be used for classes");
5762 if (!value_target_set)
5763 value_target = new LocalTemporary (ec, type);
5765 IMemoryLocation ml = (IMemoryLocation) value_target;
5766 ml.AddressOf (ec, AddressOp.Store);
5768 Invocation.EmitArguments (ec, method, Arguments, false, null);
5771 ec.ig.Emit (OpCodes.Initobj, type);
5773 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5775 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
5780 /// 14.5.10.2: Represents an array creation expression.
5784 /// There are two possible scenarios here: one is an array creation
5785 /// expression that specifies the dimensions and optionally the
5786 /// initialization data and the other which does not need dimensions
5787 /// specified but where initialization data is mandatory.
5789 public class ArrayCreation : Expression {
5790 Expression requested_base_type;
5791 ArrayList initializers;
5794 // The list of Argument types.
5795 // This is used to construct the `newarray' or constructor signature
5797 ArrayList arguments;
5800 // Method used to create the array object.
5802 MethodBase new_method = null;
5804 Type array_element_type;
5805 Type underlying_type;
5806 bool is_one_dimensional = false;
5807 bool is_builtin_type = false;
5808 bool expect_initializers = false;
5809 int num_arguments = 0;
5813 ArrayList array_data;
5818 // The number of array initializers that we can handle
5819 // via the InitializeArray method - through EmitStaticInitializers
5821 int num_automatic_initializers;
5823 const int max_automatic_initializers = 6;
5825 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
5827 this.requested_base_type = requested_base_type;
5828 this.initializers = initializers;
5832 arguments = new ArrayList ();
5834 foreach (Expression e in exprs) {
5835 arguments.Add (new Argument (e, Argument.AType.Expression));
5840 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
5842 this.requested_base_type = requested_base_type;
5843 this.initializers = initializers;
5847 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
5849 //string tmp = rank.Substring (rank.LastIndexOf ('['));
5851 //dimensions = tmp.Length - 1;
5852 expect_initializers = true;
5855 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
5857 StringBuilder sb = new StringBuilder (rank);
5860 for (int i = 1; i < idx_count; i++)
5865 return new ComposedCast (base_type, sb.ToString (), loc);
5868 void Error_IncorrectArrayInitializer ()
5870 Error (178, "Invalid rank specifier: expected `,' or `]'");
5873 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
5875 if (specified_dims) {
5876 Argument a = (Argument) arguments [idx];
5878 if (!a.Resolve (ec, loc))
5881 if (!(a.Expr is Constant)) {
5882 Error (150, "A constant value is expected");
5886 int value = (int) ((Constant) a.Expr).GetValue ();
5888 if (value != probe.Count) {
5889 Error_IncorrectArrayInitializer ();
5893 bounds [idx] = value;
5896 int child_bounds = -1;
5897 for (int i = 0; i < probe.Count; ++i) {
5898 object o = probe [i];
5899 if (o is ArrayList) {
5900 ArrayList sub_probe = o as ArrayList;
5901 int current_bounds = sub_probe.Count;
5903 if (child_bounds == -1)
5904 child_bounds = current_bounds;
5906 else if (child_bounds != current_bounds){
5907 Error_IncorrectArrayInitializer ();
5910 if (specified_dims && (idx + 1 >= arguments.Count)){
5911 Error (623, "Array initializers can only be used in a variable or field initializer. Try using a new expression instead");
5915 bool ret = CheckIndices (ec, sub_probe, idx + 1, specified_dims);
5919 if (child_bounds != -1){
5920 Error_IncorrectArrayInitializer ();
5924 Expression tmp = (Expression) o;
5925 tmp = tmp.Resolve (ec);
5930 // Console.WriteLine ("I got: " + tmp);
5931 // Handle initialization from vars, fields etc.
5933 Expression conv = Convert.ImplicitConversionRequired (
5934 ec, tmp, underlying_type, loc);
5939 if (conv is StringConstant || conv is DecimalConstant || conv is NullCast) {
5940 // These are subclasses of Constant that can appear as elements of an
5941 // array that cannot be statically initialized (with num_automatic_initializers
5942 // > max_automatic_initializers), so num_automatic_initializers should be left as zero.
5943 array_data.Add (conv);
5944 } else if (conv is Constant) {
5945 // These are the types of Constant that can appear in arrays that can be
5946 // statically allocated.
5947 array_data.Add (conv);
5948 num_automatic_initializers++;
5950 array_data.Add (conv);
5957 public void UpdateIndices (EmitContext ec)
5960 for (ArrayList probe = initializers; probe != null;) {
5961 if (probe.Count > 0 && probe [0] is ArrayList) {
5962 Expression e = new IntConstant (probe.Count, Location.Null);
5963 arguments.Add (new Argument (e, Argument.AType.Expression));
5965 bounds [i++] = probe.Count;
5967 probe = (ArrayList) probe [0];
5970 Expression e = new IntConstant (probe.Count, Location.Null);
5971 arguments.Add (new Argument (e, Argument.AType.Expression));
5973 bounds [i++] = probe.Count;
5980 public bool ValidateInitializers (EmitContext ec, Type array_type)
5982 if (initializers == null) {
5983 if (expect_initializers)
5989 if (underlying_type == null)
5993 // We use this to store all the date values in the order in which we
5994 // will need to store them in the byte blob later
5996 array_data = new ArrayList ();
5997 bounds = new Hashtable ();
6001 if (arguments != null) {
6002 ret = CheckIndices (ec, initializers, 0, true);
6005 arguments = new ArrayList ();
6007 ret = CheckIndices (ec, initializers, 0, false);
6014 if (arguments.Count != dimensions) {
6015 Error_IncorrectArrayInitializer ();
6024 // Creates the type of the array
6026 bool LookupType (EmitContext ec)
6028 StringBuilder array_qualifier = new StringBuilder (rank);
6031 // `In the first form allocates an array instace of the type that results
6032 // from deleting each of the individual expression from the expression list'
6034 if (num_arguments > 0) {
6035 array_qualifier.Append ("[");
6036 for (int i = num_arguments-1; i > 0; i--)
6037 array_qualifier.Append (",");
6038 array_qualifier.Append ("]");
6044 TypeExpr array_type_expr;
6045 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
6046 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec, false);
6047 if (array_type_expr == null)
6050 type = array_type_expr.ResolveType (ec);
6052 if (!type.IsArray) {
6053 Error (622, "Can only use array initializer expressions to assign to array types. Try using a new expression instead.");
6056 underlying_type = TypeManager.GetElementType (type);
6057 dimensions = type.GetArrayRank ();
6062 public override Expression DoResolve (EmitContext ec)
6066 if (!LookupType (ec))
6070 // First step is to validate the initializers and fill
6071 // in any missing bits
6073 if (!ValidateInitializers (ec, type))
6076 if (arguments == null)
6079 arg_count = arguments.Count;
6080 foreach (Argument a in arguments){
6081 if (!a.Resolve (ec, loc))
6084 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
6085 if (real_arg == null)
6092 array_element_type = TypeManager.GetElementType (type);
6094 if (array_element_type.IsAbstract && array_element_type.IsSealed) {
6095 Report.Error (719, loc, "`{0}': array elements cannot be of static type", TypeManager.CSharpName (array_element_type));
6099 if (arg_count == 1) {
6100 is_one_dimensional = true;
6101 eclass = ExprClass.Value;
6105 is_builtin_type = TypeManager.IsBuiltinType (type);
6107 if (is_builtin_type) {
6110 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
6111 AllBindingFlags, loc);
6113 if (!(ml is MethodGroupExpr)) {
6114 ml.Error_UnexpectedKind (ec, "method group", loc);
6119 Error (-6, "New invocation: Can not find a constructor for " +
6120 "this argument list");
6124 new_method = Invocation.OverloadResolve (
6125 ec, (MethodGroupExpr) ml, arguments, false, loc);
6127 if (new_method == null) {
6128 Error (-6, "New invocation: Can not find a constructor for " +
6129 "this argument list");
6133 eclass = ExprClass.Value;
6136 ModuleBuilder mb = CodeGen.Module.Builder;
6137 ArrayList args = new ArrayList ();
6139 if (arguments != null) {
6140 for (int i = 0; i < arg_count; i++)
6141 args.Add (TypeManager.int32_type);
6144 Type [] arg_types = null;
6147 arg_types = new Type [args.Count];
6149 args.CopyTo (arg_types, 0);
6151 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
6154 if (new_method == null) {
6155 Error (-6, "New invocation: Can not find a constructor for " +
6156 "this argument list");
6160 eclass = ExprClass.Value;
6165 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
6170 int count = array_data.Count;
6172 if (underlying_type.IsEnum)
6173 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
6175 factor = GetTypeSize (underlying_type);
6177 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
6179 data = new byte [(count * factor + 4) & ~3];
6182 for (int i = 0; i < count; ++i) {
6183 object v = array_data [i];
6185 if (v is EnumConstant)
6186 v = ((EnumConstant) v).Child;
6188 if (v is Constant && !(v is StringConstant))
6189 v = ((Constant) v).GetValue ();
6195 if (underlying_type == TypeManager.int64_type){
6196 if (!(v is Expression)){
6197 long val = (long) v;
6199 for (int j = 0; j < factor; ++j) {
6200 data [idx + j] = (byte) (val & 0xFF);
6204 } else if (underlying_type == TypeManager.uint64_type){
6205 if (!(v is Expression)){
6206 ulong val = (ulong) v;
6208 for (int j = 0; j < factor; ++j) {
6209 data [idx + j] = (byte) (val & 0xFF);
6213 } else if (underlying_type == TypeManager.float_type) {
6214 if (!(v is Expression)){
6215 element = BitConverter.GetBytes ((float) v);
6217 for (int j = 0; j < factor; ++j)
6218 data [idx + j] = element [j];
6220 } else if (underlying_type == TypeManager.double_type) {
6221 if (!(v is Expression)){
6222 element = BitConverter.GetBytes ((double) v);
6224 for (int j = 0; j < factor; ++j)
6225 data [idx + j] = element [j];
6227 } else if (underlying_type == TypeManager.char_type){
6228 if (!(v is Expression)){
6229 int val = (int) ((char) v);
6231 data [idx] = (byte) (val & 0xff);
6232 data [idx+1] = (byte) (val >> 8);
6234 } else if (underlying_type == TypeManager.short_type){
6235 if (!(v is Expression)){
6236 int val = (int) ((short) v);
6238 data [idx] = (byte) (val & 0xff);
6239 data [idx+1] = (byte) (val >> 8);
6241 } else if (underlying_type == TypeManager.ushort_type){
6242 if (!(v is Expression)){
6243 int val = (int) ((ushort) v);
6245 data [idx] = (byte) (val & 0xff);
6246 data [idx+1] = (byte) (val >> 8);
6248 } else if (underlying_type == TypeManager.int32_type) {
6249 if (!(v is Expression)){
6252 data [idx] = (byte) (val & 0xff);
6253 data [idx+1] = (byte) ((val >> 8) & 0xff);
6254 data [idx+2] = (byte) ((val >> 16) & 0xff);
6255 data [idx+3] = (byte) (val >> 24);
6257 } else if (underlying_type == TypeManager.uint32_type) {
6258 if (!(v is Expression)){
6259 uint val = (uint) v;
6261 data [idx] = (byte) (val & 0xff);
6262 data [idx+1] = (byte) ((val >> 8) & 0xff);
6263 data [idx+2] = (byte) ((val >> 16) & 0xff);
6264 data [idx+3] = (byte) (val >> 24);
6266 } else if (underlying_type == TypeManager.sbyte_type) {
6267 if (!(v is Expression)){
6268 sbyte val = (sbyte) v;
6269 data [idx] = (byte) val;
6271 } else if (underlying_type == TypeManager.byte_type) {
6272 if (!(v is Expression)){
6273 byte val = (byte) v;
6274 data [idx] = (byte) val;
6276 } else if (underlying_type == TypeManager.bool_type) {
6277 if (!(v is Expression)){
6278 bool val = (bool) v;
6279 data [idx] = (byte) (val ? 1 : 0);
6281 } else if (underlying_type == TypeManager.decimal_type){
6282 if (!(v is Expression)){
6283 int [] bits = Decimal.GetBits ((decimal) v);
6286 // FIXME: For some reason, this doesn't work on the MS runtime.
6287 int [] nbits = new int [4];
6288 nbits [0] = bits [3];
6289 nbits [1] = bits [2];
6290 nbits [2] = bits [0];
6291 nbits [3] = bits [1];
6293 for (int j = 0; j < 4; j++){
6294 data [p++] = (byte) (nbits [j] & 0xff);
6295 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6296 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6297 data [p++] = (byte) (nbits [j] >> 24);
6301 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6310 // Emits the initializers for the array
6312 void EmitStaticInitializers (EmitContext ec)
6315 // First, the static data
6318 ILGenerator ig = ec.ig;
6320 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6322 fb = RootContext.MakeStaticData (data);
6324 ig.Emit (OpCodes.Dup);
6325 ig.Emit (OpCodes.Ldtoken, fb);
6326 ig.Emit (OpCodes.Call,
6327 TypeManager.void_initializearray_array_fieldhandle);
6331 // Emits pieces of the array that can not be computed at compile
6332 // time (variables and string locations).
6334 // This always expect the top value on the stack to be the array
6336 void EmitDynamicInitializers (EmitContext ec)
6338 ILGenerator ig = ec.ig;
6339 int dims = bounds.Count;
6340 int [] current_pos = new int [dims];
6341 int top = array_data.Count;
6343 MethodInfo set = null;
6347 ModuleBuilder mb = null;
6348 mb = CodeGen.Module.Builder;
6349 args = new Type [dims + 1];
6352 for (j = 0; j < dims; j++)
6353 args [j] = TypeManager.int32_type;
6355 args [j] = array_element_type;
6357 set = mb.GetArrayMethod (
6359 CallingConventions.HasThis | CallingConventions.Standard,
6360 TypeManager.void_type, args);
6363 for (int i = 0; i < top; i++){
6365 Expression e = null;
6367 if (array_data [i] is Expression)
6368 e = (Expression) array_data [i];
6372 // Basically we do this for string literals and
6373 // other non-literal expressions
6375 if (e is EnumConstant){
6376 e = ((EnumConstant) e).Child;
6379 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6380 num_automatic_initializers <= max_automatic_initializers) {
6381 Type etype = e.Type;
6383 ig.Emit (OpCodes.Dup);
6385 for (int idx = 0; idx < dims; idx++)
6386 IntConstant.EmitInt (ig, current_pos [idx]);
6389 // If we are dealing with a struct, get the
6390 // address of it, so we can store it.
6393 TypeManager.IsValueType (etype) &&
6394 (!TypeManager.IsBuiltinOrEnum (etype) ||
6395 etype == TypeManager.decimal_type)) {
6400 // Let new know that we are providing
6401 // the address where to store the results
6403 n.DisableTemporaryValueType ();
6406 ig.Emit (OpCodes.Ldelema, etype);
6413 OpCode op = ArrayAccess.GetStoreOpcode (etype, out is_stobj);
6415 ig.Emit (OpCodes.Stobj, etype);
6419 ig.Emit (OpCodes.Call, set);
6427 for (int j = dims - 1; j >= 0; j--){
6429 if (current_pos [j] < (int) bounds [j])
6431 current_pos [j] = 0;
6436 void EmitArrayArguments (EmitContext ec)
6438 ILGenerator ig = ec.ig;
6440 foreach (Argument a in arguments) {
6441 Type atype = a.Type;
6444 if (atype == TypeManager.uint64_type)
6445 ig.Emit (OpCodes.Conv_Ovf_U4);
6446 else if (atype == TypeManager.int64_type)
6447 ig.Emit (OpCodes.Conv_Ovf_I4);
6451 public override void Emit (EmitContext ec)
6453 ILGenerator ig = ec.ig;
6455 EmitArrayArguments (ec);
6456 if (is_one_dimensional)
6457 ig.Emit (OpCodes.Newarr, array_element_type);
6459 if (is_builtin_type)
6460 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6462 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6465 if (initializers != null){
6467 // FIXME: Set this variable correctly.
6469 bool dynamic_initializers = true;
6471 // This will never be true for array types that cannot be statically
6472 // initialized. num_automatic_initializers will always be zero. See
6474 if (num_automatic_initializers > max_automatic_initializers)
6475 EmitStaticInitializers (ec);
6477 if (dynamic_initializers)
6478 EmitDynamicInitializers (ec);
6482 public object EncodeAsAttribute ()
6484 if (!is_one_dimensional){
6485 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6489 if (array_data == null){
6490 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6494 object [] ret = new object [array_data.Count];
6496 foreach (Expression e in array_data){
6499 if (e is NullLiteral)
6502 if (!Attribute.GetAttributeArgumentExpression (e, Location, array_element_type, out v))
6512 /// Represents the `this' construct
6514 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6517 VariableInfo variable_info;
6519 public This (Block block, Location loc)
6525 public This (Location loc)
6530 public VariableInfo VariableInfo {
6531 get { return variable_info; }
6534 public bool VerifyFixed ()
6536 return !TypeManager.IsValueType (Type);
6539 public bool ResolveBase (EmitContext ec)
6541 eclass = ExprClass.Variable;
6542 type = ec.ContainerType;
6545 Error (26, "Keyword `this' is not valid in a static property, static method, or static field initializer");
6549 if (block != null && block.Toplevel.ThisVariable != null)
6550 variable_info = block.Toplevel.ThisVariable.VariableInfo;
6552 if (ec.CurrentAnonymousMethod != null)
6558 public override Expression DoResolve (EmitContext ec)
6560 if (!ResolveBase (ec))
6563 if ((variable_info != null) && !(type.IsValueType && ec.OmitStructFlowAnalysis) && !variable_info.IsAssigned (ec)) {
6564 Error (188, "The `this' object cannot be used before all of its fields are assigned to");
6565 variable_info.SetAssigned (ec);
6569 if (ec.IsFieldInitializer) {
6570 Error (27, "Keyword `this' is not available in the current context");
6577 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6579 if (!ResolveBase (ec))
6582 if (variable_info != null)
6583 variable_info.SetAssigned (ec);
6585 if (ec.TypeContainer is Class){
6586 Error (1604, "Cannot assign to 'this' because it is read-only");
6593 public void Emit (EmitContext ec, bool leave_copy)
6597 ec.ig.Emit (OpCodes.Dup);
6600 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
6602 ILGenerator ig = ec.ig;
6604 if (ec.TypeContainer is Struct){
6608 ec.ig.Emit (OpCodes.Dup);
6609 ig.Emit (OpCodes.Stobj, type);
6611 throw new Exception ("how did you get here");
6615 public override void Emit (EmitContext ec)
6617 ILGenerator ig = ec.ig;
6620 if (ec.TypeContainer is Struct)
6621 ig.Emit (OpCodes.Ldobj, type);
6624 public override int GetHashCode()
6626 return block.GetHashCode ();
6629 public override bool Equals (object obj)
6631 This t = obj as This;
6635 return block == t.block;
6638 public void AddressOf (EmitContext ec, AddressOp mode)
6643 // FIGURE OUT WHY LDARG_S does not work
6645 // consider: struct X { int val; int P { set { val = value; }}}
6647 // Yes, this looks very bad. Look at `NOTAS' for
6649 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
6654 /// Represents the `__arglist' construct
6656 public class ArglistAccess : Expression
6658 public ArglistAccess (Location loc)
6663 public bool ResolveBase (EmitContext ec)
6665 eclass = ExprClass.Variable;
6666 type = TypeManager.runtime_argument_handle_type;
6670 public override Expression DoResolve (EmitContext ec)
6672 if (!ResolveBase (ec))
6675 if (ec.IsFieldInitializer || !ec.CurrentBlock.Toplevel.HasVarargs) {
6676 Error (190, "The __arglist construct is valid only within " +
6677 "a variable argument method.");
6684 public override void Emit (EmitContext ec)
6686 ec.ig.Emit (OpCodes.Arglist);
6691 /// Represents the `__arglist (....)' construct
6693 public class Arglist : Expression
6695 public readonly Argument[] Arguments;
6697 public Arglist (Argument[] args, Location l)
6703 public Type[] ArgumentTypes {
6705 Type[] retval = new Type [Arguments.Length];
6706 for (int i = 0; i < Arguments.Length; i++)
6707 retval [i] = Arguments [i].Type;
6712 public override Expression DoResolve (EmitContext ec)
6714 eclass = ExprClass.Variable;
6715 type = TypeManager.runtime_argument_handle_type;
6717 foreach (Argument arg in Arguments) {
6718 if (!arg.Resolve (ec, loc))
6725 public override void Emit (EmitContext ec)
6727 foreach (Argument arg in Arguments)
6733 // This produces the value that renders an instance, used by the iterators code
6735 public class ProxyInstance : Expression, IMemoryLocation {
6736 public override Expression DoResolve (EmitContext ec)
6738 eclass = ExprClass.Variable;
6739 type = ec.ContainerType;
6743 public override void Emit (EmitContext ec)
6745 ec.ig.Emit (OpCodes.Ldarg_0);
6749 public void AddressOf (EmitContext ec, AddressOp mode)
6751 ec.ig.Emit (OpCodes.Ldarg_0);
6756 /// Implements the typeof operator
6758 public class TypeOf : Expression {
6759 public Expression QueriedType;
6760 protected Type typearg;
6762 public TypeOf (Expression queried_type, Location l)
6764 QueriedType = queried_type;
6768 public override Expression DoResolve (EmitContext ec)
6770 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
6774 typearg = texpr.ResolveType (ec);
6776 if (typearg == TypeManager.void_type) {
6777 Error (673, "System.Void cannot be used from C#. Use typeof (void) to get the void type object");
6781 if (typearg.IsPointer && !ec.InUnsafe){
6786 type = TypeManager.type_type;
6787 // Even though what is returned is a type object, it's treated as a value by the compiler.
6788 // In particular, 'typeof (Foo).X' is something totally different from 'Foo.X'.
6789 eclass = ExprClass.Value;
6793 public override void Emit (EmitContext ec)
6795 ec.ig.Emit (OpCodes.Ldtoken, typearg);
6796 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6799 public Type TypeArg {
6800 get { return typearg; }
6805 /// Implements the `typeof (void)' operator
6807 public class TypeOfVoid : TypeOf {
6808 public TypeOfVoid (Location l) : base (null, l)
6813 public override Expression DoResolve (EmitContext ec)
6815 type = TypeManager.type_type;
6816 typearg = TypeManager.void_type;
6817 // See description in TypeOf.
6818 eclass = ExprClass.Value;
6824 /// Implements the sizeof expression
6826 public class SizeOf : Expression {
6827 public Expression QueriedType;
6830 public SizeOf (Expression queried_type, Location l)
6832 this.QueriedType = queried_type;
6836 public override Expression DoResolve (EmitContext ec)
6838 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
6842 type_queried = texpr.ResolveType (ec);
6844 int size_of = GetTypeSize (type_queried);
6846 return new IntConstant (size_of, loc);
6850 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)",
6851 TypeManager.CSharpName (type_queried));
6855 if (!TypeManager.VerifyUnManaged (type_queried, loc)){
6859 type = TypeManager.int32_type;
6860 eclass = ExprClass.Value;
6864 public override void Emit (EmitContext ec)
6866 int size = GetTypeSize (type_queried);
6869 ec.ig.Emit (OpCodes.Sizeof, type_queried);
6871 IntConstant.EmitInt (ec.ig, size);
6876 /// Implements the qualified-alias-member (::) expression.
6878 public class QualifiedAliasMember : Expression
6880 string alias, identifier;
6882 public QualifiedAliasMember (string alias, string identifier, Location l)
6885 this.identifier = identifier;
6889 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
6891 if (alias == "global")
6892 return new MemberAccess (RootNamespace.Global, identifier, loc).ResolveAsTypeStep (ec, silent);
6894 int errors = Report.Errors;
6895 FullNamedExpression fne = ec.DeclSpace.NamespaceEntry.LookupAlias (alias);
6897 if (errors == Report.Errors)
6898 Report.Error (432, loc, "Alias `{0}' not found", alias);
6901 if (fne.eclass != ExprClass.Namespace) {
6903 Report.Error (431, loc, "`{0}' cannot be used with '::' since it denotes a type", alias);
6906 return new MemberAccess (fne, identifier, loc).ResolveAsTypeStep (ec, silent);
6909 public override Expression DoResolve (EmitContext ec)
6911 FullNamedExpression fne;
6912 if (alias == "global") {
6913 fne = RootNamespace.Global;
6915 int errors = Report.Errors;
6916 fne = ec.DeclSpace.NamespaceEntry.LookupAlias (alias);
6918 if (errors == Report.Errors)
6919 Report.Error (432, loc, "Alias `{0}' not found", alias);
6924 Expression retval = new MemberAccess (fne, identifier, loc).DoResolve (ec);
6928 if (!(retval is FullNamedExpression)) {
6929 Report.Error (687, loc, "The expression `{0}::{1}' did not resolve to a namespace or a type", alias, identifier);
6933 // We defer this check till the end to match the behaviour of CSC
6934 if (fne.eclass != ExprClass.Namespace) {
6935 Report.Error (431, loc, "`{0}' cannot be used with '::' since it denotes a type", alias);
6941 public override void Emit (EmitContext ec)
6943 throw new InternalErrorException ("QualifiedAliasMember found in resolved tree");
6947 public override string ToString ()
6949 return alias + "::" + identifier;
6952 public override string GetSignatureForError ()
6959 /// Implements the member access expression
6961 public class MemberAccess : Expression {
6962 public readonly string Identifier;
6965 // TODO: Location can be removed
6966 public MemberAccess (Expression expr, string id, Location l)
6970 loc = expr.Location;
6973 public Expression Expr {
6974 get { return expr; }
6977 // TODO: this method has very poor performace for Enum fields and
6978 // probably for other constants as well
6979 Expression DoResolve (EmitContext ec, Expression right_side)
6982 throw new Exception ();
6985 // Resolve the expression with flow analysis turned off, we'll do the definite
6986 // assignment checks later. This is because we don't know yet what the expression
6987 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
6988 // definite assignment check on the actual field and not on the whole struct.
6991 SimpleName original = expr as SimpleName;
6992 Expression new_expr = expr.Resolve (ec,
6993 ResolveFlags.VariableOrValue | ResolveFlags.Type |
6994 ResolveFlags.Intermediate | ResolveFlags.DisableStructFlowAnalysis);
6996 if (new_expr == null)
6999 if (new_expr is Namespace) {
7000 Namespace ns = (Namespace) new_expr;
7001 FullNamedExpression retval = ns.Lookup (ec.DeclSpace, Identifier, loc);
7003 Report.Error (234, loc, "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
7004 Identifier, ns.FullName);
7008 Type expr_type = new_expr.Type;
7009 if (expr_type.IsPointer){
7010 Error (23, "The `.' operator can not be applied to pointer operands (" +
7011 TypeManager.CSharpName (expr_type) + ")");
7015 Expression member_lookup;
7016 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
7017 if (member_lookup == null)
7020 if (member_lookup is TypeExpr) {
7021 if (!(new_expr is TypeExpr) &&
7022 (original == null || !original.IdenticalNameAndTypeName (ec, new_expr, loc))) {
7023 Report.Error (572, loc, "`{0}': cannot reference a type through an expression; try `{1}' instead",
7024 Identifier, member_lookup.GetSignatureForError ());
7028 return member_lookup;
7031 MemberExpr me = (MemberExpr) member_lookup;
7032 member_lookup = me.ResolveMemberAccess (ec, new_expr, loc, original);
7033 if (member_lookup == null)
7036 if (original != null && !TypeManager.IsValueType (expr_type)) {
7037 me = member_lookup as MemberExpr;
7038 if (me != null && me.IsInstance) {
7039 LocalVariableReference var = new_expr as LocalVariableReference;
7040 if (var != null && !var.VerifyAssigned (ec))
7045 // The following DoResolve/DoResolveLValue will do the definite assignment
7048 if (right_side != null)
7049 return member_lookup.DoResolveLValue (ec, right_side);
7051 return member_lookup.DoResolve (ec);
7054 public override Expression DoResolve (EmitContext ec)
7056 return DoResolve (ec, null);
7059 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7061 return DoResolve (ec, right_side);
7064 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
7066 return ResolveNamespaceOrType (ec, silent);
7069 public FullNamedExpression ResolveNamespaceOrType (EmitContext ec, bool silent)
7071 FullNamedExpression new_expr = expr.ResolveAsTypeStep (ec, silent);
7073 if (new_expr == null) {
7074 Report.Error (234, "No such name or typespace {0}", expr);
7078 if (new_expr is Namespace) {
7079 Namespace ns = (Namespace) new_expr;
7080 FullNamedExpression retval = ns.Lookup (ec.DeclSpace, Identifier, loc);
7081 if (!silent && retval == null)
7082 Report.Error (234, loc, "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
7083 Identifier, ns.FullName);
7087 Type expr_type = new_expr.Type;
7089 if (expr_type.IsPointer){
7090 Error (23, "The `.' operator can not be applied to pointer operands (" +
7091 TypeManager.CSharpName (expr_type) + ")");
7095 Expression member_lookup = MemberLookup (ec, expr_type, expr_type, Identifier, loc);
7096 if (member_lookup == null) {
7097 int errors = Report.Errors;
7098 MemberLookupFailed (ec, expr_type, expr_type, Identifier, null, false, loc);
7100 if (!silent && errors == Report.Errors) {
7101 Report.Error (426, loc, "The nested type `{0}' does not exist in the type `{1}'",
7102 Identifier, new_expr.GetSignatureForError ());
7107 if (!(member_lookup is TypeExpr)) {
7108 new_expr.Error_UnexpectedKind (ec, "type", loc);
7112 member_lookup = member_lookup.Resolve (ec, ResolveFlags.Type);
7113 return (member_lookup as TypeExpr);
7116 public override void Emit (EmitContext ec)
7118 throw new Exception ("Should not happen");
7121 public override string ToString ()
7123 return expr + "." + Identifier;
7126 public override string GetSignatureForError ()
7128 return expr.GetSignatureForError () + "." + Identifier;
7133 /// Implements checked expressions
7135 public class CheckedExpr : Expression {
7137 public Expression Expr;
7139 public CheckedExpr (Expression e, Location l)
7145 public override Expression DoResolve (EmitContext ec)
7147 bool last_check = ec.CheckState;
7148 bool last_const_check = ec.ConstantCheckState;
7150 ec.CheckState = true;
7151 ec.ConstantCheckState = true;
7152 Expr = Expr.Resolve (ec);
7153 ec.CheckState = last_check;
7154 ec.ConstantCheckState = last_const_check;
7159 if (Expr is Constant)
7162 eclass = Expr.eclass;
7167 public override void Emit (EmitContext ec)
7169 bool last_check = ec.CheckState;
7170 bool last_const_check = ec.ConstantCheckState;
7172 ec.CheckState = true;
7173 ec.ConstantCheckState = true;
7175 ec.CheckState = last_check;
7176 ec.ConstantCheckState = last_const_check;
7182 /// Implements the unchecked expression
7184 public class UnCheckedExpr : Expression {
7186 public Expression Expr;
7188 public UnCheckedExpr (Expression e, Location l)
7194 public override Expression DoResolve (EmitContext ec)
7196 bool last_check = ec.CheckState;
7197 bool last_const_check = ec.ConstantCheckState;
7199 ec.CheckState = false;
7200 ec.ConstantCheckState = false;
7201 Expr = Expr.Resolve (ec);
7202 ec.CheckState = last_check;
7203 ec.ConstantCheckState = last_const_check;
7208 if (Expr is Constant)
7211 eclass = Expr.eclass;
7216 public override void Emit (EmitContext ec)
7218 bool last_check = ec.CheckState;
7219 bool last_const_check = ec.ConstantCheckState;
7221 ec.CheckState = false;
7222 ec.ConstantCheckState = false;
7224 ec.CheckState = last_check;
7225 ec.ConstantCheckState = last_const_check;
7231 /// An Element Access expression.
7233 /// During semantic analysis these are transformed into
7234 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7236 public class ElementAccess : Expression {
7237 public ArrayList Arguments;
7238 public Expression Expr;
7240 public ElementAccess (Expression e, ArrayList e_list)
7249 Arguments = new ArrayList ();
7250 foreach (Expression tmp in e_list)
7251 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7255 bool CommonResolve (EmitContext ec)
7257 Expr = Expr.Resolve (ec);
7262 if (Arguments == null)
7265 foreach (Argument a in Arguments){
7266 if (!a.Resolve (ec, loc))
7273 Expression MakePointerAccess (EmitContext ec, Type t)
7275 if (t == TypeManager.void_ptr_type){
7276 Error (242, "The array index operation is not valid on void pointers");
7279 if (Arguments.Count != 1){
7280 Error (196, "A pointer must be indexed by only one value");
7285 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc).Resolve (ec);
7288 return new Indirection (p, loc).Resolve (ec);
7291 public override Expression DoResolve (EmitContext ec)
7293 if (!CommonResolve (ec))
7297 // We perform some simple tests, and then to "split" the emit and store
7298 // code we create an instance of a different class, and return that.
7300 // I am experimenting with this pattern.
7304 if (t == TypeManager.array_type){
7305 Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `System.Array'");
7310 return (new ArrayAccess (this, loc)).Resolve (ec);
7312 return MakePointerAccess (ec, Expr.Type);
7314 FieldExpr fe = Expr as FieldExpr;
7316 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
7318 return MakePointerAccess (ec, ff.ElementType);
7321 return (new IndexerAccess (this, loc)).Resolve (ec);
7324 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7326 if (!CommonResolve (ec))
7331 return (new ArrayAccess (this, loc)).DoResolveLValue (ec, right_side);
7334 return MakePointerAccess (ec, Expr.Type);
7336 FieldExpr fe = Expr as FieldExpr;
7338 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
7340 if (!(fe.InstanceExpression is LocalVariableReference) &&
7341 !(fe.InstanceExpression is This)) {
7342 Report.Error (1708, loc, "Fixed size buffers can only be accessed through locals or fields");
7345 // TODO: not sure whether it is correct
7346 // if (!ec.InFixedInitializer) {
7347 // Error (1666, "You cannot use fixed sized buffers contained in unfixed expressions. Try using the fixed statement");
7350 return MakePointerAccess (ec, ff.ElementType);
7353 return (new IndexerAccess (this, loc)).DoResolveLValue (ec, right_side);
7356 public override void Emit (EmitContext ec)
7358 throw new Exception ("Should never be reached");
7363 /// Implements array access
7365 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7367 // Points to our "data" repository
7371 LocalTemporary temp;
7374 public ArrayAccess (ElementAccess ea_data, Location l)
7377 eclass = ExprClass.Variable;
7381 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7383 return DoResolve (ec);
7386 public override Expression DoResolve (EmitContext ec)
7389 ExprClass eclass = ea.Expr.eclass;
7391 // As long as the type is valid
7392 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7393 eclass == ExprClass.Value)) {
7394 ea.Expr.Error_UnexpectedKind ("variable or value");
7399 Type t = ea.Expr.Type;
7400 if (t.GetArrayRank () != ea.Arguments.Count){
7401 Report.Error (22, ea.Location, "Wrong number of indexes `{0}' inside [], expected `{1}'",
7402 ea.Arguments.Count, t.GetArrayRank ());
7406 type = TypeManager.GetElementType (t);
7407 if (type.IsPointer && !ec.InUnsafe){
7408 UnsafeError (ea.Location);
7412 foreach (Argument a in ea.Arguments){
7413 Type argtype = a.Type;
7415 if (argtype == TypeManager.int32_type ||
7416 argtype == TypeManager.uint32_type ||
7417 argtype == TypeManager.int64_type ||
7418 argtype == TypeManager.uint64_type) {
7419 Constant c = a.Expr as Constant;
7420 if (c != null && c.IsNegative) {
7421 Report.Warning (251, 2, ea.Location, "Indexing an array with a negative index (array indices always start at zero)");
7427 // Mhm. This is strage, because the Argument.Type is not the same as
7428 // Argument.Expr.Type: the value changes depending on the ref/out setting.
7430 // Wonder if I will run into trouble for this.
7432 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
7437 eclass = ExprClass.Variable;
7443 /// Emits the right opcode to load an object of Type `t'
7444 /// from an array of T
7446 static public void EmitLoadOpcode (ILGenerator ig, Type type)
7448 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7449 ig.Emit (OpCodes.Ldelem_U1);
7450 else if (type == TypeManager.sbyte_type)
7451 ig.Emit (OpCodes.Ldelem_I1);
7452 else if (type == TypeManager.short_type)
7453 ig.Emit (OpCodes.Ldelem_I2);
7454 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7455 ig.Emit (OpCodes.Ldelem_U2);
7456 else if (type == TypeManager.int32_type)
7457 ig.Emit (OpCodes.Ldelem_I4);
7458 else if (type == TypeManager.uint32_type)
7459 ig.Emit (OpCodes.Ldelem_U4);
7460 else if (type == TypeManager.uint64_type)
7461 ig.Emit (OpCodes.Ldelem_I8);
7462 else if (type == TypeManager.int64_type)
7463 ig.Emit (OpCodes.Ldelem_I8);
7464 else if (type == TypeManager.float_type)
7465 ig.Emit (OpCodes.Ldelem_R4);
7466 else if (type == TypeManager.double_type)
7467 ig.Emit (OpCodes.Ldelem_R8);
7468 else if (type == TypeManager.intptr_type)
7469 ig.Emit (OpCodes.Ldelem_I);
7470 else if (TypeManager.IsEnumType (type)){
7471 EmitLoadOpcode (ig, TypeManager.EnumToUnderlying (type));
7472 } else if (type.IsValueType){
7473 ig.Emit (OpCodes.Ldelema, type);
7474 ig.Emit (OpCodes.Ldobj, type);
7475 } else if (type.IsPointer)
7476 ig.Emit (OpCodes.Ldelem_I);
7478 ig.Emit (OpCodes.Ldelem_Ref);
7482 /// Returns the right opcode to store an object of Type `t'
7483 /// from an array of T.
7485 static public OpCode GetStoreOpcode (Type t, out bool is_stobj)
7487 //Console.WriteLine (new System.Diagnostics.StackTrace ());
7489 t = TypeManager.TypeToCoreType (t);
7490 if (TypeManager.IsEnumType (t))
7491 t = TypeManager.EnumToUnderlying (t);
7492 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
7493 t == TypeManager.bool_type)
7494 return OpCodes.Stelem_I1;
7495 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
7496 t == TypeManager.char_type)
7497 return OpCodes.Stelem_I2;
7498 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
7499 return OpCodes.Stelem_I4;
7500 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
7501 return OpCodes.Stelem_I8;
7502 else if (t == TypeManager.float_type)
7503 return OpCodes.Stelem_R4;
7504 else if (t == TypeManager.double_type)
7505 return OpCodes.Stelem_R8;
7506 else if (t == TypeManager.intptr_type) {
7508 return OpCodes.Stobj;
7509 } else if (t.IsValueType) {
7511 return OpCodes.Stobj;
7512 } else if (t.IsPointer)
7513 return OpCodes.Stelem_I;
7515 return OpCodes.Stelem_Ref;
7518 MethodInfo FetchGetMethod ()
7520 ModuleBuilder mb = CodeGen.Module.Builder;
7521 int arg_count = ea.Arguments.Count;
7522 Type [] args = new Type [arg_count];
7525 for (int i = 0; i < arg_count; i++){
7526 //args [i++] = a.Type;
7527 args [i] = TypeManager.int32_type;
7530 get = mb.GetArrayMethod (
7531 ea.Expr.Type, "Get",
7532 CallingConventions.HasThis |
7533 CallingConventions.Standard,
7539 MethodInfo FetchAddressMethod ()
7541 ModuleBuilder mb = CodeGen.Module.Builder;
7542 int arg_count = ea.Arguments.Count;
7543 Type [] args = new Type [arg_count];
7547 ret_type = TypeManager.GetReferenceType (type);
7549 for (int i = 0; i < arg_count; i++){
7550 //args [i++] = a.Type;
7551 args [i] = TypeManager.int32_type;
7554 address = mb.GetArrayMethod (
7555 ea.Expr.Type, "Address",
7556 CallingConventions.HasThis |
7557 CallingConventions.Standard,
7564 // Load the array arguments into the stack.
7566 // If we have been requested to cache the values (cached_locations array
7567 // initialized), then load the arguments the first time and store them
7568 // in locals. otherwise load from local variables.
7570 void LoadArrayAndArguments (EmitContext ec)
7572 ILGenerator ig = ec.ig;
7575 foreach (Argument a in ea.Arguments){
7576 Type argtype = a.Expr.Type;
7580 if (argtype == TypeManager.int64_type)
7581 ig.Emit (OpCodes.Conv_Ovf_I);
7582 else if (argtype == TypeManager.uint64_type)
7583 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7587 public void Emit (EmitContext ec, bool leave_copy)
7589 int rank = ea.Expr.Type.GetArrayRank ();
7590 ILGenerator ig = ec.ig;
7593 LoadArrayAndArguments (ec);
7596 EmitLoadOpcode (ig, type);
7600 method = FetchGetMethod ();
7601 ig.Emit (OpCodes.Call, method);
7604 LoadFromPtr (ec.ig, this.type);
7607 ec.ig.Emit (OpCodes.Dup);
7608 temp = new LocalTemporary (ec, this.type);
7613 public override void Emit (EmitContext ec)
7618 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
7620 int rank = ea.Expr.Type.GetArrayRank ();
7621 ILGenerator ig = ec.ig;
7622 Type t = source.Type;
7623 prepared = prepare_for_load;
7625 if (prepare_for_load) {
7626 AddressOf (ec, AddressOp.LoadStore);
7627 ec.ig.Emit (OpCodes.Dup);
7630 ec.ig.Emit (OpCodes.Dup);
7631 temp = new LocalTemporary (ec, this.type);
7634 StoreFromPtr (ec.ig, t);
7642 LoadArrayAndArguments (ec);
7646 OpCode op = GetStoreOpcode (t, out is_stobj);
7648 // The stobj opcode used by value types will need
7649 // an address on the stack, not really an array/array
7653 ig.Emit (OpCodes.Ldelema, t);
7657 ec.ig.Emit (OpCodes.Dup);
7658 temp = new LocalTemporary (ec, this.type);
7663 ig.Emit (OpCodes.Stobj, t);
7667 ModuleBuilder mb = CodeGen.Module.Builder;
7668 int arg_count = ea.Arguments.Count;
7669 Type [] args = new Type [arg_count + 1];
7674 ec.ig.Emit (OpCodes.Dup);
7675 temp = new LocalTemporary (ec, this.type);
7679 for (int i = 0; i < arg_count; i++){
7680 //args [i++] = a.Type;
7681 args [i] = TypeManager.int32_type;
7684 args [arg_count] = type;
7686 set = mb.GetArrayMethod (
7687 ea.Expr.Type, "Set",
7688 CallingConventions.HasThis |
7689 CallingConventions.Standard,
7690 TypeManager.void_type, args);
7692 ig.Emit (OpCodes.Call, set);
7699 public void AddressOf (EmitContext ec, AddressOp mode)
7701 int rank = ea.Expr.Type.GetArrayRank ();
7702 ILGenerator ig = ec.ig;
7704 LoadArrayAndArguments (ec);
7707 ig.Emit (OpCodes.Ldelema, type);
7709 MethodInfo address = FetchAddressMethod ();
7710 ig.Emit (OpCodes.Call, address);
7714 public void EmitGetLength (EmitContext ec, int dim)
7716 int rank = ea.Expr.Type.GetArrayRank ();
7717 ILGenerator ig = ec.ig;
7721 ig.Emit (OpCodes.Ldlen);
7722 ig.Emit (OpCodes.Conv_I4);
7724 IntLiteral.EmitInt (ig, dim);
7725 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
7731 // note that the ArrayList itself in mutable. We just can't assign to 'Properties' again.
7732 public readonly ArrayList Properties;
7733 static Indexers empty;
7735 public struct Indexer {
7736 public readonly PropertyInfo PropertyInfo;
7737 public readonly MethodInfo Getter, Setter;
7739 public Indexer (PropertyInfo property_info, MethodInfo get, MethodInfo set)
7741 this.PropertyInfo = property_info;
7749 empty = new Indexers (null);
7752 Indexers (ArrayList array)
7757 static void Append (ref Indexers ix, Type caller_type, MemberInfo [] mi)
7762 foreach (PropertyInfo property in mi){
7763 MethodInfo get, set;
7765 get = property.GetGetMethod (true);
7766 set = property.GetSetMethod (true);
7767 if (get != null && !Expression.IsAccessorAccessible (caller_type, get, out dummy))
7769 if (set != null && !Expression.IsAccessorAccessible (caller_type, set, out dummy))
7771 if (get != null || set != null) {
7773 ix = new Indexers (new ArrayList ());
7774 ix.Properties.Add (new Indexer (property, get, set));
7779 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
7781 string p_name = TypeManager.IndexerPropertyName (lookup_type);
7783 return TypeManager.MemberLookup (
7784 caller_type, caller_type, lookup_type, MemberTypes.Property,
7785 BindingFlags.Public | BindingFlags.Instance |
7786 BindingFlags.DeclaredOnly, p_name, null);
7789 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
7791 Indexers ix = empty;
7793 Type copy = lookup_type;
7794 while (copy != TypeManager.object_type && copy != null){
7795 Append (ref ix, caller_type, GetIndexersForTypeOrInterface (caller_type, copy));
7796 copy = copy.BaseType;
7799 if (lookup_type.IsInterface) {
7800 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
7801 if (ifaces != null) {
7802 foreach (Type itype in ifaces)
7803 Append (ref ix, caller_type, GetIndexersForTypeOrInterface (caller_type, itype));
7812 /// Expressions that represent an indexer call.
7814 public class IndexerAccess : Expression, IAssignMethod {
7816 // Points to our "data" repository
7818 MethodInfo get, set;
7819 ArrayList set_arguments;
7820 bool is_base_indexer;
7822 protected Type indexer_type;
7823 protected Type current_type;
7824 protected Expression instance_expr;
7825 protected ArrayList arguments;
7827 public IndexerAccess (ElementAccess ea, Location loc)
7828 : this (ea.Expr, false, loc)
7830 this.arguments = ea.Arguments;
7833 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
7836 this.instance_expr = instance_expr;
7837 this.is_base_indexer = is_base_indexer;
7838 this.eclass = ExprClass.Value;
7842 protected virtual bool CommonResolve (EmitContext ec)
7844 indexer_type = instance_expr.Type;
7845 current_type = ec.ContainerType;
7850 public override Expression DoResolve (EmitContext ec)
7852 ArrayList AllGetters = new ArrayList();
7853 if (!CommonResolve (ec))
7857 // Step 1: Query for all `Item' *properties*. Notice
7858 // that the actual methods are pointed from here.
7860 // This is a group of properties, piles of them.
7862 bool found_any = false, found_any_getters = false;
7863 Type lookup_type = indexer_type;
7865 Indexers ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
7866 if (ilist.Properties != null) {
7868 foreach (Indexers.Indexer ix in ilist.Properties) {
7869 if (ix.Getter != null)
7870 AllGetters.Add (ix.Getter);
7874 if (AllGetters.Count > 0) {
7875 found_any_getters = true;
7876 get = (MethodInfo) Invocation.OverloadResolve (
7877 ec, new MethodGroupExpr (AllGetters, loc),
7878 arguments, false, loc);
7882 Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
7883 TypeManager.CSharpName (indexer_type));
7887 if (!found_any_getters) {
7888 Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
7894 Invocation.Error_WrongNumArguments (loc, "this", arguments.Count);
7899 // Only base will allow this invocation to happen.
7901 if (get.IsAbstract && this is BaseIndexerAccess){
7902 Error_CannotCallAbstractBase (TypeManager.CSharpSignature (get));
7906 type = get.ReturnType;
7907 if (type.IsPointer && !ec.InUnsafe){
7912 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
7914 eclass = ExprClass.IndexerAccess;
7918 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7920 ArrayList AllSetters = new ArrayList();
7921 if (!CommonResolve (ec))
7924 bool found_any = false, found_any_setters = false;
7926 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
7927 if (ilist.Properties != null) {
7929 foreach (Indexers.Indexer ix in ilist.Properties) {
7930 if (ix.Setter != null)
7931 AllSetters.Add (ix.Setter);
7934 if (AllSetters.Count > 0) {
7935 found_any_setters = true;
7936 set_arguments = (ArrayList) arguments.Clone ();
7937 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
7938 set = (MethodInfo) Invocation.OverloadResolve (
7939 ec, new MethodGroupExpr (AllSetters, loc),
7940 set_arguments, false, loc);
7944 Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
7945 TypeManager.CSharpName (indexer_type));
7949 if (!found_any_setters) {
7950 Error (154, "indexer can not be used in this context, because " +
7951 "it lacks a `set' accessor");
7956 Invocation.Error_WrongNumArguments (loc, "this", arguments.Count);
7961 // Only base will allow this invocation to happen.
7963 if (set.IsAbstract && this is BaseIndexerAccess){
7964 Error_CannotCallAbstractBase (TypeManager.CSharpSignature (set));
7969 // Now look for the actual match in the list of indexers to set our "return" type
7971 type = TypeManager.void_type; // default value
7972 foreach (Indexers.Indexer ix in ilist.Properties){
7973 if (ix.Setter == set){
7974 type = ix.PropertyInfo.PropertyType;
7979 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
7981 eclass = ExprClass.IndexerAccess;
7985 bool prepared = false;
7986 LocalTemporary temp;
7988 public void Emit (EmitContext ec, bool leave_copy)
7990 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc, prepared, false);
7992 ec.ig.Emit (OpCodes.Dup);
7993 temp = new LocalTemporary (ec, Type);
7999 // source is ignored, because we already have a copy of it from the
8000 // LValue resolution and we have already constructed a pre-cached
8001 // version of the arguments (ea.set_arguments);
8003 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8005 prepared = prepare_for_load;
8006 Argument a = (Argument) set_arguments [set_arguments.Count - 1];
8011 ec.ig.Emit (OpCodes.Dup);
8012 temp = new LocalTemporary (ec, Type);
8015 } else if (leave_copy) {
8016 temp = new LocalTemporary (ec, Type);
8022 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc, false, prepared);
8029 public override void Emit (EmitContext ec)
8036 /// The base operator for method names
8038 public class BaseAccess : Expression {
8041 public BaseAccess (string member, Location l)
8043 this.member = member;
8047 public override Expression DoResolve (EmitContext ec)
8049 Expression c = CommonResolve (ec);
8055 // MethodGroups use this opportunity to flag an error on lacking ()
8057 if (!(c is MethodGroupExpr))
8058 return c.Resolve (ec);
8062 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8064 Expression c = CommonResolve (ec);
8070 // MethodGroups use this opportunity to flag an error on lacking ()
8072 if (! (c is MethodGroupExpr))
8073 return c.DoResolveLValue (ec, right_side);
8078 Expression CommonResolve (EmitContext ec)
8080 Expression member_lookup;
8081 Type current_type = ec.ContainerType;
8082 Type base_type = current_type.BaseType;
8085 Error (1511, "Keyword `base' is not available in a static method");
8089 if (ec.IsFieldInitializer){
8090 Error (1512, "Keyword `base' is not available in the current context");
8094 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type, member,
8095 AllMemberTypes, AllBindingFlags, loc);
8096 if (member_lookup == null) {
8097 MemberLookupFailed (ec, base_type, base_type, member, null, true, loc);
8104 left = new TypeExpression (base_type, loc);
8106 left = ec.GetThis (loc);
8108 MemberExpr me = (MemberExpr) member_lookup;
8110 Expression e = me.ResolveMemberAccess (ec, left, loc, null);
8112 if (e is PropertyExpr) {
8113 PropertyExpr pe = (PropertyExpr) e;
8118 if (e is MethodGroupExpr)
8119 ((MethodGroupExpr) e).IsBase = true;
8124 public override void Emit (EmitContext ec)
8126 throw new Exception ("Should never be called");
8131 /// The base indexer operator
8133 public class BaseIndexerAccess : IndexerAccess {
8134 public BaseIndexerAccess (ArrayList args, Location loc)
8135 : base (null, true, loc)
8137 arguments = new ArrayList ();
8138 foreach (Expression tmp in args)
8139 arguments.Add (new Argument (tmp, Argument.AType.Expression));
8142 protected override bool CommonResolve (EmitContext ec)
8144 instance_expr = ec.GetThis (loc);
8146 current_type = ec.ContainerType.BaseType;
8147 indexer_type = current_type;
8149 foreach (Argument a in arguments){
8150 if (!a.Resolve (ec, loc))
8159 /// This class exists solely to pass the Type around and to be a dummy
8160 /// that can be passed to the conversion functions (this is used by
8161 /// foreach implementation to typecast the object return value from
8162 /// get_Current into the proper type. All code has been generated and
8163 /// we only care about the side effect conversions to be performed
8165 /// This is also now used as a placeholder where a no-action expression
8166 /// is needed (the `New' class).
8168 public class EmptyExpression : Expression {
8169 public static readonly EmptyExpression Null = new EmptyExpression ();
8171 static EmptyExpression temp = new EmptyExpression ();
8172 public static EmptyExpression Grab ()
8175 throw new InternalErrorException ("Nested Grab");
8176 EmptyExpression retval = temp;
8181 public static void Release (EmptyExpression e)
8184 throw new InternalErrorException ("Already released");
8188 // TODO: should be protected
8189 public EmptyExpression ()
8191 type = TypeManager.object_type;
8192 eclass = ExprClass.Value;
8193 loc = Location.Null;
8196 public EmptyExpression (Type t)
8199 eclass = ExprClass.Value;
8200 loc = Location.Null;
8203 public override Expression DoResolve (EmitContext ec)
8208 public override void Emit (EmitContext ec)
8210 // nothing, as we only exist to not do anything.
8214 // This is just because we might want to reuse this bad boy
8215 // instead of creating gazillions of EmptyExpressions.
8216 // (CanImplicitConversion uses it)
8218 public void SetType (Type t)
8224 public class UserCast : Expression {
8228 public UserCast (MethodInfo method, Expression source, Location l)
8230 this.method = method;
8231 this.source = source;
8232 type = method.ReturnType;
8233 eclass = ExprClass.Value;
8237 public Expression Source {
8243 public override Expression DoResolve (EmitContext ec)
8246 // We are born fully resolved
8251 public override void Emit (EmitContext ec)
8253 ILGenerator ig = ec.ig;
8257 if (method is MethodInfo)
8258 ig.Emit (OpCodes.Call, (MethodInfo) method);
8260 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
8266 // This class is used to "construct" the type during a typecast
8267 // operation. Since the Type.GetType class in .NET can parse
8268 // the type specification, we just use this to construct the type
8269 // one bit at a time.
8271 public class ComposedCast : TypeExpr {
8275 public ComposedCast (Expression left, string dim)
8276 : this (left, dim, left.Location)
8280 public ComposedCast (Expression left, string dim, Location l)
8287 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
8289 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec, false);
8293 bool old = ec.TestObsoleteMethodUsage;
8294 ec.TestObsoleteMethodUsage = false;
8295 Type ltype = lexpr.ResolveType (ec);
8296 ec.TestObsoleteMethodUsage = old;
8298 if ((ltype == TypeManager.void_type) && (dim != "*")) {
8299 Report.Error (1547, Location,
8300 "Keyword 'void' cannot be used in this context");
8304 if (dim == "*" && !TypeManager.VerifyUnManaged (ltype, loc)) {
8308 type = TypeManager.GetConstructedType (ltype, dim);
8310 throw new InternalErrorException ("Couldn't create computed type " + ltype + dim);
8313 if (!ec.InUnsafe && type.IsPointer){
8318 if (type.IsArray && (type.GetElementType () == TypeManager.arg_iterator_type ||
8319 type.GetElementType () == TypeManager.typed_reference_type)) {
8320 Report.Error (611, loc, "Array elements cannot be of type `{0}'", TypeManager.CSharpName (type.GetElementType ()));
8324 eclass = ExprClass.Type;
8328 public override string Name {
8334 public override string FullName {
8336 return type.FullName;
8341 public class FixedBufferPtr : Expression {
8344 public FixedBufferPtr (Expression array, Type array_type, Location l)
8349 type = TypeManager.GetPointerType (array_type);
8350 eclass = ExprClass.Value;
8353 public override void Emit(EmitContext ec)
8358 public override Expression DoResolve (EmitContext ec)
8361 // We are born fully resolved
8369 // This class is used to represent the address of an array, used
8370 // only by the Fixed statement, this generates "&a [0]" construct
8371 // for fixed (char *pa = a)
8373 public class ArrayPtr : FixedBufferPtr {
8376 public ArrayPtr (Expression array, Type array_type, Location l):
8377 base (array, array_type, l)
8379 this.array_type = array_type;
8382 public override void Emit (EmitContext ec)
8386 ILGenerator ig = ec.ig;
8387 IntLiteral.EmitInt (ig, 0);
8388 ig.Emit (OpCodes.Ldelema, array_type);
8393 // Used by the fixed statement
8395 public class StringPtr : Expression {
8398 public StringPtr (LocalBuilder b, Location l)
8401 eclass = ExprClass.Value;
8402 type = TypeManager.char_ptr_type;
8406 public override Expression DoResolve (EmitContext ec)
8408 // This should never be invoked, we are born in fully
8409 // initialized state.
8414 public override void Emit (EmitContext ec)
8416 ILGenerator ig = ec.ig;
8418 ig.Emit (OpCodes.Ldloc, b);
8419 ig.Emit (OpCodes.Conv_I);
8420 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
8421 ig.Emit (OpCodes.Add);
8426 // Implements the `stackalloc' keyword
8428 public class StackAlloc : Expression {
8433 public StackAlloc (Expression type, Expression count, Location l)
8440 public override Expression DoResolve (EmitContext ec)
8442 count = count.Resolve (ec);
8446 if (count.Type != TypeManager.int32_type){
8447 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8452 Constant c = count as Constant;
8453 if (c != null && c.IsNegative) {
8454 Report.Error (247, loc, "Cannot use a negative size with stackalloc");
8458 if (ec.InCatch || ec.InFinally) {
8459 Error (255, "Cannot use stackalloc in finally or catch");
8463 TypeExpr texpr = t.ResolveAsTypeTerminal (ec, false);
8467 otype = texpr.ResolveType (ec);
8469 if (!TypeManager.VerifyUnManaged (otype, loc))
8472 type = TypeManager.GetPointerType (otype);
8473 eclass = ExprClass.Value;
8478 public override void Emit (EmitContext ec)
8480 int size = GetTypeSize (otype);
8481 ILGenerator ig = ec.ig;
8484 ig.Emit (OpCodes.Sizeof, otype);
8486 IntConstant.EmitInt (ig, size);
8488 ig.Emit (OpCodes.Mul);
8489 ig.Emit (OpCodes.Localloc);