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, Location loc)
100 public override Expression DoResolve (EmitContext ec)
102 Expr = Expr.Resolve (ec);
106 public override void Emit (EmitContext ec)
108 throw new Exception ("Should not happen");
113 /// Unary expressions.
117 /// Unary implements unary expressions. It derives from
118 /// ExpressionStatement becuase the pre/post increment/decrement
119 /// operators can be used in a statement context.
121 public class Unary : Expression {
122 public enum Operator : byte {
123 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
124 Indirection, AddressOf, TOP
127 public Operator Oper;
128 public Expression Expr;
130 public Unary (Operator op, Expression expr, Location loc)
138 /// Returns a stringified representation of the Operator
140 static public string OperName (Operator oper)
143 case Operator.UnaryPlus:
145 case Operator.UnaryNegation:
147 case Operator.LogicalNot:
149 case Operator.OnesComplement:
151 case Operator.AddressOf:
153 case Operator.Indirection:
157 return oper.ToString ();
160 public static readonly string [] oper_names;
164 oper_names = new string [(int)Operator.TOP];
166 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
167 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
168 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
169 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
170 oper_names [(int) Operator.Indirection] = "op_Indirection";
171 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
174 void Error23 (Type t)
177 23, "Operator " + OperName (Oper) +
178 " cannot be applied to operand of type `" +
179 TypeManager.CSharpName (t) + "'");
183 /// The result has been already resolved:
185 /// FIXME: a minus constant -128 sbyte cant be turned into a
188 static Expression TryReduceNegative (Constant expr)
192 if (expr is IntConstant)
193 e = new IntConstant (-((IntConstant) expr).Value);
194 else if (expr is UIntConstant){
195 uint value = ((UIntConstant) expr).Value;
197 if (value < 2147483649)
198 return new IntConstant (-(int)value);
200 e = new LongConstant (-value);
202 else if (expr is LongConstant)
203 e = new LongConstant (-((LongConstant) expr).Value);
204 else if (expr is ULongConstant){
205 ulong value = ((ULongConstant) expr).Value;
207 if (value < 9223372036854775809)
208 return new LongConstant(-(long)value);
210 else if (expr is FloatConstant)
211 e = new FloatConstant (-((FloatConstant) expr).Value);
212 else if (expr is DoubleConstant)
213 e = new DoubleConstant (-((DoubleConstant) expr).Value);
214 else if (expr is DecimalConstant)
215 e = new DecimalConstant (-((DecimalConstant) expr).Value);
216 else if (expr is ShortConstant)
217 e = new IntConstant (-((ShortConstant) expr).Value);
218 else if (expr is UShortConstant)
219 e = new IntConstant (-((UShortConstant) expr).Value);
220 else if (expr is SByteConstant)
221 e = new IntConstant (-((SByteConstant) expr).Value);
222 else if (expr is ByteConstant)
223 e = new IntConstant (-((ByteConstant) expr).Value);
228 // This routine will attempt to simplify the unary expression when the
229 // argument is a constant. The result is returned in `result' and the
230 // function returns true or false depending on whether a reduction
231 // was performed or not
233 bool Reduce (EmitContext ec, Constant e, out Expression result)
235 Type expr_type = e.Type;
238 case Operator.UnaryPlus:
242 case Operator.UnaryNegation:
243 result = TryReduceNegative (e);
244 return result != null;
246 case Operator.LogicalNot:
247 if (expr_type != TypeManager.bool_type) {
253 BoolConstant b = (BoolConstant) e;
254 result = new BoolConstant (!(b.Value));
257 case Operator.OnesComplement:
258 if (!((expr_type == TypeManager.int32_type) ||
259 (expr_type == TypeManager.uint32_type) ||
260 (expr_type == TypeManager.int64_type) ||
261 (expr_type == TypeManager.uint64_type) ||
262 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
265 if (Convert.ImplicitConversionExists (ec, e, TypeManager.int32_type)){
266 result = new Cast (new TypeExpression (TypeManager.int32_type, loc), e, loc);
267 result = result.Resolve (ec);
268 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint32_type)){
269 result = new Cast (new TypeExpression (TypeManager.uint32_type, loc), e, loc);
270 result = result.Resolve (ec);
271 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.int64_type)){
272 result = new Cast (new TypeExpression (TypeManager.int64_type, loc), e, loc);
273 result = result.Resolve (ec);
274 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint64_type)){
275 result = new Cast (new TypeExpression (TypeManager.uint64_type, loc), e, loc);
276 result = result.Resolve (ec);
279 if (result == null || !(result is Constant)){
285 expr_type = result.Type;
286 e = (Constant) result;
289 if (e is EnumConstant){
290 EnumConstant enum_constant = (EnumConstant) e;
293 if (Reduce (ec, enum_constant.Child, out reduced)){
294 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
302 if (expr_type == TypeManager.int32_type){
303 result = new IntConstant (~ ((IntConstant) e).Value);
304 } else if (expr_type == TypeManager.uint32_type){
305 result = new UIntConstant (~ ((UIntConstant) e).Value);
306 } else if (expr_type == TypeManager.int64_type){
307 result = new LongConstant (~ ((LongConstant) e).Value);
308 } else if (expr_type == TypeManager.uint64_type){
309 result = new ULongConstant (~ ((ULongConstant) e).Value);
317 case Operator.AddressOf:
321 case Operator.Indirection:
325 throw new Exception ("Can not constant fold: " + Oper.ToString());
328 Expression ResolveOperator (EmitContext ec)
331 // Step 1: Default operations on CLI native types.
334 // Attempt to use a constant folding operation.
335 if (Expr is Constant){
338 if (Reduce (ec, (Constant) Expr, out result))
343 // Step 2: Perform Operator Overload location
345 Type expr_type = Expr.Type;
349 op_name = oper_names [(int) Oper];
351 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
354 Expression e = StaticCallExpr.MakeSimpleCall (
355 ec, (MethodGroupExpr) mg, Expr, loc);
365 // Only perform numeric promotions on:
368 if (expr_type == null)
372 case Operator.LogicalNot:
373 if (expr_type != TypeManager.bool_type) {
374 Expr = ResolveBoolean (ec, Expr, loc);
381 type = TypeManager.bool_type;
384 case Operator.OnesComplement:
385 if (!((expr_type == TypeManager.int32_type) ||
386 (expr_type == TypeManager.uint32_type) ||
387 (expr_type == TypeManager.int64_type) ||
388 (expr_type == TypeManager.uint64_type) ||
389 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
392 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
394 type = TypeManager.int32_type;
397 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint32_type, loc);
399 type = TypeManager.uint32_type;
402 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
404 type = TypeManager.int64_type;
407 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint64_type, loc);
409 type = TypeManager.uint64_type;
418 case Operator.AddressOf:
419 if (Expr.eclass != ExprClass.Variable){
420 Error (211, "Cannot take the address of non-variables");
429 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
433 IVariable variable = Expr as IVariable;
434 if (!ec.InFixedInitializer && ((variable == null) || !variable.VerifyFixed (false))) {
435 Error (212, "You can only take the address of an unfixed expression inside " +
436 "of a fixed statement initializer");
440 if (ec.InFixedInitializer && ((variable != null) && variable.VerifyFixed (false))) {
441 Error (213, "You can not fix an already fixed expression");
445 LocalVariableReference lr = Expr as LocalVariableReference;
447 if (lr.local_info.IsCaptured){
448 AnonymousMethod.Error_AddressOfCapturedVar (lr.Name, loc);
451 lr.local_info.AddressTaken = true;
452 lr.local_info.Used = true;
455 // According to the specs, a variable is considered definitely assigned if you take
457 if ((variable != null) && (variable.VariableInfo != null))
458 variable.VariableInfo.SetAssigned (ec);
460 type = TypeManager.GetPointerType (Expr.Type);
463 case Operator.Indirection:
469 if (!expr_type.IsPointer){
470 Error (193, "The * or -> operator can only be applied to pointers");
475 // We create an Indirection expression, because
476 // it can implement the IMemoryLocation.
478 return new Indirection (Expr, loc);
480 case Operator.UnaryPlus:
482 // A plus in front of something is just a no-op, so return the child.
486 case Operator.UnaryNegation:
488 // Deals with -literals
489 // int operator- (int x)
490 // long operator- (long x)
491 // float operator- (float f)
492 // double operator- (double d)
493 // decimal operator- (decimal d)
495 Expression expr = null;
498 // transform - - expr into expr
501 Unary unary = (Unary) Expr;
503 if (unary.Oper == Operator.UnaryNegation)
508 // perform numeric promotions to int,
512 // The following is inneficient, because we call
513 // ImplicitConversion too many times.
515 // It is also not clear if we should convert to Float
516 // or Double initially.
518 if (expr_type == TypeManager.uint32_type){
520 // FIXME: handle exception to this rule that
521 // permits the int value -2147483648 (-2^31) to
522 // bt wrote as a decimal interger literal
524 type = TypeManager.int64_type;
525 Expr = Convert.ImplicitConversion (ec, Expr, type, loc);
529 if (expr_type == TypeManager.uint64_type){
531 // FIXME: Handle exception of `long value'
532 // -92233720368547758087 (-2^63) to be wrote as
533 // decimal integer literal.
539 if (expr_type == TypeManager.float_type){
544 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
551 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
558 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.double_type, loc);
569 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
570 TypeManager.CSharpName (expr_type) + "'");
574 public override Expression DoResolve (EmitContext ec)
576 if (Oper == Operator.AddressOf)
577 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
579 Expr = Expr.Resolve (ec);
584 eclass = ExprClass.Value;
585 return ResolveOperator (ec);
588 public override Expression DoResolveLValue (EmitContext ec, Expression right)
590 if (Oper == Operator.Indirection)
591 return base.DoResolveLValue (ec, right);
593 Error (131, "The left-hand side of an assignment must be a " +
594 "variable, property or indexer");
598 public override void Emit (EmitContext ec)
600 ILGenerator ig = ec.ig;
603 case Operator.UnaryPlus:
604 throw new Exception ("This should be caught by Resolve");
606 case Operator.UnaryNegation:
608 ig.Emit (OpCodes.Ldc_I4_0);
609 if (type == TypeManager.int64_type)
610 ig.Emit (OpCodes.Conv_U8);
612 ig.Emit (OpCodes.Sub_Ovf);
615 ig.Emit (OpCodes.Neg);
620 case Operator.LogicalNot:
622 ig.Emit (OpCodes.Ldc_I4_0);
623 ig.Emit (OpCodes.Ceq);
626 case Operator.OnesComplement:
628 ig.Emit (OpCodes.Not);
631 case Operator.AddressOf:
632 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
636 throw new Exception ("This should not happen: Operator = "
641 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
643 if (Oper == Operator.LogicalNot)
644 Expr.EmitBranchable (ec, target, !onTrue);
646 base.EmitBranchable (ec, target, onTrue);
649 public override string ToString ()
651 return "Unary (" + Oper + ", " + Expr + ")";
657 // Unary operators are turned into Indirection expressions
658 // after semantic analysis (this is so we can take the address
659 // of an indirection).
661 public class Indirection : Expression, IMemoryLocation, IAssignMethod {
663 LocalTemporary temporary;
666 public Indirection (Expression expr, Location l)
669 this.type = TypeManager.GetElementType (expr.Type);
670 eclass = ExprClass.Variable;
674 void LoadExprValue (EmitContext ec)
678 public override void Emit (EmitContext ec)
683 LoadFromPtr (ec.ig, Type);
686 public void Emit (EmitContext ec, bool leave_copy)
690 ec.ig.Emit (OpCodes.Dup);
691 temporary = new LocalTemporary (ec, expr.Type);
692 temporary.Store (ec);
696 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
698 prepared = prepare_for_load;
702 if (prepare_for_load)
703 ec.ig.Emit (OpCodes.Dup);
707 ec.ig.Emit (OpCodes.Dup);
708 temporary = new LocalTemporary (ec, expr.Type);
709 temporary.Store (ec);
712 StoreFromPtr (ec.ig, type);
714 if (temporary != null)
718 public void AddressOf (EmitContext ec, AddressOp Mode)
723 public override Expression DoResolve (EmitContext ec)
726 // Born fully resolved
731 public override string ToString ()
733 return "*(" + expr + ")";
738 /// Unary Mutator expressions (pre and post ++ and --)
742 /// UnaryMutator implements ++ and -- expressions. It derives from
743 /// ExpressionStatement becuase the pre/post increment/decrement
744 /// operators can be used in a statement context.
746 /// FIXME: Idea, we could split this up in two classes, one simpler
747 /// for the common case, and one with the extra fields for more complex
748 /// classes (indexers require temporary access; overloaded require method)
751 public class UnaryMutator : ExpressionStatement {
753 public enum Mode : byte {
760 PreDecrement = IsDecrement,
761 PostIncrement = IsPost,
762 PostDecrement = IsPost | IsDecrement
766 bool is_expr = false;
767 bool recurse = false;
772 // This is expensive for the simplest case.
774 StaticCallExpr method;
776 public UnaryMutator (Mode m, Expression e, Location l)
783 static string OperName (Mode mode)
785 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
789 void Error23 (Type t)
792 23, "Operator " + OperName (mode) +
793 " cannot be applied to operand of type `" +
794 TypeManager.CSharpName (t) + "'");
798 /// Returns whether an object of type `t' can be incremented
799 /// or decremented with add/sub (ie, basically whether we can
800 /// use pre-post incr-decr operations on it, but it is not a
801 /// System.Decimal, which we require operator overloading to catch)
803 static bool IsIncrementableNumber (Type t)
805 return (t == TypeManager.sbyte_type) ||
806 (t == TypeManager.byte_type) ||
807 (t == TypeManager.short_type) ||
808 (t == TypeManager.ushort_type) ||
809 (t == TypeManager.int32_type) ||
810 (t == TypeManager.uint32_type) ||
811 (t == TypeManager.int64_type) ||
812 (t == TypeManager.uint64_type) ||
813 (t == TypeManager.char_type) ||
814 (t.IsSubclassOf (TypeManager.enum_type)) ||
815 (t == TypeManager.float_type) ||
816 (t == TypeManager.double_type) ||
817 (t.IsPointer && t != TypeManager.void_ptr_type);
820 Expression ResolveOperator (EmitContext ec)
822 Type expr_type = expr.Type;
825 // Step 1: Perform Operator Overload location
830 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
831 op_name = "op_Increment";
833 op_name = "op_Decrement";
835 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
837 if (mg == null && expr_type.BaseType != null)
838 mg = MemberLookup (ec, expr_type.BaseType, op_name,
839 MemberTypes.Method, AllBindingFlags, loc);
842 method = StaticCallExpr.MakeSimpleCall (
843 ec, (MethodGroupExpr) mg, expr, loc);
850 // The operand of the prefix/postfix increment decrement operators
851 // should be an expression that is classified as a variable,
852 // a property access or an indexer access
855 if (expr.eclass == ExprClass.Variable){
856 LocalVariableReference var = expr as LocalVariableReference;
857 if ((var != null) && var.IsReadOnly)
858 Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
859 if (IsIncrementableNumber (expr_type) ||
860 expr_type == TypeManager.decimal_type){
863 } else if (expr.eclass == ExprClass.IndexerAccess){
864 IndexerAccess ia = (IndexerAccess) expr;
866 expr = ia.ResolveLValue (ec, this);
871 } else if (expr.eclass == ExprClass.PropertyAccess){
872 PropertyExpr pe = (PropertyExpr) expr;
874 if (pe.VerifyAssignable ())
879 expr.Error_UnexpectedKind ("variable, indexer or property access", loc);
883 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
884 TypeManager.CSharpName (expr_type) + "'");
888 public override Expression DoResolve (EmitContext ec)
890 expr = expr.Resolve (ec);
895 eclass = ExprClass.Value;
896 return ResolveOperator (ec);
899 static int PtrTypeSize (Type t)
901 return GetTypeSize (TypeManager.GetElementType (t));
905 // Loads the proper "1" into the stack based on the type, then it emits the
906 // opcode for the operation requested
908 void LoadOneAndEmitOp (EmitContext ec, Type t)
911 // Measure if getting the typecode and using that is more/less efficient
912 // that comparing types. t.GetTypeCode() is an internal call.
914 ILGenerator ig = ec.ig;
916 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
917 LongConstant.EmitLong (ig, 1);
918 else if (t == TypeManager.double_type)
919 ig.Emit (OpCodes.Ldc_R8, 1.0);
920 else if (t == TypeManager.float_type)
921 ig.Emit (OpCodes.Ldc_R4, 1.0F);
922 else if (t.IsPointer){
923 int n = PtrTypeSize (t);
926 ig.Emit (OpCodes.Sizeof, t);
928 IntConstant.EmitInt (ig, n);
930 ig.Emit (OpCodes.Ldc_I4_1);
933 // Now emit the operation
936 if (t == TypeManager.int32_type ||
937 t == TypeManager.int64_type){
938 if ((mode & Mode.IsDecrement) != 0)
939 ig.Emit (OpCodes.Sub_Ovf);
941 ig.Emit (OpCodes.Add_Ovf);
942 } else if (t == TypeManager.uint32_type ||
943 t == TypeManager.uint64_type){
944 if ((mode & Mode.IsDecrement) != 0)
945 ig.Emit (OpCodes.Sub_Ovf_Un);
947 ig.Emit (OpCodes.Add_Ovf_Un);
949 if ((mode & Mode.IsDecrement) != 0)
950 ig.Emit (OpCodes.Sub_Ovf);
952 ig.Emit (OpCodes.Add_Ovf);
955 if ((mode & Mode.IsDecrement) != 0)
956 ig.Emit (OpCodes.Sub);
958 ig.Emit (OpCodes.Add);
961 if (t == TypeManager.sbyte_type){
963 ig.Emit (OpCodes.Conv_Ovf_I1);
965 ig.Emit (OpCodes.Conv_I1);
966 } else if (t == TypeManager.byte_type){
968 ig.Emit (OpCodes.Conv_Ovf_U1);
970 ig.Emit (OpCodes.Conv_U1);
971 } else if (t == TypeManager.short_type){
973 ig.Emit (OpCodes.Conv_Ovf_I2);
975 ig.Emit (OpCodes.Conv_I2);
976 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
978 ig.Emit (OpCodes.Conv_Ovf_U2);
980 ig.Emit (OpCodes.Conv_U2);
985 void EmitCode (EmitContext ec, bool is_expr)
988 this.is_expr = is_expr;
989 ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
993 public override void Emit (EmitContext ec)
996 // We use recurse to allow ourselfs to be the source
997 // of an assignment. This little hack prevents us from
998 // having to allocate another expression
1001 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
1003 LoadOneAndEmitOp (ec, expr.Type);
1005 ec.ig.Emit (OpCodes.Call, method.Method);
1010 EmitCode (ec, true);
1013 public override void EmitStatement (EmitContext ec)
1015 EmitCode (ec, false);
1020 /// Base class for the `Is' and `As' classes.
1024 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1027 public abstract class Probe : Expression {
1028 public Expression ProbeType;
1029 protected Expression expr;
1030 protected Type probe_type;
1032 public Probe (Expression expr, Expression probe_type, Location l)
1034 ProbeType = probe_type;
1039 public Expression Expr {
1045 public override Expression DoResolve (EmitContext ec)
1047 TypeExpr texpr = ProbeType.ResolveAsTypeTerminal (ec);
1050 probe_type = texpr.Type;
1052 CheckObsoleteAttribute (probe_type);
1054 expr = expr.Resolve (ec);
1058 if (expr.Type.IsPointer) {
1059 Report.Error (244, loc, "\"is\" or \"as\" are not valid on pointer types");
1067 /// Implementation of the `is' operator.
1069 public class Is : Probe {
1070 public Is (Expression expr, Expression probe_type, Location l)
1071 : base (expr, probe_type, l)
1076 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1081 public override void Emit (EmitContext ec)
1083 ILGenerator ig = ec.ig;
1088 case Action.AlwaysFalse:
1089 ig.Emit (OpCodes.Pop);
1090 IntConstant.EmitInt (ig, 0);
1092 case Action.AlwaysTrue:
1093 ig.Emit (OpCodes.Pop);
1094 IntConstant.EmitInt (ig, 1);
1096 case Action.LeaveOnStack:
1097 // the `e != null' rule.
1098 ig.Emit (OpCodes.Ldnull);
1099 ig.Emit (OpCodes.Ceq);
1100 ig.Emit (OpCodes.Ldc_I4_0);
1101 ig.Emit (OpCodes.Ceq);
1104 ig.Emit (OpCodes.Isinst, probe_type);
1105 ig.Emit (OpCodes.Ldnull);
1106 ig.Emit (OpCodes.Cgt_Un);
1109 throw new Exception ("never reached");
1112 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
1114 ILGenerator ig = ec.ig;
1117 case Action.AlwaysFalse:
1119 ig.Emit (OpCodes.Br, target);
1122 case Action.AlwaysTrue:
1124 ig.Emit (OpCodes.Br, target);
1127 case Action.LeaveOnStack:
1128 // the `e != null' rule.
1130 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1134 ig.Emit (OpCodes.Isinst, probe_type);
1135 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1138 throw new Exception ("never reached");
1141 public override Expression DoResolve (EmitContext ec)
1143 Expression e = base.DoResolve (ec);
1145 if ((e == null) || (expr == null))
1148 Type etype = expr.Type;
1149 bool warning_always_matches = false;
1150 bool warning_never_matches = false;
1152 type = TypeManager.bool_type;
1153 eclass = ExprClass.Value;
1156 // First case, if at compile time, there is an implicit conversion
1157 // then e != null (objects) or true (value types)
1159 e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1162 if (etype.IsValueType)
1163 action = Action.AlwaysTrue;
1165 action = Action.LeaveOnStack;
1167 warning_always_matches = true;
1168 } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1169 if (etype.IsGenericParameter)
1170 expr = new BoxedCast (expr, etype);
1173 // Second case: explicit reference convresion
1175 if (expr is NullLiteral)
1176 action = Action.AlwaysFalse;
1178 action = Action.Probe;
1180 action = Action.AlwaysFalse;
1181 warning_never_matches = true;
1184 if (warning_always_matches)
1185 Warning (183, "The given expression is always of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1186 else if (warning_never_matches){
1187 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1188 Warning (184, "The given expression is never of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1196 /// Implementation of the `as' operator.
1198 public class As : Probe {
1199 public As (Expression expr, Expression probe_type, Location l)
1200 : base (expr, probe_type, l)
1204 bool do_isinst = false;
1206 public override void Emit (EmitContext ec)
1208 ILGenerator ig = ec.ig;
1213 ig.Emit (OpCodes.Isinst, probe_type);
1216 static void Error_CannotConvertType (Type source, Type target, Location loc)
1219 39, loc, "as operator can not convert from `" +
1220 TypeManager.CSharpName (source) + "' to `" +
1221 TypeManager.CSharpName (target) + "'");
1224 public override Expression DoResolve (EmitContext ec)
1226 Expression e = base.DoResolve (ec);
1232 eclass = ExprClass.Value;
1233 Type etype = expr.Type;
1235 if (TypeManager.IsValueType (probe_type)){
1236 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1237 TypeManager.CSharpName (probe_type) + " is a value type)");
1242 e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1249 if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1250 if (etype.IsGenericParameter)
1251 expr = new BoxedCast (expr, etype);
1257 Error_CannotConvertType (etype, probe_type, loc);
1263 /// This represents a typecast in the source language.
1265 /// FIXME: Cast expressions have an unusual set of parsing
1266 /// rules, we need to figure those out.
1268 public class Cast : Expression {
1269 Expression target_type;
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 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1296 if (!ec.ConstantCheckState)
1299 if ((value < min) || (value > max)) {
1300 Error (221, "Constant value `" + value + "' cannot be converted " +
1301 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1302 "syntax to override)");
1309 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1311 if (!ec.ConstantCheckState)
1315 Error (221, "Constant value `" + value + "' cannot be converted " +
1316 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1317 "syntax to override)");
1324 bool CheckUnsigned (EmitContext ec, long value, Type type)
1326 if (!ec.ConstantCheckState)
1330 Error (221, "Constant value `" + value + "' cannot be converted " +
1331 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1332 "syntax to override)");
1340 /// Attempts to do a compile-time folding of a constant cast.
1342 Expression TryReduce (EmitContext ec, Type target_type)
1344 Expression real_expr = expr;
1345 if (real_expr is EnumConstant)
1346 real_expr = ((EnumConstant) real_expr).Child;
1348 if (real_expr is ByteConstant){
1349 byte v = ((ByteConstant) real_expr).Value;
1351 if (target_type == TypeManager.sbyte_type) {
1352 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1354 return new SByteConstant ((sbyte) v);
1356 if (target_type == TypeManager.short_type)
1357 return new ShortConstant ((short) v);
1358 if (target_type == TypeManager.ushort_type)
1359 return new UShortConstant ((ushort) v);
1360 if (target_type == TypeManager.int32_type)
1361 return new IntConstant ((int) v);
1362 if (target_type == TypeManager.uint32_type)
1363 return new UIntConstant ((uint) v);
1364 if (target_type == TypeManager.int64_type)
1365 return new LongConstant ((long) v);
1366 if (target_type == TypeManager.uint64_type)
1367 return new ULongConstant ((ulong) v);
1368 if (target_type == TypeManager.float_type)
1369 return new FloatConstant ((float) v);
1370 if (target_type == TypeManager.double_type)
1371 return new DoubleConstant ((double) v);
1372 if (target_type == TypeManager.char_type)
1373 return new CharConstant ((char) v);
1374 if (target_type == TypeManager.decimal_type)
1375 return new DecimalConstant ((decimal) v);
1377 if (real_expr is SByteConstant){
1378 sbyte v = ((SByteConstant) real_expr).Value;
1380 if (target_type == TypeManager.byte_type) {
1381 if (!CheckUnsigned (ec, v, target_type))
1383 return new ByteConstant ((byte) v);
1385 if (target_type == TypeManager.short_type)
1386 return new ShortConstant ((short) v);
1387 if (target_type == TypeManager.ushort_type) {
1388 if (!CheckUnsigned (ec, v, target_type))
1390 return new UShortConstant ((ushort) v);
1391 } if (target_type == TypeManager.int32_type)
1392 return new IntConstant ((int) v);
1393 if (target_type == TypeManager.uint32_type) {
1394 if (!CheckUnsigned (ec, v, target_type))
1396 return new UIntConstant ((uint) v);
1397 } if (target_type == TypeManager.int64_type)
1398 return new LongConstant ((long) v);
1399 if (target_type == TypeManager.uint64_type) {
1400 if (!CheckUnsigned (ec, v, target_type))
1402 return new ULongConstant ((ulong) v);
1404 if (target_type == TypeManager.float_type)
1405 return new FloatConstant ((float) v);
1406 if (target_type == TypeManager.double_type)
1407 return new DoubleConstant ((double) v);
1408 if (target_type == TypeManager.char_type) {
1409 if (!CheckUnsigned (ec, v, target_type))
1411 return new CharConstant ((char) v);
1413 if (target_type == TypeManager.decimal_type)
1414 return new DecimalConstant ((decimal) v);
1416 if (real_expr is ShortConstant){
1417 short v = ((ShortConstant) real_expr).Value;
1419 if (target_type == TypeManager.byte_type) {
1420 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1422 return new ByteConstant ((byte) v);
1424 if (target_type == TypeManager.sbyte_type) {
1425 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1427 return new SByteConstant ((sbyte) v);
1429 if (target_type == TypeManager.ushort_type) {
1430 if (!CheckUnsigned (ec, v, target_type))
1432 return new UShortConstant ((ushort) v);
1434 if (target_type == TypeManager.int32_type)
1435 return new IntConstant ((int) v);
1436 if (target_type == TypeManager.uint32_type) {
1437 if (!CheckUnsigned (ec, v, target_type))
1439 return new UIntConstant ((uint) v);
1441 if (target_type == TypeManager.int64_type)
1442 return new LongConstant ((long) v);
1443 if (target_type == TypeManager.uint64_type) {
1444 if (!CheckUnsigned (ec, v, target_type))
1446 return new ULongConstant ((ulong) v);
1448 if (target_type == TypeManager.float_type)
1449 return new FloatConstant ((float) v);
1450 if (target_type == TypeManager.double_type)
1451 return new DoubleConstant ((double) v);
1452 if (target_type == TypeManager.char_type) {
1453 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1455 return new CharConstant ((char) v);
1457 if (target_type == TypeManager.decimal_type)
1458 return new DecimalConstant ((decimal) v);
1460 if (real_expr is UShortConstant){
1461 ushort v = ((UShortConstant) real_expr).Value;
1463 if (target_type == TypeManager.byte_type) {
1464 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1466 return new ByteConstant ((byte) v);
1468 if (target_type == TypeManager.sbyte_type) {
1469 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1471 return new SByteConstant ((sbyte) v);
1473 if (target_type == TypeManager.short_type) {
1474 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1476 return new ShortConstant ((short) v);
1478 if (target_type == TypeManager.int32_type)
1479 return new IntConstant ((int) v);
1480 if (target_type == TypeManager.uint32_type)
1481 return new UIntConstant ((uint) v);
1482 if (target_type == TypeManager.int64_type)
1483 return new LongConstant ((long) v);
1484 if (target_type == TypeManager.uint64_type)
1485 return new ULongConstant ((ulong) v);
1486 if (target_type == TypeManager.float_type)
1487 return new FloatConstant ((float) v);
1488 if (target_type == TypeManager.double_type)
1489 return new DoubleConstant ((double) v);
1490 if (target_type == TypeManager.char_type) {
1491 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1493 return new CharConstant ((char) v);
1495 if (target_type == TypeManager.decimal_type)
1496 return new DecimalConstant ((decimal) v);
1498 if (real_expr is IntConstant){
1499 int v = ((IntConstant) real_expr).Value;
1501 if (target_type == TypeManager.byte_type) {
1502 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1504 return new ByteConstant ((byte) v);
1506 if (target_type == TypeManager.sbyte_type) {
1507 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1509 return new SByteConstant ((sbyte) v);
1511 if (target_type == TypeManager.short_type) {
1512 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1514 return new ShortConstant ((short) v);
1516 if (target_type == TypeManager.ushort_type) {
1517 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1519 return new UShortConstant ((ushort) v);
1521 if (target_type == TypeManager.uint32_type) {
1522 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1524 return new UIntConstant ((uint) v);
1526 if (target_type == TypeManager.int64_type)
1527 return new LongConstant ((long) v);
1528 if (target_type == TypeManager.uint64_type) {
1529 if (!CheckUnsigned (ec, v, target_type))
1531 return new ULongConstant ((ulong) v);
1533 if (target_type == TypeManager.float_type)
1534 return new FloatConstant ((float) v);
1535 if (target_type == TypeManager.double_type)
1536 return new DoubleConstant ((double) v);
1537 if (target_type == TypeManager.char_type) {
1538 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1540 return new CharConstant ((char) v);
1542 if (target_type == TypeManager.decimal_type)
1543 return new DecimalConstant ((decimal) v);
1545 if (real_expr is UIntConstant){
1546 uint v = ((UIntConstant) real_expr).Value;
1548 if (target_type == TypeManager.byte_type) {
1549 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1551 return new ByteConstant ((byte) v);
1553 if (target_type == TypeManager.sbyte_type) {
1554 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1556 return new SByteConstant ((sbyte) v);
1558 if (target_type == TypeManager.short_type) {
1559 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1561 return new ShortConstant ((short) v);
1563 if (target_type == TypeManager.ushort_type) {
1564 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1566 return new UShortConstant ((ushort) v);
1568 if (target_type == TypeManager.int32_type) {
1569 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1571 return new IntConstant ((int) v);
1573 if (target_type == TypeManager.int64_type)
1574 return new LongConstant ((long) v);
1575 if (target_type == TypeManager.uint64_type)
1576 return new ULongConstant ((ulong) v);
1577 if (target_type == TypeManager.float_type)
1578 return new FloatConstant ((float) v);
1579 if (target_type == TypeManager.double_type)
1580 return new DoubleConstant ((double) v);
1581 if (target_type == TypeManager.char_type) {
1582 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1584 return new CharConstant ((char) v);
1586 if (target_type == TypeManager.decimal_type)
1587 return new DecimalConstant ((decimal) v);
1589 if (real_expr is LongConstant){
1590 long v = ((LongConstant) real_expr).Value;
1592 if (target_type == TypeManager.byte_type) {
1593 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1595 return new ByteConstant ((byte) v);
1597 if (target_type == TypeManager.sbyte_type) {
1598 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1600 return new SByteConstant ((sbyte) v);
1602 if (target_type == TypeManager.short_type) {
1603 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1605 return new ShortConstant ((short) v);
1607 if (target_type == TypeManager.ushort_type) {
1608 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1610 return new UShortConstant ((ushort) v);
1612 if (target_type == TypeManager.int32_type) {
1613 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1615 return new IntConstant ((int) v);
1617 if (target_type == TypeManager.uint32_type) {
1618 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1620 return new UIntConstant ((uint) v);
1622 if (target_type == TypeManager.uint64_type) {
1623 if (!CheckUnsigned (ec, v, target_type))
1625 return new ULongConstant ((ulong) v);
1627 if (target_type == TypeManager.float_type)
1628 return new FloatConstant ((float) v);
1629 if (target_type == TypeManager.double_type)
1630 return new DoubleConstant ((double) v);
1631 if (target_type == TypeManager.char_type) {
1632 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1634 return new CharConstant ((char) v);
1636 if (target_type == TypeManager.decimal_type)
1637 return new DecimalConstant ((decimal) v);
1639 if (real_expr is ULongConstant){
1640 ulong v = ((ULongConstant) real_expr).Value;
1642 if (target_type == TypeManager.byte_type) {
1643 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1645 return new ByteConstant ((byte) v);
1647 if (target_type == TypeManager.sbyte_type) {
1648 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1650 return new SByteConstant ((sbyte) v);
1652 if (target_type == TypeManager.short_type) {
1653 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1655 return new ShortConstant ((short) v);
1657 if (target_type == TypeManager.ushort_type) {
1658 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1660 return new UShortConstant ((ushort) v);
1662 if (target_type == TypeManager.int32_type) {
1663 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1665 return new IntConstant ((int) v);
1667 if (target_type == TypeManager.uint32_type) {
1668 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1670 return new UIntConstant ((uint) v);
1672 if (target_type == TypeManager.int64_type) {
1673 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1675 return new LongConstant ((long) v);
1677 if (target_type == TypeManager.float_type)
1678 return new FloatConstant ((float) v);
1679 if (target_type == TypeManager.double_type)
1680 return new DoubleConstant ((double) v);
1681 if (target_type == TypeManager.char_type) {
1682 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1684 return new CharConstant ((char) v);
1686 if (target_type == TypeManager.decimal_type)
1687 return new DecimalConstant ((decimal) v);
1689 if (real_expr is FloatConstant){
1690 float v = ((FloatConstant) real_expr).Value;
1692 if (target_type == TypeManager.byte_type)
1693 return new ByteConstant ((byte) v);
1694 if (target_type == TypeManager.sbyte_type)
1695 return new SByteConstant ((sbyte) v);
1696 if (target_type == TypeManager.short_type)
1697 return new ShortConstant ((short) v);
1698 if (target_type == TypeManager.ushort_type)
1699 return new UShortConstant ((ushort) v);
1700 if (target_type == TypeManager.int32_type)
1701 return new IntConstant ((int) v);
1702 if (target_type == TypeManager.uint32_type)
1703 return new UIntConstant ((uint) v);
1704 if (target_type == TypeManager.int64_type)
1705 return new LongConstant ((long) v);
1706 if (target_type == TypeManager.uint64_type)
1707 return new ULongConstant ((ulong) v);
1708 if (target_type == TypeManager.double_type)
1709 return new DoubleConstant ((double) v);
1710 if (target_type == TypeManager.char_type)
1711 return new CharConstant ((char) v);
1712 if (target_type == TypeManager.decimal_type)
1713 return new DecimalConstant ((decimal) v);
1715 if (real_expr is DoubleConstant){
1716 double v = ((DoubleConstant) real_expr).Value;
1718 if (target_type == TypeManager.byte_type){
1719 return new ByteConstant ((byte) v);
1720 } if (target_type == TypeManager.sbyte_type)
1721 return new SByteConstant ((sbyte) v);
1722 if (target_type == TypeManager.short_type)
1723 return new ShortConstant ((short) v);
1724 if (target_type == TypeManager.ushort_type)
1725 return new UShortConstant ((ushort) v);
1726 if (target_type == TypeManager.int32_type)
1727 return new IntConstant ((int) v);
1728 if (target_type == TypeManager.uint32_type)
1729 return new UIntConstant ((uint) v);
1730 if (target_type == TypeManager.int64_type)
1731 return new LongConstant ((long) v);
1732 if (target_type == TypeManager.uint64_type)
1733 return new ULongConstant ((ulong) v);
1734 if (target_type == TypeManager.float_type)
1735 return new FloatConstant ((float) v);
1736 if (target_type == TypeManager.char_type)
1737 return new CharConstant ((char) v);
1738 if (target_type == TypeManager.decimal_type)
1739 return new DecimalConstant ((decimal) v);
1742 if (real_expr is CharConstant){
1743 char v = ((CharConstant) real_expr).Value;
1745 if (target_type == TypeManager.byte_type) {
1746 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1748 return new ByteConstant ((byte) v);
1750 if (target_type == TypeManager.sbyte_type) {
1751 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1753 return new SByteConstant ((sbyte) v);
1755 if (target_type == TypeManager.short_type) {
1756 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1758 return new ShortConstant ((short) v);
1760 if (target_type == TypeManager.int32_type)
1761 return new IntConstant ((int) v);
1762 if (target_type == TypeManager.uint32_type)
1763 return new UIntConstant ((uint) v);
1764 if (target_type == TypeManager.int64_type)
1765 return new LongConstant ((long) v);
1766 if (target_type == TypeManager.uint64_type)
1767 return new ULongConstant ((ulong) v);
1768 if (target_type == TypeManager.float_type)
1769 return new FloatConstant ((float) v);
1770 if (target_type == TypeManager.double_type)
1771 return new DoubleConstant ((double) v);
1772 if (target_type == TypeManager.char_type) {
1773 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1775 return new CharConstant ((char) v);
1777 if (target_type == TypeManager.decimal_type)
1778 return new DecimalConstant ((decimal) v);
1784 public override Expression DoResolve (EmitContext ec)
1786 expr = expr.Resolve (ec);
1790 TypeExpr target = target_type.ResolveAsTypeTerminal (ec);
1796 CheckObsoleteAttribute (type);
1798 if (type.IsAbstract && type.IsSealed) {
1799 Report.Error (716, loc, "Cannot convert to static type '{0}'", TypeManager.CSharpName (type));
1803 eclass = ExprClass.Value;
1805 if (expr is Constant){
1806 Expression e = TryReduce (ec, type);
1812 if (type.IsPointer && !ec.InUnsafe) {
1816 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1820 public override void Emit (EmitContext ec)
1823 // This one will never happen
1825 throw new Exception ("Should not happen");
1830 /// Binary operators
1832 public class Binary : Expression {
1833 public enum Operator : byte {
1834 Multiply, Division, Modulus,
1835 Addition, Subtraction,
1836 LeftShift, RightShift,
1837 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1838 Equality, Inequality,
1848 Expression left, right;
1850 // This must be kept in sync with Operator!!!
1851 public static readonly string [] oper_names;
1855 oper_names = new string [(int) Operator.TOP];
1857 oper_names [(int) Operator.Multiply] = "op_Multiply";
1858 oper_names [(int) Operator.Division] = "op_Division";
1859 oper_names [(int) Operator.Modulus] = "op_Modulus";
1860 oper_names [(int) Operator.Addition] = "op_Addition";
1861 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1862 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1863 oper_names [(int) Operator.RightShift] = "op_RightShift";
1864 oper_names [(int) Operator.LessThan] = "op_LessThan";
1865 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1866 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1867 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1868 oper_names [(int) Operator.Equality] = "op_Equality";
1869 oper_names [(int) Operator.Inequality] = "op_Inequality";
1870 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1871 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1872 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1873 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1874 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1877 public Binary (Operator oper, Expression left, Expression right, Location loc)
1885 public Operator Oper {
1894 public Expression Left {
1903 public Expression Right {
1914 /// Returns a stringified representation of the Operator
1916 static string OperName (Operator oper)
1919 case Operator.Multiply:
1921 case Operator.Division:
1923 case Operator.Modulus:
1925 case Operator.Addition:
1927 case Operator.Subtraction:
1929 case Operator.LeftShift:
1931 case Operator.RightShift:
1933 case Operator.LessThan:
1935 case Operator.GreaterThan:
1937 case Operator.LessThanOrEqual:
1939 case Operator.GreaterThanOrEqual:
1941 case Operator.Equality:
1943 case Operator.Inequality:
1945 case Operator.BitwiseAnd:
1947 case Operator.BitwiseOr:
1949 case Operator.ExclusiveOr:
1951 case Operator.LogicalOr:
1953 case Operator.LogicalAnd:
1957 return oper.ToString ();
1960 public override string ToString ()
1962 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1963 right.ToString () + ")";
1966 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1968 if (expr.Type == target_type)
1971 return Convert.ImplicitConversion (ec, expr, target_type, loc);
1974 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1977 34, loc, "Operator `" + OperName (oper)
1978 + "' is ambiguous on operands of type `"
1979 + TypeManager.CSharpName (l) + "' "
1980 + "and `" + TypeManager.CSharpName (r)
1984 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
1986 if ((l == t) || (r == t))
1989 if (!check_user_conversions)
1992 if (Convert.ImplicitUserConversionExists (ec, l, t))
1994 else if (Convert.ImplicitUserConversionExists (ec, r, t))
2001 // Note that handling the case l == Decimal || r == Decimal
2002 // is taken care of by the Step 1 Operator Overload resolution.
2004 // If `check_user_conv' is true, we also check whether a user-defined conversion
2005 // exists. Note that we only need to do this if both arguments are of a user-defined
2006 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
2007 // so we don't explicitly check for performance reasons.
2009 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
2011 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
2013 // If either operand is of type double, the other operand is
2014 // conveted to type double.
2016 if (r != TypeManager.double_type)
2017 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
2018 if (l != TypeManager.double_type)
2019 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
2021 type = TypeManager.double_type;
2022 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
2024 // if either operand is of type float, the other operand is
2025 // converted to type float.
2027 if (r != TypeManager.double_type)
2028 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
2029 if (l != TypeManager.double_type)
2030 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
2031 type = TypeManager.float_type;
2032 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2036 // If either operand is of type ulong, the other operand is
2037 // converted to type ulong. or an error ocurrs if the other
2038 // operand is of type sbyte, short, int or long
2040 if (l == TypeManager.uint64_type){
2041 if (r != TypeManager.uint64_type){
2042 if (right is IntConstant){
2043 IntConstant ic = (IntConstant) right;
2045 e = Convert.TryImplicitIntConversion (l, ic);
2048 } else if (right is LongConstant){
2049 long ll = ((LongConstant) right).Value;
2052 right = new ULongConstant ((ulong) ll);
2054 e = Convert.ImplicitNumericConversion (ec, right, l, loc);
2061 if (left is IntConstant){
2062 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
2065 } else if (left is LongConstant){
2066 long ll = ((LongConstant) left).Value;
2069 left = new ULongConstant ((ulong) ll);
2071 e = Convert.ImplicitNumericConversion (ec, left, r, loc);
2078 if ((other == TypeManager.sbyte_type) ||
2079 (other == TypeManager.short_type) ||
2080 (other == TypeManager.int32_type) ||
2081 (other == TypeManager.int64_type))
2082 Error_OperatorAmbiguous (loc, oper, l, r);
2084 left = ForceConversion (ec, left, TypeManager.uint64_type);
2085 right = ForceConversion (ec, right, TypeManager.uint64_type);
2087 type = TypeManager.uint64_type;
2088 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2090 // If either operand is of type long, the other operand is converted
2093 if (l != TypeManager.int64_type)
2094 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
2095 if (r != TypeManager.int64_type)
2096 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
2098 type = TypeManager.int64_type;
2099 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2101 // If either operand is of type uint, and the other
2102 // operand is of type sbyte, short or int, othe operands are
2103 // converted to type long (unless we have an int constant).
2107 if (l == TypeManager.uint32_type){
2108 if (right is IntConstant){
2109 IntConstant ic = (IntConstant) right;
2113 right = new UIntConstant ((uint) val);
2120 } else if (r == TypeManager.uint32_type){
2121 if (left is IntConstant){
2122 IntConstant ic = (IntConstant) left;
2126 left = new UIntConstant ((uint) val);
2135 if ((other == TypeManager.sbyte_type) ||
2136 (other == TypeManager.short_type) ||
2137 (other == TypeManager.int32_type)){
2138 left = ForceConversion (ec, left, TypeManager.int64_type);
2139 right = ForceConversion (ec, right, TypeManager.int64_type);
2140 type = TypeManager.int64_type;
2143 // if either operand is of type uint, the other
2144 // operand is converd to type uint
2146 left = ForceConversion (ec, left, TypeManager.uint32_type);
2147 right = ForceConversion (ec, right, TypeManager.uint32_type);
2148 type = TypeManager.uint32_type;
2150 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2151 if (l != TypeManager.decimal_type)
2152 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
2154 if (r != TypeManager.decimal_type)
2155 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
2156 type = TypeManager.decimal_type;
2158 left = ForceConversion (ec, left, TypeManager.int32_type);
2159 right = ForceConversion (ec, right, TypeManager.int32_type);
2161 type = TypeManager.int32_type;
2164 return (left != null) && (right != null);
2167 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2169 Report.Error (19, loc,
2170 "Operator " + name + " cannot be applied to operands of type `" +
2171 TypeManager.CSharpName (l) + "' and `" +
2172 TypeManager.CSharpName (r) + "'");
2175 void Error_OperatorCannotBeApplied ()
2177 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2180 static bool is_unsigned (Type t)
2182 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2183 t == TypeManager.short_type || t == TypeManager.byte_type);
2186 static bool is_user_defined (Type t)
2188 if (t.IsSubclassOf (TypeManager.value_type) &&
2189 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2195 Expression Make32or64 (EmitContext ec, Expression e)
2199 if (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2200 t == TypeManager.int64_type || t == TypeManager.uint64_type)
2202 Expression ee = Convert.ImplicitConversion (ec, e, TypeManager.int32_type, loc);
2205 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint32_type, loc);
2208 ee = Convert.ImplicitConversion (ec, e, TypeManager.int64_type, loc);
2211 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint64_type, loc);
2217 Expression CheckShiftArguments (EmitContext ec)
2221 e = ForceConversion (ec, right, TypeManager.int32_type);
2223 Error_OperatorCannotBeApplied ();
2228 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
2229 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
2230 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
2231 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
2235 if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
2236 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (31), loc);
2237 right = right.DoResolve (ec);
2239 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (63), loc);
2240 right = right.DoResolve (ec);
2245 Error_OperatorCannotBeApplied ();
2249 Expression ResolveOperator (EmitContext ec)
2252 Type r = right.Type;
2255 // Special cases: string or type parameter comapred to null
2257 if (oper == Operator.Equality || oper == Operator.Inequality){
2258 if ((!TypeManager.IsValueType (l) && r == TypeManager.null_type) ||
2259 (!TypeManager.IsValueType (r) && l == TypeManager.null_type)) {
2260 Type = TypeManager.bool_type;
2265 if (l.IsGenericParameter && (right is NullLiteral)) {
2266 if (l.BaseType == TypeManager.value_type) {
2267 Error_OperatorCannotBeApplied ();
2271 left = new BoxedCast (left);
2272 Type = TypeManager.bool_type;
2276 if (r.IsGenericParameter && (left is NullLiteral)) {
2277 if (r.BaseType == TypeManager.value_type) {
2278 Error_OperatorCannotBeApplied ();
2282 right = new BoxedCast (right);
2283 Type = TypeManager.bool_type;
2288 if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
2289 Type = TypeManager.bool_type;
2296 // Do not perform operator overload resolution when both sides are
2299 if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
2301 // Step 1: Perform Operator Overload location
2303 Expression left_expr, right_expr;
2305 string op = oper_names [(int) oper];
2307 MethodGroupExpr union;
2308 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2310 right_expr = MemberLookup (
2311 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2312 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2314 union = (MethodGroupExpr) left_expr;
2316 if (union != null) {
2317 ArrayList args = new ArrayList (2);
2318 args.Add (new Argument (left, Argument.AType.Expression));
2319 args.Add (new Argument (right, Argument.AType.Expression));
2321 MethodBase method = Invocation.OverloadResolve (
2322 ec, union, args, true, Location.Null);
2324 if (method != null) {
2325 MethodInfo mi = (MethodInfo) method;
2327 return new BinaryMethod (mi.ReturnType, method, args);
2333 // Step 0: String concatenation (because overloading will get this wrong)
2335 if (oper == Operator.Addition){
2337 // If any of the arguments is a string, cast to string
2340 // Simple constant folding
2341 if (left is StringConstant && right is StringConstant)
2342 return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value);
2344 if (l == TypeManager.string_type || r == TypeManager.string_type) {
2346 if (r == TypeManager.void_type || l == TypeManager.void_type) {
2347 Error_OperatorCannotBeApplied ();
2351 // try to fold it in on the left
2352 if (left is StringConcat) {
2355 // We have to test here for not-null, since we can be doubly-resolved
2356 // take care of not appending twice
2359 type = TypeManager.string_type;
2360 ((StringConcat) left).Append (ec, right);
2361 return left.Resolve (ec);
2367 // Otherwise, start a new concat expression
2368 return new StringConcat (ec, loc, left, right).Resolve (ec);
2372 // Transform a + ( - b) into a - b
2374 if (right is Unary){
2375 Unary right_unary = (Unary) right;
2377 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2378 oper = Operator.Subtraction;
2379 right = right_unary.Expr;
2385 if (oper == Operator.Equality || oper == Operator.Inequality){
2386 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2387 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2388 Error_OperatorCannotBeApplied ();
2392 type = TypeManager.bool_type;
2397 // operator != (object a, object b)
2398 // operator == (object a, object b)
2400 // For this to be used, both arguments have to be reference-types.
2401 // Read the rationale on the spec (14.9.6)
2403 // Also, if at compile time we know that the classes do not inherit
2404 // one from the other, then we catch the error there.
2406 if (!(l.IsValueType || r.IsValueType)){
2407 type = TypeManager.bool_type;
2412 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2416 // Also, a standard conversion must exist from either one
2418 if (!(Convert.ImplicitStandardConversionExists (ec, left, r) ||
2419 Convert.ImplicitStandardConversionExists (ec, right, l))){
2420 Error_OperatorCannotBeApplied ();
2424 // We are going to have to convert to an object to compare
2426 if (l != TypeManager.object_type)
2427 left = new EmptyCast (left, TypeManager.object_type);
2428 if (r != TypeManager.object_type)
2429 right = new EmptyCast (right, TypeManager.object_type);
2432 // FIXME: CSC here catches errors cs254 and cs252
2438 // One of them is a valuetype, but the other one is not.
2440 if (!l.IsValueType || !r.IsValueType) {
2441 Error_OperatorCannotBeApplied ();
2446 // Only perform numeric promotions on:
2447 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2449 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2450 if (TypeManager.IsDelegateType (l)){
2451 if (((right.eclass == ExprClass.MethodGroup) ||
2452 (r == TypeManager.anonymous_method_type))){
2453 if ((RootContext.Version != LanguageVersion.ISO_1)){
2454 Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2462 if (TypeManager.IsDelegateType (r)){
2464 ArrayList args = new ArrayList (2);
2466 args = new ArrayList (2);
2467 args.Add (new Argument (left, Argument.AType.Expression));
2468 args.Add (new Argument (right, Argument.AType.Expression));
2470 if (oper == Operator.Addition)
2471 method = TypeManager.delegate_combine_delegate_delegate;
2473 method = TypeManager.delegate_remove_delegate_delegate;
2476 Error_OperatorCannotBeApplied ();
2480 return new BinaryDelegate (l, method, args);
2485 // Pointer arithmetic:
2487 // T* operator + (T* x, int y);
2488 // T* operator + (T* x, uint y);
2489 // T* operator + (T* x, long y);
2490 // T* operator + (T* x, ulong y);
2492 // T* operator + (int y, T* x);
2493 // T* operator + (uint y, T *x);
2494 // T* operator + (long y, T *x);
2495 // T* operator + (ulong y, T *x);
2497 // T* operator - (T* x, int y);
2498 // T* operator - (T* x, uint y);
2499 // T* operator - (T* x, long y);
2500 // T* operator - (T* x, ulong y);
2502 // long operator - (T* x, T *y)
2505 if (r.IsPointer && oper == Operator.Subtraction){
2507 return new PointerArithmetic (
2508 false, left, right, TypeManager.int64_type,
2511 Expression t = Make32or64 (ec, right);
2513 return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc).Resolve (ec);
2515 } else if (r.IsPointer && oper == Operator.Addition){
2516 Expression t = Make32or64 (ec, left);
2518 return new PointerArithmetic (true, right, t, r, loc).Resolve (ec);
2523 // Enumeration operators
2525 bool lie = TypeManager.IsEnumType (l);
2526 bool rie = TypeManager.IsEnumType (r);
2530 // U operator - (E e, E f)
2532 if (oper == Operator.Subtraction){
2534 type = TypeManager.EnumToUnderlying (l);
2537 Error_OperatorCannotBeApplied ();
2543 // operator + (E e, U x)
2544 // operator - (E e, U x)
2546 if (oper == Operator.Addition || oper == Operator.Subtraction){
2547 Type enum_type = lie ? l : r;
2548 Type other_type = lie ? r : l;
2549 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2551 if (underlying_type != other_type){
2552 temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
2562 Error_OperatorCannotBeApplied ();
2571 temp = Convert.ImplicitConversion (ec, right, l, loc);
2575 Error_OperatorCannotBeApplied ();
2579 temp = Convert.ImplicitConversion (ec, left, r, loc);
2584 Error_OperatorCannotBeApplied ();
2589 if (oper == Operator.Equality || oper == Operator.Inequality ||
2590 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2591 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2592 if (left.Type != right.Type){
2593 Error_OperatorCannotBeApplied ();
2596 type = TypeManager.bool_type;
2600 if (oper == Operator.BitwiseAnd ||
2601 oper == Operator.BitwiseOr ||
2602 oper == Operator.ExclusiveOr){
2606 Error_OperatorCannotBeApplied ();
2610 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2611 return CheckShiftArguments (ec);
2613 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2614 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2615 type = TypeManager.bool_type;
2620 Error_OperatorCannotBeApplied ();
2624 Expression e = new ConditionalLogicalOperator (
2625 oper == Operator.LogicalAnd, left, right, l, loc);
2626 return e.Resolve (ec);
2630 // operator & (bool x, bool y)
2631 // operator | (bool x, bool y)
2632 // operator ^ (bool x, bool y)
2634 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2635 if (oper == Operator.BitwiseAnd ||
2636 oper == Operator.BitwiseOr ||
2637 oper == Operator.ExclusiveOr){
2644 // Pointer comparison
2646 if (l.IsPointer && r.IsPointer){
2647 if (oper == Operator.Equality || oper == Operator.Inequality ||
2648 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2649 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2650 type = TypeManager.bool_type;
2656 // This will leave left or right set to null if there is an error
2658 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2659 DoNumericPromotions (ec, l, r, check_user_conv);
2660 if (left == null || right == null){
2661 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2666 // reload our cached types if required
2671 if (oper == Operator.BitwiseAnd ||
2672 oper == Operator.BitwiseOr ||
2673 oper == Operator.ExclusiveOr){
2675 if (((l == TypeManager.int32_type) ||
2676 (l == TypeManager.uint32_type) ||
2677 (l == TypeManager.short_type) ||
2678 (l == TypeManager.ushort_type) ||
2679 (l == TypeManager.int64_type) ||
2680 (l == TypeManager.uint64_type))){
2683 Error_OperatorCannotBeApplied ();
2687 Error_OperatorCannotBeApplied ();
2692 if (oper == Operator.Equality ||
2693 oper == Operator.Inequality ||
2694 oper == Operator.LessThanOrEqual ||
2695 oper == Operator.LessThan ||
2696 oper == Operator.GreaterThanOrEqual ||
2697 oper == Operator.GreaterThan){
2698 type = TypeManager.bool_type;
2704 public override Expression DoResolve (EmitContext ec)
2706 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2707 left = ((ParenthesizedExpression) left).Expr;
2708 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2712 if (left.eclass == ExprClass.Type) {
2713 Error (75, "Casting a negative value needs to have the value in parentheses.");
2717 left = left.Resolve (ec);
2722 Constant lc = left as Constant;
2723 if (lc != null && lc.Type == TypeManager.bool_type &&
2724 ((oper == Operator.LogicalAnd && (bool)lc.GetValue () == false) ||
2725 (oper == Operator.LogicalOr && (bool)lc.GetValue () == true))) {
2727 // TODO: make a sence to resolve unreachable expression as we do for statement
2728 Report.Warning (429, 4, loc, "Unreachable expression code detected");
2732 right = right.Resolve (ec);
2736 eclass = ExprClass.Value;
2738 Constant rc = right as Constant;
2739 if (rc != null & lc != null){
2740 Expression e = ConstantFold.BinaryFold (
2741 ec, oper, lc, rc, loc);
2746 return ResolveOperator (ec);
2750 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2751 /// context of a conditional bool expression. This function will return
2752 /// false if it is was possible to use EmitBranchable, or true if it was.
2754 /// The expression's code is generated, and we will generate a branch to `target'
2755 /// if the resulting expression value is equal to isTrue
2757 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2759 ILGenerator ig = ec.ig;
2762 // This is more complicated than it looks, but its just to avoid
2763 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2764 // but on top of that we want for == and != to use a special path
2765 // if we are comparing against null
2767 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
2768 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2771 // put the constant on the rhs, for simplicity
2773 if (left is Constant) {
2774 Expression swap = right;
2779 if (((Constant) right).IsZeroInteger) {
2782 ig.Emit (OpCodes.Brtrue, target);
2784 ig.Emit (OpCodes.Brfalse, target);
2787 } else if (right is BoolConstant){
2789 if (my_on_true != ((BoolConstant) right).Value)
2790 ig.Emit (OpCodes.Brtrue, target);
2792 ig.Emit (OpCodes.Brfalse, target);
2797 } else if (oper == Operator.LogicalAnd) {
2800 Label tests_end = ig.DefineLabel ();
2802 left.EmitBranchable (ec, tests_end, false);
2803 right.EmitBranchable (ec, target, true);
2804 ig.MarkLabel (tests_end);
2806 left.EmitBranchable (ec, target, false);
2807 right.EmitBranchable (ec, target, false);
2812 } else if (oper == Operator.LogicalOr){
2814 left.EmitBranchable (ec, target, true);
2815 right.EmitBranchable (ec, target, true);
2818 Label tests_end = ig.DefineLabel ();
2819 left.EmitBranchable (ec, tests_end, true);
2820 right.EmitBranchable (ec, target, false);
2821 ig.MarkLabel (tests_end);
2826 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2827 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2828 oper == Operator.Equality || oper == Operator.Inequality)) {
2829 base.EmitBranchable (ec, target, onTrue);
2837 bool isUnsigned = is_unsigned (t) || t == TypeManager.double_type || t == TypeManager.float_type;
2840 case Operator.Equality:
2842 ig.Emit (OpCodes.Beq, target);
2844 ig.Emit (OpCodes.Bne_Un, target);
2847 case Operator.Inequality:
2849 ig.Emit (OpCodes.Bne_Un, target);
2851 ig.Emit (OpCodes.Beq, target);
2854 case Operator.LessThan:
2857 ig.Emit (OpCodes.Blt_Un, target);
2859 ig.Emit (OpCodes.Blt, target);
2862 ig.Emit (OpCodes.Bge_Un, target);
2864 ig.Emit (OpCodes.Bge, target);
2867 case Operator.GreaterThan:
2870 ig.Emit (OpCodes.Bgt_Un, target);
2872 ig.Emit (OpCodes.Bgt, target);
2875 ig.Emit (OpCodes.Ble_Un, target);
2877 ig.Emit (OpCodes.Ble, target);
2880 case Operator.LessThanOrEqual:
2883 ig.Emit (OpCodes.Ble_Un, target);
2885 ig.Emit (OpCodes.Ble, target);
2888 ig.Emit (OpCodes.Bgt_Un, target);
2890 ig.Emit (OpCodes.Bgt, target);
2894 case Operator.GreaterThanOrEqual:
2897 ig.Emit (OpCodes.Bge_Un, target);
2899 ig.Emit (OpCodes.Bge, target);
2902 ig.Emit (OpCodes.Blt_Un, target);
2904 ig.Emit (OpCodes.Blt, target);
2907 Console.WriteLine (oper);
2908 throw new Exception ("what is THAT");
2912 public override void Emit (EmitContext ec)
2914 ILGenerator ig = ec.ig;
2919 // Handle short-circuit operators differently
2922 if (oper == Operator.LogicalAnd) {
2923 Label load_zero = ig.DefineLabel ();
2924 Label end = ig.DefineLabel ();
2926 left.EmitBranchable (ec, load_zero, false);
2928 ig.Emit (OpCodes.Br, end);
2930 ig.MarkLabel (load_zero);
2931 ig.Emit (OpCodes.Ldc_I4_0);
2934 } else if (oper == Operator.LogicalOr) {
2935 Label load_one = ig.DefineLabel ();
2936 Label end = ig.DefineLabel ();
2938 left.EmitBranchable (ec, load_one, true);
2940 ig.Emit (OpCodes.Br, end);
2942 ig.MarkLabel (load_one);
2943 ig.Emit (OpCodes.Ldc_I4_1);
2951 bool isUnsigned = is_unsigned (left.Type);
2954 case Operator.Multiply:
2956 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2957 opcode = OpCodes.Mul_Ovf;
2958 else if (isUnsigned)
2959 opcode = OpCodes.Mul_Ovf_Un;
2961 opcode = OpCodes.Mul;
2963 opcode = OpCodes.Mul;
2967 case Operator.Division:
2969 opcode = OpCodes.Div_Un;
2971 opcode = OpCodes.Div;
2974 case Operator.Modulus:
2976 opcode = OpCodes.Rem_Un;
2978 opcode = OpCodes.Rem;
2981 case Operator.Addition:
2983 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2984 opcode = OpCodes.Add_Ovf;
2985 else if (isUnsigned)
2986 opcode = OpCodes.Add_Ovf_Un;
2988 opcode = OpCodes.Add;
2990 opcode = OpCodes.Add;
2993 case Operator.Subtraction:
2995 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2996 opcode = OpCodes.Sub_Ovf;
2997 else if (isUnsigned)
2998 opcode = OpCodes.Sub_Ovf_Un;
3000 opcode = OpCodes.Sub;
3002 opcode = OpCodes.Sub;
3005 case Operator.RightShift:
3007 opcode = OpCodes.Shr_Un;
3009 opcode = OpCodes.Shr;
3012 case Operator.LeftShift:
3013 opcode = OpCodes.Shl;
3016 case Operator.Equality:
3017 opcode = OpCodes.Ceq;
3020 case Operator.Inequality:
3021 ig.Emit (OpCodes.Ceq);
3022 ig.Emit (OpCodes.Ldc_I4_0);
3024 opcode = OpCodes.Ceq;
3027 case Operator.LessThan:
3029 opcode = OpCodes.Clt_Un;
3031 opcode = OpCodes.Clt;
3034 case Operator.GreaterThan:
3036 opcode = OpCodes.Cgt_Un;
3038 opcode = OpCodes.Cgt;
3041 case Operator.LessThanOrEqual:
3042 Type lt = left.Type;
3044 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
3045 ig.Emit (OpCodes.Cgt_Un);
3047 ig.Emit (OpCodes.Cgt);
3048 ig.Emit (OpCodes.Ldc_I4_0);
3050 opcode = OpCodes.Ceq;
3053 case Operator.GreaterThanOrEqual:
3054 Type le = left.Type;
3056 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3057 ig.Emit (OpCodes.Clt_Un);
3059 ig.Emit (OpCodes.Clt);
3061 ig.Emit (OpCodes.Ldc_I4_0);
3063 opcode = OpCodes.Ceq;
3066 case Operator.BitwiseOr:
3067 opcode = OpCodes.Or;
3070 case Operator.BitwiseAnd:
3071 opcode = OpCodes.And;
3074 case Operator.ExclusiveOr:
3075 opcode = OpCodes.Xor;
3079 throw new Exception ("This should not happen: Operator = "
3080 + oper.ToString ());
3088 // Object created by Binary when the binary operator uses an method instead of being
3089 // a binary operation that maps to a CIL binary operation.
3091 public class BinaryMethod : Expression {
3092 public MethodBase method;
3093 public ArrayList Arguments;
3095 public BinaryMethod (Type t, MethodBase m, ArrayList args)
3100 eclass = ExprClass.Value;
3103 public override Expression DoResolve (EmitContext ec)
3108 public override void Emit (EmitContext ec)
3110 ILGenerator ig = ec.ig;
3112 if (Arguments != null)
3113 Invocation.EmitArguments (ec, method, Arguments, false, null);
3115 if (method is MethodInfo)
3116 ig.Emit (OpCodes.Call, (MethodInfo) method);
3118 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3123 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3124 // b, c, d... may be strings or objects.
3126 public class StringConcat : Expression {
3128 bool invalid = false;
3129 bool emit_conv_done = false;
3131 // Are we also concating objects?
3133 bool is_strings_only = true;
3135 public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
3138 type = TypeManager.string_type;
3139 eclass = ExprClass.Value;
3141 operands = new ArrayList (2);
3146 public override Expression DoResolve (EmitContext ec)
3154 public void Append (EmitContext ec, Expression operand)
3159 if (operand is StringConstant && operands.Count != 0) {
3160 StringConstant last_operand = operands [operands.Count - 1] as StringConstant;
3161 if (last_operand != null) {
3162 operands [operands.Count - 1] = new StringConstant (last_operand.Value + ((StringConstant) operand).Value);
3168 // Conversion to object
3170 if (operand.Type != TypeManager.string_type) {
3171 Expression no = Convert.ImplicitConversion (ec, operand, TypeManager.object_type, loc);
3174 Binary.Error_OperatorCannotBeApplied (loc, "+", TypeManager.string_type, operand.Type);
3180 operands.Add (operand);
3183 public override void Emit (EmitContext ec)
3185 MethodInfo concat_method = null;
3188 // Do conversion to arguments; check for strings only
3191 // This can get called multiple times, so we have to deal with that.
3192 if (!emit_conv_done) {
3193 emit_conv_done = true;
3194 for (int i = 0; i < operands.Count; i ++) {
3195 Expression e = (Expression) operands [i];
3196 is_strings_only &= e.Type == TypeManager.string_type;
3199 for (int i = 0; i < operands.Count; i ++) {
3200 Expression e = (Expression) operands [i];
3202 if (! is_strings_only && e.Type == TypeManager.string_type) {
3203 // need to make sure this is an object, because the EmitParams
3204 // method might look at the type of this expression, see it is a
3205 // string and emit a string [] when we want an object [];
3207 e = new EmptyCast (e, TypeManager.object_type);
3209 operands [i] = new Argument (e, Argument.AType.Expression);
3214 // Find the right method
3216 switch (operands.Count) {
3219 // This should not be possible, because simple constant folding
3220 // is taken care of in the Binary code.
3222 throw new Exception ("how did you get here?");
3225 concat_method = is_strings_only ?
3226 TypeManager.string_concat_string_string :
3227 TypeManager.string_concat_object_object ;
3230 concat_method = is_strings_only ?
3231 TypeManager.string_concat_string_string_string :
3232 TypeManager.string_concat_object_object_object ;
3236 // There is not a 4 param overlaod for object (the one that there is
3237 // is actually a varargs methods, and is only in corlib because it was
3238 // introduced there before.).
3240 if (!is_strings_only)
3243 concat_method = TypeManager.string_concat_string_string_string_string;
3246 concat_method = is_strings_only ?
3247 TypeManager.string_concat_string_dot_dot_dot :
3248 TypeManager.string_concat_object_dot_dot_dot ;
3252 Invocation.EmitArguments (ec, concat_method, operands, false, null);
3253 ec.ig.Emit (OpCodes.Call, concat_method);
3258 // Object created with +/= on delegates
3260 public class BinaryDelegate : Expression {
3264 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3269 eclass = ExprClass.Value;
3272 public override Expression DoResolve (EmitContext ec)
3277 public override void Emit (EmitContext ec)
3279 ILGenerator ig = ec.ig;
3281 Invocation.EmitArguments (ec, method, args, false, null);
3283 ig.Emit (OpCodes.Call, (MethodInfo) method);
3284 ig.Emit (OpCodes.Castclass, type);
3287 public Expression Right {
3289 Argument arg = (Argument) args [1];
3294 public bool IsAddition {
3296 return method == TypeManager.delegate_combine_delegate_delegate;
3302 // User-defined conditional logical operator
3303 public class ConditionalLogicalOperator : Expression {
3304 Expression left, right;
3307 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3310 eclass = ExprClass.Value;
3314 this.is_and = is_and;
3317 protected void Error19 ()
3319 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3322 protected void Error218 ()
3324 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3325 "declarations of operator true and operator false");
3328 Expression op_true, op_false, op;
3329 LocalTemporary left_temp;
3331 public override Expression DoResolve (EmitContext ec)
3334 Expression operator_group;
3336 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3337 if (operator_group == null) {
3342 left_temp = new LocalTemporary (ec, type);
3344 ArrayList arguments = new ArrayList ();
3345 arguments.Add (new Argument (left_temp, Argument.AType.Expression));
3346 arguments.Add (new Argument (right, Argument.AType.Expression));
3347 method = Invocation.OverloadResolve (
3348 ec, (MethodGroupExpr) operator_group, arguments, false, loc)
3350 if ((method == null) || (method.ReturnType != type)) {
3355 op = new StaticCallExpr (method, arguments, loc);
3357 op_true = GetOperatorTrue (ec, left_temp, loc);
3358 op_false = GetOperatorFalse (ec, left_temp, loc);
3359 if ((op_true == null) || (op_false == null)) {
3367 public override void Emit (EmitContext ec)
3369 ILGenerator ig = ec.ig;
3370 Label false_target = ig.DefineLabel ();
3371 Label end_target = ig.DefineLabel ();
3374 left_temp.Store (ec);
3376 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
3377 left_temp.Emit (ec);
3378 ig.Emit (OpCodes.Br, end_target);
3379 ig.MarkLabel (false_target);
3381 ig.MarkLabel (end_target);
3385 public class PointerArithmetic : Expression {
3386 Expression left, right;
3390 // We assume that `l' is always a pointer
3392 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3398 is_add = is_addition;
3401 public override Expression DoResolve (EmitContext ec)
3403 eclass = ExprClass.Variable;
3405 if (left.Type == TypeManager.void_ptr_type) {
3406 Error (242, "The operation in question is undefined on void pointers");
3413 public override void Emit (EmitContext ec)
3415 Type op_type = left.Type;
3416 ILGenerator ig = ec.ig;
3417 Type element = TypeManager.GetElementType (op_type);
3418 int size = GetTypeSize (element);
3419 Type rtype = right.Type;
3421 if (rtype.IsPointer){
3423 // handle (pointer - pointer)
3427 ig.Emit (OpCodes.Sub);
3431 ig.Emit (OpCodes.Sizeof, element);
3433 IntLiteral.EmitInt (ig, size);
3434 ig.Emit (OpCodes.Div);
3436 ig.Emit (OpCodes.Conv_I8);
3439 // handle + and - on (pointer op int)
3442 ig.Emit (OpCodes.Conv_I);
3446 ig.Emit (OpCodes.Sizeof, element);
3448 IntLiteral.EmitInt (ig, size);
3449 if (rtype == TypeManager.int64_type)
3450 ig.Emit (OpCodes.Conv_I8);
3451 else if (rtype == TypeManager.uint64_type)
3452 ig.Emit (OpCodes.Conv_U8);
3453 ig.Emit (OpCodes.Mul);
3456 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
3457 ig.Emit (OpCodes.Conv_I);
3460 ig.Emit (OpCodes.Add);
3462 ig.Emit (OpCodes.Sub);
3468 /// Implements the ternary conditional operator (?:)
3470 public class Conditional : Expression {
3471 Expression expr, trueExpr, falseExpr;
3473 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3476 this.trueExpr = trueExpr;
3477 this.falseExpr = falseExpr;
3481 public Expression Expr {
3487 public Expression TrueExpr {
3493 public Expression FalseExpr {
3499 public override Expression DoResolve (EmitContext ec)
3501 expr = expr.Resolve (ec);
3506 if (expr.Type != TypeManager.bool_type){
3507 expr = Expression.ResolveBoolean (
3514 trueExpr = trueExpr.Resolve (ec);
3515 falseExpr = falseExpr.Resolve (ec);
3517 if (trueExpr == null || falseExpr == null)
3520 eclass = ExprClass.Value;
3521 if (trueExpr.Type == falseExpr.Type)
3522 type = trueExpr.Type;
3525 Type true_type = trueExpr.Type;
3526 Type false_type = falseExpr.Type;
3529 // First, if an implicit conversion exists from trueExpr
3530 // to falseExpr, then the result type is of type falseExpr.Type
3532 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3535 // Check if both can convert implicitl to each other's type
3537 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3539 "Can not compute type of conditional expression " +
3540 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3541 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3542 "' convert implicitly to each other");
3547 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3551 Error (173, "The type of the conditional expression can " +
3552 "not be computed because there is no implicit conversion" +
3553 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3554 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3559 if (expr is BoolConstant){
3560 BoolConstant bc = (BoolConstant) expr;
3571 public override void Emit (EmitContext ec)
3573 ILGenerator ig = ec.ig;
3574 Label false_target = ig.DefineLabel ();
3575 Label end_target = ig.DefineLabel ();
3577 expr.EmitBranchable (ec, false_target, false);
3579 ig.Emit (OpCodes.Br, end_target);
3580 ig.MarkLabel (false_target);
3581 falseExpr.Emit (ec);
3582 ig.MarkLabel (end_target);
3590 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3591 public readonly string Name;
3592 public readonly Block Block;
3593 public LocalInfo local_info;
3596 LocalTemporary temp;
3598 public LocalVariableReference (Block block, string name, Location l)
3603 eclass = ExprClass.Variable;
3607 // Setting `is_readonly' to false will allow you to create a writable
3608 // reference to a read-only variable. This is used by foreach and using.
3610 public LocalVariableReference (Block block, string name, Location l,
3611 LocalInfo local_info, bool is_readonly)
3612 : this (block, name, l)
3614 this.local_info = local_info;
3615 this.is_readonly = is_readonly;
3618 public VariableInfo VariableInfo {
3620 return local_info.VariableInfo;
3624 public bool IsReadOnly {
3630 protected Expression DoResolveBase (EmitContext ec, Expression lvalue_right_side)
3632 if (local_info == null) {
3633 local_info = Block.GetLocalInfo (Name);
3636 if (lvalue_right_side == EmptyExpression.Null)
3637 local_info.Used = true;
3639 is_readonly = local_info.ReadOnly;
3642 type = local_info.VariableType;
3644 VariableInfo variable_info = local_info.VariableInfo;
3645 if (lvalue_right_side != null){
3647 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3651 if (variable_info != null)
3652 variable_info.SetAssigned (ec);
3655 Expression e = Block.GetConstantExpression (Name);
3657 local_info.Used = true;
3658 eclass = ExprClass.Value;
3659 return e.Resolve (ec);
3662 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3665 if (lvalue_right_side == null)
3666 local_info.Used = true;
3668 if (ec.CurrentAnonymousMethod != null){
3670 // If we are referencing a variable from the external block
3671 // flag it for capturing
3673 if (local_info.Block.Toplevel != ec.CurrentBlock.Toplevel){
3674 if (local_info.AddressTaken){
3675 AnonymousMethod.Error_AddressOfCapturedVar (local_info.Name, loc);
3678 ec.CaptureVariable (local_info);
3685 public override Expression DoResolve (EmitContext ec)
3687 return DoResolveBase (ec, null);
3690 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3692 Expression ret = DoResolveBase (ec, right_side);
3694 CheckObsoleteAttribute (ret.Type);
3699 public bool VerifyFixed (bool is_expression)
3701 return !is_expression || local_info.IsFixed;
3704 public override void Emit (EmitContext ec)
3706 ILGenerator ig = ec.ig;
3708 if (local_info.FieldBuilder == null){
3710 // A local variable on the local CLR stack
3712 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3715 // A local variable captured by anonymous methods.
3718 ec.EmitCapturedVariableInstance (local_info);
3720 ig.Emit (OpCodes.Ldfld, local_info.FieldBuilder);
3724 public void Emit (EmitContext ec, bool leave_copy)
3728 ec.ig.Emit (OpCodes.Dup);
3729 if (local_info.FieldBuilder != null){
3730 temp = new LocalTemporary (ec, Type);
3736 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3738 ILGenerator ig = ec.ig;
3739 prepared = prepare_for_load;
3741 if (local_info.FieldBuilder == null){
3743 // A local variable on the local CLR stack
3745 if (local_info.LocalBuilder == null)
3746 throw new Exception ("This should not happen: both Field and Local are null");
3750 ec.ig.Emit (OpCodes.Dup);
3751 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3754 // A local variable captured by anonymous methods or itereators.
3756 ec.EmitCapturedVariableInstance (local_info);
3758 if (prepare_for_load)
3759 ig.Emit (OpCodes.Dup);
3762 ig.Emit (OpCodes.Dup);
3763 temp = new LocalTemporary (ec, Type);
3766 ig.Emit (OpCodes.Stfld, local_info.FieldBuilder);
3772 public void AddressOf (EmitContext ec, AddressOp mode)
3774 ILGenerator ig = ec.ig;
3776 if (local_info.FieldBuilder == null){
3778 // A local variable on the local CLR stack
3780 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3783 // A local variable captured by anonymous methods or iterators
3785 ec.EmitCapturedVariableInstance (local_info);
3786 ig.Emit (OpCodes.Ldflda, local_info.FieldBuilder);
3790 public override string ToString ()
3792 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3797 /// This represents a reference to a parameter in the intermediate
3800 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3806 public Parameter.Modifier mod;
3807 public bool is_ref, is_out, prepared;
3821 LocalTemporary temp;
3823 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3830 eclass = ExprClass.Variable;
3833 public VariableInfo VariableInfo {
3837 public bool VerifyFixed (bool is_expression)
3839 return !is_expression || TypeManager.IsValueType (type);
3842 public bool IsAssigned (EmitContext ec, Location loc)
3844 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsAssigned (vi))
3847 Report.Error (165, loc,
3848 "Use of unassigned parameter `" + name + "'");
3852 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3854 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3857 Report.Error (170, loc,
3858 "Use of possibly unassigned field `" + field_name + "'");
3862 public void SetAssigned (EmitContext ec)
3864 if (is_out && ec.DoFlowAnalysis)
3865 ec.CurrentBranching.SetAssigned (vi);
3868 public void SetFieldAssigned (EmitContext ec, string field_name)
3870 if (is_out && ec.DoFlowAnalysis)
3871 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3874 protected void DoResolveBase (EmitContext ec)
3876 type = pars.GetParameterInfo (ec, idx, out mod);
3877 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3878 is_out = (mod & Parameter.Modifier.OUT) != 0;
3879 eclass = ExprClass.Variable;
3882 vi = block.ParameterMap [idx];
3884 if (ec.CurrentAnonymousMethod != null){
3886 Report.Error (1628, Location,
3887 "Can not reference a ref or out parameter in an anonymous method");
3892 // If we are referencing the parameter from the external block
3893 // flag it for capturing
3895 //Console.WriteLine ("Is parameter `{0}' local? {1}", name, block.IsLocalParameter (name));
3896 if (!block.IsLocalParameter (name)){
3897 ec.CaptureParameter (name, type, idx);
3903 // Notice that for ref/out parameters, the type exposed is not the
3904 // same type exposed externally.
3907 // externally we expose "int&"
3908 // here we expose "int".
3910 // We record this in "is_ref". This means that the type system can treat
3911 // the type as it is expected, but when we generate the code, we generate
3912 // the alternate kind of code.
3914 public override Expression DoResolve (EmitContext ec)
3918 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3921 if (ec.RemapToProxy)
3922 return ec.RemapParameter (idx);
3927 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3933 if (ec.RemapToProxy)
3934 return ec.RemapParameterLValue (idx, right_side);
3939 static public void EmitLdArg (ILGenerator ig, int x)
3943 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3944 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3945 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3946 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3947 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3950 ig.Emit (OpCodes.Ldarg, x);
3954 // This method is used by parameters that are references, that are
3955 // being passed as references: we only want to pass the pointer (that
3956 // is already stored in the parameter, not the address of the pointer,
3957 // and not the value of the variable).
3959 public void EmitLoad (EmitContext ec)
3961 ILGenerator ig = ec.ig;
3967 EmitLdArg (ig, arg_idx);
3970 // FIXME: Review for anonymous methods
3974 public override void Emit (EmitContext ec)
3976 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
3977 ec.EmitParameter (name);
3984 public void Emit (EmitContext ec, bool leave_copy)
3986 ILGenerator ig = ec.ig;
3992 EmitLdArg (ig, arg_idx);
3996 ec.ig.Emit (OpCodes.Dup);
3999 // If we are a reference, we loaded on the stack a pointer
4000 // Now lets load the real value
4002 LoadFromPtr (ig, type);
4006 ec.ig.Emit (OpCodes.Dup);
4009 temp = new LocalTemporary (ec, type);
4015 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
4017 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4018 ec.EmitAssignParameter (name, source, leave_copy, prepare_for_load);
4022 ILGenerator ig = ec.ig;
4025 prepared = prepare_for_load;
4030 if (is_ref && !prepared)
4031 EmitLdArg (ig, arg_idx);
4036 ec.ig.Emit (OpCodes.Dup);
4040 temp = new LocalTemporary (ec, type);
4044 StoreFromPtr (ig, type);
4050 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
4052 ig.Emit (OpCodes.Starg, arg_idx);
4056 public void AddressOf (EmitContext ec, AddressOp mode)
4058 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4059 ec.EmitAddressOfParameter (name);
4070 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
4072 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
4075 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
4077 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
4084 /// Used for arguments to New(), Invocation()
4086 public class Argument {
4087 public enum AType : byte {
4092 //FIXME: These two are mbas specific and the
4093 // related changes need to be propagated
4098 public readonly AType ArgType;
4099 public Expression Expr;
4101 public Argument (Expression expr, AType type)
4104 this.ArgType = type;
4107 public Argument (Expression expr)
4110 this.ArgType = AType.Expression;
4115 if (ArgType == AType.Ref || ArgType == AType.Out)
4116 return TypeManager.GetReferenceType (Expr.Type);
4122 public Parameter.Modifier GetParameterModifier ()
4126 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
4129 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
4132 return Parameter.Modifier.NONE;
4136 public static string FullDesc (Argument a)
4138 if (a.ArgType == AType.ArgList)
4141 return (a.ArgType == AType.Ref ? "ref " :
4142 (a.ArgType == AType.Out ? "out " : "")) +
4143 TypeManager.CSharpName (a.Expr.Type);
4146 public bool ResolveMethodGroup (EmitContext ec, Location loc)
4148 ConstructedType ctype = Expr as ConstructedType;
4150 Expr = ctype.GetSimpleName (ec);
4152 // FIXME: csc doesn't report any error if you try to use `ref' or
4153 // `out' in a delegate creation expression.
4154 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4161 public bool Resolve (EmitContext ec, Location loc)
4163 if (ArgType == AType.Ref) {
4164 Expr = Expr.Resolve (ec);
4168 if (!ec.IsConstructor) {
4169 FieldExpr fe = Expr as FieldExpr;
4170 if (fe != null && fe.FieldInfo.IsInitOnly) {
4171 if (fe.FieldInfo.IsStatic)
4172 Report.Error (199, loc, "A static readonly field cannot be passed ref or out (except in a static constructor)");
4174 Report.Error (192, loc, "A readonly field cannot be passed ref or out (except in a constructor)");
4178 Expr = Expr.ResolveLValue (ec, Expr);
4179 } else if (ArgType == AType.Out)
4180 Expr = Expr.ResolveLValue (ec, EmptyExpression.Null);
4182 Expr = Expr.Resolve (ec);
4187 if (ArgType == AType.Expression)
4191 // Catch errors where fields of a MarshalByRefObject are passed as ref or out
4192 // This is only allowed for `this'
4194 FieldExpr fe = Expr as FieldExpr;
4195 if (fe != null && !fe.IsStatic){
4196 Expression instance = fe.InstanceExpression;
4198 if (instance.GetType () != typeof (This)){
4199 if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
4200 Report.SymbolRelatedToPreviousError (fe.InstanceExpression.Type);
4201 Report.Error (197, loc, "Cannot pass '{0}' as ref or out or take its address because it is a member of a marshal-by-reference class",
4209 if (Expr.eclass != ExprClass.Variable){
4211 // We just probe to match the CSC output
4213 if (Expr.eclass == ExprClass.PropertyAccess ||
4214 Expr.eclass == ExprClass.IndexerAccess){
4217 "A property or indexer can not be passed as an out or ref " +
4222 "An lvalue is required as an argument to out or ref");
4230 public void Emit (EmitContext ec)
4233 // Ref and Out parameters need to have their addresses taken.
4235 // ParameterReferences might already be references, so we want
4236 // to pass just the value
4238 if (ArgType == AType.Ref || ArgType == AType.Out){
4239 AddressOp mode = AddressOp.Store;
4241 if (ArgType == AType.Ref)
4242 mode |= AddressOp.Load;
4244 if (Expr is ParameterReference){
4245 ParameterReference pr = (ParameterReference) Expr;
4251 pr.AddressOf (ec, mode);
4254 ((IMemoryLocation)Expr).AddressOf (ec, mode);
4262 /// Invocation of methods or delegates.
4264 public class Invocation : ExpressionStatement {
4265 public readonly ArrayList Arguments;
4267 public Expression expr;
4268 MethodBase method = null;
4270 static Hashtable method_parameter_cache;
4272 static Invocation ()
4274 method_parameter_cache = new PtrHashtable ();
4278 // arguments is an ArrayList, but we do not want to typecast,
4279 // as it might be null.
4281 // FIXME: only allow expr to be a method invocation or a
4282 // delegate invocation (7.5.5)
4284 public Invocation (Expression expr, ArrayList arguments, Location l)
4287 Arguments = arguments;
4291 public Expression Expr {
4298 /// Returns the Parameters (a ParameterData interface) for the
4301 public static ParameterData GetParameterData (MethodBase mb)
4303 object pd = method_parameter_cache [mb];
4307 return (ParameterData) pd;
4309 ip = TypeManager.LookupParametersByBuilder (mb);
4311 method_parameter_cache [mb] = ip;
4313 return (ParameterData) ip;
4315 ReflectionParameters rp = new ReflectionParameters (mb);
4316 method_parameter_cache [mb] = rp;
4318 return (ParameterData) rp;
4323 /// Determines "better conversion" as specified in 7.4.2.3
4325 /// Returns : p if a->p is better,
4326 /// q if a->q is better,
4327 /// null if neither is better
4329 static Type BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
4331 Type argument_type = TypeManager.TypeToCoreType (a.Type);
4332 Expression argument_expr = a.Expr;
4334 // p = TypeManager.TypeToCoreType (p);
4335 // q = TypeManager.TypeToCoreType (q);
4337 if (argument_type == null)
4338 throw new Exception ("Expression of type " + a.Expr +
4339 " does not resolve its type");
4341 if (p == null || q == null)
4342 throw new InternalErrorException ("BetterConversion Got a null conversion");
4347 if (argument_expr is NullLiteral) {
4349 // If the argument is null and one of the types to compare is 'object' and
4350 // the other is a reference type, we prefer the other.
4352 // This follows from the usual rules:
4353 // * There is an implicit conversion from 'null' to type 'object'
4354 // * There is an implicit conversion from 'null' to any reference type
4355 // * There is an implicit conversion from any reference type to type 'object'
4356 // * There is no implicit conversion from type 'object' to other reference types
4357 // => Conversion of 'null' to a reference type is better than conversion to 'object'
4359 // FIXME: This probably isn't necessary, since the type of a NullLiteral is the
4360 // null type. I think it used to be 'object' and thus needed a special
4361 // case to avoid the immediately following two checks.
4363 if (!p.IsValueType && q == TypeManager.object_type)
4365 if (!q.IsValueType && p == TypeManager.object_type)
4369 if (argument_type == p)
4372 if (argument_type == q)
4375 Expression p_tmp = new EmptyExpression (p);
4376 Expression q_tmp = new EmptyExpression (q);
4378 bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
4379 bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
4381 if (p_to_q && !q_to_p)
4384 if (q_to_p && !p_to_q)
4387 if (p == TypeManager.sbyte_type)
4388 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4389 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4391 if (q == TypeManager.sbyte_type)
4392 if (p == TypeManager.byte_type || p == TypeManager.ushort_type ||
4393 p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4396 if (p == TypeManager.short_type)
4397 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4398 q == TypeManager.uint64_type)
4401 if (q == TypeManager.short_type)
4402 if (p == TypeManager.ushort_type || p == TypeManager.uint32_type ||
4403 p == TypeManager.uint64_type)
4406 if (p == TypeManager.int32_type)
4407 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4410 if (q == TypeManager.int32_type)
4411 if (p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4414 if (p == TypeManager.int64_type)
4415 if (q == TypeManager.uint64_type)
4417 if (q == TypeManager.int64_type)
4418 if (p == TypeManager.uint64_type)
4425 /// Determines "Better function" between candidate
4426 /// and the current best match
4429 /// Returns a boolean indicating :
4430 /// false if candidate ain't better
4431 /// true if candidate is better than the current best match
4433 static bool BetterFunction (EmitContext ec, ArrayList args, int argument_count,
4434 MethodBase candidate, bool candidate_params,
4435 MethodBase best, bool best_params, Location loc)
4437 ParameterData candidate_pd = GetParameterData (candidate);
4438 ParameterData best_pd = GetParameterData (best);
4440 int cand_count = candidate_pd.Count;
4443 // If there is no best method, than this one
4444 // is better, however, if we already found a
4445 // best method, we cant tell. This happens
4456 // interface IFooBar : IFoo, IBar {}
4458 // We cant tell if IFoo.DoIt is better than IBar.DoIt
4460 // However, we have to consider that
4461 // Trim (); is better than Trim (params char[] chars);
4463 if (cand_count == 0 && argument_count == 0)
4464 return !candidate_params && best_params;
4466 if ((candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS) &&
4467 (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.ARGLIST))
4468 if (cand_count != argument_count)
4471 bool better_at_least_one = false;
4472 bool is_equal = true;
4474 for (int j = 0; j < argument_count; ++j) {
4475 Argument a = (Argument) args [j];
4477 Type ct = TypeManager.TypeToCoreType (candidate_pd.ParameterType (j));
4478 Type bt = TypeManager.TypeToCoreType (best_pd.ParameterType (j));
4480 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4481 if (candidate_params)
4482 ct = TypeManager.GetElementType (ct);
4484 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4486 bt = TypeManager.GetElementType (bt);
4488 if (!ct.Equals (bt))
4491 Type better = BetterConversion (ec, a, ct, bt, loc);
4492 // for each argument, the conversion to 'ct' should be no worse than
4493 // the conversion to 'bt'.
4497 // for at least one argument, the conversion to 'ct' should be better than
4498 // the conversion to 'bt'.
4500 better_at_least_one = true;
4504 // If a method (in the normal form) with the
4505 // same signature as the expanded form of the
4506 // current best params method already exists,
4507 // the expanded form is not applicable so we
4508 // force it to select the candidate
4510 if (!candidate_params && best_params && cand_count == argument_count)
4514 // If two methods have equal parameter types, but
4515 // only one of them is generic, the non-generic one wins.
4518 if (TypeManager.IsGenericMethod (best) && !TypeManager.IsGenericMethod (candidate))
4520 else if (!TypeManager.IsGenericMethod (best) && TypeManager.IsGenericMethod (candidate))
4524 return better_at_least_one;
4527 public static string FullMethodDesc (MethodBase mb)
4529 string ret_type = "";
4534 if (mb is MethodInfo)
4535 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
4537 StringBuilder sb = new StringBuilder (ret_type);
4539 sb.Append (mb.ReflectedType.ToString ());
4541 sb.Append (mb.Name);
4543 ParameterData pd = GetParameterData (mb);
4545 int count = pd.Count;
4548 for (int i = count; i > 0; ) {
4551 sb.Append (pd.ParameterDesc (count - i - 1));
4557 return sb.ToString ();
4560 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4562 MemberInfo [] miset;
4563 MethodGroupExpr union;
4568 return (MethodGroupExpr) mg2;
4571 return (MethodGroupExpr) mg1;
4574 MethodGroupExpr left_set = null, right_set = null;
4575 int length1 = 0, length2 = 0;
4577 left_set = (MethodGroupExpr) mg1;
4578 length1 = left_set.Methods.Length;
4580 right_set = (MethodGroupExpr) mg2;
4581 length2 = right_set.Methods.Length;
4583 ArrayList common = new ArrayList ();
4585 foreach (MethodBase r in right_set.Methods){
4586 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
4590 miset = new MemberInfo [length1 + length2 - common.Count];
4591 left_set.Methods.CopyTo (miset, 0);
4595 foreach (MethodBase r in right_set.Methods) {
4596 if (!common.Contains (r))
4600 union = new MethodGroupExpr (miset, loc);
4605 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4606 ArrayList arguments, int arg_count,
4607 ref MethodBase candidate)
4609 return IsParamsMethodApplicable (
4610 ec, me, arguments, arg_count, false, ref candidate) ||
4611 IsParamsMethodApplicable (
4612 ec, me, arguments, arg_count, true, ref candidate);
4617 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4618 ArrayList arguments, int arg_count,
4619 bool do_varargs, ref MethodBase candidate)
4621 if (!me.HasTypeArguments &&
4622 !TypeManager.InferParamsTypeArguments (ec, arguments, ref candidate))
4625 return IsParamsMethodApplicable (
4626 ec, arguments, arg_count, candidate, do_varargs);
4630 /// Determines if the candidate method, if a params method, is applicable
4631 /// in its expanded form to the given set of arguments
4633 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
4634 int arg_count, MethodBase candidate,
4637 ParameterData pd = GetParameterData (candidate);
4639 int pd_count = pd.Count;
4644 int count = pd_count - 1;
4646 if (pd.ParameterModifier (count) != Parameter.Modifier.ARGLIST)
4648 if (pd_count != arg_count)
4651 if (pd.ParameterModifier (count) != Parameter.Modifier.PARAMS)
4655 if (count > arg_count)
4658 if (pd_count == 1 && arg_count == 0)
4662 // If we have come this far, the case which
4663 // remains is when the number of parameters is
4664 // less than or equal to the argument count.
4666 for (int i = 0; i < count; ++i) {
4668 Argument a = (Argument) arguments [i];
4670 Parameter.Modifier a_mod = a.GetParameterModifier () &
4671 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4672 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4673 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4675 if (a_mod == p_mod) {
4677 if (a_mod == Parameter.Modifier.NONE)
4678 if (!Convert.ImplicitConversionExists (ec,
4680 pd.ParameterType (i)))
4683 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4684 Type pt = pd.ParameterType (i);
4687 pt = TypeManager.GetReferenceType (pt);
4698 Argument a = (Argument) arguments [count];
4699 if (!(a.Expr is Arglist))
4705 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4707 for (int i = pd_count - 1; i < arg_count; i++) {
4708 Argument a = (Argument) arguments [i];
4710 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4717 static bool IsApplicable (EmitContext ec, MethodGroupExpr me,
4718 ArrayList arguments, int arg_count,
4719 ref MethodBase candidate)
4721 if (!me.HasTypeArguments &&
4722 !TypeManager.InferTypeArguments (ec, arguments, ref candidate))
4725 return IsApplicable (ec, arguments, arg_count, candidate);
4729 /// Determines if the candidate method is applicable (section 14.4.2.1)
4730 /// to the given set of arguments
4732 static bool IsApplicable (EmitContext ec, ArrayList arguments, int arg_count,
4733 MethodBase candidate)
4735 ParameterData pd = GetParameterData (candidate);
4737 if (arg_count != pd.Count)
4740 for (int i = arg_count; i > 0; ) {
4743 Argument a = (Argument) arguments [i];
4745 Parameter.Modifier a_mod = a.GetParameterModifier () &
4746 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4747 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4748 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4751 if (a_mod == p_mod ||
4752 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4753 if (a_mod == Parameter.Modifier.NONE) {
4754 if (!Convert.ImplicitConversionExists (ec,
4756 pd.ParameterType (i)))
4760 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4761 Type pt = pd.ParameterType (i);
4764 pt = TypeManager.GetReferenceType (pt);
4776 static private bool IsAncestralType (Type first_type, Type second_type)
4778 return first_type != second_type &&
4779 (second_type.IsSubclassOf (first_type) ||
4780 TypeManager.ImplementsInterface (second_type, first_type));
4784 /// Find the Applicable Function Members (7.4.2.1)
4786 /// me: Method Group expression with the members to select.
4787 /// it might contain constructors or methods (or anything
4788 /// that maps to a method).
4790 /// Arguments: ArrayList containing resolved Argument objects.
4792 /// loc: The location if we want an error to be reported, or a Null
4793 /// location for "probing" purposes.
4795 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4796 /// that is the best match of me on Arguments.
4799 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4800 ArrayList Arguments, bool may_fail,
4803 MethodBase method = null;
4804 bool method_params = false;
4805 Type applicable_type = null;
4807 ArrayList candidates = new ArrayList ();
4810 // Used to keep a map between the candidate
4811 // and whether it is being considered in its
4812 // normal or expanded form
4814 // false is normal form, true is expanded form
4816 Hashtable candidate_to_form = null;
4818 if (Arguments != null)
4819 arg_count = Arguments.Count;
4822 if ((me.Name == "Invoke") &&
4823 TypeManager.IsDelegateType (me.DeclaringType)) {
4824 Error_InvokeOnDelegate (loc);
4829 MethodBase[] methods = me.Methods;
4832 // First we construct the set of applicable methods
4834 bool is_sorted = true;
4835 for (int i = 0; i < methods.Length; i++){
4836 Type decl_type = methods [i].DeclaringType;
4839 // If we have already found an applicable method
4840 // we eliminate all base types (Section 14.5.5.1)
4842 if ((applicable_type != null) &&
4843 IsAncestralType (decl_type, applicable_type))
4847 // Check if candidate is applicable (section 14.4.2.1)
4848 // Is candidate applicable in normal form?
4850 bool is_applicable = IsApplicable (
4851 ec, me, Arguments, arg_count, ref methods [i]);
4853 if (!is_applicable &&
4854 (IsParamsMethodApplicable (
4855 ec, me, Arguments, arg_count, ref methods [i]))) {
4856 MethodBase candidate = methods [i];
4857 if (candidate_to_form == null)
4858 candidate_to_form = new PtrHashtable ();
4859 candidate_to_form [candidate] = candidate;
4860 // Candidate is applicable in expanded form
4861 is_applicable = true;
4867 candidates.Add (methods [i]);
4869 if (applicable_type == null)
4870 applicable_type = decl_type;
4871 else if (applicable_type != decl_type) {
4873 if (IsAncestralType (applicable_type, decl_type))
4874 applicable_type = decl_type;
4878 int candidate_top = candidates.Count;
4880 if (candidate_top == 0) {
4882 // Okay so we have failed to find anything so we
4883 // return by providing info about the closest match
4885 for (int i = 0; i < methods.Length; ++i) {
4886 MethodBase c = (MethodBase) methods [i];
4887 ParameterData pd = GetParameterData (c);
4889 if (pd.Count != arg_count)
4892 if (!TypeManager.InferTypeArguments (ec, Arguments, ref c))
4895 VerifyArgumentsCompat (ec, Arguments, arg_count,
4896 c, false, null, may_fail, loc);
4901 string report_name = me.Name;
4902 if (report_name == ".ctor")
4903 report_name = me.DeclaringType.ToString ();
4905 for (int i = 0; i < methods.Length; ++i) {
4906 MethodBase c = methods [i];
4907 ParameterData pd = GetParameterData (c);
4909 if (pd.Count != arg_count)
4912 if (TypeManager.InferTypeArguments (ec, Arguments, ref c))
4916 411, loc, "The type arguments for " +
4917 "method `{0}' cannot be infered from " +
4918 "the usage. Try specifying the type " +
4919 "arguments explicitly.", report_name);
4923 Error_WrongNumArguments (
4924 loc, report_name, arg_count);
4933 // At this point, applicable_type is _one_ of the most derived types
4934 // in the set of types containing the methods in this MethodGroup.
4935 // Filter the candidates so that they only contain methods from the
4936 // most derived types.
4939 int finalized = 0; // Number of finalized candidates
4942 // Invariant: applicable_type is a most derived type
4944 // We'll try to complete Section 14.5.5.1 for 'applicable_type' by
4945 // eliminating all it's base types. At the same time, we'll also move
4946 // every unrelated type to the end of the array, and pick the next
4947 // 'applicable_type'.
4949 Type next_applicable_type = null;
4950 int j = finalized; // where to put the next finalized candidate
4951 int k = finalized; // where to put the next undiscarded candidate
4952 for (int i = finalized; i < candidate_top; ++i) {
4953 Type decl_type = ((MethodBase) candidates[i]).DeclaringType;
4955 if (decl_type == applicable_type) {
4956 candidates[k++] = candidates[j];
4957 candidates[j++] = candidates[i];
4961 if (IsAncestralType (decl_type, applicable_type))
4964 if (next_applicable_type != null &&
4965 IsAncestralType (decl_type, next_applicable_type))
4968 candidates[k++] = candidates[i];
4970 if (next_applicable_type == null ||
4971 IsAncestralType (next_applicable_type, decl_type))
4972 next_applicable_type = decl_type;
4975 applicable_type = next_applicable_type;
4978 } while (applicable_type != null);
4982 // Now we actually find the best method
4985 method = (MethodBase) candidates[0];
4986 method_params = candidate_to_form != null && candidate_to_form.Contains (method);
4987 for (int ix = 1; ix < candidate_top; ix++){
4988 MethodBase candidate = (MethodBase) candidates [ix];
4989 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4991 if (BetterFunction (ec, Arguments, arg_count,
4992 candidate, cand_params,
4993 method, method_params, loc)) {
4995 method_params = cand_params;
5000 // Now check that there are no ambiguities i.e the selected method
5001 // should be better than all the others
5003 bool ambiguous = false;
5004 for (int ix = 0; ix < candidate_top; ix++){
5005 MethodBase candidate = (MethodBase) candidates [ix];
5007 if (candidate == method)
5010 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
5011 if (!BetterFunction (ec, Arguments, arg_count,
5012 method, method_params,
5013 candidate, cand_params,
5015 Report.SymbolRelatedToPreviousError (candidate);
5021 Report.SymbolRelatedToPreviousError (method);
5022 Report.Error (121, loc, "Ambiguous call when selecting function due to implicit casts");
5027 // And now check if the arguments are all
5028 // compatible, perform conversions if
5029 // necessary etc. and return if everything is
5032 if (!VerifyArgumentsCompat (ec, Arguments, arg_count, method,
5033 method_params, null, may_fail, loc))
5039 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
5041 Report.Error (1501, loc,
5042 "No overload for method `" + name + "' takes `" +
5043 arg_count + "' arguments");
5046 static void Error_InvokeOnDelegate (Location loc)
5048 Report.Error (1533, loc,
5049 "Invoke cannot be called directly on a delegate");
5052 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
5053 Type delegate_type, string arg_sig, string par_desc)
5055 if (delegate_type == null)
5056 Report.Error (1502, loc,
5057 "The best overloaded match for method '" +
5058 FullMethodDesc (method) +
5059 "' has some invalid arguments");
5061 Report.Error (1594, loc,
5062 "Delegate '" + delegate_type.ToString () +
5063 "' has some invalid arguments.");
5064 Report.Error (1503, loc,
5065 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
5066 idx, arg_sig, par_desc));
5069 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
5070 int arg_count, MethodBase method,
5071 bool chose_params_expanded,
5072 Type delegate_type, bool may_fail,
5075 ParameterData pd = GetParameterData (method);
5076 int pd_count = pd.Count;
5078 for (int j = 0; j < arg_count; j++) {
5079 Argument a = (Argument) Arguments [j];
5080 Expression a_expr = a.Expr;
5081 Type parameter_type = pd.ParameterType (j);
5082 Parameter.Modifier pm = pd.ParameterModifier (j);
5084 if (pm == Parameter.Modifier.PARAMS){
5085 if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
5087 Error_InvalidArguments (
5088 loc, j, method, delegate_type,
5089 Argument.FullDesc (a), pd.ParameterDesc (j));
5093 if (chose_params_expanded)
5094 parameter_type = TypeManager.GetElementType (parameter_type);
5095 } else if (pm == Parameter.Modifier.ARGLIST){
5101 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
5103 Error_InvalidArguments (
5104 loc, j, method, delegate_type,
5105 Argument.FullDesc (a), pd.ParameterDesc (j));
5113 if (!TypeManager.IsEqual (a.Type, parameter_type)){
5116 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
5120 Error_InvalidArguments (
5121 loc, j, method, delegate_type,
5122 Argument.FullDesc (a), pd.ParameterDesc (j));
5127 // Update the argument with the implicit conversion
5133 if (parameter_type.IsPointer){
5140 Parameter.Modifier a_mod = a.GetParameterModifier () &
5141 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5142 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
5143 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5145 if (a_mod != p_mod &&
5146 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
5148 Report.Error (1502, loc,
5149 "The best overloaded match for method '" + FullMethodDesc (method)+
5150 "' has some invalid arguments");
5151 Report.Error (1503, loc,
5152 "Argument " + (j+1) +
5153 ": Cannot convert from '" + Argument.FullDesc (a)
5154 + "' to '" + pd.ParameterDesc (j) + "'");
5164 public override Expression DoResolve (EmitContext ec)
5167 // First, resolve the expression that is used to
5168 // trigger the invocation
5170 if (expr is ConstructedType)
5171 expr = ((ConstructedType) expr).GetSimpleName (ec);
5173 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
5177 if (!(expr is MethodGroupExpr)) {
5178 Type expr_type = expr.Type;
5180 if (expr_type != null){
5181 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
5183 return (new DelegateInvocation (
5184 this.expr, Arguments, loc)).Resolve (ec);
5188 if (!(expr is MethodGroupExpr)){
5189 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup, loc);
5194 // Next, evaluate all the expressions in the argument list
5196 if (Arguments != null){
5197 foreach (Argument a in Arguments){
5198 if (!a.Resolve (ec, loc))
5203 MethodGroupExpr mg = (MethodGroupExpr) expr;
5204 method = OverloadResolve (ec, mg, Arguments, false, loc);
5209 MethodInfo mi = method as MethodInfo;
5211 type = TypeManager.TypeToCoreType (mi.ReturnType);
5212 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null)) {
5213 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
5217 Expression iexpr = mg.InstanceExpression;
5218 if (mi.IsStatic && (iexpr != null) && !(iexpr is This)) {
5219 if (mg.IdenticalTypeName)
5220 mg.InstanceExpression = null;
5222 MemberAccess.error176 (loc, mi.Name);
5228 if (type.IsPointer){
5236 // Only base will allow this invocation to happen.
5238 if (mg.IsBase && method.IsAbstract){
5239 Report.Error (205, loc, "Cannot call an abstract base member: " +
5240 FullMethodDesc (method));
5244 if (method.Name == "Finalize" && Arguments == null) {
5246 Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
5248 Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
5252 if ((method.Attributes & MethodAttributes.SpecialName) != 0){
5253 if (TypeManager.LookupDeclSpace (method.DeclaringType) != null || TypeManager.IsSpecialMethod (method)) {
5254 Report.Error (571, loc, TypeManager.CSharpSignature (method) + ": can not call operator or accessor");
5259 if (mg.InstanceExpression != null)
5260 mg.InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
5262 eclass = ExprClass.Value;
5267 // Emits the list of arguments as an array
5269 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
5271 ILGenerator ig = ec.ig;
5272 int count = arguments.Count - idx;
5273 Argument a = (Argument) arguments [idx];
5274 Type t = a.Expr.Type;
5276 IntConstant.EmitInt (ig, count);
5277 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
5279 int top = arguments.Count;
5280 for (int j = idx; j < top; j++){
5281 a = (Argument) arguments [j];
5283 ig.Emit (OpCodes.Dup);
5284 IntConstant.EmitInt (ig, j - idx);
5286 bool is_stobj, has_type_arg;
5287 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj, out has_type_arg);
5289 ig.Emit (OpCodes.Ldelema, t);
5301 /// Emits a list of resolved Arguments that are in the arguments
5304 /// The MethodBase argument might be null if the
5305 /// emission of the arguments is known not to contain
5306 /// a `params' field (for example in constructors or other routines
5307 /// that keep their arguments in this structure)
5309 /// if `dup_args' is true, a copy of the arguments will be left
5310 /// on the stack. If `dup_args' is true, you can specify `this_arg'
5311 /// which will be duplicated before any other args. Only EmitCall
5312 /// should be using this interface.
5314 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments, bool dup_args, LocalTemporary this_arg)
5318 pd = GetParameterData (mb);
5322 LocalTemporary [] temps = null;
5325 temps = new LocalTemporary [arguments.Count];
5328 // If we are calling a params method with no arguments, special case it
5330 if (arguments == null){
5331 if (pd != null && pd.Count > 0 &&
5332 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
5333 ILGenerator ig = ec.ig;
5335 IntConstant.EmitInt (ig, 0);
5336 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
5342 int top = arguments.Count;
5344 for (int i = 0; i < top; i++){
5345 Argument a = (Argument) arguments [i];
5348 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
5350 // Special case if we are passing the same data as the
5351 // params argument, do not put it in an array.
5353 if (pd.ParameterType (i) == a.Type)
5356 EmitParams (ec, i, arguments);
5363 ec.ig.Emit (OpCodes.Dup);
5364 (temps [i] = new LocalTemporary (ec, a.Type)).Store (ec);
5369 if (this_arg != null)
5372 for (int i = 0; i < top; i ++)
5373 temps [i].Emit (ec);
5376 if (pd != null && pd.Count > top &&
5377 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
5378 ILGenerator ig = ec.ig;
5380 IntConstant.EmitInt (ig, 0);
5381 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
5385 static Type[] GetVarargsTypes (EmitContext ec, MethodBase mb,
5386 ArrayList arguments)
5388 ParameterData pd = GetParameterData (mb);
5390 if (arguments == null)
5391 return new Type [0];
5393 Argument a = (Argument) arguments [pd.Count - 1];
5394 Arglist list = (Arglist) a.Expr;
5396 return list.ArgumentTypes;
5400 /// This checks the ConditionalAttribute on the method
5402 static bool IsMethodExcluded (MethodBase method, EmitContext ec)
5404 if (method.IsConstructor)
5407 IMethodData md = TypeManager.GetMethod (method);
5409 return md.IsExcluded (ec);
5411 // For some methods (generated by delegate class) GetMethod returns null
5412 // because they are not included in builder_to_method table
5413 if (method.DeclaringType is TypeBuilder)
5416 return AttributeTester.IsConditionalMethodExcluded (method);
5420 /// is_base tells whether we want to force the use of the `call'
5421 /// opcode instead of using callvirt. Call is required to call
5422 /// a specific method, while callvirt will always use the most
5423 /// recent method in the vtable.
5425 /// is_static tells whether this is an invocation on a static method
5427 /// instance_expr is an expression that represents the instance
5428 /// it must be non-null if is_static is false.
5430 /// method is the method to invoke.
5432 /// Arguments is the list of arguments to pass to the method or constructor.
5434 public static void EmitCall (EmitContext ec, bool is_base,
5435 bool is_static, Expression instance_expr,
5436 MethodBase method, ArrayList Arguments, Location loc)
5438 EmitCall (ec, is_base, is_static, instance_expr, method, Arguments, loc, false, false);
5441 // `dup_args' leaves an extra copy of the arguments on the stack
5442 // `omit_args' does not leave any arguments at all.
5443 // So, basically, you could make one call with `dup_args' set to true,
5444 // and then another with `omit_args' set to true, and the two calls
5445 // would have the same set of arguments. However, each argument would
5446 // only have been evaluated once.
5447 public static void EmitCall (EmitContext ec, bool is_base,
5448 bool is_static, Expression instance_expr,
5449 MethodBase method, ArrayList Arguments, Location loc,
5450 bool dup_args, bool omit_args)
5452 ILGenerator ig = ec.ig;
5453 bool struct_call = false;
5454 bool this_call = false;
5455 LocalTemporary this_arg = null;
5457 Type decl_type = method.DeclaringType;
5459 if (!RootContext.StdLib) {
5460 // Replace any calls to the system's System.Array type with calls to
5461 // the newly created one.
5462 if (method == TypeManager.system_int_array_get_length)
5463 method = TypeManager.int_array_get_length;
5464 else if (method == TypeManager.system_int_array_get_rank)
5465 method = TypeManager.int_array_get_rank;
5466 else if (method == TypeManager.system_object_array_clone)
5467 method = TypeManager.object_array_clone;
5468 else if (method == TypeManager.system_int_array_get_length_int)
5469 method = TypeManager.int_array_get_length_int;
5470 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5471 method = TypeManager.int_array_get_lower_bound_int;
5472 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5473 method = TypeManager.int_array_get_upper_bound_int;
5474 else if (method == TypeManager.system_void_array_copyto_array_int)
5475 method = TypeManager.void_array_copyto_array_int;
5478 if (ec.TestObsoleteMethodUsage) {
5480 // This checks ObsoleteAttribute on the method and on the declaring type
5482 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
5484 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
5486 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
5488 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
5492 if (IsMethodExcluded (method, ec))
5496 this_call = instance_expr == null;
5497 if (decl_type.IsValueType || (!this_call && instance_expr.Type.IsValueType))
5501 // If this is ourselves, push "this"
5506 ig.Emit (OpCodes.Ldarg_0);
5509 Type iexpr_type = instance_expr.Type;
5512 // Push the instance expression
5514 if (TypeManager.IsValueType (iexpr_type)) {
5516 // Special case: calls to a function declared in a
5517 // reference-type with a value-type argument need
5518 // to have their value boxed.
5519 if (decl_type.IsValueType ||
5520 iexpr_type.IsGenericParameter) {
5522 // If the expression implements IMemoryLocation, then
5523 // we can optimize and use AddressOf on the
5526 // If not we have to use some temporary storage for
5528 if (instance_expr is IMemoryLocation) {
5529 ((IMemoryLocation)instance_expr).
5530 AddressOf (ec, AddressOp.LoadStore);
5532 LocalTemporary temp = new LocalTemporary (ec, iexpr_type);
5533 instance_expr.Emit (ec);
5535 temp.AddressOf (ec, AddressOp.Load);
5538 // avoid the overhead of doing this all the time.
5540 t = TypeManager.GetReferenceType (iexpr_type);
5542 instance_expr.Emit (ec);
5543 ig.Emit (OpCodes.Box, instance_expr.Type);
5544 t = TypeManager.object_type;
5547 instance_expr.Emit (ec);
5548 t = instance_expr.Type;
5553 this_arg = new LocalTemporary (ec, t);
5554 ig.Emit (OpCodes.Dup);
5555 this_arg.Store (ec);
5561 EmitArguments (ec, method, Arguments, dup_args, this_arg);
5563 if ((instance_expr != null) && (instance_expr.Type.IsGenericParameter))
5564 ig.Emit (OpCodes.Constrained, instance_expr.Type);
5567 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
5568 call_op = OpCodes.Call;
5570 call_op = OpCodes.Callvirt;
5572 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
5573 Type[] varargs_types = GetVarargsTypes (ec, method, Arguments);
5574 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
5581 // and DoFoo is not virtual, you can omit the callvirt,
5582 // because you don't need the null checking behavior.
5584 if (method is MethodInfo)
5585 ig.Emit (call_op, (MethodInfo) method);
5587 ig.Emit (call_op, (ConstructorInfo) method);
5590 public override void Emit (EmitContext ec)
5592 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5594 EmitCall (ec, mg.IsBase, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5597 public override void EmitStatement (EmitContext ec)
5602 // Pop the return value if there is one
5604 if (method is MethodInfo){
5605 Type ret = ((MethodInfo)method).ReturnType;
5606 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5607 ec.ig.Emit (OpCodes.Pop);
5612 public class InvocationOrCast : ExpressionStatement
5615 Expression argument;
5617 public InvocationOrCast (Expression expr, Expression argument, Location loc)
5620 this.argument = argument;
5624 public override Expression DoResolve (EmitContext ec)
5627 // First try to resolve it as a cast.
5629 TypeExpr te = expr.ResolveAsTypeStep (ec) as TypeExpr;
5630 if ((te != null) && (te.eclass == ExprClass.Type)) {
5631 Cast cast = new Cast (te, argument, loc);
5632 return cast.Resolve (ec);
5636 // This can either be a type or a delegate invocation.
5637 // Let's just resolve it and see what we'll get.
5639 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5644 // Ok, so it's a Cast.
5646 if (expr.eclass == ExprClass.Type) {
5647 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
5648 return cast.Resolve (ec);
5652 // It's a delegate invocation.
5654 if (!TypeManager.IsDelegateType (expr.Type)) {
5655 Error (149, "Method name expected");
5659 ArrayList args = new ArrayList ();
5660 args.Add (new Argument (argument, Argument.AType.Expression));
5661 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5662 return invocation.Resolve (ec);
5667 Error (201, "Only assignment, call, increment, decrement and new object " +
5668 "expressions can be used as a statement");
5671 public override ExpressionStatement ResolveStatement (EmitContext ec)
5674 // First try to resolve it as a cast.
5676 TypeExpr te = expr.ResolveAsTypeStep (ec) as TypeExpr;
5677 if ((te != null) && (te.eclass == ExprClass.Type)) {
5683 // This can either be a type or a delegate invocation.
5684 // Let's just resolve it and see what we'll get.
5686 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5687 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5693 // It's a delegate invocation.
5695 if (!TypeManager.IsDelegateType (expr.Type)) {
5696 Error (149, "Method name expected");
5700 ArrayList args = new ArrayList ();
5701 args.Add (new Argument (argument, Argument.AType.Expression));
5702 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5703 return invocation.ResolveStatement (ec);
5706 public override void Emit (EmitContext ec)
5708 throw new Exception ("Cannot happen");
5711 public override void EmitStatement (EmitContext ec)
5713 throw new Exception ("Cannot happen");
5718 // This class is used to "disable" the code generation for the
5719 // temporary variable when initializing value types.
5721 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5722 public void AddressOf (EmitContext ec, AddressOp Mode)
5729 /// Implements the new expression
5731 public class New : ExpressionStatement, IMemoryLocation {
5732 public readonly ArrayList Arguments;
5735 // During bootstrap, it contains the RequestedType,
5736 // but if `type' is not null, it *might* contain a NewDelegate
5737 // (because of field multi-initialization)
5739 public Expression RequestedType;
5741 MethodBase method = null;
5744 // If set, the new expression is for a value_target, and
5745 // we will not leave anything on the stack.
5747 Expression value_target;
5748 bool value_target_set = false;
5749 bool is_type_parameter = false;
5751 public New (Expression requested_type, ArrayList arguments, Location l)
5753 RequestedType = requested_type;
5754 Arguments = arguments;
5758 public bool SetValueTypeVariable (Expression value)
5760 value_target = value;
5761 value_target_set = true;
5762 if (!(value_target is IMemoryLocation)){
5763 Error_UnexpectedKind ("variable", loc);
5770 // This function is used to disable the following code sequence for
5771 // value type initialization:
5773 // AddressOf (temporary)
5777 // Instead the provide will have provided us with the address on the
5778 // stack to store the results.
5780 static Expression MyEmptyExpression;
5782 public void DisableTemporaryValueType ()
5784 if (MyEmptyExpression == null)
5785 MyEmptyExpression = new EmptyAddressOf ();
5788 // To enable this, look into:
5789 // test-34 and test-89 and self bootstrapping.
5791 // For instance, we can avoid a copy by using `newobj'
5792 // instead of Call + Push-temp on value types.
5793 // value_target = MyEmptyExpression;
5796 public override Expression DoResolve (EmitContext ec)
5799 // The New DoResolve might be called twice when initializing field
5800 // expressions (see EmitFieldInitializers, the call to
5801 // GetInitializerExpression will perform a resolve on the expression,
5802 // and later the assign will trigger another resolution
5804 // This leads to bugs (#37014)
5807 if (RequestedType is NewDelegate)
5808 return RequestedType;
5812 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec);
5820 CheckObsoleteAttribute (type);
5822 bool IsDelegate = TypeManager.IsDelegateType (type);
5825 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5826 if (RequestedType != null)
5827 if (!(RequestedType is DelegateCreation))
5828 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
5829 return RequestedType;
5832 if (type.IsGenericParameter) {
5833 if (!TypeManager.HasConstructorConstraint (type)) {
5834 Error (304, String.Format (
5835 "Cannot create an instance of the " +
5836 "variable type '{0}' because it " +
5837 "doesn't have the new() constraint",
5842 if ((Arguments != null) && (Arguments.Count != 0)) {
5843 Error (417, String.Format (
5844 "`{0}': cannot provide arguments " +
5845 "when creating an instance of a " +
5846 "variable type.", type));
5850 is_type_parameter = true;
5851 eclass = ExprClass.Value;
5855 if (type.IsInterface || type.IsAbstract){
5856 Error (144, "It is not possible to create instances of interfaces or abstract classes");
5860 if (type.IsAbstract && type.IsSealed) {
5861 Report.Error (712, loc, "Cannot create an instance of the static class '{0}'", TypeManager.CSharpName (type));
5865 bool is_struct = type.IsValueType;
5866 eclass = ExprClass.Value;
5869 // SRE returns a match for .ctor () on structs (the object constructor),
5870 // so we have to manually ignore it.
5872 if (is_struct && Arguments == null)
5876 ml = MemberLookupFinal (ec, type, type, ".ctor",
5877 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
5878 MemberTypes.Constructor,
5879 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5884 if (! (ml is MethodGroupExpr)){
5886 ml.Error_UnexpectedKind ("method group", loc);
5892 if (Arguments != null){
5893 foreach (Argument a in Arguments){
5894 if (!a.Resolve (ec, loc))
5899 method = Invocation.OverloadResolve (
5900 ec, (MethodGroupExpr) ml, Arguments, false, loc);
5904 if (method == null) {
5905 if (!is_struct || Arguments.Count > 0) {
5906 Error (1501, String.Format (
5907 "New invocation: Can not find a constructor in `{0}' for this argument list",
5908 TypeManager.CSharpName (type)));
5916 bool DoEmitTypeParameter (EmitContext ec)
5918 ILGenerator ig = ec.ig;
5920 ig.Emit (OpCodes.Ldtoken, type);
5921 ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
5922 ig.Emit (OpCodes.Call, TypeManager.activator_create_instance);
5923 ig.Emit (OpCodes.Unbox_Any, type);
5929 // This DoEmit can be invoked in two contexts:
5930 // * As a mechanism that will leave a value on the stack (new object)
5931 // * As one that wont (init struct)
5933 // You can control whether a value is required on the stack by passing
5934 // need_value_on_stack. The code *might* leave a value on the stack
5935 // so it must be popped manually
5937 // If we are dealing with a ValueType, we have a few
5938 // situations to deal with:
5940 // * The target is a ValueType, and we have been provided
5941 // the instance (this is easy, we are being assigned).
5943 // * The target of New is being passed as an argument,
5944 // to a boxing operation or a function that takes a
5947 // In this case, we need to create a temporary variable
5948 // that is the argument of New.
5950 // Returns whether a value is left on the stack
5952 bool DoEmit (EmitContext ec, bool need_value_on_stack)
5954 bool is_value_type = TypeManager.IsValueType (type);
5955 ILGenerator ig = ec.ig;
5960 // Allow DoEmit() to be called multiple times.
5961 // We need to create a new LocalTemporary each time since
5962 // you can't share LocalBuilders among ILGeneators.
5963 if (!value_target_set)
5964 value_target = new LocalTemporary (ec, type);
5966 ml = (IMemoryLocation) value_target;
5967 ml.AddressOf (ec, AddressOp.Store);
5971 Invocation.EmitArguments (ec, method, Arguments, false, null);
5975 ig.Emit (OpCodes.Initobj, type);
5977 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5978 if (need_value_on_stack){
5979 value_target.Emit (ec);
5984 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
5989 public override void Emit (EmitContext ec)
5991 if (is_type_parameter)
5992 DoEmitTypeParameter (ec);
5997 public override void EmitStatement (EmitContext ec)
5999 if (is_type_parameter)
6000 throw new InvalidOperationException ();
6002 if (DoEmit (ec, false))
6003 ec.ig.Emit (OpCodes.Pop);
6006 public void AddressOf (EmitContext ec, AddressOp Mode)
6008 if (is_type_parameter)
6009 throw new InvalidOperationException ();
6011 if (!type.IsValueType){
6013 // We throw an exception. So far, I believe we only need to support
6015 // foreach (int j in new StructType ())
6018 throw new Exception ("AddressOf should not be used for classes");
6021 if (!value_target_set)
6022 value_target = new LocalTemporary (ec, type);
6024 IMemoryLocation ml = (IMemoryLocation) value_target;
6025 ml.AddressOf (ec, AddressOp.Store);
6027 Invocation.EmitArguments (ec, method, Arguments, false, null);
6030 ec.ig.Emit (OpCodes.Initobj, type);
6032 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6034 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
6039 /// 14.5.10.2: Represents an array creation expression.
6043 /// There are two possible scenarios here: one is an array creation
6044 /// expression that specifies the dimensions and optionally the
6045 /// initialization data and the other which does not need dimensions
6046 /// specified but where initialization data is mandatory.
6048 public class ArrayCreation : Expression {
6049 Expression requested_base_type;
6050 ArrayList initializers;
6053 // The list of Argument types.
6054 // This is used to construct the `newarray' or constructor signature
6056 ArrayList arguments;
6059 // Method used to create the array object.
6061 MethodBase new_method = null;
6063 Type array_element_type;
6064 Type underlying_type;
6065 bool is_one_dimensional = false;
6066 bool is_builtin_type = false;
6067 bool expect_initializers = false;
6068 int num_arguments = 0;
6072 ArrayList array_data;
6077 // The number of array initializers that we can handle
6078 // via the InitializeArray method - through EmitStaticInitializers
6080 int num_automatic_initializers;
6082 const int max_automatic_initializers = 6;
6084 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
6086 this.requested_base_type = requested_base_type;
6087 this.initializers = initializers;
6091 arguments = new ArrayList ();
6093 foreach (Expression e in exprs) {
6094 arguments.Add (new Argument (e, Argument.AType.Expression));
6099 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
6101 this.requested_base_type = requested_base_type;
6102 this.initializers = initializers;
6106 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
6108 //string tmp = rank.Substring (rank.LastIndexOf ('['));
6110 //dimensions = tmp.Length - 1;
6111 expect_initializers = true;
6114 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
6116 StringBuilder sb = new StringBuilder (rank);
6119 for (int i = 1; i < idx_count; i++)
6124 return new ComposedCast (base_type, sb.ToString (), loc);
6127 void Error_IncorrectArrayInitializer ()
6129 Error (178, "Incorrectly structured array initializer");
6132 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
6134 if (specified_dims) {
6135 Argument a = (Argument) arguments [idx];
6137 if (!a.Resolve (ec, loc))
6140 if (!(a.Expr is Constant)) {
6141 Error (150, "A constant value is expected");
6145 int value = (int) ((Constant) a.Expr).GetValue ();
6147 if (value != probe.Count) {
6148 Error_IncorrectArrayInitializer ();
6152 bounds [idx] = value;
6155 int child_bounds = -1;
6156 foreach (object o in probe) {
6157 if (o is ArrayList) {
6158 int current_bounds = ((ArrayList) o).Count;
6160 if (child_bounds == -1)
6161 child_bounds = current_bounds;
6163 else if (child_bounds != current_bounds){
6164 Error_IncorrectArrayInitializer ();
6167 if (specified_dims && (idx + 1 >= arguments.Count)){
6168 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
6172 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
6176 if (child_bounds != -1){
6177 Error_IncorrectArrayInitializer ();
6181 Expression tmp = (Expression) o;
6182 tmp = tmp.Resolve (ec);
6186 // Console.WriteLine ("I got: " + tmp);
6187 // Handle initialization from vars, fields etc.
6189 Expression conv = Convert.ImplicitConversionRequired (
6190 ec, tmp, underlying_type, loc);
6195 if (conv is StringConstant || conv is DecimalConstant || conv is NullCast) {
6196 // These are subclasses of Constant that can appear as elements of an
6197 // array that cannot be statically initialized (with num_automatic_initializers
6198 // > max_automatic_initializers), so num_automatic_initializers should be left as zero.
6199 array_data.Add (conv);
6200 } else if (conv is Constant) {
6201 // These are the types of Constant that can appear in arrays that can be
6202 // statically allocated.
6203 array_data.Add (conv);
6204 num_automatic_initializers++;
6206 array_data.Add (conv);
6213 public void UpdateIndices (EmitContext ec)
6216 for (ArrayList probe = initializers; probe != null;) {
6217 if (probe.Count > 0 && probe [0] is ArrayList) {
6218 Expression e = new IntConstant (probe.Count);
6219 arguments.Add (new Argument (e, Argument.AType.Expression));
6221 bounds [i++] = probe.Count;
6223 probe = (ArrayList) probe [0];
6226 Expression e = new IntConstant (probe.Count);
6227 arguments.Add (new Argument (e, Argument.AType.Expression));
6229 bounds [i++] = probe.Count;
6236 public bool ValidateInitializers (EmitContext ec, Type array_type)
6238 if (initializers == null) {
6239 if (expect_initializers)
6245 if (underlying_type == null)
6249 // We use this to store all the date values in the order in which we
6250 // will need to store them in the byte blob later
6252 array_data = new ArrayList ();
6253 bounds = new Hashtable ();
6257 if (arguments != null) {
6258 ret = CheckIndices (ec, initializers, 0, true);
6261 arguments = new ArrayList ();
6263 ret = CheckIndices (ec, initializers, 0, false);
6270 if (arguments.Count != dimensions) {
6271 Error_IncorrectArrayInitializer ();
6280 // Converts `source' to an int, uint, long or ulong.
6282 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
6286 bool old_checked = ec.CheckState;
6287 ec.CheckState = true;
6289 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
6290 if (target == null){
6291 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
6292 if (target == null){
6293 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
6294 if (target == null){
6295 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
6297 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
6301 ec.CheckState = old_checked;
6304 // Only positive constants are allowed at compile time
6306 if (target is Constant){
6307 if (target is IntConstant){
6308 if (((IntConstant) target).Value < 0){
6309 Expression.Error_NegativeArrayIndex (loc);
6314 if (target is LongConstant){
6315 if (((LongConstant) target).Value < 0){
6316 Expression.Error_NegativeArrayIndex (loc);
6327 // Creates the type of the array
6329 bool LookupType (EmitContext ec)
6331 StringBuilder array_qualifier = new StringBuilder (rank);
6334 // `In the first form allocates an array instace of the type that results
6335 // from deleting each of the individual expression from the expression list'
6337 if (num_arguments > 0) {
6338 array_qualifier.Append ("[");
6339 for (int i = num_arguments-1; i > 0; i--)
6340 array_qualifier.Append (",");
6341 array_qualifier.Append ("]");
6347 TypeExpr array_type_expr;
6348 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
6349 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec);
6350 if (array_type_expr == null)
6353 type = array_type_expr.Type;
6355 if (!type.IsArray) {
6356 Error (622, "Can only use array initializer expressions to assign to array types. Try using a new expression instead.");
6359 underlying_type = TypeManager.GetElementType (type);
6360 dimensions = type.GetArrayRank ();
6365 public override Expression DoResolve (EmitContext ec)
6369 if (!LookupType (ec))
6373 // First step is to validate the initializers and fill
6374 // in any missing bits
6376 if (!ValidateInitializers (ec, type))
6379 if (arguments == null)
6382 arg_count = arguments.Count;
6383 foreach (Argument a in arguments){
6384 if (!a.Resolve (ec, loc))
6387 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
6388 if (real_arg == null)
6395 array_element_type = TypeManager.GetElementType (type);
6397 if (array_element_type.IsAbstract && array_element_type.IsSealed) {
6398 Report.Error (719, loc, "'{0}': array elements cannot be of static type", TypeManager.CSharpName (array_element_type));
6402 if (arg_count == 1) {
6403 is_one_dimensional = true;
6404 eclass = ExprClass.Value;
6408 is_builtin_type = TypeManager.IsBuiltinType (type);
6410 if (is_builtin_type) {
6413 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
6414 AllBindingFlags, loc);
6416 if (!(ml is MethodGroupExpr)) {
6417 ml.Error_UnexpectedKind ("method group", loc);
6422 Error (-6, "New invocation: Can not find a constructor for " +
6423 "this argument list");
6427 new_method = Invocation.OverloadResolve (
6428 ec, (MethodGroupExpr) ml, arguments, false, loc);
6430 if (new_method == null) {
6431 Error (-6, "New invocation: Can not find a constructor for " +
6432 "this argument list");
6436 eclass = ExprClass.Value;
6439 ModuleBuilder mb = CodeGen.Module.Builder;
6440 ArrayList args = new ArrayList ();
6442 if (arguments != null) {
6443 for (int i = 0; i < arg_count; i++)
6444 args.Add (TypeManager.int32_type);
6447 Type [] arg_types = null;
6450 arg_types = new Type [args.Count];
6452 args.CopyTo (arg_types, 0);
6454 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
6457 if (new_method == null) {
6458 Error (-6, "New invocation: Can not find a constructor for " +
6459 "this argument list");
6463 eclass = ExprClass.Value;
6468 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
6473 int count = array_data.Count;
6475 if (underlying_type.IsEnum)
6476 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
6478 factor = GetTypeSize (underlying_type);
6480 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
6482 data = new byte [(count * factor + 4) & ~3];
6485 for (int i = 0; i < count; ++i) {
6486 object v = array_data [i];
6488 if (v is EnumConstant)
6489 v = ((EnumConstant) v).Child;
6491 if (v is Constant && !(v is StringConstant))
6492 v = ((Constant) v).GetValue ();
6498 if (underlying_type == TypeManager.int64_type){
6499 if (!(v is Expression)){
6500 long val = (long) v;
6502 for (int j = 0; j < factor; ++j) {
6503 data [idx + j] = (byte) (val & 0xFF);
6507 } else if (underlying_type == TypeManager.uint64_type){
6508 if (!(v is Expression)){
6509 ulong val = (ulong) v;
6511 for (int j = 0; j < factor; ++j) {
6512 data [idx + j] = (byte) (val & 0xFF);
6516 } else if (underlying_type == TypeManager.float_type) {
6517 if (!(v is Expression)){
6518 element = BitConverter.GetBytes ((float) v);
6520 for (int j = 0; j < factor; ++j)
6521 data [idx + j] = element [j];
6523 } else if (underlying_type == TypeManager.double_type) {
6524 if (!(v is Expression)){
6525 element = BitConverter.GetBytes ((double) v);
6527 for (int j = 0; j < factor; ++j)
6528 data [idx + j] = element [j];
6530 } else if (underlying_type == TypeManager.char_type){
6531 if (!(v is Expression)){
6532 int val = (int) ((char) v);
6534 data [idx] = (byte) (val & 0xff);
6535 data [idx+1] = (byte) (val >> 8);
6537 } else if (underlying_type == TypeManager.short_type){
6538 if (!(v is Expression)){
6539 int val = (int) ((short) v);
6541 data [idx] = (byte) (val & 0xff);
6542 data [idx+1] = (byte) (val >> 8);
6544 } else if (underlying_type == TypeManager.ushort_type){
6545 if (!(v is Expression)){
6546 int val = (int) ((ushort) v);
6548 data [idx] = (byte) (val & 0xff);
6549 data [idx+1] = (byte) (val >> 8);
6551 } else if (underlying_type == TypeManager.int32_type) {
6552 if (!(v is Expression)){
6555 data [idx] = (byte) (val & 0xff);
6556 data [idx+1] = (byte) ((val >> 8) & 0xff);
6557 data [idx+2] = (byte) ((val >> 16) & 0xff);
6558 data [idx+3] = (byte) (val >> 24);
6560 } else if (underlying_type == TypeManager.uint32_type) {
6561 if (!(v is Expression)){
6562 uint val = (uint) v;
6564 data [idx] = (byte) (val & 0xff);
6565 data [idx+1] = (byte) ((val >> 8) & 0xff);
6566 data [idx+2] = (byte) ((val >> 16) & 0xff);
6567 data [idx+3] = (byte) (val >> 24);
6569 } else if (underlying_type == TypeManager.sbyte_type) {
6570 if (!(v is Expression)){
6571 sbyte val = (sbyte) v;
6572 data [idx] = (byte) val;
6574 } else if (underlying_type == TypeManager.byte_type) {
6575 if (!(v is Expression)){
6576 byte val = (byte) v;
6577 data [idx] = (byte) val;
6579 } else if (underlying_type == TypeManager.bool_type) {
6580 if (!(v is Expression)){
6581 bool val = (bool) v;
6582 data [idx] = (byte) (val ? 1 : 0);
6584 } else if (underlying_type == TypeManager.decimal_type){
6585 if (!(v is Expression)){
6586 int [] bits = Decimal.GetBits ((decimal) v);
6589 // FIXME: For some reason, this doesn't work on the MS runtime.
6590 int [] nbits = new int [4];
6591 nbits [0] = bits [3];
6592 nbits [1] = bits [2];
6593 nbits [2] = bits [0];
6594 nbits [3] = bits [1];
6596 for (int j = 0; j < 4; j++){
6597 data [p++] = (byte) (nbits [j] & 0xff);
6598 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6599 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6600 data [p++] = (byte) (nbits [j] >> 24);
6604 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6613 // Emits the initializers for the array
6615 void EmitStaticInitializers (EmitContext ec)
6618 // First, the static data
6621 ILGenerator ig = ec.ig;
6623 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6625 fb = RootContext.MakeStaticData (data);
6627 ig.Emit (OpCodes.Dup);
6628 ig.Emit (OpCodes.Ldtoken, fb);
6629 ig.Emit (OpCodes.Call,
6630 TypeManager.void_initializearray_array_fieldhandle);
6634 // Emits pieces of the array that can not be computed at compile
6635 // time (variables and string locations).
6637 // This always expect the top value on the stack to be the array
6639 void EmitDynamicInitializers (EmitContext ec)
6641 ILGenerator ig = ec.ig;
6642 int dims = bounds.Count;
6643 int [] current_pos = new int [dims];
6644 int top = array_data.Count;
6646 MethodInfo set = null;
6650 ModuleBuilder mb = null;
6651 mb = CodeGen.Module.Builder;
6652 args = new Type [dims + 1];
6655 for (j = 0; j < dims; j++)
6656 args [j] = TypeManager.int32_type;
6658 args [j] = array_element_type;
6660 set = mb.GetArrayMethod (
6662 CallingConventions.HasThis | CallingConventions.Standard,
6663 TypeManager.void_type, args);
6666 for (int i = 0; i < top; i++){
6668 Expression e = null;
6670 if (array_data [i] is Expression)
6671 e = (Expression) array_data [i];
6675 // Basically we do this for string literals and
6676 // other non-literal expressions
6678 if (e is EnumConstant){
6679 e = ((EnumConstant) e).Child;
6682 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6683 num_automatic_initializers <= max_automatic_initializers) {
6684 Type etype = e.Type;
6686 ig.Emit (OpCodes.Dup);
6688 for (int idx = 0; idx < dims; idx++)
6689 IntConstant.EmitInt (ig, current_pos [idx]);
6692 // If we are dealing with a struct, get the
6693 // address of it, so we can store it.
6696 etype.IsSubclassOf (TypeManager.value_type) &&
6697 (!TypeManager.IsBuiltinOrEnum (etype) ||
6698 etype == TypeManager.decimal_type)) {
6703 // Let new know that we are providing
6704 // the address where to store the results
6706 n.DisableTemporaryValueType ();
6709 ig.Emit (OpCodes.Ldelema, etype);
6715 bool is_stobj, has_type_arg;
6716 OpCode op = ArrayAccess.GetStoreOpcode (
6717 etype, out is_stobj,
6720 ig.Emit (OpCodes.Stobj, etype);
6721 else if (has_type_arg)
6722 ig.Emit (op, etype);
6726 ig.Emit (OpCodes.Call, set);
6733 for (int j = dims - 1; j >= 0; j--){
6735 if (current_pos [j] < (int) bounds [j])
6737 current_pos [j] = 0;
6742 void EmitArrayArguments (EmitContext ec)
6744 ILGenerator ig = ec.ig;
6746 foreach (Argument a in arguments) {
6747 Type atype = a.Type;
6750 if (atype == TypeManager.uint64_type)
6751 ig.Emit (OpCodes.Conv_Ovf_U4);
6752 else if (atype == TypeManager.int64_type)
6753 ig.Emit (OpCodes.Conv_Ovf_I4);
6757 public override void Emit (EmitContext ec)
6759 ILGenerator ig = ec.ig;
6761 EmitArrayArguments (ec);
6762 if (is_one_dimensional)
6763 ig.Emit (OpCodes.Newarr, array_element_type);
6765 if (is_builtin_type)
6766 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6768 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6771 if (initializers != null){
6773 // FIXME: Set this variable correctly.
6775 bool dynamic_initializers = true;
6777 // This will never be true for array types that cannot be statically
6778 // initialized. num_automatic_initializers will always be zero. See
6780 if (num_automatic_initializers > max_automatic_initializers)
6781 EmitStaticInitializers (ec);
6783 if (dynamic_initializers)
6784 EmitDynamicInitializers (ec);
6788 public object EncodeAsAttribute ()
6790 if (!is_one_dimensional){
6791 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6795 if (array_data == null){
6796 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6800 object [] ret = new object [array_data.Count];
6802 foreach (Expression e in array_data){
6805 if (e is NullLiteral)
6808 if (!Attribute.GetAttributeArgumentExpression (e, Location, array_element_type, out v))
6818 /// Represents the `this' construct
6820 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6823 VariableInfo variable_info;
6825 public This (Block block, Location loc)
6831 public This (Location loc)
6836 public VariableInfo VariableInfo {
6837 get { return variable_info; }
6840 public bool VerifyFixed (bool is_expression)
6842 if ((variable_info == null) || (variable_info.LocalInfo == null))
6845 return variable_info.LocalInfo.IsFixed;
6848 public bool ResolveBase (EmitContext ec)
6850 eclass = ExprClass.Variable;
6852 if (ec.TypeContainer.CurrentType != null)
6853 type = ec.TypeContainer.CurrentType;
6855 type = ec.ContainerType;
6858 Error (26, "Keyword this not valid in static code");
6862 if ((block != null) && (block.ThisVariable != null))
6863 variable_info = block.ThisVariable.VariableInfo;
6868 public override Expression DoResolve (EmitContext ec)
6870 if (!ResolveBase (ec))
6873 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
6874 Error (188, "The this object cannot be used before all " +
6875 "of its fields are assigned to");
6876 variable_info.SetAssigned (ec);
6880 if (ec.IsFieldInitializer) {
6881 Error (27, "Keyword `this' can't be used outside a constructor, " +
6882 "a method or a property.");
6889 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6891 if (!ResolveBase (ec))
6894 if (variable_info != null)
6895 variable_info.SetAssigned (ec);
6897 if (ec.TypeContainer is Class){
6898 Error (1604, "Cannot assign to `this'");
6905 public void Emit (EmitContext ec, bool leave_copy)
6909 ec.ig.Emit (OpCodes.Dup);
6912 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
6914 ILGenerator ig = ec.ig;
6916 if (ec.TypeContainer is Struct){
6920 ec.ig.Emit (OpCodes.Dup);
6921 ig.Emit (OpCodes.Stobj, type);
6923 throw new Exception ("how did you get here");
6927 public override void Emit (EmitContext ec)
6929 ILGenerator ig = ec.ig;
6932 if (ec.TypeContainer is Struct)
6933 ig.Emit (OpCodes.Ldobj, type);
6936 public void AddressOf (EmitContext ec, AddressOp mode)
6941 // FIGURE OUT WHY LDARG_S does not work
6943 // consider: struct X { int val; int P { set { val = value; }}}
6945 // Yes, this looks very bad. Look at `NOTAS' for
6947 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
6952 /// Represents the `__arglist' construct
6954 public class ArglistAccess : Expression
6956 public ArglistAccess (Location loc)
6961 public bool ResolveBase (EmitContext ec)
6963 eclass = ExprClass.Variable;
6964 type = TypeManager.runtime_argument_handle_type;
6968 public override Expression DoResolve (EmitContext ec)
6970 if (!ResolveBase (ec))
6973 if (ec.IsFieldInitializer || !ec.CurrentBlock.HasVarargs) {
6974 Error (190, "The __arglist construct is valid only within " +
6975 "a variable argument method.");
6982 public override void Emit (EmitContext ec)
6984 ec.ig.Emit (OpCodes.Arglist);
6989 /// Represents the `__arglist (....)' construct
6991 public class Arglist : Expression
6993 public readonly Argument[] Arguments;
6995 public Arglist (Argument[] args, Location l)
7001 public Type[] ArgumentTypes {
7003 Type[] retval = new Type [Arguments.Length];
7004 for (int i = 0; i < Arguments.Length; i++)
7005 retval [i] = Arguments [i].Type;
7010 public override Expression DoResolve (EmitContext ec)
7012 eclass = ExprClass.Variable;
7013 type = TypeManager.runtime_argument_handle_type;
7015 foreach (Argument arg in Arguments) {
7016 if (!arg.Resolve (ec, loc))
7023 public override void Emit (EmitContext ec)
7025 foreach (Argument arg in Arguments)
7031 // This produces the value that renders an instance, used by the iterators code
7033 public class ProxyInstance : Expression, IMemoryLocation {
7034 public override Expression DoResolve (EmitContext ec)
7036 eclass = ExprClass.Variable;
7037 type = ec.ContainerType;
7041 public override void Emit (EmitContext ec)
7043 ec.ig.Emit (OpCodes.Ldarg_0);
7047 public void AddressOf (EmitContext ec, AddressOp mode)
7049 ec.ig.Emit (OpCodes.Ldarg_0);
7054 /// Implements the typeof operator
7056 public class TypeOf : Expression {
7057 public Expression QueriedType;
7058 protected Type typearg;
7060 public TypeOf (Expression queried_type, Location l)
7062 QueriedType = queried_type;
7066 public override Expression DoResolve (EmitContext ec)
7068 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec);
7072 typearg = texpr.Type;
7074 if (typearg == TypeManager.void_type) {
7075 Error (673, "System.Void cannot be used from C# - " +
7076 "use typeof (void) to get the void type object");
7080 if (typearg.IsPointer && !ec.InUnsafe){
7084 CheckObsoleteAttribute (typearg);
7086 type = TypeManager.type_type;
7087 eclass = ExprClass.Type;
7091 public override void Emit (EmitContext ec)
7093 ec.ig.Emit (OpCodes.Ldtoken, typearg);
7094 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
7097 public Type TypeArg {
7098 get { return typearg; }
7103 /// Implements the `typeof (void)' operator
7105 public class TypeOfVoid : TypeOf {
7106 public TypeOfVoid (Location l) : base (null, l)
7111 public override Expression DoResolve (EmitContext ec)
7113 type = TypeManager.type_type;
7114 typearg = TypeManager.void_type;
7115 eclass = ExprClass.Type;
7121 /// Implements the sizeof expression
7123 public class SizeOf : Expression {
7124 public Expression QueriedType;
7127 public SizeOf (Expression queried_type, Location l)
7129 this.QueriedType = queried_type;
7133 public override Expression DoResolve (EmitContext ec)
7137 233, loc, "Sizeof may only be used in an unsafe context " +
7138 "(consider using System.Runtime.InteropServices.Marshal.SizeOf");
7142 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec);
7146 if (texpr is TypeParameterExpr){
7147 ((TypeParameterExpr)texpr).Error_CannotUseAsUnmanagedType (loc);
7151 type_queried = texpr.Type;
7153 CheckObsoleteAttribute (type_queried);
7155 if (!TypeManager.IsUnmanagedType (type_queried)){
7156 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
7160 type = TypeManager.int32_type;
7161 eclass = ExprClass.Value;
7165 public override void Emit (EmitContext ec)
7167 int size = GetTypeSize (type_queried);
7170 ec.ig.Emit (OpCodes.Sizeof, type_queried);
7172 IntConstant.EmitInt (ec.ig, size);
7177 /// Implements the member access expression
7179 public class MemberAccess : Expression {
7180 public string Identifier;
7181 protected Expression expr;
7182 protected TypeArguments args;
7184 public MemberAccess (Expression expr, string id, Location l)
7191 public MemberAccess (Expression expr, string id, TypeArguments args,
7193 : this (expr, id, l)
7198 public Expression Expr {
7204 public static void error176 (Location loc, string name)
7206 Report.Error (176, loc, "Static member `" +
7207 name + "' cannot be accessed " +
7208 "with an instance reference, qualify with a " +
7209 "type name instead");
7212 public static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Expression left, Location loc)
7214 SimpleName sn = left_original as SimpleName;
7215 if (sn == null || left == null || left.Type.Name != sn.Name)
7218 return RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc) != null;
7221 // TODO: possible optimalization
7222 // Cache resolved constant result in FieldBuilder <-> expresion map
7223 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
7224 Expression left, Location loc,
7225 Expression left_original)
7227 bool left_is_type, left_is_explicit;
7229 // If `left' is null, then we're called from SimpleNameResolve and this is
7230 // a member in the currently defining class.
7232 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
7233 left_is_explicit = false;
7235 // Implicitly default to `this' unless we're static.
7236 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
7237 left = ec.GetThis (loc);
7239 left_is_type = left is TypeExpr;
7240 left_is_explicit = true;
7243 if (member_lookup is FieldExpr){
7244 FieldExpr fe = (FieldExpr) member_lookup;
7245 FieldInfo fi = fe.FieldInfo.Mono_GetGenericFieldDefinition ();
7246 Type decl_type = fi.DeclaringType;
7248 bool is_emitted = fi is FieldBuilder;
7249 Type t = fi.FieldType;
7252 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
7256 if (!c.LookupConstantValue (out o))
7259 object real_value = ((Constant) c.Expr).GetValue ();
7261 return Constantify (real_value, t);
7265 // IsInitOnly is because of MS compatibility, I don't know why but they emit decimal constant as InitOnly
7266 if (fi.IsInitOnly && !is_emitted && t == TypeManager.decimal_type) {
7267 object[] attrs = fi.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
7268 if (attrs.Length == 1)
7269 return new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
7276 o = TypeManager.GetValue ((FieldBuilder) fi);
7278 o = fi.GetValue (fi);
7280 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
7281 if (left_is_explicit && !left_is_type &&
7282 !IdenticalNameAndTypeName (ec, left_original, member_lookup, loc)) {
7283 error176 (loc, fe.FieldInfo.Name);
7287 Expression enum_member = MemberLookup (
7288 ec, decl_type, "value__", MemberTypes.Field,
7289 AllBindingFlags, loc);
7291 Enum en = TypeManager.LookupEnum (decl_type);
7295 c = Constantify (o, en.UnderlyingType);
7297 c = Constantify (o, enum_member.Type);
7299 return new EnumConstant (c, decl_type);
7302 Expression exp = Constantify (o, t);
7304 if (left_is_explicit && !left_is_type) {
7305 error176 (loc, fe.FieldInfo.Name);
7312 if (t.IsPointer && !ec.InUnsafe){
7318 if (member_lookup is EventExpr) {
7319 EventExpr ee = (EventExpr) member_lookup;
7322 // If the event is local to this class, we transform ourselves into
7326 if (ee.EventInfo.DeclaringType == ec.ContainerType ||
7327 TypeManager.IsNestedChildOf(ec.ContainerType, ee.EventInfo.DeclaringType)) {
7328 MemberInfo mi = GetFieldFromEvent (ee);
7332 // If this happens, then we have an event with its own
7333 // accessors and private field etc so there's no need
7334 // to transform ourselves.
7336 ee.InstanceExpression = left;
7340 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
7343 Report.Error (-200, loc, "Internal error!!");
7347 if (!left_is_explicit)
7350 ee.InstanceExpression = left;
7352 return ResolveMemberAccess (ec, ml, left, loc, left_original);
7356 if (member_lookup is IMemberExpr) {
7357 IMemberExpr me = (IMemberExpr) member_lookup;
7358 MethodGroupExpr mg = me as MethodGroupExpr;
7361 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
7362 mg.IsExplicitImpl = left_is_explicit;
7365 if ((ec.IsFieldInitializer || ec.IsStatic) &&
7366 IdenticalNameAndTypeName (ec, left_original, member_lookup, loc))
7367 return member_lookup;
7369 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
7374 if (!me.IsInstance){
7375 if (IdenticalNameAndTypeName (ec, left_original, left, loc))
7376 return member_lookup;
7378 if (left_is_explicit) {
7379 error176 (loc, me.Name);
7385 // Since we can not check for instance objects in SimpleName,
7386 // becaue of the rule that allows types and variables to share
7387 // the name (as long as they can be de-ambiguated later, see
7388 // IdenticalNameAndTypeName), we have to check whether left
7389 // is an instance variable in a static context
7391 // However, if the left-hand value is explicitly given, then
7392 // it is already our instance expression, so we aren't in
7396 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
7397 IMemberExpr mexp = (IMemberExpr) left;
7399 if (!mexp.IsStatic){
7400 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
7405 if ((mg != null) && IdenticalNameAndTypeName (ec, left_original, left, loc))
7406 mg.IdenticalTypeName = true;
7408 me.InstanceExpression = left;
7411 return member_lookup;
7414 Console.WriteLine ("Left is: " + left);
7415 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
7416 Environment.Exit (1);
7420 public virtual Expression DoResolve (EmitContext ec, Expression right_side,
7424 throw new Exception ();
7427 // Resolve the expression with flow analysis turned off, we'll do the definite
7428 // assignment checks later. This is because we don't know yet what the expression
7429 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7430 // definite assignment check on the actual field and not on the whole struct.
7433 Expression original = expr;
7434 expr = expr.Resolve (ec, flags | ResolveFlags.Intermediate | ResolveFlags.DisableFlowAnalysis);
7438 if (expr is SimpleName){
7439 SimpleName child_expr = (SimpleName) expr;
7440 string fqname = DeclSpace.MakeFQN (child_expr.Name, Identifier);
7442 Expression new_expr;
7444 new_expr = new ConstructedType (fqname, args, loc);
7446 new_expr = new SimpleName (fqname, loc);
7448 return new_expr.Resolve (ec, flags);
7452 // TODO: I mailed Ravi about this, and apparently we can get rid
7453 // of this and put it in the right place.
7455 // Handle enums here when they are in transit.
7456 // Note that we cannot afford to hit MemberLookup in this case because
7457 // it will fail to find any members at all
7461 if (expr is TypeExpr){
7462 expr_type = expr.Type;
7464 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
7465 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", expr_type);
7469 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
7470 Enum en = TypeManager.LookupEnum (expr_type);
7473 object value = en.LookupEnumValue (ec, Identifier, loc);
7476 MemberCore mc = en.GetDefinition (Identifier);
7477 ObsoleteAttribute oa = mc.GetObsoleteAttribute (en);
7479 AttributeTester.Report_ObsoleteMessage (oa, mc.GetSignatureForError (), Location);
7481 oa = en.GetObsoleteAttribute (en);
7483 AttributeTester.Report_ObsoleteMessage (oa, en.GetSignatureForError (), Location);
7486 Constant c = Constantify (value, en.UnderlyingType);
7487 return new EnumConstant (c, expr_type);
7490 CheckObsoleteAttribute (expr_type);
7492 FieldInfo fi = expr_type.GetField (Identifier);
7494 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
7496 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), Location);
7501 expr_type = expr.Type;
7503 if (expr_type.IsPointer){
7504 Error (23, "The `.' operator can not be applied to pointer operands (" +
7505 TypeManager.CSharpName (expr_type) + ")");
7509 int errors = Report.Errors;
7511 Expression member_lookup;
7512 member_lookup = MemberLookup (
7513 ec, expr_type, expr_type, Identifier, loc);
7514 if ((member_lookup == null) && (args != null)) {
7515 string lookup_id = MemberName.MakeName (Identifier, args);
7516 member_lookup = MemberLookup (
7517 ec, expr_type, expr_type, lookup_id, loc);
7519 if (member_lookup == null) {
7520 MemberLookupFailed (
7521 ec, expr_type, expr_type, Identifier, null, loc);
7525 if (member_lookup is TypeExpr) {
7526 if (!(expr is TypeExpr) && !(expr is SimpleName)) {
7527 Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
7528 member_lookup.Type + "' instead");
7532 return member_lookup;
7536 string full_name = expr_type + "." + Identifier;
7538 if (member_lookup is FieldExpr) {
7539 Report.Error (307, loc, "The field `{0}' cannot " +
7540 "be used with type arguments", full_name);
7542 } else if (member_lookup is EventExpr) {
7543 Report.Error (307, loc, "The event `{0}' cannot " +
7544 "be used with type arguments", full_name);
7546 } else if (member_lookup is PropertyExpr) {
7547 Report.Error (307, loc, "The property `{0}' cannot " +
7548 "be used with type arguments", full_name);
7553 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
7554 if (member_lookup == null)
7558 MethodGroupExpr mg = member_lookup as MethodGroupExpr;
7560 throw new InternalErrorException ();
7562 return mg.ResolveGeneric (ec, args);
7565 // The following DoResolve/DoResolveLValue will do the definite assignment
7568 if (right_side != null)
7569 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
7571 member_lookup = member_lookup.DoResolve (ec);
7573 return member_lookup;
7576 public override Expression DoResolve (EmitContext ec)
7578 return DoResolve (ec, null, ResolveFlags.VariableOrValue |
7579 ResolveFlags.SimpleName | ResolveFlags.Type);
7582 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7584 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
7585 ResolveFlags.SimpleName | ResolveFlags.Type);
7588 public override Expression ResolveAsTypeStep (EmitContext ec)
7590 string fname = null;
7591 MemberAccess full_expr = this;
7592 while (full_expr != null) {
7594 fname = String.Concat (full_expr.Identifier, ".", fname);
7596 fname = full_expr.Identifier;
7598 fname = MemberName.MakeName (fname, args);
7600 if (full_expr.Expr is SimpleName) {
7601 string full_name = String.Concat (((SimpleName) full_expr.Expr).Name, ".", fname);
7602 Type fully_qualified = ec.DeclSpace.FindType (loc, full_name);
7603 if (fully_qualified != null) {
7605 return new TypeExpression (fully_qualified, loc);
7607 ConstructedType ctype = new ConstructedType (fully_qualified, args, loc);
7608 return ctype.ResolveAsTypeStep (ec);
7612 full_expr = full_expr.Expr as MemberAccess;
7615 Expression new_expr = expr.ResolveAsTypeStep (ec);
7617 if (new_expr == null)
7620 if (new_expr is SimpleName){
7621 SimpleName child_expr = (SimpleName) new_expr;
7622 string fqname = DeclSpace.MakeFQN (child_expr.Name, Identifier);
7625 new_expr = new ConstructedType (fqname, args, loc);
7627 new_expr = new SimpleName (fqname, loc);
7629 return new_expr.ResolveAsTypeStep (ec);
7632 TypeExpr tnew_expr = new_expr.ResolveAsTypeTerminal (ec);
7633 if (tnew_expr == null)
7636 Type expr_type = tnew_expr.Type;
7638 if (expr_type.IsPointer){
7639 Error (23, "The `.' operator can not be applied to pointer operands (" +
7640 TypeManager.CSharpName (expr_type) + ")");
7644 Expression member_lookup;
7646 lookup_id = MemberName.MakeName (Identifier, args);
7647 member_lookup = MemberLookupFinal (
7648 ec, expr_type, expr_type, lookup_id, loc);
7649 if (member_lookup == null)
7652 TypeExpr texpr = member_lookup as TypeExpr;
7656 texpr = texpr.ResolveAsTypeTerminal (ec);
7660 TypeArguments the_args = args;
7661 if (TypeManager.HasGenericArguments (expr_type)) {
7662 Type[] decl_args = TypeManager.GetTypeArguments (expr_type);
7664 TypeArguments new_args = new TypeArguments (loc);
7665 foreach (Type decl in decl_args)
7666 new_args.Add (new TypeExpression (decl, loc));
7669 new_args.Add (args);
7671 the_args = new_args;
7674 if (the_args != null) {
7675 ConstructedType ctype = new ConstructedType (texpr.Type, the_args, loc);
7676 return ctype.ResolveAsTypeStep (ec);
7682 public override void Emit (EmitContext ec)
7684 throw new Exception ("Should not happen");
7687 public override string ToString ()
7689 return expr + "." + MemberName.MakeName (Identifier, args);
7694 /// Implements checked expressions
7696 public class CheckedExpr : Expression {
7698 public Expression Expr;
7700 public CheckedExpr (Expression e, Location l)
7706 public override Expression DoResolve (EmitContext ec)
7708 bool last_check = ec.CheckState;
7709 bool last_const_check = ec.ConstantCheckState;
7711 ec.CheckState = true;
7712 ec.ConstantCheckState = true;
7713 Expr = Expr.Resolve (ec);
7714 ec.CheckState = last_check;
7715 ec.ConstantCheckState = last_const_check;
7720 if (Expr is Constant)
7723 eclass = Expr.eclass;
7728 public override void Emit (EmitContext ec)
7730 bool last_check = ec.CheckState;
7731 bool last_const_check = ec.ConstantCheckState;
7733 ec.CheckState = true;
7734 ec.ConstantCheckState = true;
7736 ec.CheckState = last_check;
7737 ec.ConstantCheckState = last_const_check;
7743 /// Implements the unchecked expression
7745 public class UnCheckedExpr : Expression {
7747 public Expression Expr;
7749 public UnCheckedExpr (Expression e, Location l)
7755 public override Expression DoResolve (EmitContext ec)
7757 bool last_check = ec.CheckState;
7758 bool last_const_check = ec.ConstantCheckState;
7760 ec.CheckState = false;
7761 ec.ConstantCheckState = false;
7762 Expr = Expr.Resolve (ec);
7763 ec.CheckState = last_check;
7764 ec.ConstantCheckState = last_const_check;
7769 if (Expr is Constant)
7772 eclass = Expr.eclass;
7777 public override void Emit (EmitContext ec)
7779 bool last_check = ec.CheckState;
7780 bool last_const_check = ec.ConstantCheckState;
7782 ec.CheckState = false;
7783 ec.ConstantCheckState = false;
7785 ec.CheckState = last_check;
7786 ec.ConstantCheckState = last_const_check;
7792 /// An Element Access expression.
7794 /// During semantic analysis these are transformed into
7795 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7797 public class ElementAccess : Expression {
7798 public ArrayList Arguments;
7799 public Expression Expr;
7801 public ElementAccess (Expression e, ArrayList e_list, Location l)
7810 Arguments = new ArrayList ();
7811 foreach (Expression tmp in e_list)
7812 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7816 bool CommonResolve (EmitContext ec)
7818 Expr = Expr.Resolve (ec);
7823 if (Arguments == null)
7826 foreach (Argument a in Arguments){
7827 if (!a.Resolve (ec, loc))
7834 Expression MakePointerAccess (EmitContext ec)
7838 if (t == TypeManager.void_ptr_type){
7839 Error (242, "The array index operation is not valid for void pointers");
7842 if (Arguments.Count != 1){
7843 Error (196, "A pointer must be indexed by a single value");
7848 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc).Resolve (ec);
7851 return new Indirection (p, loc).Resolve (ec);
7854 public override Expression DoResolve (EmitContext ec)
7856 if (!CommonResolve (ec))
7860 // We perform some simple tests, and then to "split" the emit and store
7861 // code we create an instance of a different class, and return that.
7863 // I am experimenting with this pattern.
7867 if (t == TypeManager.array_type){
7868 Report.Error (21, loc, "Cannot use indexer on System.Array");
7873 return (new ArrayAccess (this, loc)).Resolve (ec);
7874 else if (t.IsPointer)
7875 return MakePointerAccess (ec);
7877 return (new IndexerAccess (this, loc)).Resolve (ec);
7880 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7882 if (!CommonResolve (ec))
7887 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
7888 else if (t.IsPointer)
7889 return MakePointerAccess (ec);
7891 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
7894 public override void Emit (EmitContext ec)
7896 throw new Exception ("Should never be reached");
7901 /// Implements array access
7903 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7905 // Points to our "data" repository
7909 LocalTemporary temp;
7912 public ArrayAccess (ElementAccess ea_data, Location l)
7915 eclass = ExprClass.Variable;
7919 public override Expression DoResolve (EmitContext ec)
7922 ExprClass eclass = ea.Expr.eclass;
7924 // As long as the type is valid
7925 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7926 eclass == ExprClass.Value)) {
7927 ea.Expr.Error_UnexpectedKind ("variable or value");
7932 Type t = ea.Expr.Type;
7933 if (t.GetArrayRank () != ea.Arguments.Count){
7935 "Incorrect number of indexes for array " +
7936 " expected: " + t.GetArrayRank () + " got: " +
7937 ea.Arguments.Count);
7941 type = TypeManager.GetElementType (t);
7942 if (type.IsPointer && !ec.InUnsafe){
7943 UnsafeError (ea.Location);
7947 foreach (Argument a in ea.Arguments){
7948 Type argtype = a.Type;
7950 if (argtype == TypeManager.int32_type ||
7951 argtype == TypeManager.uint32_type ||
7952 argtype == TypeManager.int64_type ||
7953 argtype == TypeManager.uint64_type) {
7954 Constant c = a.Expr as Constant;
7955 if (c != null && c.IsNegative) {
7956 Report.Warning (251, 2, a.Expr.Location, "Indexing an array with a negative index (array indices always start at zero)");
7962 // Mhm. This is strage, because the Argument.Type is not the same as
7963 // Argument.Expr.Type: the value changes depending on the ref/out setting.
7965 // Wonder if I will run into trouble for this.
7967 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
7972 eclass = ExprClass.Variable;
7978 /// Emits the right opcode to load an object of Type `t'
7979 /// from an array of T
7981 static public void EmitLoadOpcode (ILGenerator ig, Type type)
7983 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7984 ig.Emit (OpCodes.Ldelem_U1);
7985 else if (type == TypeManager.sbyte_type)
7986 ig.Emit (OpCodes.Ldelem_I1);
7987 else if (type == TypeManager.short_type)
7988 ig.Emit (OpCodes.Ldelem_I2);
7989 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7990 ig.Emit (OpCodes.Ldelem_U2);
7991 else if (type == TypeManager.int32_type)
7992 ig.Emit (OpCodes.Ldelem_I4);
7993 else if (type == TypeManager.uint32_type)
7994 ig.Emit (OpCodes.Ldelem_U4);
7995 else if (type == TypeManager.uint64_type)
7996 ig.Emit (OpCodes.Ldelem_I8);
7997 else if (type == TypeManager.int64_type)
7998 ig.Emit (OpCodes.Ldelem_I8);
7999 else if (type == TypeManager.float_type)
8000 ig.Emit (OpCodes.Ldelem_R4);
8001 else if (type == TypeManager.double_type)
8002 ig.Emit (OpCodes.Ldelem_R8);
8003 else if (type == TypeManager.intptr_type)
8004 ig.Emit (OpCodes.Ldelem_I);
8005 else if (TypeManager.IsEnumType (type)){
8006 EmitLoadOpcode (ig, TypeManager.EnumToUnderlying (type));
8007 } else if (type.IsValueType){
8008 ig.Emit (OpCodes.Ldelema, type);
8009 ig.Emit (OpCodes.Ldobj, type);
8010 } else if (type.IsGenericParameter)
8011 ig.Emit (OpCodes.Ldelem_Any, type);
8013 ig.Emit (OpCodes.Ldelem_Ref);
8017 /// Returns the right opcode to store an object of Type `t'
8018 /// from an array of T.
8020 static public OpCode GetStoreOpcode (Type t, out bool is_stobj, out bool has_type_arg)
8022 //Console.WriteLine (new System.Diagnostics.StackTrace ());
8023 has_type_arg = false; is_stobj = false;
8024 t = TypeManager.TypeToCoreType (t);
8025 if (TypeManager.IsEnumType (t))
8026 t = TypeManager.EnumToUnderlying (t);
8027 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
8028 t == TypeManager.bool_type)
8029 return OpCodes.Stelem_I1;
8030 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
8031 t == TypeManager.char_type)
8032 return OpCodes.Stelem_I2;
8033 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
8034 return OpCodes.Stelem_I4;
8035 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
8036 return OpCodes.Stelem_I8;
8037 else if (t == TypeManager.float_type)
8038 return OpCodes.Stelem_R4;
8039 else if (t == TypeManager.double_type)
8040 return OpCodes.Stelem_R8;
8041 else if (t == TypeManager.intptr_type) {
8042 has_type_arg = true;
8044 return OpCodes.Stobj;
8045 } else if (t.IsValueType) {
8046 has_type_arg = true;
8048 return OpCodes.Stobj;
8049 } else if (t.IsGenericParameter) {
8050 has_type_arg = true;
8051 return OpCodes.Stelem_Any;
8053 return OpCodes.Stelem_Ref;
8056 MethodInfo FetchGetMethod ()
8058 ModuleBuilder mb = CodeGen.Module.Builder;
8059 int arg_count = ea.Arguments.Count;
8060 Type [] args = new Type [arg_count];
8063 for (int i = 0; i < arg_count; i++){
8064 //args [i++] = a.Type;
8065 args [i] = TypeManager.int32_type;
8068 get = mb.GetArrayMethod (
8069 ea.Expr.Type, "Get",
8070 CallingConventions.HasThis |
8071 CallingConventions.Standard,
8077 MethodInfo FetchAddressMethod ()
8079 ModuleBuilder mb = CodeGen.Module.Builder;
8080 int arg_count = ea.Arguments.Count;
8081 Type [] args = new Type [arg_count];
8085 ret_type = TypeManager.GetReferenceType (type);
8087 for (int i = 0; i < arg_count; i++){
8088 //args [i++] = a.Type;
8089 args [i] = TypeManager.int32_type;
8092 address = mb.GetArrayMethod (
8093 ea.Expr.Type, "Address",
8094 CallingConventions.HasThis |
8095 CallingConventions.Standard,
8102 // Load the array arguments into the stack.
8104 // If we have been requested to cache the values (cached_locations array
8105 // initialized), then load the arguments the first time and store them
8106 // in locals. otherwise load from local variables.
8108 void LoadArrayAndArguments (EmitContext ec)
8110 ILGenerator ig = ec.ig;
8113 foreach (Argument a in ea.Arguments){
8114 Type argtype = a.Expr.Type;
8118 if (argtype == TypeManager.int64_type)
8119 ig.Emit (OpCodes.Conv_Ovf_I);
8120 else if (argtype == TypeManager.uint64_type)
8121 ig.Emit (OpCodes.Conv_Ovf_I_Un);
8125 public void Emit (EmitContext ec, bool leave_copy)
8127 int rank = ea.Expr.Type.GetArrayRank ();
8128 ILGenerator ig = ec.ig;
8131 LoadArrayAndArguments (ec);
8134 EmitLoadOpcode (ig, type);
8138 method = FetchGetMethod ();
8139 ig.Emit (OpCodes.Call, method);
8142 LoadFromPtr (ec.ig, this.type);
8145 ec.ig.Emit (OpCodes.Dup);
8146 temp = new LocalTemporary (ec, this.type);
8151 public override void Emit (EmitContext ec)
8156 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8158 int rank = ea.Expr.Type.GetArrayRank ();
8159 ILGenerator ig = ec.ig;
8160 Type t = source.Type;
8161 prepared = prepare_for_load;
8163 if (prepare_for_load) {
8164 AddressOf (ec, AddressOp.LoadStore);
8165 ec.ig.Emit (OpCodes.Dup);
8168 ec.ig.Emit (OpCodes.Dup);
8169 temp = new LocalTemporary (ec, this.type);
8172 StoreFromPtr (ec.ig, t);
8180 LoadArrayAndArguments (ec);
8183 bool is_stobj, has_type_arg;
8184 OpCode op = GetStoreOpcode (t, out is_stobj, out has_type_arg);
8187 // The stobj opcode used by value types will need
8188 // an address on the stack, not really an array/array
8192 ig.Emit (OpCodes.Ldelema, t);
8196 ec.ig.Emit (OpCodes.Dup);
8197 temp = new LocalTemporary (ec, this.type);
8202 ig.Emit (OpCodes.Stobj, t);
8203 else if (has_type_arg)
8208 ModuleBuilder mb = CodeGen.Module.Builder;
8209 int arg_count = ea.Arguments.Count;
8210 Type [] args = new Type [arg_count + 1];
8215 ec.ig.Emit (OpCodes.Dup);
8216 temp = new LocalTemporary (ec, this.type);
8220 for (int i = 0; i < arg_count; i++){
8221 //args [i++] = a.Type;
8222 args [i] = TypeManager.int32_type;
8225 args [arg_count] = type;
8227 set = mb.GetArrayMethod (
8228 ea.Expr.Type, "Set",
8229 CallingConventions.HasThis |
8230 CallingConventions.Standard,
8231 TypeManager.void_type, args);
8233 ig.Emit (OpCodes.Call, set);
8240 public void AddressOf (EmitContext ec, AddressOp mode)
8242 int rank = ea.Expr.Type.GetArrayRank ();
8243 ILGenerator ig = ec.ig;
8245 LoadArrayAndArguments (ec);
8248 ig.Emit (OpCodes.Ldelema, type);
8250 MethodInfo address = FetchAddressMethod ();
8251 ig.Emit (OpCodes.Call, address);
8258 public ArrayList Properties;
8259 static Hashtable map;
8261 public struct Indexer {
8262 public readonly Type Type;
8263 public readonly MethodInfo Getter, Setter;
8265 public Indexer (Type type, MethodInfo get, MethodInfo set)
8275 map = new Hashtable ();
8280 Properties = new ArrayList ();
8283 void Append (MemberInfo [] mi)
8285 foreach (PropertyInfo property in mi){
8286 MethodInfo get, set;
8288 get = property.GetGetMethod (true);
8289 set = property.GetSetMethod (true);
8290 Properties.Add (new Indexer (property.PropertyType, get, set));
8294 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
8296 string p_name = TypeManager.IndexerPropertyName (lookup_type);
8298 MemberInfo [] mi = TypeManager.MemberLookup (
8299 caller_type, caller_type, lookup_type, MemberTypes.Property,
8300 BindingFlags.Public | BindingFlags.Instance |
8301 BindingFlags.DeclaredOnly, p_name, null);
8303 if (mi == null || mi.Length == 0)
8309 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
8311 Indexers ix = (Indexers) map [lookup_type];
8316 Type copy = lookup_type;
8317 while (copy != TypeManager.object_type && copy != null){
8318 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
8322 ix = new Indexers ();
8327 copy = copy.BaseType;
8330 if (!lookup_type.IsInterface)
8333 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
8334 if (ifaces != null) {
8335 foreach (Type itype in ifaces) {
8336 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
8339 ix = new Indexers ();
8351 /// Expressions that represent an indexer call.
8353 public class IndexerAccess : Expression, IAssignMethod {
8355 // Points to our "data" repository
8357 MethodInfo get, set;
8358 ArrayList set_arguments;
8359 bool is_base_indexer;
8361 protected Type indexer_type;
8362 protected Type current_type;
8363 protected Expression instance_expr;
8364 protected ArrayList arguments;
8366 public IndexerAccess (ElementAccess ea, Location loc)
8367 : this (ea.Expr, false, loc)
8369 this.arguments = ea.Arguments;
8372 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
8375 this.instance_expr = instance_expr;
8376 this.is_base_indexer = is_base_indexer;
8377 this.eclass = ExprClass.Value;
8381 protected virtual bool CommonResolve (EmitContext ec)
8383 indexer_type = instance_expr.Type;
8384 current_type = ec.ContainerType;
8389 public override Expression DoResolve (EmitContext ec)
8391 ArrayList AllGetters = new ArrayList();
8392 if (!CommonResolve (ec))
8396 // Step 1: Query for all `Item' *properties*. Notice
8397 // that the actual methods are pointed from here.
8399 // This is a group of properties, piles of them.
8401 bool found_any = false, found_any_getters = false;
8402 Type lookup_type = indexer_type;
8405 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
8406 if (ilist != null) {
8408 if (ilist.Properties != null) {
8409 foreach (Indexers.Indexer ix in ilist.Properties) {
8410 if (ix.Getter != null)
8411 AllGetters.Add(ix.Getter);
8416 if (AllGetters.Count > 0) {
8417 found_any_getters = true;
8418 get = (MethodInfo) Invocation.OverloadResolve (
8419 ec, new MethodGroupExpr (AllGetters, loc),
8420 arguments, false, loc);
8424 Report.Error (21, loc,
8425 "Type `" + TypeManager.CSharpName (indexer_type) +
8426 "' does not have any indexers defined");
8430 if (!found_any_getters) {
8431 Error (154, "indexer can not be used in this context, because " +
8432 "it lacks a `get' accessor");
8437 Error (1501, "No Overload for method `this' takes `" +
8438 arguments.Count + "' arguments");
8443 // Only base will allow this invocation to happen.
8445 if (get.IsAbstract && this is BaseIndexerAccess){
8446 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
8450 type = get.ReturnType;
8451 if (type.IsPointer && !ec.InUnsafe){
8456 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8458 eclass = ExprClass.IndexerAccess;
8462 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8464 ArrayList AllSetters = new ArrayList();
8465 if (!CommonResolve (ec))
8468 bool found_any = false, found_any_setters = false;
8470 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
8471 if (ilist != null) {
8473 if (ilist.Properties != null) {
8474 foreach (Indexers.Indexer ix in ilist.Properties) {
8475 if (ix.Setter != null)
8476 AllSetters.Add(ix.Setter);
8480 if (AllSetters.Count > 0) {
8481 found_any_setters = true;
8482 set_arguments = (ArrayList) arguments.Clone ();
8483 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
8484 set = (MethodInfo) Invocation.OverloadResolve (
8485 ec, new MethodGroupExpr (AllSetters, loc),
8486 set_arguments, false, loc);
8490 Report.Error (21, loc,
8491 "Type `" + TypeManager.CSharpName (indexer_type) +
8492 "' does not have any indexers defined");
8496 if (!found_any_setters) {
8497 Error (154, "indexer can not be used in this context, because " +
8498 "it lacks a `set' accessor");
8503 Error (1501, "No Overload for method `this' takes `" +
8504 arguments.Count + "' arguments");
8509 // Only base will allow this invocation to happen.
8511 if (set.IsAbstract && this is BaseIndexerAccess){
8512 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
8517 // Now look for the actual match in the list of indexers to set our "return" type
8519 type = TypeManager.void_type; // default value
8520 foreach (Indexers.Indexer ix in ilist.Properties){
8521 if (ix.Setter == set){
8527 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8529 eclass = ExprClass.IndexerAccess;
8533 bool prepared = false;
8534 LocalTemporary temp;
8536 public void Emit (EmitContext ec, bool leave_copy)
8538 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc, prepared, false);
8540 ec.ig.Emit (OpCodes.Dup);
8541 temp = new LocalTemporary (ec, Type);
8547 // source is ignored, because we already have a copy of it from the
8548 // LValue resolution and we have already constructed a pre-cached
8549 // version of the arguments (ea.set_arguments);
8551 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8553 prepared = prepare_for_load;
8554 Argument a = (Argument) set_arguments [set_arguments.Count - 1];
8559 ec.ig.Emit (OpCodes.Dup);
8560 temp = new LocalTemporary (ec, Type);
8563 } else if (leave_copy) {
8564 temp = new LocalTemporary (ec, Type);
8570 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc, false, prepared);
8577 public override void Emit (EmitContext ec)
8584 /// The base operator for method names
8586 public class BaseAccess : Expression {
8587 public string member;
8589 public BaseAccess (string member, Location l)
8591 this.member = member;
8595 public override Expression DoResolve (EmitContext ec)
8597 Expression c = CommonResolve (ec);
8603 // MethodGroups use this opportunity to flag an error on lacking ()
8605 if (!(c is MethodGroupExpr))
8606 return c.Resolve (ec);
8610 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8612 Expression c = CommonResolve (ec);
8618 // MethodGroups use this opportunity to flag an error on lacking ()
8620 if (! (c is MethodGroupExpr))
8621 return c.DoResolveLValue (ec, right_side);
8626 Expression CommonResolve (EmitContext ec)
8628 Expression member_lookup;
8629 Type current_type = ec.ContainerType;
8630 Type base_type = current_type.BaseType;
8634 Error (1511, "Keyword base is not allowed in static method");
8638 if (ec.IsFieldInitializer){
8639 Error (1512, "Keyword base is not available in the current context");
8643 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type,
8644 member, AllMemberTypes, AllBindingFlags,
8646 if (member_lookup == null) {
8647 MemberLookupFailed (
8648 ec, base_type, base_type, member, null, loc);
8655 left = new TypeExpression (base_type, loc);
8657 left = ec.GetThis (loc);
8659 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
8661 if (e is PropertyExpr){
8662 PropertyExpr pe = (PropertyExpr) e;
8667 if (e is MethodGroupExpr)
8668 ((MethodGroupExpr) e).IsBase = true;
8673 public override void Emit (EmitContext ec)
8675 throw new Exception ("Should never be called");
8680 /// The base indexer operator
8682 public class BaseIndexerAccess : IndexerAccess {
8683 public BaseIndexerAccess (ArrayList args, Location loc)
8684 : base (null, true, loc)
8686 arguments = new ArrayList ();
8687 foreach (Expression tmp in args)
8688 arguments.Add (new Argument (tmp, Argument.AType.Expression));
8691 protected override bool CommonResolve (EmitContext ec)
8693 instance_expr = ec.GetThis (loc);
8695 current_type = ec.ContainerType.BaseType;
8696 indexer_type = current_type;
8698 foreach (Argument a in arguments){
8699 if (!a.Resolve (ec, loc))
8708 /// This class exists solely to pass the Type around and to be a dummy
8709 /// that can be passed to the conversion functions (this is used by
8710 /// foreach implementation to typecast the object return value from
8711 /// get_Current into the proper type. All code has been generated and
8712 /// we only care about the side effect conversions to be performed
8714 /// This is also now used as a placeholder where a no-action expression
8715 /// is needed (the `New' class).
8717 public class EmptyExpression : Expression {
8718 public static readonly EmptyExpression Null = new EmptyExpression ();
8720 // TODO: should be protected
8721 public EmptyExpression ()
8723 type = TypeManager.object_type;
8724 eclass = ExprClass.Value;
8725 loc = Location.Null;
8728 public EmptyExpression (Type t)
8731 eclass = ExprClass.Value;
8732 loc = Location.Null;
8735 public override Expression DoResolve (EmitContext ec)
8740 public override void Emit (EmitContext ec)
8742 // nothing, as we only exist to not do anything.
8746 // This is just because we might want to reuse this bad boy
8747 // instead of creating gazillions of EmptyExpressions.
8748 // (CanImplicitConversion uses it)
8750 public void SetType (Type t)
8756 public class UserCast : Expression {
8760 public UserCast (MethodInfo method, Expression source, Location l)
8762 this.method = method;
8763 this.source = source;
8764 type = method.ReturnType;
8765 eclass = ExprClass.Value;
8769 public Expression Source {
8775 public override Expression DoResolve (EmitContext ec)
8778 // We are born fully resolved
8783 public override void Emit (EmitContext ec)
8785 ILGenerator ig = ec.ig;
8789 if (method is MethodInfo)
8790 ig.Emit (OpCodes.Call, (MethodInfo) method);
8792 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
8798 // This class is used to "construct" the type during a typecast
8799 // operation. Since the Type.GetType class in .NET can parse
8800 // the type specification, we just use this to construct the type
8801 // one bit at a time.
8803 public class ComposedCast : TypeExpr {
8807 public ComposedCast (Expression left, string dim, Location l)
8814 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
8816 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec);
8820 Type ltype = lexpr.Type;
8822 if ((ltype == TypeManager.void_type) && (dim != "*")) {
8823 Report.Error (1547, Location,
8824 "Keyword 'void' cannot be used in this context");
8829 while ((pos < dim.Length) && (dim [pos] == '[')) {
8832 if (dim [pos] == ']') {
8833 ltype = ltype.MakeArrayType ();
8836 if (pos < dim.Length)
8840 eclass = ExprClass.Type;
8845 while (dim [pos] == ',') {
8849 if ((dim [pos] != ']') || (pos != dim.Length-1))
8852 type = ltype.MakeArrayType (rank + 1);
8853 eclass = ExprClass.Type;
8858 // ltype.Fullname is already fully qualified, so we can skip
8859 // a lot of probes, and go directly to TypeManager.LookupType
8861 string fname = ltype.FullName != null ? ltype.FullName : ltype.Name;
8862 string cname = fname + dim;
8863 type = TypeManager.LookupTypeDirect (cname);
8866 // For arrays of enumerations we are having a problem
8867 // with the direct lookup. Need to investigate.
8869 // For now, fall back to the full lookup in that case.
8871 type = RootContext.LookupType (ec.DeclSpace, cname, false, loc);
8876 if (!ec.InUnsafe && type.IsPointer){
8881 eclass = ExprClass.Type;
8885 public override string Name {
8893 // This class is used to represent the address of an array, used
8894 // only by the Fixed statement, this is like the C "&a [0]" construct.
8896 public class ArrayPtr : Expression {
8899 public ArrayPtr (Expression array, Location l)
8901 Type array_type = TypeManager.GetElementType (array.Type);
8905 type = TypeManager.GetPointerType (array_type);
8906 eclass = ExprClass.Value;
8910 public override void Emit (EmitContext ec)
8912 ILGenerator ig = ec.ig;
8915 IntLiteral.EmitInt (ig, 0);
8916 ig.Emit (OpCodes.Ldelema, TypeManager.GetElementType (array.Type));
8919 public override Expression DoResolve (EmitContext ec)
8922 // We are born fully resolved
8929 // Used by the fixed statement
8931 public class StringPtr : Expression {
8934 public StringPtr (LocalBuilder b, Location l)
8937 eclass = ExprClass.Value;
8938 type = TypeManager.char_ptr_type;
8942 public override Expression DoResolve (EmitContext ec)
8944 // This should never be invoked, we are born in fully
8945 // initialized state.
8950 public override void Emit (EmitContext ec)
8952 ILGenerator ig = ec.ig;
8954 ig.Emit (OpCodes.Ldloc, b);
8955 ig.Emit (OpCodes.Conv_I);
8956 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
8957 ig.Emit (OpCodes.Add);
8962 // Implements the `stackalloc' keyword
8964 public class StackAlloc : Expression {
8969 public StackAlloc (Expression type, Expression count, Location l)
8976 public override Expression DoResolve (EmitContext ec)
8978 count = count.Resolve (ec);
8982 if (count.Type != TypeManager.int32_type){
8983 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8988 Constant c = count as Constant;
8989 if (c != null && c.IsNegative) {
8990 Report.Error (247, loc, "Cannot use a negative size with stackalloc");
8994 if (ec.CurrentBranching.InCatch () ||
8995 ec.CurrentBranching.InFinally (true)) {
8997 "stackalloc can not be used in a catch or finally block");
9001 TypeExpr texpr = t.ResolveAsTypeTerminal (ec);
9007 if (!TypeManager.VerifyUnManaged (otype, loc))
9010 type = TypeManager.GetPointerType (otype);
9011 eclass = ExprClass.Value;
9016 public override void Emit (EmitContext ec)
9018 int size = GetTypeSize (otype);
9019 ILGenerator ig = ec.ig;
9022 ig.Emit (OpCodes.Sizeof, otype);
9024 IntConstant.EmitInt (ig, size);
9026 ig.Emit (OpCodes.Mul);
9027 ig.Emit (OpCodes.Localloc);