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:
424 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
428 IVariable variable = Expr as IVariable;
429 bool is_fixed = variable != null && variable.VerifyFixed (false);
431 if (!ec.InFixedInitializer && !is_fixed) {
432 Error (212, "You can only take the address of an unfixed expression inside " +
433 "of a fixed statement initializer");
437 if (ec.InFixedInitializer && is_fixed) {
438 Error (213, "You can not fix an already fixed expression");
442 LocalVariableReference lr = Expr as LocalVariableReference;
444 if (lr.local_info.IsCaptured){
445 AnonymousMethod.Error_AddressOfCapturedVar (lr.Name, loc);
448 lr.local_info.AddressTaken = true;
449 lr.local_info.Used = true;
452 // According to the specs, a variable is considered definitely assigned if you take
454 if ((variable != null) && (variable.VariableInfo != null)){
455 variable.VariableInfo.SetAssigned (ec);
458 type = TypeManager.GetPointerType (Expr.Type);
461 case Operator.Indirection:
467 if (!expr_type.IsPointer){
468 Error (193, "The * or -> operator can only be applied to pointers");
473 // We create an Indirection expression, because
474 // it can implement the IMemoryLocation.
476 return new Indirection (Expr, loc);
478 case Operator.UnaryPlus:
480 // A plus in front of something is just a no-op, so return the child.
484 case Operator.UnaryNegation:
486 // Deals with -literals
487 // int operator- (int x)
488 // long operator- (long x)
489 // float operator- (float f)
490 // double operator- (double d)
491 // decimal operator- (decimal d)
493 Expression expr = null;
496 // transform - - expr into expr
499 Unary unary = (Unary) Expr;
501 if (unary.Oper == Operator.UnaryNegation)
506 // perform numeric promotions to int,
510 // The following is inneficient, because we call
511 // ImplicitConversion too many times.
513 // It is also not clear if we should convert to Float
514 // or Double initially.
516 if (expr_type == TypeManager.uint32_type){
518 // FIXME: handle exception to this rule that
519 // permits the int value -2147483648 (-2^31) to
520 // bt wrote as a decimal interger literal
522 type = TypeManager.int64_type;
523 Expr = Convert.ImplicitConversion (ec, Expr, type, loc);
527 if (expr_type == TypeManager.uint64_type){
529 // FIXME: Handle exception of `long value'
530 // -92233720368547758087 (-2^63) to be wrote as
531 // decimal integer literal.
537 if (expr_type == TypeManager.float_type){
542 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
549 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
556 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.double_type, loc);
567 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
568 TypeManager.CSharpName (expr_type) + "'");
572 public override Expression DoResolve (EmitContext ec)
574 if (Oper == Operator.AddressOf) {
575 Expr = Expr.DoResolveLValue (ec, new EmptyExpression ());
577 if (Expr == null || Expr.eclass != ExprClass.Variable){
578 Error (211, "Cannot take the address of non-variables");
583 Expr = Expr.Resolve (ec);
588 eclass = ExprClass.Value;
589 return ResolveOperator (ec);
592 public override Expression DoResolveLValue (EmitContext ec, Expression right)
594 if (Oper == Operator.Indirection)
595 return DoResolve (ec);
600 public override void Emit (EmitContext ec)
602 ILGenerator ig = ec.ig;
605 case Operator.UnaryPlus:
606 throw new Exception ("This should be caught by Resolve");
608 case Operator.UnaryNegation:
610 ig.Emit (OpCodes.Ldc_I4_0);
611 if (type == TypeManager.int64_type)
612 ig.Emit (OpCodes.Conv_U8);
614 ig.Emit (OpCodes.Sub_Ovf);
617 ig.Emit (OpCodes.Neg);
622 case Operator.LogicalNot:
624 ig.Emit (OpCodes.Ldc_I4_0);
625 ig.Emit (OpCodes.Ceq);
628 case Operator.OnesComplement:
630 ig.Emit (OpCodes.Not);
633 case Operator.AddressOf:
634 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
638 throw new Exception ("This should not happen: Operator = "
643 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
645 if (Oper == Operator.LogicalNot)
646 Expr.EmitBranchable (ec, target, !onTrue);
648 base.EmitBranchable (ec, target, onTrue);
651 public override string ToString ()
653 return "Unary (" + Oper + ", " + Expr + ")";
659 // Unary operators are turned into Indirection expressions
660 // after semantic analysis (this is so we can take the address
661 // of an indirection).
663 public class Indirection : Expression, IMemoryLocation, IAssignMethod, IVariable {
665 LocalTemporary temporary;
668 public Indirection (Expression expr, Location l)
671 type = TypeManager.HasElementType (expr.Type) ? TypeManager.GetElementType (expr.Type) : expr.Type;
672 eclass = ExprClass.Variable;
676 void LoadExprValue (EmitContext ec)
680 public override void Emit (EmitContext ec)
685 LoadFromPtr (ec.ig, Type);
688 public void Emit (EmitContext ec, bool leave_copy)
692 ec.ig.Emit (OpCodes.Dup);
693 temporary = new LocalTemporary (ec, expr.Type);
694 temporary.Store (ec);
698 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
700 prepared = prepare_for_load;
704 if (prepare_for_load)
705 ec.ig.Emit (OpCodes.Dup);
709 ec.ig.Emit (OpCodes.Dup);
710 temporary = new LocalTemporary (ec, expr.Type);
711 temporary.Store (ec);
714 StoreFromPtr (ec.ig, type);
716 if (temporary != null)
720 public void AddressOf (EmitContext ec, AddressOp Mode)
725 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
727 return DoResolve (ec);
730 public override Expression DoResolve (EmitContext ec)
733 // Born fully resolved
738 public override string ToString ()
740 return "*(" + expr + ")";
743 #region IVariable Members
745 public VariableInfo VariableInfo {
751 public bool VerifyFixed (bool is_expression)
760 /// Unary Mutator expressions (pre and post ++ and --)
764 /// UnaryMutator implements ++ and -- expressions. It derives from
765 /// ExpressionStatement becuase the pre/post increment/decrement
766 /// operators can be used in a statement context.
768 /// FIXME: Idea, we could split this up in two classes, one simpler
769 /// for the common case, and one with the extra fields for more complex
770 /// classes (indexers require temporary access; overloaded require method)
773 public class UnaryMutator : ExpressionStatement {
775 public enum Mode : byte {
782 PreDecrement = IsDecrement,
783 PostIncrement = IsPost,
784 PostDecrement = IsPost | IsDecrement
788 bool is_expr = false;
789 bool recurse = false;
794 // This is expensive for the simplest case.
796 StaticCallExpr method;
798 public UnaryMutator (Mode m, Expression e, Location l)
805 static string OperName (Mode mode)
807 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
811 void Error23 (Type t)
814 23, "Operator " + OperName (mode) +
815 " cannot be applied to operand of type `" +
816 TypeManager.CSharpName (t) + "'");
820 /// Returns whether an object of type `t' can be incremented
821 /// or decremented with add/sub (ie, basically whether we can
822 /// use pre-post incr-decr operations on it, but it is not a
823 /// System.Decimal, which we require operator overloading to catch)
825 static bool IsIncrementableNumber (Type t)
827 return (t == TypeManager.sbyte_type) ||
828 (t == TypeManager.byte_type) ||
829 (t == TypeManager.short_type) ||
830 (t == TypeManager.ushort_type) ||
831 (t == TypeManager.int32_type) ||
832 (t == TypeManager.uint32_type) ||
833 (t == TypeManager.int64_type) ||
834 (t == TypeManager.uint64_type) ||
835 (t == TypeManager.char_type) ||
836 (t.IsSubclassOf (TypeManager.enum_type)) ||
837 (t == TypeManager.float_type) ||
838 (t == TypeManager.double_type) ||
839 (t.IsPointer && t != TypeManager.void_ptr_type);
842 Expression ResolveOperator (EmitContext ec)
844 Type expr_type = expr.Type;
847 // Step 1: Perform Operator Overload location
852 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
853 op_name = "op_Increment";
855 op_name = "op_Decrement";
857 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
860 method = StaticCallExpr.MakeSimpleCall (
861 ec, (MethodGroupExpr) mg, expr, loc);
864 } else if (!IsIncrementableNumber (expr_type)) {
865 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
866 TypeManager.CSharpName (expr_type) + "'");
871 // The operand of the prefix/postfix increment decrement operators
872 // should be an expression that is classified as a variable,
873 // a property access or an indexer access
876 if (expr.eclass == ExprClass.Variable){
877 LocalVariableReference var = expr as LocalVariableReference;
878 if ((var != null) && var.IsReadOnly) {
879 Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
882 } else if (expr.eclass == ExprClass.IndexerAccess || expr.eclass == ExprClass.PropertyAccess){
883 expr = expr.ResolveLValue (ec, this);
887 expr.Error_UnexpectedKind ("variable, indexer or property access", loc);
894 public override Expression DoResolve (EmitContext ec)
896 expr = expr.Resolve (ec);
901 eclass = ExprClass.Value;
902 return ResolveOperator (ec);
905 static int PtrTypeSize (Type t)
907 return GetTypeSize (TypeManager.GetElementType (t));
911 // Loads the proper "1" into the stack based on the type, then it emits the
912 // opcode for the operation requested
914 void LoadOneAndEmitOp (EmitContext ec, Type t)
917 // Measure if getting the typecode and using that is more/less efficient
918 // that comparing types. t.GetTypeCode() is an internal call.
920 ILGenerator ig = ec.ig;
922 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
923 LongConstant.EmitLong (ig, 1);
924 else if (t == TypeManager.double_type)
925 ig.Emit (OpCodes.Ldc_R8, 1.0);
926 else if (t == TypeManager.float_type)
927 ig.Emit (OpCodes.Ldc_R4, 1.0F);
928 else if (t.IsPointer){
929 int n = PtrTypeSize (t);
932 ig.Emit (OpCodes.Sizeof, t);
934 IntConstant.EmitInt (ig, n);
936 ig.Emit (OpCodes.Ldc_I4_1);
939 // Now emit the operation
942 if (t == TypeManager.int32_type ||
943 t == TypeManager.int64_type){
944 if ((mode & Mode.IsDecrement) != 0)
945 ig.Emit (OpCodes.Sub_Ovf);
947 ig.Emit (OpCodes.Add_Ovf);
948 } else if (t == TypeManager.uint32_type ||
949 t == TypeManager.uint64_type){
950 if ((mode & Mode.IsDecrement) != 0)
951 ig.Emit (OpCodes.Sub_Ovf_Un);
953 ig.Emit (OpCodes.Add_Ovf_Un);
955 if ((mode & Mode.IsDecrement) != 0)
956 ig.Emit (OpCodes.Sub_Ovf);
958 ig.Emit (OpCodes.Add_Ovf);
961 if ((mode & Mode.IsDecrement) != 0)
962 ig.Emit (OpCodes.Sub);
964 ig.Emit (OpCodes.Add);
967 if (t == TypeManager.sbyte_type){
969 ig.Emit (OpCodes.Conv_Ovf_I1);
971 ig.Emit (OpCodes.Conv_I1);
972 } else if (t == TypeManager.byte_type){
974 ig.Emit (OpCodes.Conv_Ovf_U1);
976 ig.Emit (OpCodes.Conv_U1);
977 } else if (t == TypeManager.short_type){
979 ig.Emit (OpCodes.Conv_Ovf_I2);
981 ig.Emit (OpCodes.Conv_I2);
982 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
984 ig.Emit (OpCodes.Conv_Ovf_U2);
986 ig.Emit (OpCodes.Conv_U2);
991 void EmitCode (EmitContext ec, bool is_expr)
994 this.is_expr = is_expr;
995 ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
999 public override void Emit (EmitContext ec)
1002 // We use recurse to allow ourselfs to be the source
1003 // of an assignment. This little hack prevents us from
1004 // having to allocate another expression
1007 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
1009 LoadOneAndEmitOp (ec, expr.Type);
1011 ec.ig.Emit (OpCodes.Call, method.Method);
1016 EmitCode (ec, true);
1019 public override void EmitStatement (EmitContext ec)
1021 EmitCode (ec, false);
1026 /// Base class for the `Is' and `As' classes.
1030 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1033 public abstract class Probe : Expression {
1034 public Expression ProbeType;
1035 protected Expression expr;
1036 protected Type probe_type;
1038 public Probe (Expression expr, Expression probe_type, Location l)
1040 ProbeType = probe_type;
1045 public Expression Expr {
1051 public override Expression DoResolve (EmitContext ec)
1053 TypeExpr texpr = ProbeType.ResolveAsTypeTerminal (ec, false);
1056 probe_type = texpr.ResolveType (ec);
1058 CheckObsoleteAttribute (probe_type);
1060 expr = expr.Resolve (ec);
1064 if (expr.Type.IsPointer) {
1065 Report.Error (244, loc, "\"is\" or \"as\" are not valid on pointer types");
1073 /// Implementation of the `is' operator.
1075 public class Is : Probe {
1076 public Is (Expression expr, Expression probe_type, Location l)
1077 : base (expr, probe_type, l)
1082 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1087 public override void Emit (EmitContext ec)
1089 ILGenerator ig = ec.ig;
1094 case Action.AlwaysFalse:
1095 ig.Emit (OpCodes.Pop);
1096 IntConstant.EmitInt (ig, 0);
1098 case Action.AlwaysTrue:
1099 ig.Emit (OpCodes.Pop);
1100 IntConstant.EmitInt (ig, 1);
1102 case Action.LeaveOnStack:
1103 // the `e != null' rule.
1104 ig.Emit (OpCodes.Ldnull);
1105 ig.Emit (OpCodes.Ceq);
1106 ig.Emit (OpCodes.Ldc_I4_0);
1107 ig.Emit (OpCodes.Ceq);
1110 ig.Emit (OpCodes.Isinst, probe_type);
1111 ig.Emit (OpCodes.Ldnull);
1112 ig.Emit (OpCodes.Cgt_Un);
1115 throw new Exception ("never reached");
1118 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
1120 ILGenerator ig = ec.ig;
1123 case Action.AlwaysFalse:
1125 ig.Emit (OpCodes.Br, target);
1128 case Action.AlwaysTrue:
1130 ig.Emit (OpCodes.Br, target);
1133 case Action.LeaveOnStack:
1134 // the `e != null' rule.
1136 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1140 ig.Emit (OpCodes.Isinst, probe_type);
1141 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1144 throw new Exception ("never reached");
1147 public override Expression DoResolve (EmitContext ec)
1149 Expression e = base.DoResolve (ec);
1151 if ((e == null) || (expr == null))
1154 Type etype = expr.Type;
1155 bool warning_always_matches = false;
1156 bool warning_never_matches = false;
1158 type = TypeManager.bool_type;
1159 eclass = ExprClass.Value;
1162 // First case, if at compile time, there is an implicit conversion
1163 // then e != null (objects) or true (value types)
1165 e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1168 if (etype.IsValueType)
1169 action = Action.AlwaysTrue;
1171 action = Action.LeaveOnStack;
1173 warning_always_matches = true;
1174 } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1176 // Second case: explicit reference convresion
1178 if (expr is NullLiteral)
1179 action = Action.AlwaysFalse;
1181 action = Action.Probe;
1183 action = Action.AlwaysFalse;
1184 warning_never_matches = true;
1187 if (warning_always_matches)
1188 Warning (183, "The given expression is always of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1189 else if (warning_never_matches){
1190 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1191 Warning (184, "The given expression is never of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1199 /// Implementation of the `as' operator.
1201 public class As : Probe {
1202 public As (Expression expr, Expression probe_type, Location l)
1203 : base (expr, probe_type, l)
1207 bool do_isinst = false;
1209 public override void Emit (EmitContext ec)
1211 ILGenerator ig = ec.ig;
1216 ig.Emit (OpCodes.Isinst, probe_type);
1219 static void Error_CannotConvertType (Type source, Type target, Location loc)
1222 39, loc, "as operator can not convert from `" +
1223 TypeManager.CSharpName (source) + "' to `" +
1224 TypeManager.CSharpName (target) + "'");
1227 public override Expression DoResolve (EmitContext ec)
1229 Expression e = base.DoResolve (ec);
1235 eclass = ExprClass.Value;
1236 Type etype = expr.Type;
1238 if (TypeManager.IsValueType (probe_type)){
1239 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1240 TypeManager.CSharpName (probe_type) + " is a value type)");
1245 e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1252 if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
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 DoResolveLValue (EmitContext ec, Expression right_side)
1786 expr = expr.DoResolveLValue (ec, right_side);
1790 return ResolveRest (ec);
1793 public override Expression DoResolve (EmitContext ec)
1795 expr = expr.Resolve (ec);
1799 return ResolveRest (ec);
1802 Expression ResolveRest (EmitContext ec)
1804 TypeExpr target = target_type.ResolveAsTypeTerminal (ec, false);
1808 type = target.ResolveType (ec);
1810 CheckObsoleteAttribute (type);
1812 if (type.IsAbstract && type.IsSealed) {
1813 Report.Error (716, loc, "Cannot convert to static type '{0}'", TypeManager.CSharpName (type));
1817 eclass = ExprClass.Value;
1819 if (expr is Constant){
1820 Expression e = TryReduce (ec, type);
1826 if (type.IsPointer && !ec.InUnsafe) {
1830 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1834 public override void Emit (EmitContext ec)
1837 // This one will never happen
1839 throw new Exception ("Should not happen");
1844 /// Binary operators
1846 public class Binary : Expression {
1847 public enum Operator : byte {
1848 Multiply, Division, Modulus,
1849 Addition, Subtraction,
1850 LeftShift, RightShift,
1851 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1852 Equality, Inequality,
1862 Expression left, right;
1864 // This must be kept in sync with Operator!!!
1865 public static readonly string [] oper_names;
1869 oper_names = new string [(int) Operator.TOP];
1871 oper_names [(int) Operator.Multiply] = "op_Multiply";
1872 oper_names [(int) Operator.Division] = "op_Division";
1873 oper_names [(int) Operator.Modulus] = "op_Modulus";
1874 oper_names [(int) Operator.Addition] = "op_Addition";
1875 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1876 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1877 oper_names [(int) Operator.RightShift] = "op_RightShift";
1878 oper_names [(int) Operator.LessThan] = "op_LessThan";
1879 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1880 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1881 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1882 oper_names [(int) Operator.Equality] = "op_Equality";
1883 oper_names [(int) Operator.Inequality] = "op_Inequality";
1884 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1885 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1886 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1887 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1888 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1891 public Binary (Operator oper, Expression left, Expression right, Location loc)
1899 public Operator Oper {
1908 public Expression Left {
1917 public Expression Right {
1928 /// Returns a stringified representation of the Operator
1930 static string OperName (Operator oper)
1933 case Operator.Multiply:
1935 case Operator.Division:
1937 case Operator.Modulus:
1939 case Operator.Addition:
1941 case Operator.Subtraction:
1943 case Operator.LeftShift:
1945 case Operator.RightShift:
1947 case Operator.LessThan:
1949 case Operator.GreaterThan:
1951 case Operator.LessThanOrEqual:
1953 case Operator.GreaterThanOrEqual:
1955 case Operator.Equality:
1957 case Operator.Inequality:
1959 case Operator.BitwiseAnd:
1961 case Operator.BitwiseOr:
1963 case Operator.ExclusiveOr:
1965 case Operator.LogicalOr:
1967 case Operator.LogicalAnd:
1971 return oper.ToString ();
1974 public override string ToString ()
1976 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1977 right.ToString () + ")";
1980 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1982 if (expr.Type == target_type)
1985 return Convert.ImplicitConversion (ec, expr, target_type, loc);
1988 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1991 34, loc, "Operator `" + OperName (oper)
1992 + "' is ambiguous on operands of type `"
1993 + TypeManager.CSharpName (l) + "' "
1994 + "and `" + TypeManager.CSharpName (r)
1998 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
2000 if ((l == t) || (r == t))
2003 if (!check_user_conversions)
2006 if (Convert.ImplicitUserConversionExists (ec, l, t))
2008 else if (Convert.ImplicitUserConversionExists (ec, r, t))
2015 // Note that handling the case l == Decimal || r == Decimal
2016 // is taken care of by the Step 1 Operator Overload resolution.
2018 // If `check_user_conv' is true, we also check whether a user-defined conversion
2019 // exists. Note that we only need to do this if both arguments are of a user-defined
2020 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
2021 // so we don't explicitly check for performance reasons.
2023 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
2025 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
2027 // If either operand is of type double, the other operand is
2028 // conveted to type double.
2030 if (r != TypeManager.double_type)
2031 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
2032 if (l != TypeManager.double_type)
2033 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
2035 type = TypeManager.double_type;
2036 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
2038 // if either operand is of type float, the other operand is
2039 // converted to type float.
2041 if (r != TypeManager.double_type)
2042 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
2043 if (l != TypeManager.double_type)
2044 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
2045 type = TypeManager.float_type;
2046 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2050 // If either operand is of type ulong, the other operand is
2051 // converted to type ulong. or an error ocurrs if the other
2052 // operand is of type sbyte, short, int or long
2054 if (l == TypeManager.uint64_type){
2055 if (r != TypeManager.uint64_type){
2056 if (right is IntConstant){
2057 IntConstant ic = (IntConstant) right;
2059 e = Convert.TryImplicitIntConversion (l, ic);
2062 } else if (right is LongConstant){
2063 long ll = ((LongConstant) right).Value;
2066 right = new ULongConstant ((ulong) ll);
2068 e = Convert.ImplicitNumericConversion (ec, right, l, loc);
2075 if (left is IntConstant){
2076 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
2079 } else if (left is LongConstant){
2080 long ll = ((LongConstant) left).Value;
2083 left = new ULongConstant ((ulong) ll);
2085 e = Convert.ImplicitNumericConversion (ec, left, r, loc);
2092 if ((other == TypeManager.sbyte_type) ||
2093 (other == TypeManager.short_type) ||
2094 (other == TypeManager.int32_type) ||
2095 (other == TypeManager.int64_type))
2096 Error_OperatorAmbiguous (loc, oper, l, r);
2098 left = ForceConversion (ec, left, TypeManager.uint64_type);
2099 right = ForceConversion (ec, right, TypeManager.uint64_type);
2101 type = TypeManager.uint64_type;
2102 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2104 // If either operand is of type long, the other operand is converted
2107 if (l != TypeManager.int64_type)
2108 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
2109 if (r != TypeManager.int64_type)
2110 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
2112 type = TypeManager.int64_type;
2113 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2115 // If either operand is of type uint, and the other
2116 // operand is of type sbyte, short or int, othe operands are
2117 // converted to type long (unless we have an int constant).
2121 if (l == TypeManager.uint32_type){
2122 if (right is IntConstant){
2123 IntConstant ic = (IntConstant) right;
2127 right = new UIntConstant ((uint) val);
2134 } else if (r == TypeManager.uint32_type){
2135 if (left is IntConstant){
2136 IntConstant ic = (IntConstant) left;
2140 left = new UIntConstant ((uint) val);
2149 if ((other == TypeManager.sbyte_type) ||
2150 (other == TypeManager.short_type) ||
2151 (other == TypeManager.int32_type)){
2152 left = ForceConversion (ec, left, TypeManager.int64_type);
2153 right = ForceConversion (ec, right, TypeManager.int64_type);
2154 type = TypeManager.int64_type;
2157 // if either operand is of type uint, the other
2158 // operand is converd to type uint
2160 left = ForceConversion (ec, left, TypeManager.uint32_type);
2161 right = ForceConversion (ec, right, TypeManager.uint32_type);
2162 type = TypeManager.uint32_type;
2164 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2165 if (l != TypeManager.decimal_type)
2166 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
2168 if (r != TypeManager.decimal_type)
2169 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
2170 type = TypeManager.decimal_type;
2172 left = ForceConversion (ec, left, TypeManager.int32_type);
2173 right = ForceConversion (ec, right, TypeManager.int32_type);
2175 type = TypeManager.int32_type;
2178 return (left != null) && (right != null);
2181 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2183 Report.Error (19, loc,
2184 "Operator " + name + " cannot be applied to operands of type `" +
2185 TypeManager.CSharpName (l) + "' and `" +
2186 TypeManager.CSharpName (r) + "'");
2189 void Error_OperatorCannotBeApplied ()
2191 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2194 static bool is_unsigned (Type t)
2196 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2197 t == TypeManager.short_type || t == TypeManager.byte_type);
2200 static bool is_user_defined (Type t)
2202 if (t.IsSubclassOf (TypeManager.value_type) &&
2203 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2209 Expression Make32or64 (EmitContext ec, Expression e)
2213 if (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2214 t == TypeManager.int64_type || t == TypeManager.uint64_type)
2216 Expression ee = Convert.ImplicitConversion (ec, e, TypeManager.int32_type, loc);
2219 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint32_type, loc);
2222 ee = Convert.ImplicitConversion (ec, e, TypeManager.int64_type, loc);
2225 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint64_type, loc);
2231 Expression CheckShiftArguments (EmitContext ec)
2235 e = ForceConversion (ec, right, TypeManager.int32_type);
2237 Error_OperatorCannotBeApplied ();
2242 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
2243 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
2244 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
2245 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
2249 if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
2250 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (31), loc);
2251 right = right.DoResolve (ec);
2253 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (63), loc);
2254 right = right.DoResolve (ec);
2259 Error_OperatorCannotBeApplied ();
2263 Expression ResolveOperator (EmitContext ec)
2266 Type r = right.Type;
2269 // Special cases: string comapred to null
2271 if (oper == Operator.Equality || oper == Operator.Inequality){
2272 if ((!TypeManager.IsValueType (l) && r == TypeManager.null_type) ||
2273 (!TypeManager.IsValueType (r) && l == TypeManager.null_type)) {
2274 Type = TypeManager.bool_type;
2280 if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
2281 Type = TypeManager.bool_type;
2288 // Do not perform operator overload resolution when both sides are
2291 if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
2293 // Step 1: Perform Operator Overload location
2295 Expression left_expr, right_expr;
2297 string op = oper_names [(int) oper];
2299 MethodGroupExpr union;
2300 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2302 right_expr = MemberLookup (
2303 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2304 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2306 union = (MethodGroupExpr) left_expr;
2308 if (union != null) {
2309 ArrayList args = new ArrayList (2);
2310 args.Add (new Argument (left, Argument.AType.Expression));
2311 args.Add (new Argument (right, Argument.AType.Expression));
2313 MethodBase method = Invocation.OverloadResolve (
2314 ec, union, args, true, Location.Null);
2316 if (method != null) {
2317 MethodInfo mi = (MethodInfo) method;
2319 return new BinaryMethod (mi.ReturnType, method, args);
2325 // Step 0: String concatenation (because overloading will get this wrong)
2327 if (oper == Operator.Addition){
2329 // If any of the arguments is a string, cast to string
2332 // Simple constant folding
2333 if (left is StringConstant && right is StringConstant)
2334 return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value);
2336 if (l == TypeManager.string_type || r == TypeManager.string_type) {
2338 if (r == TypeManager.void_type || l == TypeManager.void_type) {
2339 Error_OperatorCannotBeApplied ();
2343 // try to fold it in on the left
2344 if (left is StringConcat) {
2347 // We have to test here for not-null, since we can be doubly-resolved
2348 // take care of not appending twice
2351 type = TypeManager.string_type;
2352 ((StringConcat) left).Append (ec, right);
2353 return left.Resolve (ec);
2359 // Otherwise, start a new concat expression
2360 return new StringConcat (ec, loc, left, right).Resolve (ec);
2364 // Transform a + ( - b) into a - b
2366 if (right is Unary){
2367 Unary right_unary = (Unary) right;
2369 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2370 oper = Operator.Subtraction;
2371 right = right_unary.Expr;
2377 if (oper == Operator.Equality || oper == Operator.Inequality){
2378 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2379 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2380 Error_OperatorCannotBeApplied ();
2384 type = TypeManager.bool_type;
2389 // operator != (object a, object b)
2390 // operator == (object a, object b)
2392 // For this to be used, both arguments have to be reference-types.
2393 // Read the rationale on the spec (14.9.6)
2395 // Also, if at compile time we know that the classes do not inherit
2396 // one from the other, then we catch the error there.
2398 if (!(l.IsValueType || r.IsValueType)){
2399 type = TypeManager.bool_type;
2404 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2408 // Also, a standard conversion must exist from either one
2410 if (!(Convert.ImplicitStandardConversionExists (ec, left, r) ||
2411 Convert.ImplicitStandardConversionExists (ec, right, l))){
2412 Error_OperatorCannotBeApplied ();
2416 // We are going to have to convert to an object to compare
2418 if (l != TypeManager.object_type)
2419 left = new EmptyCast (left, TypeManager.object_type);
2420 if (r != TypeManager.object_type)
2421 right = new EmptyCast (right, TypeManager.object_type);
2424 // FIXME: CSC here catches errors cs254 and cs252
2430 // One of them is a valuetype, but the other one is not.
2432 if (!l.IsValueType || !r.IsValueType) {
2433 Error_OperatorCannotBeApplied ();
2438 // Only perform numeric promotions on:
2439 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2441 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2442 if (l.IsSubclassOf (TypeManager.delegate_type)){
2443 if (((right.eclass == ExprClass.MethodGroup) ||
2444 (r == TypeManager.anonymous_method_type))){
2445 if ((RootContext.Version != LanguageVersion.ISO_1)){
2446 Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2454 if (r.IsSubclassOf (TypeManager.delegate_type)){
2456 ArrayList args = new ArrayList (2);
2458 args = new ArrayList (2);
2459 args.Add (new Argument (left, Argument.AType.Expression));
2460 args.Add (new Argument (right, Argument.AType.Expression));
2462 if (oper == Operator.Addition)
2463 method = TypeManager.delegate_combine_delegate_delegate;
2465 method = TypeManager.delegate_remove_delegate_delegate;
2468 Error_OperatorCannotBeApplied ();
2472 return new BinaryDelegate (l, method, args);
2477 // Pointer arithmetic:
2479 // T* operator + (T* x, int y);
2480 // T* operator + (T* x, uint y);
2481 // T* operator + (T* x, long y);
2482 // T* operator + (T* x, ulong y);
2484 // T* operator + (int y, T* x);
2485 // T* operator + (uint y, T *x);
2486 // T* operator + (long y, T *x);
2487 // T* operator + (ulong y, T *x);
2489 // T* operator - (T* x, int y);
2490 // T* operator - (T* x, uint y);
2491 // T* operator - (T* x, long y);
2492 // T* operator - (T* x, ulong y);
2494 // long operator - (T* x, T *y)
2497 if (r.IsPointer && oper == Operator.Subtraction){
2499 return new PointerArithmetic (
2500 false, left, right, TypeManager.int64_type,
2503 Expression t = Make32or64 (ec, right);
2505 return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc).Resolve (ec);
2507 } else if (r.IsPointer && oper == Operator.Addition){
2508 Expression t = Make32or64 (ec, left);
2510 return new PointerArithmetic (true, right, t, r, loc).Resolve (ec);
2515 // Enumeration operators
2517 bool lie = TypeManager.IsEnumType (l);
2518 bool rie = TypeManager.IsEnumType (r);
2522 // U operator - (E e, E f)
2524 if (oper == Operator.Subtraction){
2526 type = TypeManager.EnumToUnderlying (l);
2529 Error_OperatorCannotBeApplied ();
2535 // operator + (E e, U x)
2536 // operator - (E e, U x)
2538 if (oper == Operator.Addition || oper == Operator.Subtraction){
2539 Type enum_type = lie ? l : r;
2540 Type other_type = lie ? r : l;
2541 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2543 if (underlying_type != other_type){
2544 temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
2554 Error_OperatorCannotBeApplied ();
2563 temp = Convert.ImplicitConversion (ec, right, l, loc);
2567 Error_OperatorCannotBeApplied ();
2571 temp = Convert.ImplicitConversion (ec, left, r, loc);
2576 Error_OperatorCannotBeApplied ();
2581 if (oper == Operator.Equality || oper == Operator.Inequality ||
2582 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2583 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2584 if (left.Type != right.Type){
2585 Error_OperatorCannotBeApplied ();
2588 type = TypeManager.bool_type;
2592 if (oper == Operator.BitwiseAnd ||
2593 oper == Operator.BitwiseOr ||
2594 oper == Operator.ExclusiveOr){
2598 Error_OperatorCannotBeApplied ();
2602 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2603 return CheckShiftArguments (ec);
2605 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2606 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2607 type = TypeManager.bool_type;
2612 Error_OperatorCannotBeApplied ();
2616 Expression e = new ConditionalLogicalOperator (
2617 oper == Operator.LogicalAnd, left, right, l, loc);
2618 return e.Resolve (ec);
2622 // operator & (bool x, bool y)
2623 // operator | (bool x, bool y)
2624 // operator ^ (bool x, bool y)
2626 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2627 if (oper == Operator.BitwiseAnd ||
2628 oper == Operator.BitwiseOr ||
2629 oper == Operator.ExclusiveOr){
2636 // Pointer comparison
2638 if (l.IsPointer && r.IsPointer){
2639 if (oper == Operator.Equality || oper == Operator.Inequality ||
2640 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2641 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2642 type = TypeManager.bool_type;
2648 // This will leave left or right set to null if there is an error
2650 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2651 DoNumericPromotions (ec, l, r, check_user_conv);
2652 if (left == null || right == null){
2653 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2658 // reload our cached types if required
2663 if (oper == Operator.BitwiseAnd ||
2664 oper == Operator.BitwiseOr ||
2665 oper == Operator.ExclusiveOr){
2667 if (((l == TypeManager.int32_type) ||
2668 (l == TypeManager.uint32_type) ||
2669 (l == TypeManager.short_type) ||
2670 (l == TypeManager.ushort_type) ||
2671 (l == TypeManager.int64_type) ||
2672 (l == TypeManager.uint64_type))){
2675 Error_OperatorCannotBeApplied ();
2679 Error_OperatorCannotBeApplied ();
2684 if (oper == Operator.Equality ||
2685 oper == Operator.Inequality ||
2686 oper == Operator.LessThanOrEqual ||
2687 oper == Operator.LessThan ||
2688 oper == Operator.GreaterThanOrEqual ||
2689 oper == Operator.GreaterThan){
2690 type = TypeManager.bool_type;
2696 public override Expression DoResolve (EmitContext ec)
2698 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2699 left = ((ParenthesizedExpression) left).Expr;
2700 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2704 if (left.eclass == ExprClass.Type) {
2705 Error (75, "Casting a negative value needs to have the value in parentheses.");
2709 left = left.Resolve (ec);
2714 Constant lc = left as Constant;
2715 if (lc != null && lc.Type == TypeManager.bool_type &&
2716 ((oper == Operator.LogicalAnd && (bool)lc.GetValue () == false) ||
2717 (oper == Operator.LogicalOr && (bool)lc.GetValue () == true))) {
2719 // TODO: make a sense to resolve unreachable expression as we do for statement
2720 Report.Warning (429, 4, loc, "Unreachable expression code detected");
2724 right = right.Resolve (ec);
2728 eclass = ExprClass.Value;
2730 Constant rc = right as Constant;
2731 if (rc != null & lc != null){
2732 Expression e = ConstantFold.BinaryFold (
2733 ec, oper, lc, rc, loc);
2738 return ResolveOperator (ec);
2742 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2743 /// context of a conditional bool expression. This function will return
2744 /// false if it is was possible to use EmitBranchable, or true if it was.
2746 /// The expression's code is generated, and we will generate a branch to `target'
2747 /// if the resulting expression value is equal to isTrue
2749 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2751 ILGenerator ig = ec.ig;
2754 // This is more complicated than it looks, but its just to avoid
2755 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2756 // but on top of that we want for == and != to use a special path
2757 // if we are comparing against null
2759 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
2760 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2763 // put the constant on the rhs, for simplicity
2765 if (left is Constant) {
2766 Expression swap = right;
2771 if (((Constant) right).IsZeroInteger) {
2774 ig.Emit (OpCodes.Brtrue, target);
2776 ig.Emit (OpCodes.Brfalse, target);
2779 } else if (right is BoolConstant) {
2781 if (my_on_true != ((BoolConstant) right).Value)
2782 ig.Emit (OpCodes.Brtrue, target);
2784 ig.Emit (OpCodes.Brfalse, target);
2789 } else if (oper == Operator.LogicalAnd) {
2792 Label tests_end = ig.DefineLabel ();
2794 left.EmitBranchable (ec, tests_end, false);
2795 right.EmitBranchable (ec, target, true);
2796 ig.MarkLabel (tests_end);
2798 left.EmitBranchable (ec, target, false);
2799 right.EmitBranchable (ec, target, false);
2804 } else if (oper == Operator.LogicalOr){
2806 left.EmitBranchable (ec, target, true);
2807 right.EmitBranchable (ec, target, true);
2810 Label tests_end = ig.DefineLabel ();
2811 left.EmitBranchable (ec, tests_end, true);
2812 right.EmitBranchable (ec, target, false);
2813 ig.MarkLabel (tests_end);
2818 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2819 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2820 oper == Operator.Equality || oper == Operator.Inequality)) {
2821 base.EmitBranchable (ec, target, onTrue);
2829 bool isUnsigned = is_unsigned (t) || t == TypeManager.double_type || t == TypeManager.float_type;
2832 case Operator.Equality:
2834 ig.Emit (OpCodes.Beq, target);
2836 ig.Emit (OpCodes.Bne_Un, target);
2839 case Operator.Inequality:
2841 ig.Emit (OpCodes.Bne_Un, target);
2843 ig.Emit (OpCodes.Beq, target);
2846 case Operator.LessThan:
2849 ig.Emit (OpCodes.Blt_Un, target);
2851 ig.Emit (OpCodes.Blt, target);
2854 ig.Emit (OpCodes.Bge_Un, target);
2856 ig.Emit (OpCodes.Bge, target);
2859 case Operator.GreaterThan:
2862 ig.Emit (OpCodes.Bgt_Un, target);
2864 ig.Emit (OpCodes.Bgt, target);
2867 ig.Emit (OpCodes.Ble_Un, target);
2869 ig.Emit (OpCodes.Ble, target);
2872 case Operator.LessThanOrEqual:
2875 ig.Emit (OpCodes.Ble_Un, target);
2877 ig.Emit (OpCodes.Ble, target);
2880 ig.Emit (OpCodes.Bgt_Un, target);
2882 ig.Emit (OpCodes.Bgt, target);
2886 case Operator.GreaterThanOrEqual:
2889 ig.Emit (OpCodes.Bge_Un, target);
2891 ig.Emit (OpCodes.Bge, target);
2894 ig.Emit (OpCodes.Blt_Un, target);
2896 ig.Emit (OpCodes.Blt, target);
2899 Console.WriteLine (oper);
2900 throw new Exception ("what is THAT");
2904 public override void Emit (EmitContext ec)
2906 ILGenerator ig = ec.ig;
2911 // Handle short-circuit operators differently
2914 if (oper == Operator.LogicalAnd) {
2915 Label load_zero = ig.DefineLabel ();
2916 Label end = ig.DefineLabel ();
2918 left.EmitBranchable (ec, load_zero, false);
2920 ig.Emit (OpCodes.Br, end);
2922 ig.MarkLabel (load_zero);
2923 ig.Emit (OpCodes.Ldc_I4_0);
2926 } else if (oper == Operator.LogicalOr) {
2927 Label load_one = ig.DefineLabel ();
2928 Label end = ig.DefineLabel ();
2930 left.EmitBranchable (ec, load_one, true);
2932 ig.Emit (OpCodes.Br, end);
2934 ig.MarkLabel (load_one);
2935 ig.Emit (OpCodes.Ldc_I4_1);
2943 bool isUnsigned = is_unsigned (left.Type);
2946 case Operator.Multiply:
2948 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2949 opcode = OpCodes.Mul_Ovf;
2950 else if (isUnsigned)
2951 opcode = OpCodes.Mul_Ovf_Un;
2953 opcode = OpCodes.Mul;
2955 opcode = OpCodes.Mul;
2959 case Operator.Division:
2961 opcode = OpCodes.Div_Un;
2963 opcode = OpCodes.Div;
2966 case Operator.Modulus:
2968 opcode = OpCodes.Rem_Un;
2970 opcode = OpCodes.Rem;
2973 case Operator.Addition:
2975 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2976 opcode = OpCodes.Add_Ovf;
2977 else if (isUnsigned)
2978 opcode = OpCodes.Add_Ovf_Un;
2980 opcode = OpCodes.Add;
2982 opcode = OpCodes.Add;
2985 case Operator.Subtraction:
2987 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2988 opcode = OpCodes.Sub_Ovf;
2989 else if (isUnsigned)
2990 opcode = OpCodes.Sub_Ovf_Un;
2992 opcode = OpCodes.Sub;
2994 opcode = OpCodes.Sub;
2997 case Operator.RightShift:
2999 opcode = OpCodes.Shr_Un;
3001 opcode = OpCodes.Shr;
3004 case Operator.LeftShift:
3005 opcode = OpCodes.Shl;
3008 case Operator.Equality:
3009 opcode = OpCodes.Ceq;
3012 case Operator.Inequality:
3013 ig.Emit (OpCodes.Ceq);
3014 ig.Emit (OpCodes.Ldc_I4_0);
3016 opcode = OpCodes.Ceq;
3019 case Operator.LessThan:
3021 opcode = OpCodes.Clt_Un;
3023 opcode = OpCodes.Clt;
3026 case Operator.GreaterThan:
3028 opcode = OpCodes.Cgt_Un;
3030 opcode = OpCodes.Cgt;
3033 case Operator.LessThanOrEqual:
3034 Type lt = left.Type;
3036 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
3037 ig.Emit (OpCodes.Cgt_Un);
3039 ig.Emit (OpCodes.Cgt);
3040 ig.Emit (OpCodes.Ldc_I4_0);
3042 opcode = OpCodes.Ceq;
3045 case Operator.GreaterThanOrEqual:
3046 Type le = left.Type;
3048 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3049 ig.Emit (OpCodes.Clt_Un);
3051 ig.Emit (OpCodes.Clt);
3053 ig.Emit (OpCodes.Ldc_I4_0);
3055 opcode = OpCodes.Ceq;
3058 case Operator.BitwiseOr:
3059 opcode = OpCodes.Or;
3062 case Operator.BitwiseAnd:
3063 opcode = OpCodes.And;
3066 case Operator.ExclusiveOr:
3067 opcode = OpCodes.Xor;
3071 throw new Exception ("This should not happen: Operator = "
3072 + oper.ToString ());
3080 // Object created by Binary when the binary operator uses an method instead of being
3081 // a binary operation that maps to a CIL binary operation.
3083 public class BinaryMethod : Expression {
3084 public MethodBase method;
3085 public ArrayList Arguments;
3087 public BinaryMethod (Type t, MethodBase m, ArrayList args)
3092 eclass = ExprClass.Value;
3095 public override Expression DoResolve (EmitContext ec)
3100 public override void Emit (EmitContext ec)
3102 ILGenerator ig = ec.ig;
3104 if (Arguments != null)
3105 Invocation.EmitArguments (ec, method, Arguments, false, null);
3107 if (method is MethodInfo)
3108 ig.Emit (OpCodes.Call, (MethodInfo) method);
3110 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3115 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3116 // b, c, d... may be strings or objects.
3118 public class StringConcat : Expression {
3120 bool invalid = false;
3121 bool emit_conv_done = false;
3123 // Are we also concating objects?
3125 bool is_strings_only = true;
3127 public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
3130 type = TypeManager.string_type;
3131 eclass = ExprClass.Value;
3133 operands = new ArrayList (2);
3138 public override Expression DoResolve (EmitContext ec)
3146 public void Append (EmitContext ec, Expression operand)
3151 if (operand is StringConstant && operands.Count != 0) {
3152 StringConstant last_operand = operands [operands.Count - 1] as StringConstant;
3153 if (last_operand != null) {
3154 operands [operands.Count - 1] = new StringConstant (last_operand.Value + ((StringConstant) operand).Value);
3160 // Conversion to object
3162 if (operand.Type != TypeManager.string_type) {
3163 Expression no = Convert.ImplicitConversion (ec, operand, TypeManager.object_type, loc);
3166 Binary.Error_OperatorCannotBeApplied (loc, "+", TypeManager.string_type, operand.Type);
3172 operands.Add (operand);
3175 public override void Emit (EmitContext ec)
3177 MethodInfo concat_method = null;
3180 // Do conversion to arguments; check for strings only
3183 // This can get called multiple times, so we have to deal with that.
3184 if (!emit_conv_done) {
3185 emit_conv_done = true;
3186 for (int i = 0; i < operands.Count; i ++) {
3187 Expression e = (Expression) operands [i];
3188 is_strings_only &= e.Type == TypeManager.string_type;
3191 for (int i = 0; i < operands.Count; i ++) {
3192 Expression e = (Expression) operands [i];
3194 if (! is_strings_only && e.Type == TypeManager.string_type) {
3195 // need to make sure this is an object, because the EmitParams
3196 // method might look at the type of this expression, see it is a
3197 // string and emit a string [] when we want an object [];
3199 e = new EmptyCast (e, TypeManager.object_type);
3201 operands [i] = new Argument (e, Argument.AType.Expression);
3206 // Find the right method
3208 switch (operands.Count) {
3211 // This should not be possible, because simple constant folding
3212 // is taken care of in the Binary code.
3214 throw new Exception ("how did you get here?");
3217 concat_method = is_strings_only ?
3218 TypeManager.string_concat_string_string :
3219 TypeManager.string_concat_object_object ;
3222 concat_method = is_strings_only ?
3223 TypeManager.string_concat_string_string_string :
3224 TypeManager.string_concat_object_object_object ;
3228 // There is not a 4 param overlaod for object (the one that there is
3229 // is actually a varargs methods, and is only in corlib because it was
3230 // introduced there before.).
3232 if (!is_strings_only)
3235 concat_method = TypeManager.string_concat_string_string_string_string;
3238 concat_method = is_strings_only ?
3239 TypeManager.string_concat_string_dot_dot_dot :
3240 TypeManager.string_concat_object_dot_dot_dot ;
3244 Invocation.EmitArguments (ec, concat_method, operands, false, null);
3245 ec.ig.Emit (OpCodes.Call, concat_method);
3250 // Object created with +/= on delegates
3252 public class BinaryDelegate : Expression {
3256 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3261 eclass = ExprClass.Value;
3264 public override Expression DoResolve (EmitContext ec)
3269 public override void Emit (EmitContext ec)
3271 ILGenerator ig = ec.ig;
3273 Invocation.EmitArguments (ec, method, args, false, null);
3275 ig.Emit (OpCodes.Call, (MethodInfo) method);
3276 ig.Emit (OpCodes.Castclass, type);
3279 public Expression Right {
3281 Argument arg = (Argument) args [1];
3286 public bool IsAddition {
3288 return method == TypeManager.delegate_combine_delegate_delegate;
3294 // User-defined conditional logical operator
3295 public class ConditionalLogicalOperator : Expression {
3296 Expression left, right;
3299 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3302 eclass = ExprClass.Value;
3306 this.is_and = is_and;
3309 protected void Error19 ()
3311 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3314 protected void Error218 ()
3316 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3317 "declarations of operator true and operator false");
3320 Expression op_true, op_false, op;
3321 LocalTemporary left_temp;
3323 public override Expression DoResolve (EmitContext ec)
3326 Expression operator_group;
3328 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3329 if (operator_group == null) {
3334 left_temp = new LocalTemporary (ec, type);
3336 ArrayList arguments = new ArrayList ();
3337 arguments.Add (new Argument (left_temp, Argument.AType.Expression));
3338 arguments.Add (new Argument (right, Argument.AType.Expression));
3339 method = Invocation.OverloadResolve (
3340 ec, (MethodGroupExpr) operator_group, arguments, false, loc)
3342 if (method == null) {
3347 if (method.ReturnType != type) {
3348 Report.Error (217, loc, "In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') " +
3349 "must have the same return type as the type of its 2 parameters", TypeManager.CSharpSignature (method));
3353 op = new StaticCallExpr (method, arguments, loc);
3355 op_true = GetOperatorTrue (ec, left_temp, loc);
3356 op_false = GetOperatorFalse (ec, left_temp, loc);
3357 if ((op_true == null) || (op_false == null)) {
3365 public override void Emit (EmitContext ec)
3367 ILGenerator ig = ec.ig;
3368 Label false_target = ig.DefineLabel ();
3369 Label end_target = ig.DefineLabel ();
3372 left_temp.Store (ec);
3374 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
3375 left_temp.Emit (ec);
3376 ig.Emit (OpCodes.Br, end_target);
3377 ig.MarkLabel (false_target);
3379 ig.MarkLabel (end_target);
3383 public class PointerArithmetic : Expression {
3384 Expression left, right;
3388 // We assume that `l' is always a pointer
3390 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3396 is_add = is_addition;
3399 public override Expression DoResolve (EmitContext ec)
3401 eclass = ExprClass.Variable;
3403 if (left.Type == TypeManager.void_ptr_type) {
3404 Error (242, "The operation in question is undefined on void pointers");
3411 public override void Emit (EmitContext ec)
3413 Type op_type = left.Type;
3414 ILGenerator ig = ec.ig;
3416 // It must be either array or fixed buffer
3417 Type element = TypeManager.HasElementType (op_type) ?
3418 element = TypeManager.GetElementType (op_type) :
3419 element = AttributeTester.GetFixedBuffer (((FieldExpr)left).FieldInfo).ElementType;
3421 int size = GetTypeSize (element);
3422 Type rtype = right.Type;
3424 if (rtype.IsPointer){
3426 // handle (pointer - pointer)
3430 ig.Emit (OpCodes.Sub);
3434 ig.Emit (OpCodes.Sizeof, element);
3436 IntLiteral.EmitInt (ig, size);
3437 ig.Emit (OpCodes.Div);
3439 ig.Emit (OpCodes.Conv_I8);
3442 // handle + and - on (pointer op int)
3445 ig.Emit (OpCodes.Conv_I);
3447 Constant right_const = right as Constant;
3448 if (right_const != null && size != 0) {
3449 Expression ex = ConstantFold.BinaryFold (ec, Binary.Operator.Multiply, new IntConstant (size), right_const, loc);
3457 ig.Emit (OpCodes.Sizeof, element);
3459 IntLiteral.EmitInt (ig, size);
3460 if (rtype == TypeManager.int64_type)
3461 ig.Emit (OpCodes.Conv_I8);
3462 else if (rtype == TypeManager.uint64_type)
3463 ig.Emit (OpCodes.Conv_U8);
3464 ig.Emit (OpCodes.Mul);
3468 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
3469 ig.Emit (OpCodes.Conv_I);
3472 ig.Emit (OpCodes.Add);
3474 ig.Emit (OpCodes.Sub);
3480 /// Implements the ternary conditional operator (?:)
3482 public class Conditional : Expression {
3483 Expression expr, trueExpr, falseExpr;
3485 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3488 this.trueExpr = trueExpr;
3489 this.falseExpr = falseExpr;
3493 public Expression Expr {
3499 public Expression TrueExpr {
3505 public Expression FalseExpr {
3511 public override Expression DoResolve (EmitContext ec)
3513 expr = expr.Resolve (ec);
3518 if (expr.Type != TypeManager.bool_type){
3519 expr = Expression.ResolveBoolean (
3526 trueExpr = trueExpr.Resolve (ec);
3527 falseExpr = falseExpr.Resolve (ec);
3529 if (trueExpr == null || falseExpr == null)
3532 eclass = ExprClass.Value;
3533 if (trueExpr.Type == falseExpr.Type)
3534 type = trueExpr.Type;
3537 Type true_type = trueExpr.Type;
3538 Type false_type = falseExpr.Type;
3541 // First, if an implicit conversion exists from trueExpr
3542 // to falseExpr, then the result type is of type falseExpr.Type
3544 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3547 // Check if both can convert implicitl to each other's type
3549 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3551 "Can not compute type of conditional expression " +
3552 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3553 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3554 "' convert implicitly to each other");
3559 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3563 Error (173, "The type of the conditional expression can " +
3564 "not be computed because there is no implicit conversion" +
3565 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3566 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3571 // Dead code optimalization
3572 if (expr is BoolConstant){
3573 BoolConstant bc = (BoolConstant) expr;
3575 Report.Warning (429, 4, bc.Value ? falseExpr.Location : trueExpr.Location, "Unreachable expression code detected");
3576 return bc.Value ? trueExpr : falseExpr;
3582 public override void Emit (EmitContext ec)
3584 ILGenerator ig = ec.ig;
3585 Label false_target = ig.DefineLabel ();
3586 Label end_target = ig.DefineLabel ();
3588 expr.EmitBranchable (ec, false_target, false);
3590 ig.Emit (OpCodes.Br, end_target);
3591 ig.MarkLabel (false_target);
3592 falseExpr.Emit (ec);
3593 ig.MarkLabel (end_target);
3601 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3602 public readonly string Name;
3603 public readonly Block Block;
3604 public LocalInfo local_info;
3607 LocalTemporary temp;
3609 public LocalVariableReference (Block block, string name, Location l)
3614 eclass = ExprClass.Variable;
3618 // Setting `is_readonly' to false will allow you to create a writable
3619 // reference to a read-only variable. This is used by foreach and using.
3621 public LocalVariableReference (Block block, string name, Location l,
3622 LocalInfo local_info, bool is_readonly)
3623 : this (block, name, l)
3625 this.local_info = local_info;
3626 this.is_readonly = is_readonly;
3629 public VariableInfo VariableInfo {
3631 return local_info.VariableInfo;
3635 public bool IsReadOnly {
3641 protected Expression DoResolveBase (EmitContext ec, Expression lvalue_right_side)
3643 if (local_info == null) {
3644 local_info = Block.GetLocalInfo (Name);
3647 if (lvalue_right_side == EmptyExpression.Null)
3648 local_info.Used = true;
3650 is_readonly = local_info.ReadOnly;
3653 type = local_info.VariableType;
3655 VariableInfo variable_info = local_info.VariableInfo;
3656 if (lvalue_right_side != null){
3658 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3662 if (variable_info != null)
3663 variable_info.SetAssigned (ec);
3666 Expression e = Block.GetConstantExpression (Name);
3668 local_info.Used = true;
3669 eclass = ExprClass.Value;
3670 return e.Resolve (ec);
3673 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3676 if (lvalue_right_side == null)
3677 local_info.Used = true;
3679 if (ec.CurrentAnonymousMethod != null){
3681 // If we are referencing a variable from the external block
3682 // flag it for capturing
3684 if (local_info.Block.Toplevel != ec.CurrentBlock.Toplevel){
3685 if (local_info.AddressTaken){
3686 AnonymousMethod.Error_AddressOfCapturedVar (local_info.Name, loc);
3689 ec.CaptureVariable (local_info);
3696 public override Expression DoResolve (EmitContext ec)
3698 return DoResolveBase (ec, null);
3701 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3703 Expression ret = DoResolveBase (ec, right_side);
3705 CheckObsoleteAttribute (ret.Type);
3710 public bool VerifyFixed (bool is_expression)
3712 return !is_expression || local_info.IsFixed;
3715 public override void Emit (EmitContext ec)
3717 ILGenerator ig = ec.ig;
3719 if (local_info.FieldBuilder == null){
3721 // A local variable on the local CLR stack
3723 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3726 // A local variable captured by anonymous methods.
3729 ec.EmitCapturedVariableInstance (local_info);
3731 ig.Emit (OpCodes.Ldfld, local_info.FieldBuilder);
3735 public void Emit (EmitContext ec, bool leave_copy)
3739 ec.ig.Emit (OpCodes.Dup);
3740 if (local_info.FieldBuilder != null){
3741 temp = new LocalTemporary (ec, Type);
3747 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3749 ILGenerator ig = ec.ig;
3750 prepared = prepare_for_load;
3752 if (local_info.FieldBuilder == null){
3754 // A local variable on the local CLR stack
3756 if (local_info.LocalBuilder == null)
3757 throw new Exception ("This should not happen: both Field and Local are null");
3761 ec.ig.Emit (OpCodes.Dup);
3762 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3765 // A local variable captured by anonymous methods or itereators.
3767 ec.EmitCapturedVariableInstance (local_info);
3769 if (prepare_for_load)
3770 ig.Emit (OpCodes.Dup);
3773 ig.Emit (OpCodes.Dup);
3774 temp = new LocalTemporary (ec, Type);
3777 ig.Emit (OpCodes.Stfld, local_info.FieldBuilder);
3783 public void AddressOf (EmitContext ec, AddressOp mode)
3785 ILGenerator ig = ec.ig;
3787 if (local_info.FieldBuilder == null){
3789 // A local variable on the local CLR stack
3791 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3794 // A local variable captured by anonymous methods or iterators
3796 ec.EmitCapturedVariableInstance (local_info);
3797 ig.Emit (OpCodes.Ldflda, local_info.FieldBuilder);
3801 public override string ToString ()
3803 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3808 /// This represents a reference to a parameter in the intermediate
3811 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3817 public Parameter.Modifier mod;
3818 public bool is_ref, is_out, prepared;
3832 LocalTemporary temp;
3834 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3841 eclass = ExprClass.Variable;
3844 public VariableInfo VariableInfo {
3848 public bool VerifyFixed (bool is_expression)
3850 return !is_expression || TypeManager.IsValueType (type);
3853 public bool IsAssigned (EmitContext ec, Location loc)
3855 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsAssigned (vi))
3858 Report.Error (165, loc,
3859 "Use of unassigned parameter `" + name + "'");
3863 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3865 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3868 Report.Error (170, loc,
3869 "Use of possibly unassigned field `" + field_name + "'");
3873 public void SetAssigned (EmitContext ec)
3875 if (is_out && ec.DoFlowAnalysis)
3876 ec.CurrentBranching.SetAssigned (vi);
3879 public void SetFieldAssigned (EmitContext ec, string field_name)
3881 if (is_out && ec.DoFlowAnalysis)
3882 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3885 protected void DoResolveBase (EmitContext ec)
3887 type = pars.GetParameterInfo (ec, idx, out mod);
3888 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3889 is_out = (mod & Parameter.Modifier.OUT) != 0;
3890 eclass = ExprClass.Variable;
3893 vi = block.ParameterMap [idx];
3895 if (ec.CurrentAnonymousMethod != null){
3897 Report.Error (1628, Location,
3898 "Can not reference a ref or out parameter in an anonymous method");
3903 // If we are referencing the parameter from the external block
3904 // flag it for capturing
3906 //Console.WriteLine ("Is parameter `{0}' local? {1}", name, block.IsLocalParameter (name));
3907 if (!block.IsLocalParameter (name)){
3908 ec.CaptureParameter (name, type, idx);
3914 // Notice that for ref/out parameters, the type exposed is not the
3915 // same type exposed externally.
3918 // externally we expose "int&"
3919 // here we expose "int".
3921 // We record this in "is_ref". This means that the type system can treat
3922 // the type as it is expected, but when we generate the code, we generate
3923 // the alternate kind of code.
3925 public override Expression DoResolve (EmitContext ec)
3929 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3932 if (ec.RemapToProxy)
3933 return ec.RemapParameter (idx);
3938 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3944 if (ec.RemapToProxy)
3945 return ec.RemapParameterLValue (idx, right_side);
3950 static public void EmitLdArg (ILGenerator ig, int x)
3954 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3955 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3956 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3957 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3958 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3961 ig.Emit (OpCodes.Ldarg, x);
3965 // This method is used by parameters that are references, that are
3966 // being passed as references: we only want to pass the pointer (that
3967 // is already stored in the parameter, not the address of the pointer,
3968 // and not the value of the variable).
3970 public void EmitLoad (EmitContext ec)
3972 ILGenerator ig = ec.ig;
3975 if (!ec.MethodIsStatic)
3979 EmitLdArg (ig, arg_idx);
3982 // FIXME: Review for anonymous methods
3986 public override void Emit (EmitContext ec)
3988 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
3989 ec.EmitParameter (name);
3996 public void Emit (EmitContext ec, bool leave_copy)
3998 ILGenerator ig = ec.ig;
4001 if (!ec.MethodIsStatic)
4004 EmitLdArg (ig, arg_idx);
4008 ec.ig.Emit (OpCodes.Dup);
4011 // If we are a reference, we loaded on the stack a pointer
4012 // Now lets load the real value
4014 LoadFromPtr (ig, type);
4018 ec.ig.Emit (OpCodes.Dup);
4021 temp = new LocalTemporary (ec, type);
4027 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
4029 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4030 ec.EmitAssignParameter (name, source, leave_copy, prepare_for_load);
4034 ILGenerator ig = ec.ig;
4037 prepared = prepare_for_load;
4039 if (!ec.MethodIsStatic)
4042 if (is_ref && !prepared)
4043 EmitLdArg (ig, arg_idx);
4048 ec.ig.Emit (OpCodes.Dup);
4052 temp = new LocalTemporary (ec, type);
4056 StoreFromPtr (ig, type);
4062 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
4064 ig.Emit (OpCodes.Starg, arg_idx);
4068 public void AddressOf (EmitContext ec, AddressOp mode)
4070 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4071 ec.EmitAddressOfParameter (name);
4077 if (!ec.MethodIsStatic)
4082 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
4084 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
4087 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
4089 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
4096 /// Used for arguments to New(), Invocation()
4098 public class Argument {
4099 public enum AType : byte {
4106 public readonly AType ArgType;
4107 public Expression Expr;
4109 public Argument (Expression expr, AType type)
4112 this.ArgType = type;
4115 public Argument (Expression expr)
4118 this.ArgType = AType.Expression;
4123 if (ArgType == AType.Ref || ArgType == AType.Out)
4124 return TypeManager.GetReferenceType (Expr.Type);
4130 public Parameter.Modifier GetParameterModifier ()
4134 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
4137 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
4140 return Parameter.Modifier.NONE;
4144 public static string FullDesc (Argument a)
4146 if (a.ArgType == AType.ArgList)
4149 return (a.ArgType == AType.Ref ? "ref " :
4150 (a.ArgType == AType.Out ? "out " : "")) +
4151 TypeManager.CSharpName (a.Expr.Type);
4154 public bool ResolveMethodGroup (EmitContext ec, Location loc)
4156 // FIXME: csc doesn't report any error if you try to use `ref' or
4157 // `out' in a delegate creation expression.
4158 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4165 void Error_LValueRequired (Location loc)
4167 Report.Error (1510, loc, "An lvalue is required as an argument to out or ref");
4170 public bool Resolve (EmitContext ec, Location loc)
4172 if (ArgType == AType.Ref) {
4173 Expr = Expr.Resolve (ec);
4177 if (!ec.IsConstructor) {
4178 FieldExpr fe = Expr as FieldExpr;
4179 if (fe != null && fe.FieldInfo.IsInitOnly) {
4180 if (fe.FieldInfo.IsStatic)
4181 Report.Error (199, loc, "A static readonly field cannot be passed ref or out (except in a static constructor)");
4183 Report.Error (192, loc, "A readonly field cannot be passed ref or out (except in a constructor)");
4187 Expr = Expr.DoResolveLValue (ec, Expr);
4189 Error_LValueRequired (loc);
4190 } else if (ArgType == AType.Out) {
4191 Expr = Expr.DoResolveLValue (ec, EmptyExpression.Null);
4193 Error_LValueRequired (loc);
4196 Expr = Expr.Resolve (ec);
4201 if (Expr is IMemberExpr) {
4202 IMemberExpr me = Expr as IMemberExpr;
4205 // This can happen with the following code:
4209 // public Y (X x) {}
4213 // public Z () : base (X) {}
4216 // SimpleNameResolve is conservative about flagging the X as
4217 // an error since it has identical name and type. However,
4218 // because there's no MemberAccess, that is not really justified.
4219 // It is still simpler to fix it here, rather than in SimpleNameResolve.
4221 if (me.IsInstance && me.InstanceExpression == null) {
4222 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
4227 if (ArgType == AType.Expression)
4231 // Catch errors where fields of a MarshalByRefObject are passed as ref or out
4232 // This is only allowed for `this'
4234 FieldExpr fe = Expr as FieldExpr;
4235 if (fe != null && !fe.IsStatic){
4236 Expression instance = fe.InstanceExpression;
4238 if (instance.GetType () != typeof (This)){
4239 if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
4240 Report.SymbolRelatedToPreviousError (fe.InstanceExpression.Type);
4241 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",
4249 if (Expr.eclass != ExprClass.Variable){
4251 // We just probe to match the CSC output
4253 if (Expr.eclass == ExprClass.PropertyAccess ||
4254 Expr.eclass == ExprClass.IndexerAccess){
4257 "A property or indexer can not be passed as an out or ref " +
4260 Error_LValueRequired (loc);
4268 public void Emit (EmitContext ec)
4271 // Ref and Out parameters need to have their addresses taken.
4273 // ParameterReferences might already be references, so we want
4274 // to pass just the value
4276 if (ArgType == AType.Ref || ArgType == AType.Out){
4277 AddressOp mode = AddressOp.Store;
4279 if (ArgType == AType.Ref)
4280 mode |= AddressOp.Load;
4282 if (Expr is ParameterReference){
4283 ParameterReference pr = (ParameterReference) Expr;
4289 pr.AddressOf (ec, mode);
4292 if (Expr is IMemoryLocation)
4293 ((IMemoryLocation) Expr).AddressOf (ec, mode);
4296 1510, Expr.Location,
4297 "An lvalue is required as an argument to out or ref");
4307 /// Invocation of methods or delegates.
4309 public class Invocation : ExpressionStatement {
4310 public readonly ArrayList Arguments;
4313 MethodBase method = null;
4316 // arguments is an ArrayList, but we do not want to typecast,
4317 // as it might be null.
4319 // FIXME: only allow expr to be a method invocation or a
4320 // delegate invocation (7.5.5)
4322 public Invocation (Expression expr, ArrayList arguments, Location l)
4325 Arguments = arguments;
4329 public Expression Expr {
4336 /// Determines "better conversion" as specified in 7.4.2.3
4338 /// Returns : p if a->p is better,
4339 /// q if a->q is better,
4340 /// null if neither is better
4342 static Type BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
4344 Type argument_type = a.Type;
4345 Expression argument_expr = a.Expr;
4347 if (argument_type == null)
4348 throw new Exception ("Expression of type " + a.Expr +
4349 " does not resolve its type");
4351 if (p == null || q == null)
4352 throw new InternalErrorException ("BetterConversion Got a null conversion");
4357 if (argument_expr is NullLiteral) {
4359 // If the argument is null and one of the types to compare is 'object' and
4360 // the other is a reference type, we prefer the other.
4362 // This follows from the usual rules:
4363 // * There is an implicit conversion from 'null' to type 'object'
4364 // * There is an implicit conversion from 'null' to any reference type
4365 // * There is an implicit conversion from any reference type to type 'object'
4366 // * There is no implicit conversion from type 'object' to other reference types
4367 // => Conversion of 'null' to a reference type is better than conversion to 'object'
4369 // FIXME: This probably isn't necessary, since the type of a NullLiteral is the
4370 // null type. I think it used to be 'object' and thus needed a special
4371 // case to avoid the immediately following two checks.
4373 if (!p.IsValueType && q == TypeManager.object_type)
4375 if (!q.IsValueType && p == TypeManager.object_type)
4379 if (argument_type == p)
4382 if (argument_type == q)
4385 Expression p_tmp = new EmptyExpression (p);
4386 Expression q_tmp = new EmptyExpression (q);
4388 bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
4389 bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
4391 if (p_to_q && !q_to_p)
4394 if (q_to_p && !p_to_q)
4397 if (p == TypeManager.sbyte_type)
4398 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4399 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4401 if (q == TypeManager.sbyte_type)
4402 if (p == TypeManager.byte_type || p == TypeManager.ushort_type ||
4403 p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4406 if (p == TypeManager.short_type)
4407 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4408 q == TypeManager.uint64_type)
4410 if (q == TypeManager.short_type)
4411 if (p == TypeManager.ushort_type || p == TypeManager.uint32_type ||
4412 p == TypeManager.uint64_type)
4415 if (p == TypeManager.int32_type)
4416 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4418 if (q == TypeManager.int32_type)
4419 if (p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4422 if (p == TypeManager.int64_type)
4423 if (q == TypeManager.uint64_type)
4425 if (q == TypeManager.int64_type)
4426 if (p == TypeManager.uint64_type)
4433 /// Determines "Better function" between candidate
4434 /// and the current best match
4437 /// Returns an integer indicating :
4438 /// false if candidate ain't better
4439 /// true if candidate is better than the current best match
4441 static bool BetterFunction (EmitContext ec, ArrayList args, int argument_count,
4442 MethodBase candidate, bool candidate_params,
4443 MethodBase best, bool best_params, Location loc)
4445 ParameterData candidate_pd = TypeManager.GetParameterData (candidate);
4446 ParameterData best_pd = TypeManager.GetParameterData (best);
4448 bool better_at_least_one = false;
4450 for (int j = 0; j < argument_count; ++j) {
4451 Argument a = (Argument) args [j];
4453 Type ct = TypeManager.TypeToCoreType (candidate_pd.ParameterType (j));
4454 Type bt = TypeManager.TypeToCoreType (best_pd.ParameterType (j));
4456 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4457 if (candidate_params)
4458 ct = TypeManager.GetElementType (ct);
4460 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4462 bt = TypeManager.GetElementType (bt);
4468 Type better = BetterConversion (ec, a, ct, bt, loc);
4470 // for each argument, the conversion to 'ct' should be no worse than
4471 // the conversion to 'bt'.
4475 // for at least one argument, the conversion to 'ct' should be better than
4476 // the conversion to 'bt'.
4478 better_at_least_one = true;
4481 if (better_at_least_one)
4485 // This handles the case
4487 // Add (float f1, float f2, float f3);
4488 // Add (params decimal [] foo);
4490 // The call Add (3, 4, 5) should be ambiguous. Without this check, the
4491 // first candidate would've chosen as better.
4497 // This handles the following cases:
4499 // Trim () is better than Trim (params char[] chars)
4500 // Concat (string s1, string s2, string s3) is better than
4501 // Concat (string s1, params string [] srest)
4503 return !candidate_params && best_params;
4506 static bool IsOverride (MethodBase cand_method, MethodBase base_method)
4508 if (!IsAncestralType (base_method.DeclaringType, cand_method.DeclaringType))
4511 ParameterData cand_pd = TypeManager.GetParameterData (cand_method);
4512 ParameterData base_pd = TypeManager.GetParameterData (base_method);
4514 if (cand_pd.Count != base_pd.Count)
4517 for (int j = 0; j < cand_pd.Count; ++j) {
4518 Parameter.Modifier cm = cand_pd.ParameterModifier (j);
4519 Parameter.Modifier bm = base_pd.ParameterModifier (j);
4520 Type ct = TypeManager.TypeToCoreType (cand_pd.ParameterType (j));
4521 Type bt = TypeManager.TypeToCoreType (base_pd.ParameterType (j));
4523 if (cm != bm || ct != bt)
4530 public static string FullMethodDesc (MethodBase mb)
4532 string ret_type = "";
4537 if (mb is MethodInfo)
4538 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
4540 StringBuilder sb = new StringBuilder (ret_type);
4542 sb.Append (mb.ReflectedType.ToString ());
4544 sb.Append (mb.Name);
4546 ParameterData pd = TypeManager.GetParameterData (mb);
4548 int count = pd.Count;
4551 for (int i = count; i > 0; ) {
4554 sb.Append (pd.ParameterDesc (count - i - 1));
4560 return sb.ToString ();
4563 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4565 MemberInfo [] miset;
4566 MethodGroupExpr union;
4571 return (MethodGroupExpr) mg2;
4574 return (MethodGroupExpr) mg1;
4577 MethodGroupExpr left_set = null, right_set = null;
4578 int length1 = 0, length2 = 0;
4580 left_set = (MethodGroupExpr) mg1;
4581 length1 = left_set.Methods.Length;
4583 right_set = (MethodGroupExpr) mg2;
4584 length2 = right_set.Methods.Length;
4586 ArrayList common = new ArrayList ();
4588 foreach (MethodBase r in right_set.Methods){
4589 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
4593 miset = new MemberInfo [length1 + length2 - common.Count];
4594 left_set.Methods.CopyTo (miset, 0);
4598 foreach (MethodBase r in right_set.Methods) {
4599 if (!common.Contains (r))
4603 union = new MethodGroupExpr (miset, loc);
4608 public static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4609 ArrayList arguments, int arg_count,
4610 ref MethodBase candidate)
4612 return IsParamsMethodApplicable (
4613 ec, me, arguments, arg_count, false, ref candidate) ||
4614 IsParamsMethodApplicable (
4615 ec, me, arguments, arg_count, true, ref candidate);
4620 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4621 ArrayList arguments, int arg_count,
4622 bool do_varargs, ref MethodBase candidate)
4624 return IsParamsMethodApplicable (
4625 ec, arguments, arg_count, candidate, do_varargs);
4629 /// Determines if the candidate method, if a params method, is applicable
4630 /// in its expanded form to the given set of arguments
4632 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
4633 int arg_count, MethodBase candidate,
4636 ParameterData pd = TypeManager.GetParameterData (candidate);
4638 int pd_count = pd.Count;
4642 int count = pd_count - 1;
4644 if (pd.ParameterModifier (count) != Parameter.Modifier.ARGLIST)
4646 if (pd_count != arg_count)
4649 if (pd.ParameterModifier (count) != Parameter.Modifier.PARAMS)
4653 if (count > arg_count)
4656 if (pd_count == 1 && arg_count == 0)
4660 // If we have come this far, the case which
4661 // remains is when the number of parameters is
4662 // less than or equal to the argument count.
4664 for (int i = 0; i < count; ++i) {
4666 Argument a = (Argument) arguments [i];
4668 Parameter.Modifier a_mod = a.GetParameterModifier () &
4669 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4670 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4671 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4673 if (a_mod == p_mod) {
4675 if (a_mod == Parameter.Modifier.NONE)
4676 if (!Convert.ImplicitConversionExists (ec,
4678 pd.ParameterType (i)))
4681 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4682 Type pt = pd.ParameterType (i);
4685 pt = TypeManager.GetReferenceType (pt);
4696 Argument a = (Argument) arguments [count];
4697 if (!(a.Expr is Arglist))
4703 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4705 for (int i = pd_count - 1; i < arg_count; i++) {
4706 Argument a = (Argument) arguments [i];
4708 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4715 public static bool IsApplicable (EmitContext ec, MethodGroupExpr me,
4716 ArrayList arguments, int arg_count,
4717 ref MethodBase candidate)
4719 return IsApplicable (ec, arguments, arg_count, candidate);
4723 /// Determines if the candidate method is applicable (section 14.4.2.1)
4724 /// to the given set of arguments
4726 static bool IsApplicable (EmitContext ec, ArrayList arguments, int arg_count,
4727 MethodBase candidate)
4729 ParameterData pd = TypeManager.GetParameterData (candidate);
4731 if (arg_count != pd.Count)
4734 for (int i = arg_count; i > 0; ) {
4737 Argument a = (Argument) arguments [i];
4739 Parameter.Modifier a_mod = a.GetParameterModifier () &
4740 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4741 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4742 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4745 if (a_mod == p_mod ||
4746 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4747 if (a_mod == Parameter.Modifier.NONE) {
4748 if (!Convert.ImplicitConversionExists (ec,
4750 pd.ParameterType (i)))
4754 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4755 Type pt = pd.ParameterType (i);
4758 pt = TypeManager.GetReferenceType (pt);
4770 static private bool IsAncestralType (Type first_type, Type second_type)
4772 return first_type != second_type &&
4773 (second_type.IsSubclassOf (first_type) ||
4774 TypeManager.ImplementsInterface (second_type, first_type));
4778 /// Find the Applicable Function Members (7.4.2.1)
4780 /// me: Method Group expression with the members to select.
4781 /// it might contain constructors or methods (or anything
4782 /// that maps to a method).
4784 /// Arguments: ArrayList containing resolved Argument objects.
4786 /// loc: The location if we want an error to be reported, or a Null
4787 /// location for "probing" purposes.
4789 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4790 /// that is the best match of me on Arguments.
4793 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4794 ArrayList Arguments, bool may_fail,
4797 MethodBase method = null;
4798 bool method_params = false;
4799 Type applicable_type = null;
4801 ArrayList candidates = new ArrayList ();
4802 ArrayList candidate_overrides = new ArrayList ();
4805 // Used to keep a map between the candidate
4806 // and whether it is being considered in its
4807 // normal or expanded form
4809 // false is normal form, true is expanded form
4811 Hashtable candidate_to_form = null;
4813 if (Arguments != null)
4814 arg_count = Arguments.Count;
4816 if ((me.Name == "Invoke") &&
4817 TypeManager.IsDelegateType (me.DeclaringType)) {
4818 Error_InvokeOnDelegate (loc);
4822 MethodBase[] methods = me.Methods;
4825 // First we construct the set of applicable methods
4827 bool is_sorted = true;
4828 for (int i = 0; i < methods.Length; i++){
4829 Type decl_type = methods [i].DeclaringType;
4832 // If we have already found an applicable method
4833 // we eliminate all base types (Section 14.5.5.1)
4835 if ((applicable_type != null) &&
4836 IsAncestralType (decl_type, applicable_type))
4840 // Methods marked 'override' don't take part in 'applicable_type'
4841 // computation, nor in the actual overload resolution.
4842 // However, they still need to be emitted instead of a base virtual method.
4843 // We avoid doing the 'applicable' test here, since it'll anyway be applied
4844 // to the base virtual function, and IsOverride is much faster than IsApplicable.
4847 methods [i].IsVirtual &&
4848 (methods [i].Attributes & MethodAttributes.NewSlot) == 0) {
4849 candidate_overrides.Add (methods [i]);
4854 // Check if candidate is applicable (section 14.4.2.1)
4855 // Is candidate applicable in normal form?
4857 bool is_applicable = IsApplicable (
4858 ec, me, Arguments, arg_count, ref methods [i]);
4860 if (!is_applicable &&
4861 (IsParamsMethodApplicable (
4862 ec, me, Arguments, arg_count, ref methods [i]))) {
4863 MethodBase candidate = methods [i];
4864 if (candidate_to_form == null)
4865 candidate_to_form = new PtrHashtable ();
4866 candidate_to_form [candidate] = candidate;
4867 // Candidate is applicable in expanded form
4868 is_applicable = true;
4874 candidates.Add (methods [i]);
4876 if (applicable_type == null)
4877 applicable_type = decl_type;
4878 else if (applicable_type != decl_type) {
4880 if (IsAncestralType (applicable_type, decl_type))
4881 applicable_type = decl_type;
4885 int candidate_top = candidates.Count;
4887 if (applicable_type == null) {
4889 // Okay so we have failed to find anything so we
4890 // return by providing info about the closest match
4892 for (int i = 0; i < methods.Length; ++i) {
4893 MethodBase c = (MethodBase) methods [i];
4894 ParameterData pd = TypeManager.GetParameterData (c);
4896 if (pd.Count != arg_count)
4899 VerifyArgumentsCompat (ec, Arguments, arg_count,
4900 c, false, null, may_fail, loc);
4905 string report_name = me.Name;
4906 if (report_name == ".ctor")
4907 report_name = me.DeclaringType.ToString ();
4909 Error_WrongNumArguments (
4910 loc, report_name, arg_count);
4919 // At this point, applicable_type is _one_ of the most derived types
4920 // in the set of types containing the methods in this MethodGroup.
4921 // Filter the candidates so that they only contain methods from the
4922 // most derived types.
4925 int finalized = 0; // Number of finalized candidates
4928 // Invariant: applicable_type is a most derived type
4930 // We'll try to complete Section 14.5.5.1 for 'applicable_type' by
4931 // eliminating all it's base types. At the same time, we'll also move
4932 // every unrelated type to the end of the array, and pick the next
4933 // 'applicable_type'.
4935 Type next_applicable_type = null;
4936 int j = finalized; // where to put the next finalized candidate
4937 int k = finalized; // where to put the next undiscarded candidate
4938 for (int i = finalized; i < candidate_top; ++i) {
4939 MethodBase candidate = (MethodBase) candidates [i];
4940 Type decl_type = candidate.DeclaringType;
4942 if (decl_type == applicable_type) {
4943 candidates [k++] = candidates [j];
4944 candidates [j++] = candidates [i];
4948 if (IsAncestralType (decl_type, applicable_type))
4951 if (next_applicable_type != null &&
4952 IsAncestralType (decl_type, next_applicable_type))
4955 candidates [k++] = candidates [i];
4957 if (next_applicable_type == null ||
4958 IsAncestralType (next_applicable_type, decl_type))
4959 next_applicable_type = decl_type;
4962 applicable_type = next_applicable_type;
4965 } while (applicable_type != null);
4969 // Now we actually find the best method
4972 method = (MethodBase) candidates [0];
4973 method_params = candidate_to_form != null && candidate_to_form.Contains (method);
4974 for (int ix = 1; ix < candidate_top; ix++){
4975 MethodBase candidate = (MethodBase) candidates [ix];
4977 if (candidate == method)
4980 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4982 if (BetterFunction (ec, Arguments, arg_count,
4983 candidate, cand_params,
4984 method, method_params, loc)) {
4986 method_params = cand_params;
4991 // Now check that there are no ambiguities i.e the selected method
4992 // should be better than all the others
4994 bool ambiguous = false;
4995 for (int ix = 0; ix < candidate_top; ix++){
4996 MethodBase candidate = (MethodBase) candidates [ix];
4998 if (candidate == method)
5001 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
5002 if (!BetterFunction (ec, Arguments, arg_count,
5003 method, method_params,
5004 candidate, cand_params,
5006 Report.SymbolRelatedToPreviousError (candidate);
5012 Report.SymbolRelatedToPreviousError (method);
5013 Report.Error (121, loc, "Ambiguous call when selecting function due to implicit casts");
5018 // If the method is a virtual function, pick an override closer to the LHS type.
5020 if (!me.IsBase && method.IsVirtual) {
5021 if ((method.Attributes & MethodAttributes.NewSlot) != MethodAttributes.NewSlot)
5022 throw new InternalErrorException (
5023 "Should not happen. An 'override' method took part in overload resolution: " + method);
5025 foreach (MethodBase candidate in candidate_overrides) {
5026 if (IsOverride (candidate, method))
5032 // And now check if the arguments are all
5033 // compatible, perform conversions if
5034 // necessary etc. and return if everything is
5037 if (!VerifyArgumentsCompat (ec, Arguments, arg_count, method,
5038 method_params, null, may_fail, loc))
5044 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
5046 Report.Error (1501, loc,
5047 "No overload for method `" + name + "' takes `" +
5048 arg_count + "' arguments");
5051 static void Error_InvokeOnDelegate (Location loc)
5053 Report.Error (1533, loc,
5054 "Invoke cannot be called directly on a delegate");
5057 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
5058 Type delegate_type, string arg_sig, string par_desc)
5060 if (delegate_type == null)
5061 Report.Error (1502, loc,
5062 "The best overloaded match for method '" +
5063 FullMethodDesc (method) +
5064 "' has some invalid arguments");
5066 Report.Error (1594, loc,
5067 "Delegate '" + delegate_type.ToString () +
5068 "' has some invalid arguments.");
5069 Report.Error (1503, loc,
5070 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
5071 idx, arg_sig, par_desc));
5074 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
5075 int arg_count, MethodBase method,
5076 bool chose_params_expanded,
5077 Type delegate_type, bool may_fail,
5080 ParameterData pd = TypeManager.GetParameterData (method);
5081 int pd_count = pd.Count;
5083 for (int j = 0; j < arg_count; j++) {
5084 Argument a = (Argument) Arguments [j];
5085 Expression a_expr = a.Expr;
5086 Type parameter_type = pd.ParameterType (j);
5087 Parameter.Modifier pm = pd.ParameterModifier (j);
5089 if (pm == Parameter.Modifier.PARAMS){
5090 if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
5092 Error_InvalidArguments (
5093 loc, j, method, delegate_type,
5094 Argument.FullDesc (a), pd.ParameterDesc (j));
5098 if (chose_params_expanded)
5099 parameter_type = TypeManager.GetElementType (parameter_type);
5100 } else if (pm == Parameter.Modifier.ARGLIST){
5106 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
5108 Error_InvalidArguments (
5109 loc, j, method, delegate_type,
5110 Argument.FullDesc (a), pd.ParameterDesc (j));
5118 if (!a.Type.Equals (parameter_type)){
5121 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
5125 Error_InvalidArguments (
5126 loc, j, method, delegate_type,
5127 Argument.FullDesc (a), pd.ParameterDesc (j));
5132 // Update the argument with the implicit conversion
5138 if (parameter_type.IsPointer){
5145 Parameter.Modifier a_mod = a.GetParameterModifier () &
5146 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5147 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
5148 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5150 if (a_mod != p_mod &&
5151 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
5153 Report.Error (1502, loc,
5154 "The best overloaded match for method '" + FullMethodDesc (method)+
5155 "' has some invalid arguments");
5156 Report.Error (1503, loc,
5157 "Argument " + (j+1) +
5158 ": Cannot convert from '" + Argument.FullDesc (a)
5159 + "' to '" + pd.ParameterDesc (j) + "'");
5169 public override Expression DoResolve (EmitContext ec)
5172 // First, resolve the expression that is used to
5173 // trigger the invocation
5175 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
5179 if (!(expr is MethodGroupExpr)) {
5180 Type expr_type = expr.Type;
5182 if (expr_type != null){
5183 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
5185 return (new DelegateInvocation (
5186 this.expr, Arguments, loc)).Resolve (ec);
5190 if (!(expr is MethodGroupExpr)){
5191 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup, loc);
5196 // Next, evaluate all the expressions in the argument list
5198 if (Arguments != null){
5199 foreach (Argument a in Arguments){
5200 if (!a.Resolve (ec, loc))
5205 MethodGroupExpr mg = (MethodGroupExpr) expr;
5206 method = OverloadResolve (ec, mg, Arguments, false, loc);
5211 MethodInfo mi = method as MethodInfo;
5213 type = TypeManager.TypeToCoreType (mi.ReturnType);
5214 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null)) {
5215 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
5219 Expression iexpr = mg.InstanceExpression;
5220 if (mi.IsStatic && (iexpr != null) && !(iexpr is This)) {
5221 if (mg.IdenticalTypeName)
5222 mg.InstanceExpression = null;
5224 MemberAccess.error176 (loc, mi.Name);
5230 if (type.IsPointer){
5238 // Only base will allow this invocation to happen.
5240 if (mg.IsBase && method.IsAbstract){
5241 Report.Error (205, loc, "Cannot call an abstract base member: " +
5242 FullMethodDesc (method));
5246 if (method.Name == "Finalize" && Arguments == null) {
5248 Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
5250 Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
5254 if ((method.Attributes & MethodAttributes.SpecialName) != 0) {
5255 if (TypeManager.LookupDeclSpace (method.DeclaringType) != null || TypeManager.IsSpecialMethod (method)) {
5256 Report.Error (571, loc, TypeManager.CSharpSignature (method) + ": can not call operator or accessor");
5261 if (mg.InstanceExpression != null)
5262 mg.InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
5264 eclass = ExprClass.Value;
5269 // Emits the list of arguments as an array
5271 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
5273 ILGenerator ig = ec.ig;
5274 int count = arguments.Count - idx;
5275 Argument a = (Argument) arguments [idx];
5276 Type t = a.Expr.Type;
5278 IntConstant.EmitInt (ig, count);
5279 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
5281 int top = arguments.Count;
5282 for (int j = idx; j < top; j++){
5283 a = (Argument) arguments [j];
5285 ig.Emit (OpCodes.Dup);
5286 IntConstant.EmitInt (ig, j - idx);
5289 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj);
5291 ig.Emit (OpCodes.Ldelema, t);
5296 ig.Emit (OpCodes.Stobj, t);
5303 /// Emits a list of resolved Arguments that are in the arguments
5306 /// The MethodBase argument might be null if the
5307 /// emission of the arguments is known not to contain
5308 /// a `params' field (for example in constructors or other routines
5309 /// that keep their arguments in this structure)
5311 /// if `dup_args' is true, a copy of the arguments will be left
5312 /// on the stack. If `dup_args' is true, you can specify `this_arg'
5313 /// which will be duplicated before any other args. Only EmitCall
5314 /// should be using this interface.
5316 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments, bool dup_args, LocalTemporary this_arg)
5320 pd = TypeManager.GetParameterData (mb);
5324 LocalTemporary [] temps = null;
5327 temps = new LocalTemporary [arguments.Count];
5330 // If we are calling a params method with no arguments, special case it
5332 if (arguments == null){
5333 if (pd != null && pd.Count > 0 &&
5334 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
5335 ILGenerator ig = ec.ig;
5337 IntConstant.EmitInt (ig, 0);
5338 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
5344 int top = arguments.Count;
5346 for (int i = 0; i < top; i++){
5347 Argument a = (Argument) arguments [i];
5350 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
5352 // Special case if we are passing the same data as the
5353 // params argument, do not put it in an array.
5355 if (pd.ParameterType (i) == a.Type)
5358 EmitParams (ec, i, arguments);
5365 ec.ig.Emit (OpCodes.Dup);
5366 (temps [i] = new LocalTemporary (ec, a.Type)).Store (ec);
5371 if (this_arg != null)
5374 for (int i = 0; i < top; i ++)
5375 temps [i].Emit (ec);
5378 if (pd != null && pd.Count > top &&
5379 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
5380 ILGenerator ig = ec.ig;
5382 IntConstant.EmitInt (ig, 0);
5383 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
5387 static Type[] GetVarargsTypes (EmitContext ec, MethodBase mb,
5388 ArrayList arguments)
5390 ParameterData pd = TypeManager.GetParameterData (mb);
5392 if (arguments == null)
5393 return new Type [0];
5395 Argument a = (Argument) arguments [pd.Count - 1];
5396 Arglist list = (Arglist) a.Expr;
5398 return list.ArgumentTypes;
5402 /// This checks the ConditionalAttribute on the method
5404 static bool IsMethodExcluded (MethodBase method, EmitContext ec)
5406 if (method.IsConstructor)
5409 IMethodData md = TypeManager.GetMethod (method);
5411 return md.IsExcluded (ec);
5413 // For some methods (generated by delegate class) GetMethod returns null
5414 // because they are not included in builder_to_method table
5415 if (method.DeclaringType is TypeBuilder)
5418 return AttributeTester.IsConditionalMethodExcluded (method);
5422 /// is_base tells whether we want to force the use of the `call'
5423 /// opcode instead of using callvirt. Call is required to call
5424 /// a specific method, while callvirt will always use the most
5425 /// recent method in the vtable.
5427 /// is_static tells whether this is an invocation on a static method
5429 /// instance_expr is an expression that represents the instance
5430 /// it must be non-null if is_static is false.
5432 /// method is the method to invoke.
5434 /// Arguments is the list of arguments to pass to the method or constructor.
5436 public static void EmitCall (EmitContext ec, bool is_base,
5437 bool is_static, Expression instance_expr,
5438 MethodBase method, ArrayList Arguments, Location loc)
5440 EmitCall (ec, is_base, is_static, instance_expr, method, Arguments, loc, false, false);
5443 // `dup_args' leaves an extra copy of the arguments on the stack
5444 // `omit_args' does not leave any arguments at all.
5445 // So, basically, you could make one call with `dup_args' set to true,
5446 // and then another with `omit_args' set to true, and the two calls
5447 // would have the same set of arguments. However, each argument would
5448 // only have been evaluated once.
5449 public static void EmitCall (EmitContext ec, bool is_base,
5450 bool is_static, Expression instance_expr,
5451 MethodBase method, ArrayList Arguments, Location loc,
5452 bool dup_args, bool omit_args)
5454 ILGenerator ig = ec.ig;
5455 bool struct_call = false;
5456 bool this_call = false;
5457 LocalTemporary this_arg = null;
5459 Type decl_type = method.DeclaringType;
5461 if (!RootContext.StdLib) {
5462 // Replace any calls to the system's System.Array type with calls to
5463 // the newly created one.
5464 if (method == TypeManager.system_int_array_get_length)
5465 method = TypeManager.int_array_get_length;
5466 else if (method == TypeManager.system_int_array_get_rank)
5467 method = TypeManager.int_array_get_rank;
5468 else if (method == TypeManager.system_object_array_clone)
5469 method = TypeManager.object_array_clone;
5470 else if (method == TypeManager.system_int_array_get_length_int)
5471 method = TypeManager.int_array_get_length_int;
5472 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5473 method = TypeManager.int_array_get_lower_bound_int;
5474 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5475 method = TypeManager.int_array_get_upper_bound_int;
5476 else if (method == TypeManager.system_void_array_copyto_array_int)
5477 method = TypeManager.void_array_copyto_array_int;
5480 if (ec.TestObsoleteMethodUsage) {
5482 // This checks ObsoleteAttribute on the method and on the declaring type
5484 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
5486 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
5489 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
5491 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
5495 if (IsMethodExcluded (method, ec))
5499 this_call = instance_expr == null;
5500 if (decl_type.IsValueType || (!this_call && instance_expr.Type.IsValueType))
5504 // If this is ourselves, push "this"
5509 ig.Emit (OpCodes.Ldarg_0);
5513 // Push the instance expression
5515 if (instance_expr.Type.IsValueType) {
5517 // Special case: calls to a function declared in a
5518 // reference-type with a value-type argument need
5519 // to have their value boxed.
5520 if (decl_type.IsValueType) {
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, instance_expr.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 (instance_expr.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);
5564 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
5565 call_op = OpCodes.Call;
5567 call_op = OpCodes.Callvirt;
5569 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
5570 Type[] varargs_types = GetVarargsTypes (ec, method, Arguments);
5571 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
5578 // and DoFoo is not virtual, you can omit the callvirt,
5579 // because you don't need the null checking behavior.
5581 if (method is MethodInfo)
5582 ig.Emit (call_op, (MethodInfo) method);
5584 ig.Emit (call_op, (ConstructorInfo) method);
5587 public override void Emit (EmitContext ec)
5589 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5591 EmitCall (ec, mg.IsBase, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5594 public override void EmitStatement (EmitContext ec)
5599 // Pop the return value if there is one
5601 if (method is MethodInfo){
5602 Type ret = ((MethodInfo)method).ReturnType;
5603 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5604 ec.ig.Emit (OpCodes.Pop);
5609 public class InvocationOrCast : ExpressionStatement
5612 Expression argument;
5614 public InvocationOrCast (Expression expr, Expression argument, Location loc)
5617 this.argument = argument;
5621 public override Expression DoResolve (EmitContext ec)
5624 // First try to resolve it as a cast.
5626 TypeExpr te = expr.ResolveAsTypeTerminal (ec, true);
5628 Cast cast = new Cast (te, argument, loc);
5629 return cast.Resolve (ec);
5633 // This can either be a type or a delegate invocation.
5634 // Let's just resolve it and see what we'll get.
5636 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5641 // Ok, so it's a Cast.
5643 if (expr.eclass == ExprClass.Type) {
5644 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
5645 return cast.Resolve (ec);
5649 // It's a delegate invocation.
5651 if (!TypeManager.IsDelegateType (expr.Type)) {
5652 Error (149, "Method name expected");
5656 ArrayList args = new ArrayList ();
5657 args.Add (new Argument (argument, Argument.AType.Expression));
5658 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5659 return invocation.Resolve (ec);
5664 Error (201, "Only assignment, call, increment, decrement and new object " +
5665 "expressions can be used as a statement");
5668 public override ExpressionStatement ResolveStatement (EmitContext ec)
5671 // First try to resolve it as a cast.
5673 TypeExpr te = expr.ResolveAsTypeTerminal (ec, true);
5680 // This can either be a type or a delegate invocation.
5681 // Let's just resolve it and see what we'll get.
5683 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5684 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5690 // It's a delegate invocation.
5692 if (!TypeManager.IsDelegateType (expr.Type)) {
5693 Error (149, "Method name expected");
5697 ArrayList args = new ArrayList ();
5698 args.Add (new Argument (argument, Argument.AType.Expression));
5699 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5700 return invocation.ResolveStatement (ec);
5703 public override void Emit (EmitContext ec)
5705 throw new Exception ("Cannot happen");
5708 public override void EmitStatement (EmitContext ec)
5710 throw new Exception ("Cannot happen");
5715 // This class is used to "disable" the code generation for the
5716 // temporary variable when initializing value types.
5718 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5719 public void AddressOf (EmitContext ec, AddressOp Mode)
5726 /// Implements the new expression
5728 public class New : ExpressionStatement, IMemoryLocation {
5729 public readonly ArrayList Arguments;
5732 // During bootstrap, it contains the RequestedType,
5733 // but if `type' is not null, it *might* contain a NewDelegate
5734 // (because of field multi-initialization)
5736 public Expression RequestedType;
5738 MethodBase method = null;
5741 // If set, the new expression is for a value_target, and
5742 // we will not leave anything on the stack.
5744 Expression value_target;
5745 bool value_target_set = false;
5747 public New (Expression requested_type, ArrayList arguments, Location l)
5749 RequestedType = requested_type;
5750 Arguments = arguments;
5754 public bool SetValueTypeVariable (Expression value)
5756 value_target = value;
5757 value_target_set = true;
5758 if (!(value_target is IMemoryLocation)){
5759 Error_UnexpectedKind ("variable", loc);
5766 // This function is used to disable the following code sequence for
5767 // value type initialization:
5769 // AddressOf (temporary)
5773 // Instead the provide will have provided us with the address on the
5774 // stack to store the results.
5776 static Expression MyEmptyExpression;
5778 public void DisableTemporaryValueType ()
5780 if (MyEmptyExpression == null)
5781 MyEmptyExpression = new EmptyAddressOf ();
5784 // To enable this, look into:
5785 // test-34 and test-89 and self bootstrapping.
5787 // For instance, we can avoid a copy by using `newobj'
5788 // instead of Call + Push-temp on value types.
5789 // value_target = MyEmptyExpression;
5794 /// Converts complex core type syntax like 'new int ()' to simple constant
5796 Expression Constantify (Type t)
5798 if (t == TypeManager.int32_type)
5799 return new IntConstant (0);
5800 if (t == TypeManager.uint32_type)
5801 return new UIntConstant (0);
5802 if (t == TypeManager.int64_type)
5803 return new LongConstant (0);
5804 if (t == TypeManager.uint64_type)
5805 return new ULongConstant (0);
5806 if (t == TypeManager.float_type)
5807 return new FloatConstant (0);
5808 if (t == TypeManager.double_type)
5809 return new DoubleConstant (0);
5810 if (t == TypeManager.short_type)
5811 return new ShortConstant (0);
5812 if (t == TypeManager.ushort_type)
5813 return new UShortConstant (0);
5814 if (t == TypeManager.sbyte_type)
5815 return new SByteConstant (0);
5816 if (t == TypeManager.byte_type)
5817 return new ByteConstant (0);
5818 if (t == TypeManager.char_type)
5819 return new CharConstant ('\0');
5820 if (t == TypeManager.bool_type)
5821 return new BoolConstant (false);
5822 if (t == TypeManager.decimal_type)
5823 return new DecimalConstant (0);
5828 public override Expression DoResolve (EmitContext ec)
5831 // The New DoResolve might be called twice when initializing field
5832 // expressions (see EmitFieldInitializers, the call to
5833 // GetInitializerExpression will perform a resolve on the expression,
5834 // and later the assign will trigger another resolution
5836 // This leads to bugs (#37014)
5839 if (RequestedType is NewDelegate)
5840 return RequestedType;
5844 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec, false);
5848 type = texpr.ResolveType (ec);
5850 if (Arguments == null) {
5851 Expression c = Constantify (type);
5856 CheckObsoleteAttribute (type);
5858 bool IsDelegate = TypeManager.IsDelegateType (type);
5861 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5862 if (RequestedType != null)
5863 if (!(RequestedType is DelegateCreation))
5864 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
5865 return RequestedType;
5868 if (type.IsAbstract && type.IsSealed) {
5869 Report.Error (712, loc, "Cannot create an instance of the static class '{0}'", TypeManager.CSharpName (type));
5873 if (type.IsInterface || type.IsAbstract){
5874 Error (144, "It is not possible to create instances of interfaces or abstract classes");
5878 bool is_struct = type.IsValueType;
5879 eclass = ExprClass.Value;
5882 // SRE returns a match for .ctor () on structs (the object constructor),
5883 // so we have to manually ignore it.
5885 if (is_struct && Arguments == null)
5889 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
5890 ml = MemberLookupFinal (ec, type, type, ".ctor",
5891 MemberTypes.Constructor,
5892 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5897 if (! (ml is MethodGroupExpr)){
5899 ml.Error_UnexpectedKind ("method group", loc);
5905 if (Arguments != null){
5906 foreach (Argument a in Arguments){
5907 if (!a.Resolve (ec, loc))
5912 method = Invocation.OverloadResolve (
5913 ec, (MethodGroupExpr) ml, Arguments, true, loc);
5917 if (method == null) {
5918 if (almostMatchedMembers.Count != 0) {
5919 MemberLookupFailed (ec, type, type, ".ctor", null, true, loc);
5923 if (!is_struct || Arguments.Count > 0) {
5924 Error (1501, String.Format (
5925 "New invocation: Can not find a constructor in `{0}' for this argument list",
5926 TypeManager.CSharpName (type)));
5935 // This DoEmit can be invoked in two contexts:
5936 // * As a mechanism that will leave a value on the stack (new object)
5937 // * As one that wont (init struct)
5939 // You can control whether a value is required on the stack by passing
5940 // need_value_on_stack. The code *might* leave a value on the stack
5941 // so it must be popped manually
5943 // If we are dealing with a ValueType, we have a few
5944 // situations to deal with:
5946 // * The target is a ValueType, and we have been provided
5947 // the instance (this is easy, we are being assigned).
5949 // * The target of New is being passed as an argument,
5950 // to a boxing operation or a function that takes a
5953 // In this case, we need to create a temporary variable
5954 // that is the argument of New.
5956 // Returns whether a value is left on the stack
5958 bool DoEmit (EmitContext ec, bool need_value_on_stack)
5960 bool is_value_type = type.IsValueType;
5961 ILGenerator ig = ec.ig;
5966 // Allow DoEmit() to be called multiple times.
5967 // We need to create a new LocalTemporary each time since
5968 // you can't share LocalBuilders among ILGeneators.
5969 if (!value_target_set)
5970 value_target = new LocalTemporary (ec, type);
5972 ml = (IMemoryLocation) value_target;
5973 ml.AddressOf (ec, AddressOp.Store);
5977 Invocation.EmitArguments (ec, method, Arguments, false, null);
5981 ig.Emit (OpCodes.Initobj, type);
5983 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5984 if (need_value_on_stack){
5985 value_target.Emit (ec);
5990 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
5995 public override void Emit (EmitContext ec)
6000 public override void EmitStatement (EmitContext ec)
6002 if (DoEmit (ec, false))
6003 ec.ig.Emit (OpCodes.Pop);
6006 public void AddressOf (EmitContext ec, AddressOp Mode)
6008 if (!type.IsValueType){
6010 // We throw an exception. So far, I believe we only need to support
6012 // foreach (int j in new StructType ())
6015 throw new Exception ("AddressOf should not be used for classes");
6018 if (!value_target_set)
6019 value_target = new LocalTemporary (ec, type);
6021 IMemoryLocation ml = (IMemoryLocation) value_target;
6022 ml.AddressOf (ec, AddressOp.Store);
6024 Invocation.EmitArguments (ec, method, Arguments, false, null);
6027 ec.ig.Emit (OpCodes.Initobj, type);
6029 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6031 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
6036 /// 14.5.10.2: Represents an array creation expression.
6040 /// There are two possible scenarios here: one is an array creation
6041 /// expression that specifies the dimensions and optionally the
6042 /// initialization data and the other which does not need dimensions
6043 /// specified but where initialization data is mandatory.
6045 public class ArrayCreation : Expression {
6046 Expression requested_base_type;
6047 ArrayList initializers;
6050 // The list of Argument types.
6051 // This is used to construct the `newarray' or constructor signature
6053 ArrayList arguments;
6056 // Method used to create the array object.
6058 MethodBase new_method = null;
6060 Type array_element_type;
6061 Type underlying_type;
6062 bool is_one_dimensional = false;
6063 bool is_builtin_type = false;
6064 bool expect_initializers = false;
6065 int num_arguments = 0;
6069 ArrayList array_data;
6074 // The number of array initializers that we can handle
6075 // via the InitializeArray method - through EmitStaticInitializers
6077 int num_automatic_initializers;
6079 const int max_automatic_initializers = 6;
6081 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
6083 this.requested_base_type = requested_base_type;
6084 this.initializers = initializers;
6088 arguments = new ArrayList ();
6090 foreach (Expression e in exprs) {
6091 arguments.Add (new Argument (e, Argument.AType.Expression));
6096 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
6098 this.requested_base_type = requested_base_type;
6099 this.initializers = initializers;
6103 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
6105 //string tmp = rank.Substring (rank.LastIndexOf ('['));
6107 //dimensions = tmp.Length - 1;
6108 expect_initializers = true;
6111 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
6113 StringBuilder sb = new StringBuilder (rank);
6116 for (int i = 1; i < idx_count; i++)
6121 return new ComposedCast (base_type, sb.ToString (), loc);
6124 void Error_IncorrectArrayInitializer ()
6126 Error (178, "Incorrectly structured array initializer");
6129 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
6131 if (specified_dims) {
6132 Argument a = (Argument) arguments [idx];
6134 if (!a.Resolve (ec, loc))
6137 if (!(a.Expr is Constant)) {
6138 Error (150, "A constant value is expected");
6142 int value = (int) ((Constant) a.Expr).GetValue ();
6144 if (value != probe.Count) {
6145 Error_IncorrectArrayInitializer ();
6149 bounds [idx] = value;
6152 int child_bounds = -1;
6153 foreach (object o in probe) {
6154 if (o is ArrayList) {
6155 int current_bounds = ((ArrayList) o).Count;
6157 if (child_bounds == -1)
6158 child_bounds = current_bounds;
6160 else if (child_bounds != current_bounds){
6161 Error_IncorrectArrayInitializer ();
6164 if (specified_dims && (idx + 1 >= arguments.Count)){
6165 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
6169 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
6173 if (child_bounds != -1){
6174 Error_IncorrectArrayInitializer ();
6178 Expression tmp = (Expression) o;
6179 tmp = tmp.Resolve (ec);
6183 // Console.WriteLine ("I got: " + tmp);
6184 // Handle initialization from vars, fields etc.
6186 Expression conv = Convert.ImplicitConversionRequired (
6187 ec, tmp, underlying_type, loc);
6192 if (conv is StringConstant || conv is DecimalConstant || conv is NullCast) {
6193 // These are subclasses of Constant that can appear as elements of an
6194 // array that cannot be statically initialized (with num_automatic_initializers
6195 // > max_automatic_initializers), so num_automatic_initializers should be left as zero.
6196 array_data.Add (conv);
6197 } else if (conv is Constant) {
6198 // These are the types of Constant that can appear in arrays that can be
6199 // statically allocated.
6200 array_data.Add (conv);
6201 num_automatic_initializers++;
6203 array_data.Add (conv);
6210 public void UpdateIndices (EmitContext ec)
6213 for (ArrayList probe = initializers; probe != null;) {
6214 if (probe.Count > 0 && probe [0] is ArrayList) {
6215 Expression e = new IntConstant (probe.Count);
6216 arguments.Add (new Argument (e, Argument.AType.Expression));
6218 bounds [i++] = probe.Count;
6220 probe = (ArrayList) probe [0];
6223 Expression e = new IntConstant (probe.Count);
6224 arguments.Add (new Argument (e, Argument.AType.Expression));
6226 bounds [i++] = probe.Count;
6233 public bool ValidateInitializers (EmitContext ec, Type array_type)
6235 if (initializers == null) {
6236 if (expect_initializers)
6242 if (underlying_type == null)
6246 // We use this to store all the date values in the order in which we
6247 // will need to store them in the byte blob later
6249 array_data = new ArrayList ();
6250 bounds = new Hashtable ();
6254 if (arguments != null) {
6255 ret = CheckIndices (ec, initializers, 0, true);
6258 arguments = new ArrayList ();
6260 ret = CheckIndices (ec, initializers, 0, false);
6267 if (arguments.Count != dimensions) {
6268 Error_IncorrectArrayInitializer ();
6277 // Converts `source' to an int, uint, long or ulong.
6279 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
6283 bool old_checked = ec.CheckState;
6284 ec.CheckState = true;
6286 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
6287 if (target == null){
6288 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
6289 if (target == null){
6290 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
6291 if (target == null){
6292 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
6294 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
6298 ec.CheckState = old_checked;
6301 // Only positive constants are allowed at compile time
6303 if (target is Constant){
6304 if (target is IntConstant){
6305 if (((IntConstant) target).Value < 0){
6306 Expression.Error_NegativeArrayIndex (loc);
6311 if (target is LongConstant){
6312 if (((LongConstant) target).Value < 0){
6313 Expression.Error_NegativeArrayIndex (loc);
6324 // Creates the type of the array
6326 bool LookupType (EmitContext ec)
6328 StringBuilder array_qualifier = new StringBuilder (rank);
6331 // `In the first form allocates an array instace of the type that results
6332 // from deleting each of the individual expression from the expression list'
6334 if (num_arguments > 0) {
6335 array_qualifier.Append ("[");
6336 for (int i = num_arguments-1; i > 0; i--)
6337 array_qualifier.Append (",");
6338 array_qualifier.Append ("]");
6344 TypeExpr array_type_expr;
6345 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
6346 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec, false);
6347 if (array_type_expr == null)
6350 type = array_type_expr.ResolveType (ec);
6352 if (!type.IsArray) {
6353 Error (622, "Can only use array initializer expressions to assign to array types. Try using a new expression instead.");
6356 underlying_type = TypeManager.GetElementType (type);
6357 dimensions = type.GetArrayRank ();
6362 public override Expression DoResolve (EmitContext ec)
6366 if (!LookupType (ec))
6370 // First step is to validate the initializers and fill
6371 // in any missing bits
6373 if (!ValidateInitializers (ec, type))
6376 if (arguments == null)
6379 arg_count = arguments.Count;
6380 foreach (Argument a in arguments){
6381 if (!a.Resolve (ec, loc))
6384 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
6385 if (real_arg == null)
6392 array_element_type = TypeManager.GetElementType (type);
6394 if (array_element_type.IsAbstract && array_element_type.IsSealed) {
6395 Report.Error (719, loc, "'{0}': array elements cannot be of static type", TypeManager.CSharpName (array_element_type));
6399 if (arg_count == 1) {
6400 is_one_dimensional = true;
6401 eclass = ExprClass.Value;
6405 is_builtin_type = TypeManager.IsBuiltinType (type);
6407 if (is_builtin_type) {
6410 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
6411 AllBindingFlags, loc);
6413 if (!(ml is MethodGroupExpr)) {
6414 ml.Error_UnexpectedKind ("method group", loc);
6419 Error (-6, "New invocation: Can not find a constructor for " +
6420 "this argument list");
6424 new_method = Invocation.OverloadResolve (
6425 ec, (MethodGroupExpr) ml, arguments, false, loc);
6427 if (new_method == null) {
6428 Error (-6, "New invocation: Can not find a constructor for " +
6429 "this argument list");
6433 eclass = ExprClass.Value;
6436 ModuleBuilder mb = CodeGen.Module.Builder;
6437 ArrayList args = new ArrayList ();
6439 if (arguments != null) {
6440 for (int i = 0; i < arg_count; i++)
6441 args.Add (TypeManager.int32_type);
6444 Type [] arg_types = null;
6447 arg_types = new Type [args.Count];
6449 args.CopyTo (arg_types, 0);
6451 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
6454 if (new_method == null) {
6455 Error (-6, "New invocation: Can not find a constructor for " +
6456 "this argument list");
6460 eclass = ExprClass.Value;
6465 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
6470 int count = array_data.Count;
6472 if (underlying_type.IsEnum)
6473 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
6475 factor = GetTypeSize (underlying_type);
6477 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
6479 data = new byte [(count * factor + 4) & ~3];
6482 for (int i = 0; i < count; ++i) {
6483 object v = array_data [i];
6485 if (v is EnumConstant)
6486 v = ((EnumConstant) v).Child;
6488 if (v is Constant && !(v is StringConstant))
6489 v = ((Constant) v).GetValue ();
6495 if (underlying_type == TypeManager.int64_type){
6496 if (!(v is Expression)){
6497 long val = (long) v;
6499 for (int j = 0; j < factor; ++j) {
6500 data [idx + j] = (byte) (val & 0xFF);
6504 } else if (underlying_type == TypeManager.uint64_type){
6505 if (!(v is Expression)){
6506 ulong val = (ulong) v;
6508 for (int j = 0; j < factor; ++j) {
6509 data [idx + j] = (byte) (val & 0xFF);
6513 } else if (underlying_type == TypeManager.float_type) {
6514 if (!(v is Expression)){
6515 element = BitConverter.GetBytes ((float) v);
6517 for (int j = 0; j < factor; ++j)
6518 data [idx + j] = element [j];
6520 } else if (underlying_type == TypeManager.double_type) {
6521 if (!(v is Expression)){
6522 element = BitConverter.GetBytes ((double) v);
6524 for (int j = 0; j < factor; ++j)
6525 data [idx + j] = element [j];
6527 } else if (underlying_type == TypeManager.char_type){
6528 if (!(v is Expression)){
6529 int val = (int) ((char) v);
6531 data [idx] = (byte) (val & 0xff);
6532 data [idx+1] = (byte) (val >> 8);
6534 } else if (underlying_type == TypeManager.short_type){
6535 if (!(v is Expression)){
6536 int val = (int) ((short) v);
6538 data [idx] = (byte) (val & 0xff);
6539 data [idx+1] = (byte) (val >> 8);
6541 } else if (underlying_type == TypeManager.ushort_type){
6542 if (!(v is Expression)){
6543 int val = (int) ((ushort) v);
6545 data [idx] = (byte) (val & 0xff);
6546 data [idx+1] = (byte) (val >> 8);
6548 } else if (underlying_type == TypeManager.int32_type) {
6549 if (!(v is Expression)){
6552 data [idx] = (byte) (val & 0xff);
6553 data [idx+1] = (byte) ((val >> 8) & 0xff);
6554 data [idx+2] = (byte) ((val >> 16) & 0xff);
6555 data [idx+3] = (byte) (val >> 24);
6557 } else if (underlying_type == TypeManager.uint32_type) {
6558 if (!(v is Expression)){
6559 uint val = (uint) v;
6561 data [idx] = (byte) (val & 0xff);
6562 data [idx+1] = (byte) ((val >> 8) & 0xff);
6563 data [idx+2] = (byte) ((val >> 16) & 0xff);
6564 data [idx+3] = (byte) (val >> 24);
6566 } else if (underlying_type == TypeManager.sbyte_type) {
6567 if (!(v is Expression)){
6568 sbyte val = (sbyte) v;
6569 data [idx] = (byte) val;
6571 } else if (underlying_type == TypeManager.byte_type) {
6572 if (!(v is Expression)){
6573 byte val = (byte) v;
6574 data [idx] = (byte) val;
6576 } else if (underlying_type == TypeManager.bool_type) {
6577 if (!(v is Expression)){
6578 bool val = (bool) v;
6579 data [idx] = (byte) (val ? 1 : 0);
6581 } else if (underlying_type == TypeManager.decimal_type){
6582 if (!(v is Expression)){
6583 int [] bits = Decimal.GetBits ((decimal) v);
6586 // FIXME: For some reason, this doesn't work on the MS runtime.
6587 int [] nbits = new int [4];
6588 nbits [0] = bits [3];
6589 nbits [1] = bits [2];
6590 nbits [2] = bits [0];
6591 nbits [3] = bits [1];
6593 for (int j = 0; j < 4; j++){
6594 data [p++] = (byte) (nbits [j] & 0xff);
6595 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6596 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6597 data [p++] = (byte) (nbits [j] >> 24);
6601 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6610 // Emits the initializers for the array
6612 void EmitStaticInitializers (EmitContext ec)
6615 // First, the static data
6618 ILGenerator ig = ec.ig;
6620 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6622 fb = RootContext.MakeStaticData (data);
6624 ig.Emit (OpCodes.Dup);
6625 ig.Emit (OpCodes.Ldtoken, fb);
6626 ig.Emit (OpCodes.Call,
6627 TypeManager.void_initializearray_array_fieldhandle);
6631 // Emits pieces of the array that can not be computed at compile
6632 // time (variables and string locations).
6634 // This always expect the top value on the stack to be the array
6636 void EmitDynamicInitializers (EmitContext ec)
6638 ILGenerator ig = ec.ig;
6639 int dims = bounds.Count;
6640 int [] current_pos = new int [dims];
6641 int top = array_data.Count;
6643 MethodInfo set = null;
6647 ModuleBuilder mb = null;
6648 mb = CodeGen.Module.Builder;
6649 args = new Type [dims + 1];
6652 for (j = 0; j < dims; j++)
6653 args [j] = TypeManager.int32_type;
6655 args [j] = array_element_type;
6657 set = mb.GetArrayMethod (
6659 CallingConventions.HasThis | CallingConventions.Standard,
6660 TypeManager.void_type, args);
6663 for (int i = 0; i < top; i++){
6665 Expression e = null;
6667 if (array_data [i] is Expression)
6668 e = (Expression) array_data [i];
6672 // Basically we do this for string literals and
6673 // other non-literal expressions
6675 if (e is EnumConstant){
6676 e = ((EnumConstant) e).Child;
6679 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6680 num_automatic_initializers <= max_automatic_initializers) {
6681 Type etype = e.Type;
6683 ig.Emit (OpCodes.Dup);
6685 for (int idx = 0; idx < dims; idx++)
6686 IntConstant.EmitInt (ig, current_pos [idx]);
6689 // If we are dealing with a struct, get the
6690 // address of it, so we can store it.
6693 etype.IsSubclassOf (TypeManager.value_type) &&
6694 (!TypeManager.IsBuiltinOrEnum (etype) ||
6695 etype == TypeManager.decimal_type)) {
6700 // Let new know that we are providing
6701 // the address where to store the results
6703 n.DisableTemporaryValueType ();
6706 ig.Emit (OpCodes.Ldelema, etype);
6713 OpCode op = ArrayAccess.GetStoreOpcode (etype, out is_stobj);
6715 ig.Emit (OpCodes.Stobj, etype);
6719 ig.Emit (OpCodes.Call, set);
6727 for (int j = dims - 1; j >= 0; j--){
6729 if (current_pos [j] < (int) bounds [j])
6731 current_pos [j] = 0;
6736 void EmitArrayArguments (EmitContext ec)
6738 ILGenerator ig = ec.ig;
6740 foreach (Argument a in arguments) {
6741 Type atype = a.Type;
6744 if (atype == TypeManager.uint64_type)
6745 ig.Emit (OpCodes.Conv_Ovf_U4);
6746 else if (atype == TypeManager.int64_type)
6747 ig.Emit (OpCodes.Conv_Ovf_I4);
6751 public override void Emit (EmitContext ec)
6753 ILGenerator ig = ec.ig;
6755 EmitArrayArguments (ec);
6756 if (is_one_dimensional)
6757 ig.Emit (OpCodes.Newarr, array_element_type);
6759 if (is_builtin_type)
6760 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6762 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6765 if (initializers != null){
6767 // FIXME: Set this variable correctly.
6769 bool dynamic_initializers = true;
6771 // This will never be true for array types that cannot be statically
6772 // initialized. num_automatic_initializers will always be zero. See
6774 if (num_automatic_initializers > max_automatic_initializers)
6775 EmitStaticInitializers (ec);
6777 if (dynamic_initializers)
6778 EmitDynamicInitializers (ec);
6782 public object EncodeAsAttribute ()
6784 if (!is_one_dimensional){
6785 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6789 if (array_data == null){
6790 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6794 object [] ret = new object [array_data.Count];
6796 foreach (Expression e in array_data){
6799 if (e is NullLiteral)
6802 if (!Attribute.GetAttributeArgumentExpression (e, Location, array_element_type, out v))
6812 /// Represents the `this' construct
6814 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6817 VariableInfo variable_info;
6819 public This (Block block, Location loc)
6825 public This (Location loc)
6830 public VariableInfo VariableInfo {
6831 get { return variable_info; }
6834 public bool VerifyFixed (bool is_expression)
6836 if ((variable_info == null) || (variable_info.LocalInfo == null))
6839 return variable_info.LocalInfo.IsFixed;
6842 public bool ResolveBase (EmitContext ec)
6844 eclass = ExprClass.Variable;
6845 type = ec.ContainerType;
6848 Error (26, "Keyword this not valid in static code");
6852 if ((block != null) && (block.ThisVariable != null))
6853 variable_info = block.ThisVariable.VariableInfo;
6855 if (ec.CurrentAnonymousMethod != null)
6861 public override Expression DoResolve (EmitContext ec)
6863 if (!ResolveBase (ec))
6866 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
6867 Error (188, "The this object cannot be used before all " +
6868 "of its fields are assigned to");
6869 variable_info.SetAssigned (ec);
6873 if (ec.IsFieldInitializer) {
6874 Error (27, "Keyword `this' can't be used outside a constructor, " +
6875 "a method or a property.");
6882 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6884 if (!ResolveBase (ec))
6887 if (variable_info != null)
6888 variable_info.SetAssigned (ec);
6890 if (ec.TypeContainer is Class){
6891 Error (1604, "Cannot assign to `this'");
6898 public void Emit (EmitContext ec, bool leave_copy)
6902 ec.ig.Emit (OpCodes.Dup);
6905 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
6907 ILGenerator ig = ec.ig;
6909 if (ec.TypeContainer is Struct){
6913 ec.ig.Emit (OpCodes.Dup);
6914 ig.Emit (OpCodes.Stobj, type);
6916 throw new Exception ("how did you get here");
6920 public override void Emit (EmitContext ec)
6922 ILGenerator ig = ec.ig;
6925 if (ec.TypeContainer is Struct)
6926 ig.Emit (OpCodes.Ldobj, type);
6929 public void AddressOf (EmitContext ec, AddressOp mode)
6934 // FIGURE OUT WHY LDARG_S does not work
6936 // consider: struct X { int val; int P { set { val = value; }}}
6938 // Yes, this looks very bad. Look at `NOTAS' for
6940 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
6945 /// Represents the `__arglist' construct
6947 public class ArglistAccess : Expression
6949 public ArglistAccess (Location loc)
6954 public bool ResolveBase (EmitContext ec)
6956 eclass = ExprClass.Variable;
6957 type = TypeManager.runtime_argument_handle_type;
6961 public override Expression DoResolve (EmitContext ec)
6963 if (!ResolveBase (ec))
6966 if (ec.IsFieldInitializer || !ec.CurrentBlock.HasVarargs) {
6967 Error (190, "The __arglist construct is valid only within " +
6968 "a variable argument method.");
6975 public override void Emit (EmitContext ec)
6977 ec.ig.Emit (OpCodes.Arglist);
6982 /// Represents the `__arglist (....)' construct
6984 public class Arglist : Expression
6986 public readonly Argument[] Arguments;
6988 public Arglist (Argument[] args, Location l)
6994 public Type[] ArgumentTypes {
6996 Type[] retval = new Type [Arguments.Length];
6997 for (int i = 0; i < Arguments.Length; i++)
6998 retval [i] = Arguments [i].Type;
7003 public override Expression DoResolve (EmitContext ec)
7005 eclass = ExprClass.Variable;
7006 type = TypeManager.runtime_argument_handle_type;
7008 foreach (Argument arg in Arguments) {
7009 if (!arg.Resolve (ec, loc))
7016 public override void Emit (EmitContext ec)
7018 foreach (Argument arg in Arguments)
7024 // This produces the value that renders an instance, used by the iterators code
7026 public class ProxyInstance : Expression, IMemoryLocation {
7027 public override Expression DoResolve (EmitContext ec)
7029 eclass = ExprClass.Variable;
7030 type = ec.ContainerType;
7034 public override void Emit (EmitContext ec)
7036 ec.ig.Emit (OpCodes.Ldarg_0);
7040 public void AddressOf (EmitContext ec, AddressOp mode)
7042 ec.ig.Emit (OpCodes.Ldarg_0);
7047 /// Implements the typeof operator
7049 public class TypeOf : Expression {
7050 public Expression QueriedType;
7051 protected Type typearg;
7053 public TypeOf (Expression queried_type, Location l)
7055 QueriedType = queried_type;
7059 public override Expression DoResolve (EmitContext ec)
7061 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
7065 typearg = texpr.ResolveType (ec);
7067 if (typearg == TypeManager.void_type) {
7068 Error (673, "System.Void cannot be used from C# - " +
7069 "use typeof (void) to get the void type object");
7073 if (typearg.IsPointer && !ec.InUnsafe){
7077 CheckObsoleteAttribute (typearg);
7079 type = TypeManager.type_type;
7080 eclass = ExprClass.Type;
7084 public override void Emit (EmitContext ec)
7086 ec.ig.Emit (OpCodes.Ldtoken, typearg);
7087 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
7090 public Type TypeArg {
7091 get { return typearg; }
7096 /// Implements the `typeof (void)' operator
7098 public class TypeOfVoid : TypeOf {
7099 public TypeOfVoid (Location l) : base (null, l)
7104 public override Expression DoResolve (EmitContext ec)
7106 type = TypeManager.type_type;
7107 typearg = TypeManager.void_type;
7108 eclass = ExprClass.Type;
7114 /// Implements the sizeof expression
7116 public class SizeOf : Expression {
7117 public Expression QueriedType;
7120 public SizeOf (Expression queried_type, Location l)
7122 this.QueriedType = queried_type;
7126 public override Expression DoResolve (EmitContext ec)
7130 233, loc, "Sizeof may only be used in an unsafe context " +
7131 "(consider using System.Runtime.InteropServices.Marshal.SizeOf");
7135 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
7139 type_queried = texpr.ResolveType (ec);
7141 CheckObsoleteAttribute (type_queried);
7143 if (!TypeManager.IsUnmanagedType (type_queried)){
7144 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
7148 type = TypeManager.int32_type;
7149 eclass = ExprClass.Value;
7153 public override void Emit (EmitContext ec)
7155 int size = GetTypeSize (type_queried);
7158 ec.ig.Emit (OpCodes.Sizeof, type_queried);
7160 IntConstant.EmitInt (ec.ig, size);
7165 /// Implements the member access expression
7167 public class MemberAccess : Expression {
7168 public readonly string Identifier;
7171 public MemberAccess (Expression expr, string id, Location l)
7178 public Expression Expr {
7184 public static void error176 (Location loc, string name)
7186 Report.Error (176, loc, "Static member `" +
7187 name + "' cannot be accessed " +
7188 "with an instance reference, qualify with a " +
7189 "type name instead");
7192 public static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Expression left, Location loc)
7194 SimpleName sn = left_original as SimpleName;
7195 if (sn == null || left == null || left.Type.Name != sn.Name)
7198 return ec.DeclSpace.LookupType (sn.Name, loc, /*ignore_cs0104*/ true) != null;
7201 // TODO: possible optimalization
7202 // Cache resolved constant result in FieldBuilder <-> expresion map
7203 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
7204 Expression left, Location loc,
7205 Expression left_original)
7207 bool left_is_type, left_is_explicit;
7209 // If `left' is null, then we're called from SimpleNameResolve and this is
7210 // a member in the currently defining class.
7212 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
7213 left_is_explicit = false;
7215 // Implicitly default to `this' unless we're static.
7216 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
7217 left = ec.GetThis (loc);
7219 left_is_type = left is TypeExpr;
7220 left_is_explicit = true;
7223 if (member_lookup is FieldExpr){
7224 FieldExpr fe = (FieldExpr) member_lookup;
7225 FieldInfo fi = fe.FieldInfo;
7226 Type decl_type = fi.DeclaringType;
7228 bool is_emitted = fi is FieldBuilder;
7229 Type t = fi.FieldType;
7232 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
7236 if (!c.LookupConstantValue (out o))
7239 object real_value = ((Constant) c.Expr).GetValue ();
7241 Expression exp = Constantify (real_value, t);
7243 if (left_is_explicit && !left_is_type && !IdenticalNameAndTypeName (ec, left_original, left, loc)) {
7244 Report.SymbolRelatedToPreviousError (c);
7245 error176 (loc, c.GetSignatureForError ());
7253 // IsInitOnly is because of MS compatibility, I don't know why but they emit decimal constant as InitOnly
7254 if (fi.IsInitOnly && !is_emitted && t == TypeManager.decimal_type) {
7255 object[] attrs = fi.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
7256 if (attrs.Length == 1)
7257 return new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
7264 o = TypeManager.GetValue ((FieldBuilder) fi);
7266 o = fi.GetValue (fi);
7268 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
7269 if (left_is_explicit && !left_is_type &&
7270 !IdenticalNameAndTypeName (ec, left_original, member_lookup, loc)) {
7271 error176 (loc, fe.FieldInfo.Name);
7275 Expression enum_member = MemberLookup (
7276 ec, decl_type, "value__", MemberTypes.Field,
7277 AllBindingFlags, loc);
7279 Enum en = TypeManager.LookupEnum (decl_type);
7283 c = Constantify (o, en.UnderlyingType);
7285 c = Constantify (o, enum_member.Type);
7287 return new EnumConstant (c, decl_type);
7290 Expression exp = Constantify (o, t);
7292 if (left_is_explicit && !left_is_type) {
7293 error176 (loc, fe.FieldInfo.Name);
7300 if (t.IsPointer && !ec.InUnsafe){
7306 if (member_lookup is EventExpr) {
7307 EventExpr ee = (EventExpr) member_lookup;
7310 // If the event is local to this class, we transform ourselves into
7314 if (ee.EventInfo.DeclaringType == ec.ContainerType ||
7315 TypeManager.IsNestedChildOf(ec.ContainerType, ee.EventInfo.DeclaringType)) {
7316 MemberInfo mi = GetFieldFromEvent (ee);
7320 // If this happens, then we have an event with its own
7321 // accessors and private field etc so there's no need
7322 // to transform ourselves.
7324 ee.InstanceExpression = left;
7328 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
7331 Report.Error (-200, loc, "Internal error!!");
7335 if (!left_is_explicit)
7338 ee.InstanceExpression = left;
7340 return ResolveMemberAccess (ec, ml, left, loc, left_original);
7344 if (member_lookup is IMemberExpr) {
7345 IMemberExpr me = (IMemberExpr) member_lookup;
7346 MethodGroupExpr mg = me as MethodGroupExpr;
7349 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
7350 mg.IsExplicitImpl = left_is_explicit;
7353 if ((ec.IsFieldInitializer || ec.IsStatic) &&
7354 IdenticalNameAndTypeName (ec, left_original, member_lookup, loc))
7355 return member_lookup;
7357 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
7362 if (!me.IsInstance) {
7363 if (IdenticalNameAndTypeName (ec, left_original, left, loc))
7364 return member_lookup;
7366 if (left_is_explicit) {
7367 error176 (loc, me.Name);
7373 // Since we can not check for instance objects in SimpleName,
7374 // becaue of the rule that allows types and variables to share
7375 // the name (as long as they can be de-ambiguated later, see
7376 // IdenticalNameAndTypeName), we have to check whether left
7377 // is an instance variable in a static context
7379 // However, if the left-hand value is explicitly given, then
7380 // it is already our instance expression, so we aren't in
7384 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
7385 IMemberExpr mexp = (IMemberExpr) left;
7387 if (!mexp.IsStatic){
7388 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
7393 if ((mg != null) && IdenticalNameAndTypeName (ec, left_original, left, loc))
7394 mg.IdenticalTypeName = true;
7396 me.InstanceExpression = left;
7399 return member_lookup;
7402 Console.WriteLine ("Left is: " + left);
7403 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
7404 Environment.Exit (1);
7408 public Expression DoResolve (EmitContext ec, Expression right_side, ResolveFlags flags)
7411 throw new Exception ();
7414 // Resolve the expression with flow analysis turned off, we'll do the definite
7415 // assignment checks later. This is because we don't know yet what the expression
7416 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7417 // definite assignment check on the actual field and not on the whole struct.
7420 Expression original = expr;
7421 expr = expr.Resolve (ec, flags | ResolveFlags.Intermediate | ResolveFlags.DisableFlowAnalysis);
7425 if (expr is Namespace) {
7426 Namespace ns = (Namespace) expr;
7427 FullNamedExpression retval = ns.Lookup (ec.DeclSpace, Identifier, loc);
7429 Report.Error (234, loc, "The type or namespace name `{0}' could not be found in namespace `{1}'", Identifier, ns.FullName);
7434 // TODO: I mailed Ravi about this, and apparently we can get rid
7435 // of this and put it in the right place.
7437 // Handle enums here when they are in transit.
7438 // Note that we cannot afford to hit MemberLookup in this case because
7439 // it will fail to find any members at all
7442 Type expr_type = expr.Type;
7443 if (expr is TypeExpr){
7444 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
7445 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", expr_type);
7449 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
7450 Enum en = TypeManager.LookupEnum (expr_type);
7453 object value = en.LookupEnumValue (ec, Identifier, loc);
7456 MemberCore mc = en.GetDefinition (Identifier);
7457 ObsoleteAttribute oa = mc.GetObsoleteAttribute (en);
7459 AttributeTester.Report_ObsoleteMessage (oa, mc.GetSignatureForError (), Location);
7461 oa = en.GetObsoleteAttribute (en);
7463 AttributeTester.Report_ObsoleteMessage (oa, en.GetSignatureForError (), Location);
7466 Constant c = Constantify (value, en.UnderlyingType);
7467 return new EnumConstant (c, expr_type);
7470 CheckObsoleteAttribute (expr_type);
7472 FieldInfo fi = expr_type.GetField (Identifier);
7474 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
7476 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), Location);
7482 if (expr_type.IsPointer){
7483 Error (23, "The `.' operator can not be applied to pointer operands (" +
7484 TypeManager.CSharpName (expr_type) + ")");
7488 Expression member_lookup;
7489 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
7490 if (member_lookup == null)
7493 if (member_lookup is TypeExpr) {
7494 if (!(expr is TypeExpr) &&
7495 !IdenticalNameAndTypeName (ec, original, expr, loc)) {
7496 Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
7497 member_lookup.Type + "' instead");
7501 return member_lookup;
7504 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
7505 if (member_lookup == null)
7508 // The following DoResolve/DoResolveLValue will do the definite assignment
7511 if (right_side != null)
7512 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
7514 member_lookup = member_lookup.DoResolve (ec);
7516 return member_lookup;
7519 public override Expression DoResolve (EmitContext ec)
7521 return DoResolve (ec, null, ResolveFlags.VariableOrValue | ResolveFlags.Type);
7524 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7526 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue | ResolveFlags.Type);
7529 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
7531 return ResolveNamespaceOrType (ec, false);
7534 public FullNamedExpression ResolveNamespaceOrType (EmitContext ec, bool silent)
7536 FullNamedExpression new_expr = expr.ResolveAsTypeStep (ec);
7538 if (new_expr == null)
7541 if (new_expr is Namespace) {
7542 Namespace ns = (Namespace) new_expr;
7543 FullNamedExpression retval = ns.Lookup (ec.DeclSpace, Identifier, loc);
7544 if (!silent && retval == null)
7545 Report.Error (234, loc, "The type or namespace name `{0}' could not be found in namespace `{1}'", Identifier, ns.FullName);
7549 Type expr_type = new_expr.Type;
7551 if (expr_type.IsPointer){
7552 Error (23, "The `.' operator can not be applied to pointer operands (" +
7553 TypeManager.CSharpName (expr_type) + ")");
7557 Expression member_lookup = MemberLookup (ec, expr_type, expr_type, Identifier, loc);
7558 if (member_lookup == null) {
7559 int errors = Report.Errors;
7560 MemberLookupFailed (ec, expr_type, expr_type, Identifier, null, false, loc);
7562 if (!silent && errors == Report.Errors)
7563 Report.Error (234, loc, "The type name `{0}' could not be found in type `{1}'",
7564 Identifier, new_expr.FullName);
7568 if (!(member_lookup is TypeExpr)) {
7569 Report.Error (118, loc, "'{0}.{1}' denotes a '{2}', where a type was expected",
7570 new_expr.FullName, Identifier, member_lookup.ExprClassName ());
7574 member_lookup = member_lookup.Resolve (ec, ResolveFlags.Type);
7575 return (member_lookup as TypeExpr);
7578 public override void Emit (EmitContext ec)
7580 throw new Exception ("Should not happen");
7583 public override string ToString ()
7585 return expr + "." + Identifier;
7590 /// Implements checked expressions
7592 public class CheckedExpr : Expression {
7594 public Expression Expr;
7596 public CheckedExpr (Expression e, Location l)
7602 public override Expression DoResolve (EmitContext ec)
7604 bool last_check = ec.CheckState;
7605 bool last_const_check = ec.ConstantCheckState;
7607 ec.CheckState = true;
7608 ec.ConstantCheckState = true;
7609 Expr = Expr.Resolve (ec);
7610 ec.CheckState = last_check;
7611 ec.ConstantCheckState = last_const_check;
7616 if (Expr is Constant)
7619 eclass = Expr.eclass;
7624 public override void Emit (EmitContext ec)
7626 bool last_check = ec.CheckState;
7627 bool last_const_check = ec.ConstantCheckState;
7629 ec.CheckState = true;
7630 ec.ConstantCheckState = true;
7632 ec.CheckState = last_check;
7633 ec.ConstantCheckState = last_const_check;
7639 /// Implements the unchecked expression
7641 public class UnCheckedExpr : Expression {
7643 public Expression Expr;
7645 public UnCheckedExpr (Expression e, Location l)
7651 public override Expression DoResolve (EmitContext ec)
7653 bool last_check = ec.CheckState;
7654 bool last_const_check = ec.ConstantCheckState;
7656 ec.CheckState = false;
7657 ec.ConstantCheckState = false;
7658 Expr = Expr.Resolve (ec);
7659 ec.CheckState = last_check;
7660 ec.ConstantCheckState = last_const_check;
7665 if (Expr is Constant)
7668 eclass = Expr.eclass;
7673 public override void Emit (EmitContext ec)
7675 bool last_check = ec.CheckState;
7676 bool last_const_check = ec.ConstantCheckState;
7678 ec.CheckState = false;
7679 ec.ConstantCheckState = false;
7681 ec.CheckState = last_check;
7682 ec.ConstantCheckState = last_const_check;
7688 /// An Element Access expression.
7690 /// During semantic analysis these are transformed into
7691 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7693 public class ElementAccess : Expression {
7694 public ArrayList Arguments;
7695 public Expression Expr;
7697 public ElementAccess (Expression e, ArrayList e_list, Location l)
7706 Arguments = new ArrayList ();
7707 foreach (Expression tmp in e_list)
7708 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7712 bool CommonResolve (EmitContext ec)
7714 Expr = Expr.Resolve (ec);
7719 if (Arguments == null)
7722 foreach (Argument a in Arguments){
7723 if (!a.Resolve (ec, loc))
7730 Expression MakePointerAccess (EmitContext ec, Type t)
7732 if (t == TypeManager.void_ptr_type){
7733 Error (242, "The array index operation is not valid for void pointers");
7736 if (Arguments.Count != 1){
7737 Error (196, "A pointer must be indexed by a single value");
7742 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc).Resolve (ec);
7745 return new Indirection (p, loc).Resolve (ec);
7748 public override Expression DoResolve (EmitContext ec)
7750 if (!CommonResolve (ec))
7754 // We perform some simple tests, and then to "split" the emit and store
7755 // code we create an instance of a different class, and return that.
7757 // I am experimenting with this pattern.
7761 if (t == TypeManager.array_type){
7762 Report.Error (21, loc, "Cannot use indexer on System.Array");
7767 return (new ArrayAccess (this, loc)).Resolve (ec);
7769 return MakePointerAccess (ec, Expr.Type);
7771 FieldExpr fe = Expr as FieldExpr;
7773 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
7775 return MakePointerAccess (ec, ff.ElementType);
7778 return (new IndexerAccess (this, loc)).Resolve (ec);
7781 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7783 if (!CommonResolve (ec))
7788 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
7791 return MakePointerAccess (ec, Expr.Type);
7793 FieldExpr fe = Expr as FieldExpr;
7795 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
7797 // TODO: not sure whether it is correct
7798 // if (!ec.InFixedInitializer) {
7799 // if (!ec.InFixedInitializer) {
7800 // Error (1666, "You cannot use fixed sized buffers contained in unfixed expressions. Try using the fixed statement.");
7803 return MakePointerAccess (ec, ff.ElementType);
7806 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
7809 public override void Emit (EmitContext ec)
7811 throw new Exception ("Should never be reached");
7816 /// Implements array access
7818 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7820 // Points to our "data" repository
7824 LocalTemporary temp;
7827 public ArrayAccess (ElementAccess ea_data, Location l)
7830 eclass = ExprClass.Variable;
7834 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7836 return DoResolve (ec);
7839 public override Expression DoResolve (EmitContext ec)
7842 ExprClass eclass = ea.Expr.eclass;
7844 // As long as the type is valid
7845 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7846 eclass == ExprClass.Value)) {
7847 ea.Expr.Error_UnexpectedKind ("variable or value");
7852 Type t = ea.Expr.Type;
7853 if (t.GetArrayRank () != ea.Arguments.Count){
7855 "Incorrect number of indexes for array " +
7856 " expected: " + t.GetArrayRank () + " got: " +
7857 ea.Arguments.Count);
7861 type = TypeManager.GetElementType (t);
7862 if (type.IsPointer && !ec.InUnsafe){
7863 UnsafeError (ea.Location);
7867 foreach (Argument a in ea.Arguments){
7868 Type argtype = a.Type;
7870 if (argtype == TypeManager.int32_type ||
7871 argtype == TypeManager.uint32_type ||
7872 argtype == TypeManager.int64_type ||
7873 argtype == TypeManager.uint64_type) {
7874 Constant c = a.Expr as Constant;
7875 if (c != null && c.IsNegative) {
7876 Report.Warning (251, 2, a.Expr.Location, "Indexing an array with a negative index (array indices always start at zero)");
7882 // Mhm. This is strage, because the Argument.Type is not the same as
7883 // Argument.Expr.Type: the value changes depending on the ref/out setting.
7885 // Wonder if I will run into trouble for this.
7887 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
7892 eclass = ExprClass.Variable;
7898 /// Emits the right opcode to load an object of Type `t'
7899 /// from an array of T
7901 static public void EmitLoadOpcode (ILGenerator ig, Type type)
7903 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7904 ig.Emit (OpCodes.Ldelem_U1);
7905 else if (type == TypeManager.sbyte_type)
7906 ig.Emit (OpCodes.Ldelem_I1);
7907 else if (type == TypeManager.short_type)
7908 ig.Emit (OpCodes.Ldelem_I2);
7909 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7910 ig.Emit (OpCodes.Ldelem_U2);
7911 else if (type == TypeManager.int32_type)
7912 ig.Emit (OpCodes.Ldelem_I4);
7913 else if (type == TypeManager.uint32_type)
7914 ig.Emit (OpCodes.Ldelem_U4);
7915 else if (type == TypeManager.uint64_type)
7916 ig.Emit (OpCodes.Ldelem_I8);
7917 else if (type == TypeManager.int64_type)
7918 ig.Emit (OpCodes.Ldelem_I8);
7919 else if (type == TypeManager.float_type)
7920 ig.Emit (OpCodes.Ldelem_R4);
7921 else if (type == TypeManager.double_type)
7922 ig.Emit (OpCodes.Ldelem_R8);
7923 else if (type == TypeManager.intptr_type)
7924 ig.Emit (OpCodes.Ldelem_I);
7925 else if (TypeManager.IsEnumType (type)){
7926 EmitLoadOpcode (ig, TypeManager.EnumToUnderlying (type));
7927 } else if (type.IsValueType){
7928 ig.Emit (OpCodes.Ldelema, type);
7929 ig.Emit (OpCodes.Ldobj, type);
7931 ig.Emit (OpCodes.Ldelem_Ref);
7935 /// Returns the right opcode to store an object of Type `t'
7936 /// from an array of T.
7938 static public OpCode GetStoreOpcode (Type t, out bool is_stobj)
7940 //Console.WriteLine (new System.Diagnostics.StackTrace ());
7942 t = TypeManager.TypeToCoreType (t);
7943 if (TypeManager.IsEnumType (t))
7944 t = TypeManager.EnumToUnderlying (t);
7945 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
7946 t == TypeManager.bool_type)
7947 return OpCodes.Stelem_I1;
7948 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
7949 t == TypeManager.char_type)
7950 return OpCodes.Stelem_I2;
7951 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
7952 return OpCodes.Stelem_I4;
7953 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
7954 return OpCodes.Stelem_I8;
7955 else if (t == TypeManager.float_type)
7956 return OpCodes.Stelem_R4;
7957 else if (t == TypeManager.double_type)
7958 return OpCodes.Stelem_R8;
7959 else if (t == TypeManager.intptr_type) {
7961 return OpCodes.Stobj;
7962 } else if (t.IsValueType) {
7964 return OpCodes.Stobj;
7966 return OpCodes.Stelem_Ref;
7969 MethodInfo FetchGetMethod ()
7971 ModuleBuilder mb = CodeGen.Module.Builder;
7972 int arg_count = ea.Arguments.Count;
7973 Type [] args = new Type [arg_count];
7976 for (int i = 0; i < arg_count; i++){
7977 //args [i++] = a.Type;
7978 args [i] = TypeManager.int32_type;
7981 get = mb.GetArrayMethod (
7982 ea.Expr.Type, "Get",
7983 CallingConventions.HasThis |
7984 CallingConventions.Standard,
7990 MethodInfo FetchAddressMethod ()
7992 ModuleBuilder mb = CodeGen.Module.Builder;
7993 int arg_count = ea.Arguments.Count;
7994 Type [] args = new Type [arg_count];
7998 ret_type = TypeManager.GetReferenceType (type);
8000 for (int i = 0; i < arg_count; i++){
8001 //args [i++] = a.Type;
8002 args [i] = TypeManager.int32_type;
8005 address = mb.GetArrayMethod (
8006 ea.Expr.Type, "Address",
8007 CallingConventions.HasThis |
8008 CallingConventions.Standard,
8015 // Load the array arguments into the stack.
8017 // If we have been requested to cache the values (cached_locations array
8018 // initialized), then load the arguments the first time and store them
8019 // in locals. otherwise load from local variables.
8021 void LoadArrayAndArguments (EmitContext ec)
8023 ILGenerator ig = ec.ig;
8026 foreach (Argument a in ea.Arguments){
8027 Type argtype = a.Expr.Type;
8031 if (argtype == TypeManager.int64_type)
8032 ig.Emit (OpCodes.Conv_Ovf_I);
8033 else if (argtype == TypeManager.uint64_type)
8034 ig.Emit (OpCodes.Conv_Ovf_I_Un);
8038 public void Emit (EmitContext ec, bool leave_copy)
8040 int rank = ea.Expr.Type.GetArrayRank ();
8041 ILGenerator ig = ec.ig;
8044 LoadArrayAndArguments (ec);
8047 EmitLoadOpcode (ig, type);
8051 method = FetchGetMethod ();
8052 ig.Emit (OpCodes.Call, method);
8055 LoadFromPtr (ec.ig, this.type);
8058 ec.ig.Emit (OpCodes.Dup);
8059 temp = new LocalTemporary (ec, this.type);
8064 public override void Emit (EmitContext ec)
8069 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8071 int rank = ea.Expr.Type.GetArrayRank ();
8072 ILGenerator ig = ec.ig;
8073 Type t = source.Type;
8074 prepared = prepare_for_load;
8076 if (prepare_for_load) {
8077 AddressOf (ec, AddressOp.LoadStore);
8078 ec.ig.Emit (OpCodes.Dup);
8081 ec.ig.Emit (OpCodes.Dup);
8082 temp = new LocalTemporary (ec, this.type);
8085 StoreFromPtr (ec.ig, t);
8093 LoadArrayAndArguments (ec);
8097 OpCode op = GetStoreOpcode (t, out is_stobj);
8099 // The stobj opcode used by value types will need
8100 // an address on the stack, not really an array/array
8104 ig.Emit (OpCodes.Ldelema, t);
8108 ec.ig.Emit (OpCodes.Dup);
8109 temp = new LocalTemporary (ec, this.type);
8114 ig.Emit (OpCodes.Stobj, t);
8118 ModuleBuilder mb = CodeGen.Module.Builder;
8119 int arg_count = ea.Arguments.Count;
8120 Type [] args = new Type [arg_count + 1];
8125 ec.ig.Emit (OpCodes.Dup);
8126 temp = new LocalTemporary (ec, this.type);
8130 for (int i = 0; i < arg_count; i++){
8131 //args [i++] = a.Type;
8132 args [i] = TypeManager.int32_type;
8135 args [arg_count] = type;
8137 set = mb.GetArrayMethod (
8138 ea.Expr.Type, "Set",
8139 CallingConventions.HasThis |
8140 CallingConventions.Standard,
8141 TypeManager.void_type, args);
8143 ig.Emit (OpCodes.Call, set);
8150 public void AddressOf (EmitContext ec, AddressOp mode)
8152 int rank = ea.Expr.Type.GetArrayRank ();
8153 ILGenerator ig = ec.ig;
8155 LoadArrayAndArguments (ec);
8158 ig.Emit (OpCodes.Ldelema, type);
8160 MethodInfo address = FetchAddressMethod ();
8161 ig.Emit (OpCodes.Call, address);
8168 public ArrayList Properties;
8169 static Hashtable map;
8171 public struct Indexer {
8172 public readonly Type Type;
8173 public readonly MethodInfo Getter, Setter;
8175 public Indexer (Type type, MethodInfo get, MethodInfo set)
8185 map = new Hashtable ();
8190 Properties = new ArrayList ();
8193 void Append (MemberInfo [] mi)
8195 foreach (PropertyInfo property in mi){
8196 MethodInfo get, set;
8198 get = property.GetGetMethod (true);
8199 set = property.GetSetMethod (true);
8200 Properties.Add (new Indexer (property.PropertyType, get, set));
8204 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
8206 string p_name = TypeManager.IndexerPropertyName (lookup_type);
8208 MemberInfo [] mi = TypeManager.MemberLookup (
8209 caller_type, caller_type, lookup_type, MemberTypes.Property,
8210 BindingFlags.Public | BindingFlags.Instance |
8211 BindingFlags.DeclaredOnly, p_name, null);
8213 if (mi == null || mi.Length == 0)
8219 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
8221 Indexers ix = (Indexers) map [lookup_type];
8226 Type copy = lookup_type;
8227 while (copy != TypeManager.object_type && copy != null){
8228 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
8232 ix = new Indexers ();
8237 copy = copy.BaseType;
8240 if (!lookup_type.IsInterface)
8243 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
8244 if (ifaces != null) {
8245 foreach (Type itype in ifaces) {
8246 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
8249 ix = new Indexers ();
8261 /// Expressions that represent an indexer call.
8263 public class IndexerAccess : Expression, IAssignMethod {
8265 // Points to our "data" repository
8267 MethodInfo get, set;
8268 ArrayList set_arguments;
8269 bool is_base_indexer;
8271 protected Type indexer_type;
8272 protected Type current_type;
8273 protected Expression instance_expr;
8274 protected ArrayList arguments;
8276 public IndexerAccess (ElementAccess ea, Location loc)
8277 : this (ea.Expr, false, loc)
8279 this.arguments = ea.Arguments;
8282 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
8285 this.instance_expr = instance_expr;
8286 this.is_base_indexer = is_base_indexer;
8287 this.eclass = ExprClass.Value;
8291 protected virtual bool CommonResolve (EmitContext ec)
8293 indexer_type = instance_expr.Type;
8294 current_type = ec.ContainerType;
8299 public override Expression DoResolve (EmitContext ec)
8301 ArrayList AllGetters = new ArrayList();
8302 if (!CommonResolve (ec))
8306 // Step 1: Query for all `Item' *properties*. Notice
8307 // that the actual methods are pointed from here.
8309 // This is a group of properties, piles of them.
8311 bool found_any = false, found_any_getters = false;
8312 Type lookup_type = indexer_type;
8315 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
8316 if (ilist != null) {
8318 if (ilist.Properties != null) {
8319 foreach (Indexers.Indexer ix in ilist.Properties) {
8320 if (ix.Getter != null)
8321 AllGetters.Add(ix.Getter);
8326 if (AllGetters.Count > 0) {
8327 found_any_getters = true;
8328 get = (MethodInfo) Invocation.OverloadResolve (
8329 ec, new MethodGroupExpr (AllGetters, loc),
8330 arguments, false, loc);
8334 Report.Error (21, loc,
8335 "Type `" + TypeManager.CSharpName (indexer_type) +
8336 "' does not have any indexers defined");
8340 if (!found_any_getters) {
8341 Error (154, "indexer can not be used in this context, because " +
8342 "it lacks a `get' accessor");
8347 Error (1501, "No Overload for method `this' takes `" +
8348 arguments.Count + "' arguments");
8353 // Only base will allow this invocation to happen.
8355 if (get.IsAbstract && this is BaseIndexerAccess){
8356 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
8360 type = get.ReturnType;
8361 if (type.IsPointer && !ec.InUnsafe){
8366 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8368 eclass = ExprClass.IndexerAccess;
8372 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8374 ArrayList AllSetters = new ArrayList();
8375 if (!CommonResolve (ec))
8378 bool found_any = false, found_any_setters = false;
8380 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
8381 if (ilist != null) {
8383 if (ilist.Properties != null) {
8384 foreach (Indexers.Indexer ix in ilist.Properties) {
8385 if (ix.Setter != null)
8386 AllSetters.Add(ix.Setter);
8390 if (AllSetters.Count > 0) {
8391 found_any_setters = true;
8392 set_arguments = (ArrayList) arguments.Clone ();
8393 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
8394 set = (MethodInfo) Invocation.OverloadResolve (
8395 ec, new MethodGroupExpr (AllSetters, loc),
8396 set_arguments, false, loc);
8400 Report.Error (21, loc,
8401 "Type `" + TypeManager.CSharpName (indexer_type) +
8402 "' does not have any indexers defined");
8406 if (!found_any_setters) {
8407 Error (154, "indexer can not be used in this context, because " +
8408 "it lacks a `set' accessor");
8413 Error (1501, "No Overload for method `this' takes `" +
8414 arguments.Count + "' arguments");
8419 // Only base will allow this invocation to happen.
8421 if (set.IsAbstract && this is BaseIndexerAccess){
8422 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
8427 // Now look for the actual match in the list of indexers to set our "return" type
8429 type = TypeManager.void_type; // default value
8430 foreach (Indexers.Indexer ix in ilist.Properties){
8431 if (ix.Setter == set){
8437 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8439 eclass = ExprClass.IndexerAccess;
8443 bool prepared = false;
8444 LocalTemporary temp;
8446 public void Emit (EmitContext ec, bool leave_copy)
8448 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc, prepared, false);
8450 ec.ig.Emit (OpCodes.Dup);
8451 temp = new LocalTemporary (ec, Type);
8457 // source is ignored, because we already have a copy of it from the
8458 // LValue resolution and we have already constructed a pre-cached
8459 // version of the arguments (ea.set_arguments);
8461 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8463 prepared = prepare_for_load;
8464 Argument a = (Argument) set_arguments [set_arguments.Count - 1];
8469 ec.ig.Emit (OpCodes.Dup);
8470 temp = new LocalTemporary (ec, Type);
8473 } else if (leave_copy) {
8474 temp = new LocalTemporary (ec, Type);
8480 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc, false, prepared);
8487 public override void Emit (EmitContext ec)
8494 /// The base operator for method names
8496 public class BaseAccess : Expression {
8499 public BaseAccess (string member, Location l)
8501 this.member = member;
8505 public override Expression DoResolve (EmitContext ec)
8507 Expression c = CommonResolve (ec);
8513 // MethodGroups use this opportunity to flag an error on lacking ()
8515 if (!(c is MethodGroupExpr))
8516 return c.Resolve (ec);
8520 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8522 Expression c = CommonResolve (ec);
8528 // MethodGroups use this opportunity to flag an error on lacking ()
8530 if (! (c is MethodGroupExpr))
8531 return c.DoResolveLValue (ec, right_side);
8536 Expression CommonResolve (EmitContext ec)
8538 Expression member_lookup;
8539 Type current_type = ec.ContainerType;
8540 Type base_type = current_type.BaseType;
8544 Error (1511, "Keyword base is not allowed in static method");
8548 if (ec.IsFieldInitializer){
8549 Error (1512, "Keyword base is not available in the current context");
8553 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type, member,
8554 AllMemberTypes, AllBindingFlags, loc);
8555 if (member_lookup == null) {
8556 MemberLookupFailed (ec, base_type, base_type, member, null, true, loc);
8563 left = new TypeExpression (base_type, loc);
8565 left = ec.GetThis (loc);
8567 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
8569 if (e is PropertyExpr){
8570 PropertyExpr pe = (PropertyExpr) e;
8575 if (e is MethodGroupExpr)
8576 ((MethodGroupExpr) e).IsBase = true;
8581 public override void Emit (EmitContext ec)
8583 throw new Exception ("Should never be called");
8588 /// The base indexer operator
8590 public class BaseIndexerAccess : IndexerAccess {
8591 public BaseIndexerAccess (ArrayList args, Location loc)
8592 : base (null, true, loc)
8594 arguments = new ArrayList ();
8595 foreach (Expression tmp in args)
8596 arguments.Add (new Argument (tmp, Argument.AType.Expression));
8599 protected override bool CommonResolve (EmitContext ec)
8601 instance_expr = ec.GetThis (loc);
8603 current_type = ec.ContainerType.BaseType;
8604 indexer_type = current_type;
8606 foreach (Argument a in arguments){
8607 if (!a.Resolve (ec, loc))
8616 /// This class exists solely to pass the Type around and to be a dummy
8617 /// that can be passed to the conversion functions (this is used by
8618 /// foreach implementation to typecast the object return value from
8619 /// get_Current into the proper type. All code has been generated and
8620 /// we only care about the side effect conversions to be performed
8622 /// This is also now used as a placeholder where a no-action expression
8623 /// is needed (the `New' class).
8625 public class EmptyExpression : Expression {
8626 public static readonly EmptyExpression Null = new EmptyExpression ();
8628 // TODO: should be protected
8629 public EmptyExpression ()
8631 type = TypeManager.object_type;
8632 eclass = ExprClass.Value;
8633 loc = Location.Null;
8636 public EmptyExpression (Type t)
8639 eclass = ExprClass.Value;
8640 loc = Location.Null;
8643 public override Expression DoResolve (EmitContext ec)
8648 public override void Emit (EmitContext ec)
8650 // nothing, as we only exist to not do anything.
8654 // This is just because we might want to reuse this bad boy
8655 // instead of creating gazillions of EmptyExpressions.
8656 // (CanImplicitConversion uses it)
8658 public void SetType (Type t)
8664 public class UserCast : Expression {
8668 public UserCast (MethodInfo method, Expression source, Location l)
8670 this.method = method;
8671 this.source = source;
8672 type = method.ReturnType;
8673 eclass = ExprClass.Value;
8677 public Expression Source {
8683 public override Expression DoResolve (EmitContext ec)
8686 // We are born fully resolved
8691 public override void Emit (EmitContext ec)
8693 ILGenerator ig = ec.ig;
8697 if (method is MethodInfo)
8698 ig.Emit (OpCodes.Call, (MethodInfo) method);
8700 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
8706 // This class is used to "construct" the type during a typecast
8707 // operation. Since the Type.GetType class in .NET can parse
8708 // the type specification, we just use this to construct the type
8709 // one bit at a time.
8711 public class ComposedCast : TypeExpr {
8715 public ComposedCast (Expression left, string dim, Location l)
8722 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
8724 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec, false);
8728 Type ltype = lexpr.ResolveType (ec);
8730 if ((ltype == TypeManager.void_type) && (dim != "*")) {
8731 Report.Error (1547, Location,
8732 "Keyword 'void' cannot be used in this context");
8737 // ltype.Fullname is already fully qualified, so we can skip
8738 // a lot of probes, and go directly to TypeManager.LookupType
8740 string cname = ltype.FullName + dim;
8741 type = TypeManager.LookupTypeDirect (cname);
8744 // For arrays of enumerations we are having a problem
8745 // with the direct lookup. Need to investigate.
8747 // For now, fall back to the full lookup in that case.
8749 FullNamedExpression e = ec.DeclSpace.LookupType (cname, loc, /*ignore_cs0104=*/ false);
8751 Report.Error (246, loc, "Cannot find type `" + cname + "'");
8755 type = ((TypeExpr) e).ResolveType (ec);
8760 if (!ec.InUnsafe && type.IsPointer){
8765 if (type.IsArray && (type.GetElementType () == TypeManager.arg_iterator_type ||
8766 type.GetElementType () == TypeManager.typed_reference_type)) {
8767 Report.Error (611, loc, "Array elements cannot be of type '{0}'", TypeManager.CSharpName (type.GetElementType ()));
8771 eclass = ExprClass.Type;
8775 public override string Name {
8781 public override string FullName {
8783 return type.FullName;
8788 public class FixedBufferPtr: Expression {
8791 public FixedBufferPtr (Expression array, Type array_type, Location l)
8796 type = TypeManager.GetPointerType (array_type);
8797 eclass = ExprClass.Value;
8800 public override void Emit(EmitContext ec)
8805 public override Expression DoResolve (EmitContext ec)
8808 // We are born fully resolved
8816 // This class is used to represent the address of an array, used
8817 // only by the Fixed statement, this generates "&a [0]" construct
8818 // for fixed (char *pa = a)
8820 public class ArrayPtr : FixedBufferPtr {
8823 public ArrayPtr (Expression array, Type array_type, Location l):
8824 base (array, array_type, l)
8826 this.array_type = array_type;
8829 public override void Emit (EmitContext ec)
8833 ILGenerator ig = ec.ig;
8834 IntLiteral.EmitInt (ig, 0);
8835 ig.Emit (OpCodes.Ldelema, array_type);
8840 // Used by the fixed statement
8842 public class StringPtr : Expression {
8845 public StringPtr (LocalBuilder b, Location l)
8848 eclass = ExprClass.Value;
8849 type = TypeManager.char_ptr_type;
8853 public override Expression DoResolve (EmitContext ec)
8855 // This should never be invoked, we are born in fully
8856 // initialized state.
8861 public override void Emit (EmitContext ec)
8863 ILGenerator ig = ec.ig;
8865 ig.Emit (OpCodes.Ldloc, b);
8866 ig.Emit (OpCodes.Conv_I);
8867 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
8868 ig.Emit (OpCodes.Add);
8873 // Implements the `stackalloc' keyword
8875 public class StackAlloc : Expression {
8880 public StackAlloc (Expression type, Expression count, Location l)
8887 public override Expression DoResolve (EmitContext ec)
8889 count = count.Resolve (ec);
8893 if (count.Type != TypeManager.int32_type){
8894 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8899 Constant c = count as Constant;
8900 if (c != null && c.IsNegative) {
8901 Report.Error (247, loc, "Cannot use a negative size with stackalloc");
8905 if (ec.CurrentBranching.InCatch () ||
8906 ec.CurrentBranching.InFinally (true)) {
8908 "stackalloc can not be used in a catch or finally block");
8912 TypeExpr texpr = t.ResolveAsTypeTerminal (ec, false);
8916 otype = texpr.ResolveType (ec);
8918 if (!TypeManager.VerifyUnManaged (otype, loc))
8921 type = TypeManager.GetPointerType (otype);
8922 eclass = ExprClass.Value;
8927 public override void Emit (EmitContext ec)
8929 int size = GetTypeSize (otype);
8930 ILGenerator ig = ec.ig;
8933 ig.Emit (OpCodes.Sizeof, otype);
8935 IntConstant.EmitInt (ig, size);
8937 ig.Emit (OpCodes.Mul);
8938 ig.Emit (OpCodes.Localloc);