2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
8 // (C) 2003, 2004 Novell, Inc.
12 namespace Mono.CSharp {
14 using System.Collections;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// This is just a helper class, it is generated by Unary, UnaryMutator
21 /// when an overloaded method has been found. It just emits the code for a
24 public class StaticCallExpr : ExpressionStatement {
28 public StaticCallExpr (MethodInfo m, ArrayList a, Location l)
34 eclass = ExprClass.Value;
38 public override Expression DoResolve (EmitContext ec)
41 // We are born fully resolved
46 public override void Emit (EmitContext ec)
49 Invocation.EmitArguments (ec, mi, args, false, null);
51 ec.ig.Emit (OpCodes.Call, mi);
55 static public StaticCallExpr MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
56 Expression e, Location loc)
61 args = new ArrayList (1);
62 Argument a = new Argument (e, Argument.AType.Expression);
64 // We need to resolve the arguments before sending them in !
65 if (!a.Resolve (ec, loc))
69 method = Invocation.OverloadResolve (
70 ec, (MethodGroupExpr) mg, args, false, loc);
75 return new StaticCallExpr ((MethodInfo) method, args, loc);
78 public override void EmitStatement (EmitContext ec)
81 if (TypeManager.TypeToCoreType (type) != TypeManager.void_type)
82 ec.ig.Emit (OpCodes.Pop);
85 public MethodInfo Method {
90 public class ParenthesizedExpression : Expression
92 public Expression Expr;
94 public ParenthesizedExpression (Expression expr, Location loc)
100 public override Expression DoResolve (EmitContext ec)
102 Expr = Expr.Resolve (ec);
106 public override void Emit (EmitContext ec)
108 throw new Exception ("Should not happen");
113 /// Unary expressions.
117 /// Unary implements unary expressions. It derives from
118 /// ExpressionStatement becuase the pre/post increment/decrement
119 /// operators can be used in a statement context.
121 public class Unary : Expression {
122 public enum Operator : byte {
123 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
124 Indirection, AddressOf, TOP
127 public Operator Oper;
128 public Expression Expr;
130 public Unary (Operator op, Expression expr, Location loc)
138 /// Returns a stringified representation of the Operator
140 static public string OperName (Operator oper)
143 case Operator.UnaryPlus:
145 case Operator.UnaryNegation:
147 case Operator.LogicalNot:
149 case Operator.OnesComplement:
151 case Operator.AddressOf:
153 case Operator.Indirection:
157 return oper.ToString ();
160 public static readonly string [] oper_names;
164 oper_names = new string [(int)Operator.TOP];
166 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
167 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
168 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
169 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
170 oper_names [(int) Operator.Indirection] = "op_Indirection";
171 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
174 void Error23 (Type t)
177 23, "Operator " + OperName (Oper) +
178 " cannot be applied to operand of type `" +
179 TypeManager.CSharpName (t) + "'");
183 /// The result has been already resolved:
185 /// FIXME: a minus constant -128 sbyte cant be turned into a
188 static Expression TryReduceNegative (Constant expr)
192 if (expr is IntConstant)
193 e = new IntConstant (-((IntConstant) expr).Value);
194 else if (expr is UIntConstant){
195 uint value = ((UIntConstant) expr).Value;
197 if (value < 2147483649)
198 return new IntConstant (-(int)value);
200 e = new LongConstant (-value);
202 else if (expr is LongConstant)
203 e = new LongConstant (-((LongConstant) expr).Value);
204 else if (expr is ULongConstant){
205 ulong value = ((ULongConstant) expr).Value;
207 if (value < 9223372036854775809)
208 return new LongConstant(-(long)value);
210 else if (expr is FloatConstant)
211 e = new FloatConstant (-((FloatConstant) expr).Value);
212 else if (expr is DoubleConstant)
213 e = new DoubleConstant (-((DoubleConstant) expr).Value);
214 else if (expr is DecimalConstant)
215 e = new DecimalConstant (-((DecimalConstant) expr).Value);
216 else if (expr is ShortConstant)
217 e = new IntConstant (-((ShortConstant) expr).Value);
218 else if (expr is UShortConstant)
219 e = new IntConstant (-((UShortConstant) expr).Value);
220 else if (expr is SByteConstant)
221 e = new IntConstant (-((SByteConstant) expr).Value);
222 else if (expr is ByteConstant)
223 e = new IntConstant (-((ByteConstant) expr).Value);
228 // This routine will attempt to simplify the unary expression when the
229 // argument is a constant. The result is returned in `result' and the
230 // function returns true or false depending on whether a reduction
231 // was performed or not
233 bool Reduce (EmitContext ec, Constant e, out Expression result)
235 Type expr_type = e.Type;
238 case Operator.UnaryPlus:
242 case Operator.UnaryNegation:
243 result = TryReduceNegative (e);
244 return result != null;
246 case Operator.LogicalNot:
247 if (expr_type != TypeManager.bool_type) {
253 BoolConstant b = (BoolConstant) e;
254 result = new BoolConstant (!(b.Value));
257 case Operator.OnesComplement:
258 if (!((expr_type == TypeManager.int32_type) ||
259 (expr_type == TypeManager.uint32_type) ||
260 (expr_type == TypeManager.int64_type) ||
261 (expr_type == TypeManager.uint64_type) ||
262 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
265 if (Convert.ImplicitConversionExists (ec, e, TypeManager.int32_type)){
266 result = new Cast (new TypeExpression (TypeManager.int32_type, loc), e, loc);
267 result = result.Resolve (ec);
268 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint32_type)){
269 result = new Cast (new TypeExpression (TypeManager.uint32_type, loc), e, loc);
270 result = result.Resolve (ec);
271 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.int64_type)){
272 result = new Cast (new TypeExpression (TypeManager.int64_type, loc), e, loc);
273 result = result.Resolve (ec);
274 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint64_type)){
275 result = new Cast (new TypeExpression (TypeManager.uint64_type, loc), e, loc);
276 result = result.Resolve (ec);
279 if (result == null || !(result is Constant)){
285 expr_type = result.Type;
286 e = (Constant) result;
289 if (e is EnumConstant){
290 EnumConstant enum_constant = (EnumConstant) e;
293 if (Reduce (ec, enum_constant.Child, out reduced)){
294 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
302 if (expr_type == TypeManager.int32_type){
303 result = new IntConstant (~ ((IntConstant) e).Value);
304 } else if (expr_type == TypeManager.uint32_type){
305 result = new UIntConstant (~ ((UIntConstant) e).Value);
306 } else if (expr_type == TypeManager.int64_type){
307 result = new LongConstant (~ ((LongConstant) e).Value);
308 } else if (expr_type == TypeManager.uint64_type){
309 result = new ULongConstant (~ ((ULongConstant) e).Value);
317 case Operator.AddressOf:
321 case Operator.Indirection:
325 throw new Exception ("Can not constant fold: " + Oper.ToString());
328 Expression ResolveOperator (EmitContext ec)
331 // Step 1: Default operations on CLI native types.
334 // Attempt to use a constant folding operation.
335 if (Expr is Constant){
338 if (Reduce (ec, (Constant) Expr, out result))
343 // Step 2: Perform Operator Overload location
345 Type expr_type = Expr.Type;
349 op_name = oper_names [(int) Oper];
351 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
354 Expression e = StaticCallExpr.MakeSimpleCall (
355 ec, (MethodGroupExpr) mg, Expr, loc);
365 // Only perform numeric promotions on:
368 if (expr_type == null)
372 case Operator.LogicalNot:
373 if (expr_type != TypeManager.bool_type) {
374 Expr = ResolveBoolean (ec, Expr, loc);
381 type = TypeManager.bool_type;
384 case Operator.OnesComplement:
385 if (!((expr_type == TypeManager.int32_type) ||
386 (expr_type == TypeManager.uint32_type) ||
387 (expr_type == TypeManager.int64_type) ||
388 (expr_type == TypeManager.uint64_type) ||
389 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
392 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
394 type = TypeManager.int32_type;
397 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint32_type, loc);
399 type = TypeManager.uint32_type;
402 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
404 type = TypeManager.int64_type;
407 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint64_type, loc);
409 type = TypeManager.uint64_type;
418 case Operator.AddressOf:
419 if (Expr.eclass != ExprClass.Variable){
420 Error (211, "Cannot take the address of non-variables");
429 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
433 IVariable variable = Expr as IVariable;
434 if (!ec.InFixedInitializer && ((variable == null) || !variable.VerifyFixed (false))) {
435 Error (212, "You can only take the address of an unfixed expression inside " +
436 "of a fixed statement initializer");
440 if (ec.InFixedInitializer && ((variable != null) && variable.VerifyFixed (false))) {
441 Error (213, "You can not fix an already fixed expression");
445 LocalVariableReference lr = Expr as LocalVariableReference;
447 if (lr.local_info.IsCaptured){
448 AnonymousMethod.Error_AddressOfCapturedVar (lr.Name, loc);
451 lr.local_info.AddressTaken = true;
452 lr.local_info.Used = true;
455 // According to the specs, a variable is considered definitely assigned if you take
457 if ((variable != null) && (variable.VariableInfo != null)){
458 variable.VariableInfo.SetAssigned (ec);
461 type = TypeManager.GetPointerType (Expr.Type);
464 case Operator.Indirection:
470 if (!expr_type.IsPointer){
471 Error (193, "The * or -> operator can only be applied to pointers");
476 // We create an Indirection expression, because
477 // it can implement the IMemoryLocation.
479 return new Indirection (Expr, loc);
481 case Operator.UnaryPlus:
483 // A plus in front of something is just a no-op, so return the child.
487 case Operator.UnaryNegation:
489 // Deals with -literals
490 // int operator- (int x)
491 // long operator- (long x)
492 // float operator- (float f)
493 // double operator- (double d)
494 // decimal operator- (decimal d)
496 Expression expr = null;
499 // transform - - expr into expr
502 Unary unary = (Unary) Expr;
504 if (unary.Oper == Operator.UnaryNegation)
509 // perform numeric promotions to int,
513 // The following is inneficient, because we call
514 // ImplicitConversion too many times.
516 // It is also not clear if we should convert to Float
517 // or Double initially.
519 if (expr_type == TypeManager.uint32_type){
521 // FIXME: handle exception to this rule that
522 // permits the int value -2147483648 (-2^31) to
523 // bt wrote as a decimal interger literal
525 type = TypeManager.int64_type;
526 Expr = Convert.ImplicitConversion (ec, Expr, type, loc);
530 if (expr_type == TypeManager.uint64_type){
532 // FIXME: Handle exception of `long value'
533 // -92233720368547758087 (-2^63) to be wrote as
534 // decimal integer literal.
540 if (expr_type == TypeManager.float_type){
545 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
552 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
559 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.double_type, loc);
570 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
571 TypeManager.CSharpName (expr_type) + "'");
575 public override Expression DoResolve (EmitContext ec)
577 if (Oper == Operator.AddressOf)
578 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
580 Expr = Expr.Resolve (ec);
585 eclass = ExprClass.Value;
586 return ResolveOperator (ec);
589 public override Expression DoResolveLValue (EmitContext ec, Expression right)
591 if (Oper == Operator.Indirection)
592 return base.DoResolveLValue (ec, right);
594 Error (131, "The left-hand side of an assignment must be a " +
595 "variable, property or indexer");
599 public override void Emit (EmitContext ec)
601 ILGenerator ig = ec.ig;
604 case Operator.UnaryPlus:
605 throw new Exception ("This should be caught by Resolve");
607 case Operator.UnaryNegation:
609 ig.Emit (OpCodes.Ldc_I4_0);
610 if (type == TypeManager.int64_type)
611 ig.Emit (OpCodes.Conv_U8);
613 ig.Emit (OpCodes.Sub_Ovf);
616 ig.Emit (OpCodes.Neg);
621 case Operator.LogicalNot:
623 ig.Emit (OpCodes.Ldc_I4_0);
624 ig.Emit (OpCodes.Ceq);
627 case Operator.OnesComplement:
629 ig.Emit (OpCodes.Not);
632 case Operator.AddressOf:
633 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
637 throw new Exception ("This should not happen: Operator = "
642 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
644 if (Oper == Operator.LogicalNot)
645 Expr.EmitBranchable (ec, target, !onTrue);
647 base.EmitBranchable (ec, target, onTrue);
650 public override string ToString ()
652 return "Unary (" + Oper + ", " + Expr + ")";
658 // Unary operators are turned into Indirection expressions
659 // after semantic analysis (this is so we can take the address
660 // of an indirection).
662 public class Indirection : Expression, IMemoryLocation, IAssignMethod {
664 LocalTemporary temporary;
667 public Indirection (Expression expr, Location l)
670 this.type = TypeManager.GetElementType (expr.Type);
671 eclass = ExprClass.Variable;
675 void LoadExprValue (EmitContext ec)
679 public override void Emit (EmitContext ec)
684 LoadFromPtr (ec.ig, Type);
687 public void Emit (EmitContext ec, bool leave_copy)
691 ec.ig.Emit (OpCodes.Dup);
692 temporary = new LocalTemporary (ec, expr.Type);
693 temporary.Store (ec);
697 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
699 prepared = prepare_for_load;
703 if (prepare_for_load)
704 ec.ig.Emit (OpCodes.Dup);
708 ec.ig.Emit (OpCodes.Dup);
709 temporary = new LocalTemporary (ec, expr.Type);
710 temporary.Store (ec);
713 StoreFromPtr (ec.ig, type);
715 if (temporary != null)
719 public void AddressOf (EmitContext ec, AddressOp Mode)
724 public override Expression DoResolve (EmitContext ec)
727 // Born fully resolved
732 public override string ToString ()
734 return "*(" + expr + ")";
739 /// Unary Mutator expressions (pre and post ++ and --)
743 /// UnaryMutator implements ++ and -- expressions. It derives from
744 /// ExpressionStatement becuase the pre/post increment/decrement
745 /// operators can be used in a statement context.
747 /// FIXME: Idea, we could split this up in two classes, one simpler
748 /// for the common case, and one with the extra fields for more complex
749 /// classes (indexers require temporary access; overloaded require method)
752 public class UnaryMutator : ExpressionStatement {
754 public enum Mode : byte {
761 PreDecrement = IsDecrement,
762 PostIncrement = IsPost,
763 PostDecrement = IsPost | IsDecrement
767 bool is_expr = false;
768 bool recurse = false;
773 // This is expensive for the simplest case.
775 StaticCallExpr method;
777 public UnaryMutator (Mode m, Expression e, Location l)
784 static string OperName (Mode mode)
786 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
790 void Error23 (Type t)
793 23, "Operator " + OperName (mode) +
794 " cannot be applied to operand of type `" +
795 TypeManager.CSharpName (t) + "'");
799 /// Returns whether an object of type `t' can be incremented
800 /// or decremented with add/sub (ie, basically whether we can
801 /// use pre-post incr-decr operations on it, but it is not a
802 /// System.Decimal, which we require operator overloading to catch)
804 static bool IsIncrementableNumber (Type t)
806 return (t == TypeManager.sbyte_type) ||
807 (t == TypeManager.byte_type) ||
808 (t == TypeManager.short_type) ||
809 (t == TypeManager.ushort_type) ||
810 (t == TypeManager.int32_type) ||
811 (t == TypeManager.uint32_type) ||
812 (t == TypeManager.int64_type) ||
813 (t == TypeManager.uint64_type) ||
814 (t == TypeManager.char_type) ||
815 (t.IsSubclassOf (TypeManager.enum_type)) ||
816 (t == TypeManager.float_type) ||
817 (t == TypeManager.double_type) ||
818 (t.IsPointer && t != TypeManager.void_ptr_type);
821 Expression ResolveOperator (EmitContext ec)
823 Type expr_type = expr.Type;
826 // Step 1: Perform Operator Overload location
831 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
832 op_name = "op_Increment";
834 op_name = "op_Decrement";
836 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
838 if (mg == null && expr_type.BaseType != null)
839 mg = MemberLookup (ec, expr_type.BaseType, op_name,
840 MemberTypes.Method, AllBindingFlags, loc);
843 method = StaticCallExpr.MakeSimpleCall (
844 ec, (MethodGroupExpr) mg, expr, loc);
851 // The operand of the prefix/postfix increment decrement operators
852 // should be an expression that is classified as a variable,
853 // a property access or an indexer access
856 if (expr.eclass == ExprClass.Variable){
857 LocalVariableReference var = expr as LocalVariableReference;
858 if ((var != null) && var.IsReadOnly)
859 Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
860 if (IsIncrementableNumber (expr_type) ||
861 expr_type == TypeManager.decimal_type){
864 } else if (expr.eclass == ExprClass.IndexerAccess){
865 IndexerAccess ia = (IndexerAccess) expr;
867 expr = ia.ResolveLValue (ec, this);
872 } else if (expr.eclass == ExprClass.PropertyAccess){
873 PropertyExpr pe = (PropertyExpr) expr;
875 if (pe.VerifyAssignable ())
880 expr.Error_UnexpectedKind ("variable, indexer or property access", loc);
884 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
885 TypeManager.CSharpName (expr_type) + "'");
889 public override Expression DoResolve (EmitContext ec)
891 expr = expr.Resolve (ec);
896 eclass = ExprClass.Value;
897 return ResolveOperator (ec);
900 static int PtrTypeSize (Type t)
902 return GetTypeSize (TypeManager.GetElementType (t));
906 // Loads the proper "1" into the stack based on the type, then it emits the
907 // opcode for the operation requested
909 void LoadOneAndEmitOp (EmitContext ec, Type t)
912 // Measure if getting the typecode and using that is more/less efficient
913 // that comparing types. t.GetTypeCode() is an internal call.
915 ILGenerator ig = ec.ig;
917 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
918 LongConstant.EmitLong (ig, 1);
919 else if (t == TypeManager.double_type)
920 ig.Emit (OpCodes.Ldc_R8, 1.0);
921 else if (t == TypeManager.float_type)
922 ig.Emit (OpCodes.Ldc_R4, 1.0F);
923 else if (t.IsPointer){
924 int n = PtrTypeSize (t);
927 ig.Emit (OpCodes.Sizeof, t);
929 IntConstant.EmitInt (ig, n);
931 ig.Emit (OpCodes.Ldc_I4_1);
934 // Now emit the operation
937 if (t == TypeManager.int32_type ||
938 t == TypeManager.int64_type){
939 if ((mode & Mode.IsDecrement) != 0)
940 ig.Emit (OpCodes.Sub_Ovf);
942 ig.Emit (OpCodes.Add_Ovf);
943 } else if (t == TypeManager.uint32_type ||
944 t == TypeManager.uint64_type){
945 if ((mode & Mode.IsDecrement) != 0)
946 ig.Emit (OpCodes.Sub_Ovf_Un);
948 ig.Emit (OpCodes.Add_Ovf_Un);
950 if ((mode & Mode.IsDecrement) != 0)
951 ig.Emit (OpCodes.Sub_Ovf);
953 ig.Emit (OpCodes.Add_Ovf);
956 if ((mode & Mode.IsDecrement) != 0)
957 ig.Emit (OpCodes.Sub);
959 ig.Emit (OpCodes.Add);
962 if (t == TypeManager.sbyte_type){
964 ig.Emit (OpCodes.Conv_Ovf_I1);
966 ig.Emit (OpCodes.Conv_I1);
967 } else if (t == TypeManager.byte_type){
969 ig.Emit (OpCodes.Conv_Ovf_U1);
971 ig.Emit (OpCodes.Conv_U1);
972 } else if (t == TypeManager.short_type){
974 ig.Emit (OpCodes.Conv_Ovf_I2);
976 ig.Emit (OpCodes.Conv_I2);
977 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
979 ig.Emit (OpCodes.Conv_Ovf_U2);
981 ig.Emit (OpCodes.Conv_U2);
986 void EmitCode (EmitContext ec, bool is_expr)
989 this.is_expr = is_expr;
990 ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
994 public override void Emit (EmitContext ec)
997 // We use recurse to allow ourselfs to be the source
998 // of an assignment. This little hack prevents us from
999 // having to allocate another expression
1002 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
1004 LoadOneAndEmitOp (ec, expr.Type);
1006 ec.ig.Emit (OpCodes.Call, method.Method);
1011 EmitCode (ec, true);
1014 public override void EmitStatement (EmitContext ec)
1016 EmitCode (ec, false);
1021 /// Base class for the `Is' and `As' classes.
1025 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1028 public abstract class Probe : Expression {
1029 public Expression ProbeType;
1030 protected Expression expr;
1031 protected Type probe_type;
1033 public Probe (Expression expr, Expression probe_type, Location l)
1035 ProbeType = probe_type;
1040 public Expression Expr {
1046 public override Expression DoResolve (EmitContext ec)
1048 TypeExpr texpr = ProbeType.ResolveAsTypeTerminal (ec, false);
1051 probe_type = texpr.ResolveType (ec);
1053 CheckObsoleteAttribute (probe_type);
1055 expr = expr.Resolve (ec);
1059 if (expr.Type.IsPointer) {
1060 Report.Error (244, loc, "\"is\" or \"as\" are not valid on pointer types");
1068 /// Implementation of the `is' operator.
1070 public class Is : Probe {
1071 public Is (Expression expr, Expression probe_type, Location l)
1072 : base (expr, probe_type, l)
1077 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1082 public override void Emit (EmitContext ec)
1084 ILGenerator ig = ec.ig;
1089 case Action.AlwaysFalse:
1090 ig.Emit (OpCodes.Pop);
1091 IntConstant.EmitInt (ig, 0);
1093 case Action.AlwaysTrue:
1094 ig.Emit (OpCodes.Pop);
1095 IntConstant.EmitInt (ig, 1);
1097 case Action.LeaveOnStack:
1098 // the `e != null' rule.
1099 ig.Emit (OpCodes.Ldnull);
1100 ig.Emit (OpCodes.Ceq);
1101 ig.Emit (OpCodes.Ldc_I4_0);
1102 ig.Emit (OpCodes.Ceq);
1105 ig.Emit (OpCodes.Isinst, probe_type);
1106 ig.Emit (OpCodes.Ldnull);
1107 ig.Emit (OpCodes.Cgt_Un);
1110 throw new Exception ("never reached");
1113 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
1115 ILGenerator ig = ec.ig;
1118 case Action.AlwaysFalse:
1120 ig.Emit (OpCodes.Br, target);
1123 case Action.AlwaysTrue:
1125 ig.Emit (OpCodes.Br, target);
1128 case Action.LeaveOnStack:
1129 // the `e != null' rule.
1131 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1135 ig.Emit (OpCodes.Isinst, probe_type);
1136 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1139 throw new Exception ("never reached");
1142 public override Expression DoResolve (EmitContext ec)
1144 Expression e = base.DoResolve (ec);
1146 if ((e == null) || (expr == null))
1149 Type etype = expr.Type;
1150 bool warning_always_matches = false;
1151 bool warning_never_matches = false;
1153 type = TypeManager.bool_type;
1154 eclass = ExprClass.Value;
1157 // First case, if at compile time, there is an implicit conversion
1158 // then e != null (objects) or true (value types)
1160 e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1163 if (etype.IsValueType)
1164 action = Action.AlwaysTrue;
1166 action = Action.LeaveOnStack;
1168 warning_always_matches = true;
1169 } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1171 // Second case: explicit reference convresion
1173 if (expr is NullLiteral)
1174 action = Action.AlwaysFalse;
1176 action = Action.Probe;
1178 action = Action.AlwaysFalse;
1179 warning_never_matches = true;
1182 if (warning_always_matches)
1183 Warning (183, "The given expression is always of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1184 else if (warning_never_matches){
1185 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1186 Warning (184, "The given expression is never of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1194 /// Implementation of the `as' operator.
1196 public class As : Probe {
1197 public As (Expression expr, Expression probe_type, Location l)
1198 : base (expr, probe_type, l)
1202 bool do_isinst = false;
1204 public override void Emit (EmitContext ec)
1206 ILGenerator ig = ec.ig;
1211 ig.Emit (OpCodes.Isinst, probe_type);
1214 static void Error_CannotConvertType (Type source, Type target, Location loc)
1217 39, loc, "as operator can not convert from `" +
1218 TypeManager.CSharpName (source) + "' to `" +
1219 TypeManager.CSharpName (target) + "'");
1222 public override Expression DoResolve (EmitContext ec)
1224 Expression e = base.DoResolve (ec);
1230 eclass = ExprClass.Value;
1231 Type etype = expr.Type;
1233 if (TypeManager.IsValueType (probe_type)){
1234 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1235 TypeManager.CSharpName (probe_type) + " is a value type)");
1240 e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1247 if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1252 Error_CannotConvertType (etype, probe_type, loc);
1258 /// This represents a typecast in the source language.
1260 /// FIXME: Cast expressions have an unusual set of parsing
1261 /// rules, we need to figure those out.
1263 public class Cast : Expression {
1264 Expression target_type;
1267 public Cast (Expression cast_type, Expression expr, Location loc)
1269 this.target_type = cast_type;
1274 public Expression TargetType {
1280 public Expression Expr {
1289 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1291 if (!ec.ConstantCheckState)
1294 if ((value < min) || (value > max)) {
1295 Error (221, "Constant value `" + value + "' cannot be converted " +
1296 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1297 "syntax to override)");
1304 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1306 if (!ec.ConstantCheckState)
1310 Error (221, "Constant value `" + value + "' cannot be converted " +
1311 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1312 "syntax to override)");
1319 bool CheckUnsigned (EmitContext ec, long value, Type type)
1321 if (!ec.ConstantCheckState)
1325 Error (221, "Constant value `" + value + "' cannot be converted " +
1326 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1327 "syntax to override)");
1335 /// Attempts to do a compile-time folding of a constant cast.
1337 Expression TryReduce (EmitContext ec, Type target_type)
1339 Expression real_expr = expr;
1340 if (real_expr is EnumConstant)
1341 real_expr = ((EnumConstant) real_expr).Child;
1343 if (real_expr is ByteConstant){
1344 byte v = ((ByteConstant) real_expr).Value;
1346 if (target_type == TypeManager.sbyte_type) {
1347 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1349 return new SByteConstant ((sbyte) v);
1351 if (target_type == TypeManager.short_type)
1352 return new ShortConstant ((short) v);
1353 if (target_type == TypeManager.ushort_type)
1354 return new UShortConstant ((ushort) v);
1355 if (target_type == TypeManager.int32_type)
1356 return new IntConstant ((int) v);
1357 if (target_type == TypeManager.uint32_type)
1358 return new UIntConstant ((uint) v);
1359 if (target_type == TypeManager.int64_type)
1360 return new LongConstant ((long) v);
1361 if (target_type == TypeManager.uint64_type)
1362 return new ULongConstant ((ulong) v);
1363 if (target_type == TypeManager.float_type)
1364 return new FloatConstant ((float) v);
1365 if (target_type == TypeManager.double_type)
1366 return new DoubleConstant ((double) v);
1367 if (target_type == TypeManager.char_type)
1368 return new CharConstant ((char) v);
1369 if (target_type == TypeManager.decimal_type)
1370 return new DecimalConstant ((decimal) v);
1372 if (real_expr is SByteConstant){
1373 sbyte v = ((SByteConstant) real_expr).Value;
1375 if (target_type == TypeManager.byte_type) {
1376 if (!CheckUnsigned (ec, v, target_type))
1378 return new ByteConstant ((byte) v);
1380 if (target_type == TypeManager.short_type)
1381 return new ShortConstant ((short) v);
1382 if (target_type == TypeManager.ushort_type) {
1383 if (!CheckUnsigned (ec, v, target_type))
1385 return new UShortConstant ((ushort) v);
1386 } if (target_type == TypeManager.int32_type)
1387 return new IntConstant ((int) v);
1388 if (target_type == TypeManager.uint32_type) {
1389 if (!CheckUnsigned (ec, v, target_type))
1391 return new UIntConstant ((uint) v);
1392 } if (target_type == TypeManager.int64_type)
1393 return new LongConstant ((long) v);
1394 if (target_type == TypeManager.uint64_type) {
1395 if (!CheckUnsigned (ec, v, target_type))
1397 return new ULongConstant ((ulong) v);
1399 if (target_type == TypeManager.float_type)
1400 return new FloatConstant ((float) v);
1401 if (target_type == TypeManager.double_type)
1402 return new DoubleConstant ((double) v);
1403 if (target_type == TypeManager.char_type) {
1404 if (!CheckUnsigned (ec, v, target_type))
1406 return new CharConstant ((char) v);
1408 if (target_type == TypeManager.decimal_type)
1409 return new DecimalConstant ((decimal) v);
1411 if (real_expr is ShortConstant){
1412 short v = ((ShortConstant) real_expr).Value;
1414 if (target_type == TypeManager.byte_type) {
1415 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1417 return new ByteConstant ((byte) v);
1419 if (target_type == TypeManager.sbyte_type) {
1420 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1422 return new SByteConstant ((sbyte) v);
1424 if (target_type == TypeManager.ushort_type) {
1425 if (!CheckUnsigned (ec, v, target_type))
1427 return new UShortConstant ((ushort) v);
1429 if (target_type == TypeManager.int32_type)
1430 return new IntConstant ((int) v);
1431 if (target_type == TypeManager.uint32_type) {
1432 if (!CheckUnsigned (ec, v, target_type))
1434 return new UIntConstant ((uint) v);
1436 if (target_type == TypeManager.int64_type)
1437 return new LongConstant ((long) v);
1438 if (target_type == TypeManager.uint64_type) {
1439 if (!CheckUnsigned (ec, v, target_type))
1441 return new ULongConstant ((ulong) v);
1443 if (target_type == TypeManager.float_type)
1444 return new FloatConstant ((float) v);
1445 if (target_type == TypeManager.double_type)
1446 return new DoubleConstant ((double) v);
1447 if (target_type == TypeManager.char_type) {
1448 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1450 return new CharConstant ((char) v);
1452 if (target_type == TypeManager.decimal_type)
1453 return new DecimalConstant ((decimal) v);
1455 if (real_expr is UShortConstant){
1456 ushort v = ((UShortConstant) real_expr).Value;
1458 if (target_type == TypeManager.byte_type) {
1459 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1461 return new ByteConstant ((byte) v);
1463 if (target_type == TypeManager.sbyte_type) {
1464 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1466 return new SByteConstant ((sbyte) v);
1468 if (target_type == TypeManager.short_type) {
1469 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1471 return new ShortConstant ((short) v);
1473 if (target_type == TypeManager.int32_type)
1474 return new IntConstant ((int) v);
1475 if (target_type == TypeManager.uint32_type)
1476 return new UIntConstant ((uint) v);
1477 if (target_type == TypeManager.int64_type)
1478 return new LongConstant ((long) v);
1479 if (target_type == TypeManager.uint64_type)
1480 return new ULongConstant ((ulong) v);
1481 if (target_type == TypeManager.float_type)
1482 return new FloatConstant ((float) v);
1483 if (target_type == TypeManager.double_type)
1484 return new DoubleConstant ((double) v);
1485 if (target_type == TypeManager.char_type) {
1486 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1488 return new CharConstant ((char) v);
1490 if (target_type == TypeManager.decimal_type)
1491 return new DecimalConstant ((decimal) v);
1493 if (real_expr is IntConstant){
1494 int v = ((IntConstant) real_expr).Value;
1496 if (target_type == TypeManager.byte_type) {
1497 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1499 return new ByteConstant ((byte) v);
1501 if (target_type == TypeManager.sbyte_type) {
1502 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1504 return new SByteConstant ((sbyte) v);
1506 if (target_type == TypeManager.short_type) {
1507 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1509 return new ShortConstant ((short) v);
1511 if (target_type == TypeManager.ushort_type) {
1512 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1514 return new UShortConstant ((ushort) v);
1516 if (target_type == TypeManager.uint32_type) {
1517 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1519 return new UIntConstant ((uint) v);
1521 if (target_type == TypeManager.int64_type)
1522 return new LongConstant ((long) v);
1523 if (target_type == TypeManager.uint64_type) {
1524 if (!CheckUnsigned (ec, v, target_type))
1526 return new ULongConstant ((ulong) v);
1528 if (target_type == TypeManager.float_type)
1529 return new FloatConstant ((float) v);
1530 if (target_type == TypeManager.double_type)
1531 return new DoubleConstant ((double) v);
1532 if (target_type == TypeManager.char_type) {
1533 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1535 return new CharConstant ((char) v);
1537 if (target_type == TypeManager.decimal_type)
1538 return new DecimalConstant ((decimal) v);
1540 if (real_expr is UIntConstant){
1541 uint v = ((UIntConstant) real_expr).Value;
1543 if (target_type == TypeManager.byte_type) {
1544 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1546 return new ByteConstant ((byte) v);
1548 if (target_type == TypeManager.sbyte_type) {
1549 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1551 return new SByteConstant ((sbyte) v);
1553 if (target_type == TypeManager.short_type) {
1554 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1556 return new ShortConstant ((short) v);
1558 if (target_type == TypeManager.ushort_type) {
1559 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1561 return new UShortConstant ((ushort) v);
1563 if (target_type == TypeManager.int32_type) {
1564 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1566 return new IntConstant ((int) v);
1568 if (target_type == TypeManager.int64_type)
1569 return new LongConstant ((long) v);
1570 if (target_type == TypeManager.uint64_type)
1571 return new ULongConstant ((ulong) v);
1572 if (target_type == TypeManager.float_type)
1573 return new FloatConstant ((float) v);
1574 if (target_type == TypeManager.double_type)
1575 return new DoubleConstant ((double) v);
1576 if (target_type == TypeManager.char_type) {
1577 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1579 return new CharConstant ((char) v);
1581 if (target_type == TypeManager.decimal_type)
1582 return new DecimalConstant ((decimal) v);
1584 if (real_expr is LongConstant){
1585 long v = ((LongConstant) real_expr).Value;
1587 if (target_type == TypeManager.byte_type) {
1588 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1590 return new ByteConstant ((byte) v);
1592 if (target_type == TypeManager.sbyte_type) {
1593 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1595 return new SByteConstant ((sbyte) v);
1597 if (target_type == TypeManager.short_type) {
1598 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1600 return new ShortConstant ((short) v);
1602 if (target_type == TypeManager.ushort_type) {
1603 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1605 return new UShortConstant ((ushort) v);
1607 if (target_type == TypeManager.int32_type) {
1608 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1610 return new IntConstant ((int) v);
1612 if (target_type == TypeManager.uint32_type) {
1613 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1615 return new UIntConstant ((uint) v);
1617 if (target_type == TypeManager.uint64_type) {
1618 if (!CheckUnsigned (ec, v, target_type))
1620 return new ULongConstant ((ulong) v);
1622 if (target_type == TypeManager.float_type)
1623 return new FloatConstant ((float) v);
1624 if (target_type == TypeManager.double_type)
1625 return new DoubleConstant ((double) v);
1626 if (target_type == TypeManager.char_type) {
1627 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1629 return new CharConstant ((char) v);
1631 if (target_type == TypeManager.decimal_type)
1632 return new DecimalConstant ((decimal) v);
1634 if (real_expr is ULongConstant){
1635 ulong v = ((ULongConstant) real_expr).Value;
1637 if (target_type == TypeManager.byte_type) {
1638 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1640 return new ByteConstant ((byte) v);
1642 if (target_type == TypeManager.sbyte_type) {
1643 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1645 return new SByteConstant ((sbyte) v);
1647 if (target_type == TypeManager.short_type) {
1648 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1650 return new ShortConstant ((short) v);
1652 if (target_type == TypeManager.ushort_type) {
1653 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1655 return new UShortConstant ((ushort) v);
1657 if (target_type == TypeManager.int32_type) {
1658 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1660 return new IntConstant ((int) v);
1662 if (target_type == TypeManager.uint32_type) {
1663 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1665 return new UIntConstant ((uint) v);
1667 if (target_type == TypeManager.int64_type) {
1668 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1670 return new LongConstant ((long) v);
1672 if (target_type == TypeManager.float_type)
1673 return new FloatConstant ((float) v);
1674 if (target_type == TypeManager.double_type)
1675 return new DoubleConstant ((double) v);
1676 if (target_type == TypeManager.char_type) {
1677 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1679 return new CharConstant ((char) v);
1681 if (target_type == TypeManager.decimal_type)
1682 return new DecimalConstant ((decimal) v);
1684 if (real_expr is FloatConstant){
1685 float v = ((FloatConstant) real_expr).Value;
1687 if (target_type == TypeManager.byte_type)
1688 return new ByteConstant ((byte) v);
1689 if (target_type == TypeManager.sbyte_type)
1690 return new SByteConstant ((sbyte) v);
1691 if (target_type == TypeManager.short_type)
1692 return new ShortConstant ((short) v);
1693 if (target_type == TypeManager.ushort_type)
1694 return new UShortConstant ((ushort) v);
1695 if (target_type == TypeManager.int32_type)
1696 return new IntConstant ((int) v);
1697 if (target_type == TypeManager.uint32_type)
1698 return new UIntConstant ((uint) v);
1699 if (target_type == TypeManager.int64_type)
1700 return new LongConstant ((long) v);
1701 if (target_type == TypeManager.uint64_type)
1702 return new ULongConstant ((ulong) v);
1703 if (target_type == TypeManager.double_type)
1704 return new DoubleConstant ((double) v);
1705 if (target_type == TypeManager.char_type)
1706 return new CharConstant ((char) v);
1707 if (target_type == TypeManager.decimal_type)
1708 return new DecimalConstant ((decimal) v);
1710 if (real_expr is DoubleConstant){
1711 double v = ((DoubleConstant) real_expr).Value;
1713 if (target_type == TypeManager.byte_type){
1714 return new ByteConstant ((byte) v);
1715 } if (target_type == TypeManager.sbyte_type)
1716 return new SByteConstant ((sbyte) v);
1717 if (target_type == TypeManager.short_type)
1718 return new ShortConstant ((short) v);
1719 if (target_type == TypeManager.ushort_type)
1720 return new UShortConstant ((ushort) v);
1721 if (target_type == TypeManager.int32_type)
1722 return new IntConstant ((int) v);
1723 if (target_type == TypeManager.uint32_type)
1724 return new UIntConstant ((uint) v);
1725 if (target_type == TypeManager.int64_type)
1726 return new LongConstant ((long) v);
1727 if (target_type == TypeManager.uint64_type)
1728 return new ULongConstant ((ulong) v);
1729 if (target_type == TypeManager.float_type)
1730 return new FloatConstant ((float) v);
1731 if (target_type == TypeManager.char_type)
1732 return new CharConstant ((char) v);
1733 if (target_type == TypeManager.decimal_type)
1734 return new DecimalConstant ((decimal) v);
1737 if (real_expr is CharConstant){
1738 char v = ((CharConstant) real_expr).Value;
1740 if (target_type == TypeManager.byte_type) {
1741 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1743 return new ByteConstant ((byte) v);
1745 if (target_type == TypeManager.sbyte_type) {
1746 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1748 return new SByteConstant ((sbyte) v);
1750 if (target_type == TypeManager.short_type) {
1751 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1753 return new ShortConstant ((short) v);
1755 if (target_type == TypeManager.int32_type)
1756 return new IntConstant ((int) v);
1757 if (target_type == TypeManager.uint32_type)
1758 return new UIntConstant ((uint) v);
1759 if (target_type == TypeManager.int64_type)
1760 return new LongConstant ((long) v);
1761 if (target_type == TypeManager.uint64_type)
1762 return new ULongConstant ((ulong) v);
1763 if (target_type == TypeManager.float_type)
1764 return new FloatConstant ((float) v);
1765 if (target_type == TypeManager.double_type)
1766 return new DoubleConstant ((double) v);
1767 if (target_type == TypeManager.char_type) {
1768 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1770 return new CharConstant ((char) v);
1772 if (target_type == TypeManager.decimal_type)
1773 return new DecimalConstant ((decimal) v);
1779 public override Expression DoResolve (EmitContext ec)
1781 expr = expr.Resolve (ec);
1785 TypeExpr target = target_type.ResolveAsTypeTerminal (ec, false);
1789 type = target.ResolveType (ec);
1791 CheckObsoleteAttribute (type);
1793 if (type.IsAbstract && type.IsSealed) {
1794 Report.Error (716, loc, "Cannot convert to static type '{0}'", TypeManager.CSharpName (type));
1798 eclass = ExprClass.Value;
1800 if (expr is Constant){
1801 Expression e = TryReduce (ec, type);
1807 if (type.IsPointer && !ec.InUnsafe) {
1811 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1815 public override void Emit (EmitContext ec)
1818 // This one will never happen
1820 throw new Exception ("Should not happen");
1825 /// Binary operators
1827 public class Binary : Expression {
1828 public enum Operator : byte {
1829 Multiply, Division, Modulus,
1830 Addition, Subtraction,
1831 LeftShift, RightShift,
1832 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1833 Equality, Inequality,
1843 Expression left, right;
1845 // This must be kept in sync with Operator!!!
1846 public static readonly string [] oper_names;
1850 oper_names = new string [(int) Operator.TOP];
1852 oper_names [(int) Operator.Multiply] = "op_Multiply";
1853 oper_names [(int) Operator.Division] = "op_Division";
1854 oper_names [(int) Operator.Modulus] = "op_Modulus";
1855 oper_names [(int) Operator.Addition] = "op_Addition";
1856 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1857 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1858 oper_names [(int) Operator.RightShift] = "op_RightShift";
1859 oper_names [(int) Operator.LessThan] = "op_LessThan";
1860 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1861 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1862 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1863 oper_names [(int) Operator.Equality] = "op_Equality";
1864 oper_names [(int) Operator.Inequality] = "op_Inequality";
1865 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1866 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1867 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1868 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1869 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1872 public Binary (Operator oper, Expression left, Expression right, Location loc)
1880 public Operator Oper {
1889 public Expression Left {
1898 public Expression Right {
1909 /// Returns a stringified representation of the Operator
1911 static string OperName (Operator oper)
1914 case Operator.Multiply:
1916 case Operator.Division:
1918 case Operator.Modulus:
1920 case Operator.Addition:
1922 case Operator.Subtraction:
1924 case Operator.LeftShift:
1926 case Operator.RightShift:
1928 case Operator.LessThan:
1930 case Operator.GreaterThan:
1932 case Operator.LessThanOrEqual:
1934 case Operator.GreaterThanOrEqual:
1936 case Operator.Equality:
1938 case Operator.Inequality:
1940 case Operator.BitwiseAnd:
1942 case Operator.BitwiseOr:
1944 case Operator.ExclusiveOr:
1946 case Operator.LogicalOr:
1948 case Operator.LogicalAnd:
1952 return oper.ToString ();
1955 public override string ToString ()
1957 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1958 right.ToString () + ")";
1961 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1963 if (expr.Type == target_type)
1966 return Convert.ImplicitConversion (ec, expr, target_type, loc);
1969 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1972 34, loc, "Operator `" + OperName (oper)
1973 + "' is ambiguous on operands of type `"
1974 + TypeManager.CSharpName (l) + "' "
1975 + "and `" + TypeManager.CSharpName (r)
1979 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
1981 if ((l == t) || (r == t))
1984 if (!check_user_conversions)
1987 if (Convert.ImplicitUserConversionExists (ec, l, t))
1989 else if (Convert.ImplicitUserConversionExists (ec, r, t))
1996 // Note that handling the case l == Decimal || r == Decimal
1997 // is taken care of by the Step 1 Operator Overload resolution.
1999 // If `check_user_conv' is true, we also check whether a user-defined conversion
2000 // exists. Note that we only need to do this if both arguments are of a user-defined
2001 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
2002 // so we don't explicitly check for performance reasons.
2004 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
2006 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
2008 // If either operand is of type double, the other operand is
2009 // conveted to type double.
2011 if (r != TypeManager.double_type)
2012 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
2013 if (l != TypeManager.double_type)
2014 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
2016 type = TypeManager.double_type;
2017 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
2019 // if either operand is of type float, the other operand is
2020 // converted to type float.
2022 if (r != TypeManager.double_type)
2023 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
2024 if (l != TypeManager.double_type)
2025 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
2026 type = TypeManager.float_type;
2027 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2031 // If either operand is of type ulong, the other operand is
2032 // converted to type ulong. or an error ocurrs if the other
2033 // operand is of type sbyte, short, int or long
2035 if (l == TypeManager.uint64_type){
2036 if (r != TypeManager.uint64_type){
2037 if (right is IntConstant){
2038 IntConstant ic = (IntConstant) right;
2040 e = Convert.TryImplicitIntConversion (l, ic);
2043 } else if (right is LongConstant){
2044 long ll = ((LongConstant) right).Value;
2047 right = new ULongConstant ((ulong) ll);
2049 e = Convert.ImplicitNumericConversion (ec, right, l, loc);
2056 if (left is IntConstant){
2057 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
2060 } else if (left is LongConstant){
2061 long ll = ((LongConstant) left).Value;
2064 left = new ULongConstant ((ulong) ll);
2066 e = Convert.ImplicitNumericConversion (ec, left, r, loc);
2073 if ((other == TypeManager.sbyte_type) ||
2074 (other == TypeManager.short_type) ||
2075 (other == TypeManager.int32_type) ||
2076 (other == TypeManager.int64_type))
2077 Error_OperatorAmbiguous (loc, oper, l, r);
2079 left = ForceConversion (ec, left, TypeManager.uint64_type);
2080 right = ForceConversion (ec, right, TypeManager.uint64_type);
2082 type = TypeManager.uint64_type;
2083 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2085 // If either operand is of type long, the other operand is converted
2088 if (l != TypeManager.int64_type)
2089 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
2090 if (r != TypeManager.int64_type)
2091 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
2093 type = TypeManager.int64_type;
2094 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2096 // If either operand is of type uint, and the other
2097 // operand is of type sbyte, short or int, othe operands are
2098 // converted to type long (unless we have an int constant).
2102 if (l == TypeManager.uint32_type){
2103 if (right is IntConstant){
2104 IntConstant ic = (IntConstant) right;
2108 right = new UIntConstant ((uint) val);
2115 } else if (r == TypeManager.uint32_type){
2116 if (left is IntConstant){
2117 IntConstant ic = (IntConstant) left;
2121 left = new UIntConstant ((uint) val);
2130 if ((other == TypeManager.sbyte_type) ||
2131 (other == TypeManager.short_type) ||
2132 (other == TypeManager.int32_type)){
2133 left = ForceConversion (ec, left, TypeManager.int64_type);
2134 right = ForceConversion (ec, right, TypeManager.int64_type);
2135 type = TypeManager.int64_type;
2138 // if either operand is of type uint, the other
2139 // operand is converd to type uint
2141 left = ForceConversion (ec, left, TypeManager.uint32_type);
2142 right = ForceConversion (ec, right, TypeManager.uint32_type);
2143 type = TypeManager.uint32_type;
2145 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2146 if (l != TypeManager.decimal_type)
2147 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
2149 if (r != TypeManager.decimal_type)
2150 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
2151 type = TypeManager.decimal_type;
2153 left = ForceConversion (ec, left, TypeManager.int32_type);
2154 right = ForceConversion (ec, right, TypeManager.int32_type);
2156 type = TypeManager.int32_type;
2159 return (left != null) && (right != null);
2162 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2164 Report.Error (19, loc,
2165 "Operator " + name + " cannot be applied to operands of type `" +
2166 TypeManager.CSharpName (l) + "' and `" +
2167 TypeManager.CSharpName (r) + "'");
2170 void Error_OperatorCannotBeApplied ()
2172 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2175 static bool is_unsigned (Type t)
2177 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2178 t == TypeManager.short_type || t == TypeManager.byte_type);
2181 static bool is_user_defined (Type t)
2183 if (t.IsSubclassOf (TypeManager.value_type) &&
2184 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2190 Expression Make32or64 (EmitContext ec, Expression e)
2194 if (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2195 t == TypeManager.int64_type || t == TypeManager.uint64_type)
2197 Expression ee = Convert.ImplicitConversion (ec, e, TypeManager.int32_type, loc);
2200 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint32_type, loc);
2203 ee = Convert.ImplicitConversion (ec, e, TypeManager.int64_type, loc);
2206 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint64_type, loc);
2212 Expression CheckShiftArguments (EmitContext ec)
2216 e = ForceConversion (ec, right, TypeManager.int32_type);
2218 Error_OperatorCannotBeApplied ();
2223 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
2224 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
2225 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
2226 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
2230 if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
2231 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (31), loc);
2232 right = right.DoResolve (ec);
2234 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (63), loc);
2235 right = right.DoResolve (ec);
2240 Error_OperatorCannotBeApplied ();
2244 Expression ResolveOperator (EmitContext ec)
2247 Type r = right.Type;
2250 // Special cases: string comapred to null
2252 if (oper == Operator.Equality || oper == Operator.Inequality){
2253 if ((!TypeManager.IsValueType (l) && r == TypeManager.null_type) ||
2254 (!TypeManager.IsValueType (r) && l == TypeManager.null_type)) {
2255 Type = TypeManager.bool_type;
2261 if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
2262 Type = TypeManager.bool_type;
2269 // Do not perform operator overload resolution when both sides are
2272 if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
2274 // Step 1: Perform Operator Overload location
2276 Expression left_expr, right_expr;
2278 string op = oper_names [(int) oper];
2280 MethodGroupExpr union;
2281 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2283 right_expr = MemberLookup (
2284 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2285 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2287 union = (MethodGroupExpr) left_expr;
2289 if (union != null) {
2290 ArrayList args = new ArrayList (2);
2291 args.Add (new Argument (left, Argument.AType.Expression));
2292 args.Add (new Argument (right, Argument.AType.Expression));
2294 MethodBase method = Invocation.OverloadResolve (
2295 ec, union, args, true, Location.Null);
2297 if (method != null) {
2298 MethodInfo mi = (MethodInfo) method;
2300 return new BinaryMethod (mi.ReturnType, method, args);
2306 // Step 0: String concatenation (because overloading will get this wrong)
2308 if (oper == Operator.Addition){
2310 // If any of the arguments is a string, cast to string
2313 // Simple constant folding
2314 if (left is StringConstant && right is StringConstant)
2315 return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value);
2317 if (l == TypeManager.string_type || r == TypeManager.string_type) {
2319 if (r == TypeManager.void_type || l == TypeManager.void_type) {
2320 Error_OperatorCannotBeApplied ();
2324 // try to fold it in on the left
2325 if (left is StringConcat) {
2328 // We have to test here for not-null, since we can be doubly-resolved
2329 // take care of not appending twice
2332 type = TypeManager.string_type;
2333 ((StringConcat) left).Append (ec, right);
2334 return left.Resolve (ec);
2340 // Otherwise, start a new concat expression
2341 return new StringConcat (ec, loc, left, right).Resolve (ec);
2345 // Transform a + ( - b) into a - b
2347 if (right is Unary){
2348 Unary right_unary = (Unary) right;
2350 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2351 oper = Operator.Subtraction;
2352 right = right_unary.Expr;
2358 if (oper == Operator.Equality || oper == Operator.Inequality){
2359 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2360 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2361 Error_OperatorCannotBeApplied ();
2365 type = TypeManager.bool_type;
2370 // operator != (object a, object b)
2371 // operator == (object a, object b)
2373 // For this to be used, both arguments have to be reference-types.
2374 // Read the rationale on the spec (14.9.6)
2376 // Also, if at compile time we know that the classes do not inherit
2377 // one from the other, then we catch the error there.
2379 if (!(l.IsValueType || r.IsValueType)){
2380 type = TypeManager.bool_type;
2385 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2389 // Also, a standard conversion must exist from either one
2391 if (!(Convert.ImplicitStandardConversionExists (ec, left, r) ||
2392 Convert.ImplicitStandardConversionExists (ec, right, l))){
2393 Error_OperatorCannotBeApplied ();
2397 // We are going to have to convert to an object to compare
2399 if (l != TypeManager.object_type)
2400 left = new EmptyCast (left, TypeManager.object_type);
2401 if (r != TypeManager.object_type)
2402 right = new EmptyCast (right, TypeManager.object_type);
2405 // FIXME: CSC here catches errors cs254 and cs252
2411 // One of them is a valuetype, but the other one is not.
2413 if (!l.IsValueType || !r.IsValueType) {
2414 Error_OperatorCannotBeApplied ();
2419 // Only perform numeric promotions on:
2420 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2422 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2423 if (l.IsSubclassOf (TypeManager.delegate_type)){
2424 if (((right.eclass == ExprClass.MethodGroup) ||
2425 (r == TypeManager.anonymous_method_type))){
2426 if ((RootContext.Version != LanguageVersion.ISO_1)){
2427 Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2435 if (r.IsSubclassOf (TypeManager.delegate_type)){
2437 ArrayList args = new ArrayList (2);
2439 args = new ArrayList (2);
2440 args.Add (new Argument (left, Argument.AType.Expression));
2441 args.Add (new Argument (right, Argument.AType.Expression));
2443 if (oper == Operator.Addition)
2444 method = TypeManager.delegate_combine_delegate_delegate;
2446 method = TypeManager.delegate_remove_delegate_delegate;
2449 Error_OperatorCannotBeApplied ();
2453 return new BinaryDelegate (l, method, args);
2458 // Pointer arithmetic:
2460 // T* operator + (T* x, int y);
2461 // T* operator + (T* x, uint y);
2462 // T* operator + (T* x, long y);
2463 // T* operator + (T* x, ulong y);
2465 // T* operator + (int y, T* x);
2466 // T* operator + (uint y, T *x);
2467 // T* operator + (long y, T *x);
2468 // T* operator + (ulong y, T *x);
2470 // T* operator - (T* x, int y);
2471 // T* operator - (T* x, uint y);
2472 // T* operator - (T* x, long y);
2473 // T* operator - (T* x, ulong y);
2475 // long operator - (T* x, T *y)
2478 if (r.IsPointer && oper == Operator.Subtraction){
2480 return new PointerArithmetic (
2481 false, left, right, TypeManager.int64_type,
2484 Expression t = Make32or64 (ec, right);
2486 return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc).Resolve (ec);
2488 } else if (r.IsPointer && oper == Operator.Addition){
2489 Expression t = Make32or64 (ec, left);
2491 return new PointerArithmetic (true, right, t, r, loc).Resolve (ec);
2496 // Enumeration operators
2498 bool lie = TypeManager.IsEnumType (l);
2499 bool rie = TypeManager.IsEnumType (r);
2503 // U operator - (E e, E f)
2505 if (oper == Operator.Subtraction){
2507 type = TypeManager.EnumToUnderlying (l);
2510 Error_OperatorCannotBeApplied ();
2516 // operator + (E e, U x)
2517 // operator - (E e, U x)
2519 if (oper == Operator.Addition || oper == Operator.Subtraction){
2520 Type enum_type = lie ? l : r;
2521 Type other_type = lie ? r : l;
2522 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2524 if (underlying_type != other_type){
2525 temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
2535 Error_OperatorCannotBeApplied ();
2544 temp = Convert.ImplicitConversion (ec, right, l, loc);
2548 Error_OperatorCannotBeApplied ();
2552 temp = Convert.ImplicitConversion (ec, left, r, loc);
2557 Error_OperatorCannotBeApplied ();
2562 if (oper == Operator.Equality || oper == Operator.Inequality ||
2563 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2564 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2565 if (left.Type != right.Type){
2566 Error_OperatorCannotBeApplied ();
2569 type = TypeManager.bool_type;
2573 if (oper == Operator.BitwiseAnd ||
2574 oper == Operator.BitwiseOr ||
2575 oper == Operator.ExclusiveOr){
2579 Error_OperatorCannotBeApplied ();
2583 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2584 return CheckShiftArguments (ec);
2586 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2587 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2588 type = TypeManager.bool_type;
2593 Error_OperatorCannotBeApplied ();
2597 Expression e = new ConditionalLogicalOperator (
2598 oper == Operator.LogicalAnd, left, right, l, loc);
2599 return e.Resolve (ec);
2603 // operator & (bool x, bool y)
2604 // operator | (bool x, bool y)
2605 // operator ^ (bool x, bool y)
2607 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2608 if (oper == Operator.BitwiseAnd ||
2609 oper == Operator.BitwiseOr ||
2610 oper == Operator.ExclusiveOr){
2617 // Pointer comparison
2619 if (l.IsPointer && r.IsPointer){
2620 if (oper == Operator.Equality || oper == Operator.Inequality ||
2621 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2622 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2623 type = TypeManager.bool_type;
2629 // This will leave left or right set to null if there is an error
2631 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2632 DoNumericPromotions (ec, l, r, check_user_conv);
2633 if (left == null || right == null){
2634 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2639 // reload our cached types if required
2644 if (oper == Operator.BitwiseAnd ||
2645 oper == Operator.BitwiseOr ||
2646 oper == Operator.ExclusiveOr){
2648 if (((l == TypeManager.int32_type) ||
2649 (l == TypeManager.uint32_type) ||
2650 (l == TypeManager.short_type) ||
2651 (l == TypeManager.ushort_type) ||
2652 (l == TypeManager.int64_type) ||
2653 (l == TypeManager.uint64_type))){
2656 Error_OperatorCannotBeApplied ();
2660 Error_OperatorCannotBeApplied ();
2665 if (oper == Operator.Equality ||
2666 oper == Operator.Inequality ||
2667 oper == Operator.LessThanOrEqual ||
2668 oper == Operator.LessThan ||
2669 oper == Operator.GreaterThanOrEqual ||
2670 oper == Operator.GreaterThan){
2671 type = TypeManager.bool_type;
2677 public override Expression DoResolve (EmitContext ec)
2679 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2680 left = ((ParenthesizedExpression) left).Expr;
2681 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2685 if (left.eclass == ExprClass.Type) {
2686 Error (75, "Casting a negative value needs to have the value in parentheses.");
2690 left = left.Resolve (ec);
2695 Constant lc = left as Constant;
2696 if (lc != null && lc.Type == TypeManager.bool_type &&
2697 ((oper == Operator.LogicalAnd && (bool)lc.GetValue () == false) ||
2698 (oper == Operator.LogicalOr && (bool)lc.GetValue () == true))) {
2700 // TODO: make a sense to resolve unreachable expression as we do for statement
2701 Report.Warning (429, 4, loc, "Unreachable expression code detected");
2705 right = right.Resolve (ec);
2709 eclass = ExprClass.Value;
2711 Constant rc = right as Constant;
2712 if (rc != null & lc != null){
2713 Expression e = ConstantFold.BinaryFold (
2714 ec, oper, lc, rc, loc);
2719 return ResolveOperator (ec);
2723 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2724 /// context of a conditional bool expression. This function will return
2725 /// false if it is was possible to use EmitBranchable, or true if it was.
2727 /// The expression's code is generated, and we will generate a branch to `target'
2728 /// if the resulting expression value is equal to isTrue
2730 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2732 ILGenerator ig = ec.ig;
2735 // This is more complicated than it looks, but its just to avoid
2736 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2737 // but on top of that we want for == and != to use a special path
2738 // if we are comparing against null
2740 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
2741 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2744 // put the constant on the rhs, for simplicity
2746 if (left is Constant) {
2747 Expression swap = right;
2752 if (((Constant) right).IsZeroInteger) {
2755 ig.Emit (OpCodes.Brtrue, target);
2757 ig.Emit (OpCodes.Brfalse, target);
2760 } else if (right is BoolConstant) {
2762 if (my_on_true != ((BoolConstant) right).Value)
2763 ig.Emit (OpCodes.Brtrue, target);
2765 ig.Emit (OpCodes.Brfalse, target);
2770 } else if (oper == Operator.LogicalAnd) {
2773 Label tests_end = ig.DefineLabel ();
2775 left.EmitBranchable (ec, tests_end, false);
2776 right.EmitBranchable (ec, target, true);
2777 ig.MarkLabel (tests_end);
2779 left.EmitBranchable (ec, target, false);
2780 right.EmitBranchable (ec, target, false);
2785 } else if (oper == Operator.LogicalOr){
2787 left.EmitBranchable (ec, target, true);
2788 right.EmitBranchable (ec, target, true);
2791 Label tests_end = ig.DefineLabel ();
2792 left.EmitBranchable (ec, tests_end, true);
2793 right.EmitBranchable (ec, target, false);
2794 ig.MarkLabel (tests_end);
2799 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2800 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2801 oper == Operator.Equality || oper == Operator.Inequality)) {
2802 base.EmitBranchable (ec, target, onTrue);
2810 bool isUnsigned = is_unsigned (t) || t == TypeManager.double_type || t == TypeManager.float_type;
2813 case Operator.Equality:
2815 ig.Emit (OpCodes.Beq, target);
2817 ig.Emit (OpCodes.Bne_Un, target);
2820 case Operator.Inequality:
2822 ig.Emit (OpCodes.Bne_Un, target);
2824 ig.Emit (OpCodes.Beq, target);
2827 case Operator.LessThan:
2830 ig.Emit (OpCodes.Blt_Un, target);
2832 ig.Emit (OpCodes.Blt, target);
2835 ig.Emit (OpCodes.Bge_Un, target);
2837 ig.Emit (OpCodes.Bge, target);
2840 case Operator.GreaterThan:
2843 ig.Emit (OpCodes.Bgt_Un, target);
2845 ig.Emit (OpCodes.Bgt, target);
2848 ig.Emit (OpCodes.Ble_Un, target);
2850 ig.Emit (OpCodes.Ble, target);
2853 case Operator.LessThanOrEqual:
2856 ig.Emit (OpCodes.Ble_Un, target);
2858 ig.Emit (OpCodes.Ble, target);
2861 ig.Emit (OpCodes.Bgt_Un, target);
2863 ig.Emit (OpCodes.Bgt, target);
2867 case Operator.GreaterThanOrEqual:
2870 ig.Emit (OpCodes.Bge_Un, target);
2872 ig.Emit (OpCodes.Bge, target);
2875 ig.Emit (OpCodes.Blt_Un, target);
2877 ig.Emit (OpCodes.Blt, target);
2880 Console.WriteLine (oper);
2881 throw new Exception ("what is THAT");
2885 public override void Emit (EmitContext ec)
2887 ILGenerator ig = ec.ig;
2892 // Handle short-circuit operators differently
2895 if (oper == Operator.LogicalAnd) {
2896 Label load_zero = ig.DefineLabel ();
2897 Label end = ig.DefineLabel ();
2899 left.EmitBranchable (ec, load_zero, false);
2901 ig.Emit (OpCodes.Br, end);
2903 ig.MarkLabel (load_zero);
2904 ig.Emit (OpCodes.Ldc_I4_0);
2907 } else if (oper == Operator.LogicalOr) {
2908 Label load_one = ig.DefineLabel ();
2909 Label end = ig.DefineLabel ();
2911 left.EmitBranchable (ec, load_one, true);
2913 ig.Emit (OpCodes.Br, end);
2915 ig.MarkLabel (load_one);
2916 ig.Emit (OpCodes.Ldc_I4_1);
2924 bool isUnsigned = is_unsigned (left.Type);
2927 case Operator.Multiply:
2929 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2930 opcode = OpCodes.Mul_Ovf;
2931 else if (isUnsigned)
2932 opcode = OpCodes.Mul_Ovf_Un;
2934 opcode = OpCodes.Mul;
2936 opcode = OpCodes.Mul;
2940 case Operator.Division:
2942 opcode = OpCodes.Div_Un;
2944 opcode = OpCodes.Div;
2947 case Operator.Modulus:
2949 opcode = OpCodes.Rem_Un;
2951 opcode = OpCodes.Rem;
2954 case Operator.Addition:
2956 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2957 opcode = OpCodes.Add_Ovf;
2958 else if (isUnsigned)
2959 opcode = OpCodes.Add_Ovf_Un;
2961 opcode = OpCodes.Add;
2963 opcode = OpCodes.Add;
2966 case Operator.Subtraction:
2968 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2969 opcode = OpCodes.Sub_Ovf;
2970 else if (isUnsigned)
2971 opcode = OpCodes.Sub_Ovf_Un;
2973 opcode = OpCodes.Sub;
2975 opcode = OpCodes.Sub;
2978 case Operator.RightShift:
2980 opcode = OpCodes.Shr_Un;
2982 opcode = OpCodes.Shr;
2985 case Operator.LeftShift:
2986 opcode = OpCodes.Shl;
2989 case Operator.Equality:
2990 opcode = OpCodes.Ceq;
2993 case Operator.Inequality:
2994 ig.Emit (OpCodes.Ceq);
2995 ig.Emit (OpCodes.Ldc_I4_0);
2997 opcode = OpCodes.Ceq;
3000 case Operator.LessThan:
3002 opcode = OpCodes.Clt_Un;
3004 opcode = OpCodes.Clt;
3007 case Operator.GreaterThan:
3009 opcode = OpCodes.Cgt_Un;
3011 opcode = OpCodes.Cgt;
3014 case Operator.LessThanOrEqual:
3015 Type lt = left.Type;
3017 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
3018 ig.Emit (OpCodes.Cgt_Un);
3020 ig.Emit (OpCodes.Cgt);
3021 ig.Emit (OpCodes.Ldc_I4_0);
3023 opcode = OpCodes.Ceq;
3026 case Operator.GreaterThanOrEqual:
3027 Type le = left.Type;
3029 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3030 ig.Emit (OpCodes.Clt_Un);
3032 ig.Emit (OpCodes.Clt);
3034 ig.Emit (OpCodes.Ldc_I4_0);
3036 opcode = OpCodes.Ceq;
3039 case Operator.BitwiseOr:
3040 opcode = OpCodes.Or;
3043 case Operator.BitwiseAnd:
3044 opcode = OpCodes.And;
3047 case Operator.ExclusiveOr:
3048 opcode = OpCodes.Xor;
3052 throw new Exception ("This should not happen: Operator = "
3053 + oper.ToString ());
3061 // Object created by Binary when the binary operator uses an method instead of being
3062 // a binary operation that maps to a CIL binary operation.
3064 public class BinaryMethod : Expression {
3065 public MethodBase method;
3066 public ArrayList Arguments;
3068 public BinaryMethod (Type t, MethodBase m, ArrayList args)
3073 eclass = ExprClass.Value;
3076 public override Expression DoResolve (EmitContext ec)
3081 public override void Emit (EmitContext ec)
3083 ILGenerator ig = ec.ig;
3085 if (Arguments != null)
3086 Invocation.EmitArguments (ec, method, Arguments, false, null);
3088 if (method is MethodInfo)
3089 ig.Emit (OpCodes.Call, (MethodInfo) method);
3091 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3096 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3097 // b, c, d... may be strings or objects.
3099 public class StringConcat : Expression {
3101 bool invalid = false;
3102 bool emit_conv_done = false;
3104 // Are we also concating objects?
3106 bool is_strings_only = true;
3108 public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
3111 type = TypeManager.string_type;
3112 eclass = ExprClass.Value;
3114 operands = new ArrayList (2);
3119 public override Expression DoResolve (EmitContext ec)
3127 public void Append (EmitContext ec, Expression operand)
3132 if (operand is StringConstant && operands.Count != 0) {
3133 StringConstant last_operand = operands [operands.Count - 1] as StringConstant;
3134 if (last_operand != null) {
3135 operands [operands.Count - 1] = new StringConstant (last_operand.Value + ((StringConstant) operand).Value);
3141 // Conversion to object
3143 if (operand.Type != TypeManager.string_type) {
3144 Expression no = Convert.ImplicitConversion (ec, operand, TypeManager.object_type, loc);
3147 Binary.Error_OperatorCannotBeApplied (loc, "+", TypeManager.string_type, operand.Type);
3153 operands.Add (operand);
3156 public override void Emit (EmitContext ec)
3158 MethodInfo concat_method = null;
3161 // Do conversion to arguments; check for strings only
3164 // This can get called multiple times, so we have to deal with that.
3165 if (!emit_conv_done) {
3166 emit_conv_done = true;
3167 for (int i = 0; i < operands.Count; i ++) {
3168 Expression e = (Expression) operands [i];
3169 is_strings_only &= e.Type == TypeManager.string_type;
3172 for (int i = 0; i < operands.Count; i ++) {
3173 Expression e = (Expression) operands [i];
3175 if (! is_strings_only && e.Type == TypeManager.string_type) {
3176 // need to make sure this is an object, because the EmitParams
3177 // method might look at the type of this expression, see it is a
3178 // string and emit a string [] when we want an object [];
3180 e = new EmptyCast (e, TypeManager.object_type);
3182 operands [i] = new Argument (e, Argument.AType.Expression);
3187 // Find the right method
3189 switch (operands.Count) {
3192 // This should not be possible, because simple constant folding
3193 // is taken care of in the Binary code.
3195 throw new Exception ("how did you get here?");
3198 concat_method = is_strings_only ?
3199 TypeManager.string_concat_string_string :
3200 TypeManager.string_concat_object_object ;
3203 concat_method = is_strings_only ?
3204 TypeManager.string_concat_string_string_string :
3205 TypeManager.string_concat_object_object_object ;
3209 // There is not a 4 param overlaod for object (the one that there is
3210 // is actually a varargs methods, and is only in corlib because it was
3211 // introduced there before.).
3213 if (!is_strings_only)
3216 concat_method = TypeManager.string_concat_string_string_string_string;
3219 concat_method = is_strings_only ?
3220 TypeManager.string_concat_string_dot_dot_dot :
3221 TypeManager.string_concat_object_dot_dot_dot ;
3225 Invocation.EmitArguments (ec, concat_method, operands, false, null);
3226 ec.ig.Emit (OpCodes.Call, concat_method);
3231 // Object created with +/= on delegates
3233 public class BinaryDelegate : Expression {
3237 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3242 eclass = ExprClass.Value;
3245 public override Expression DoResolve (EmitContext ec)
3250 public override void Emit (EmitContext ec)
3252 ILGenerator ig = ec.ig;
3254 Invocation.EmitArguments (ec, method, args, false, null);
3256 ig.Emit (OpCodes.Call, (MethodInfo) method);
3257 ig.Emit (OpCodes.Castclass, type);
3260 public Expression Right {
3262 Argument arg = (Argument) args [1];
3267 public bool IsAddition {
3269 return method == TypeManager.delegate_combine_delegate_delegate;
3275 // User-defined conditional logical operator
3276 public class ConditionalLogicalOperator : Expression {
3277 Expression left, right;
3280 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3283 eclass = ExprClass.Value;
3287 this.is_and = is_and;
3290 protected void Error19 ()
3292 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3295 protected void Error218 ()
3297 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3298 "declarations of operator true and operator false");
3301 Expression op_true, op_false, op;
3302 LocalTemporary left_temp;
3304 public override Expression DoResolve (EmitContext ec)
3307 Expression operator_group;
3309 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3310 if (operator_group == null) {
3315 left_temp = new LocalTemporary (ec, type);
3317 ArrayList arguments = new ArrayList ();
3318 arguments.Add (new Argument (left_temp, Argument.AType.Expression));
3319 arguments.Add (new Argument (right, Argument.AType.Expression));
3320 method = Invocation.OverloadResolve (
3321 ec, (MethodGroupExpr) operator_group, arguments, false, loc)
3323 if ((method == null) || (method.ReturnType != type)) {
3328 op = new StaticCallExpr (method, arguments, loc);
3330 op_true = GetOperatorTrue (ec, left_temp, loc);
3331 op_false = GetOperatorFalse (ec, left_temp, loc);
3332 if ((op_true == null) || (op_false == null)) {
3340 public override void Emit (EmitContext ec)
3342 ILGenerator ig = ec.ig;
3343 Label false_target = ig.DefineLabel ();
3344 Label end_target = ig.DefineLabel ();
3347 left_temp.Store (ec);
3349 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
3350 left_temp.Emit (ec);
3351 ig.Emit (OpCodes.Br, end_target);
3352 ig.MarkLabel (false_target);
3354 ig.MarkLabel (end_target);
3358 public class PointerArithmetic : Expression {
3359 Expression left, right;
3363 // We assume that `l' is always a pointer
3365 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3371 is_add = is_addition;
3374 public override Expression DoResolve (EmitContext ec)
3376 eclass = ExprClass.Variable;
3378 if (left.Type == TypeManager.void_ptr_type) {
3379 Error (242, "The operation in question is undefined on void pointers");
3386 public override void Emit (EmitContext ec)
3388 Type op_type = left.Type;
3389 ILGenerator ig = ec.ig;
3390 Type element = TypeManager.GetElementType (op_type);
3391 int size = GetTypeSize (element);
3392 Type rtype = right.Type;
3394 if (rtype.IsPointer){
3396 // handle (pointer - pointer)
3400 ig.Emit (OpCodes.Sub);
3404 ig.Emit (OpCodes.Sizeof, element);
3406 IntLiteral.EmitInt (ig, size);
3407 ig.Emit (OpCodes.Div);
3409 ig.Emit (OpCodes.Conv_I8);
3412 // handle + and - on (pointer op int)
3415 ig.Emit (OpCodes.Conv_I);
3419 ig.Emit (OpCodes.Sizeof, element);
3421 IntLiteral.EmitInt (ig, size);
3422 if (rtype == TypeManager.int64_type)
3423 ig.Emit (OpCodes.Conv_I8);
3424 else if (rtype == TypeManager.uint64_type)
3425 ig.Emit (OpCodes.Conv_U8);
3426 ig.Emit (OpCodes.Mul);
3429 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
3430 ig.Emit (OpCodes.Conv_I);
3433 ig.Emit (OpCodes.Add);
3435 ig.Emit (OpCodes.Sub);
3441 /// Implements the ternary conditional operator (?:)
3443 public class Conditional : Expression {
3444 Expression expr, trueExpr, falseExpr;
3446 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3449 this.trueExpr = trueExpr;
3450 this.falseExpr = falseExpr;
3454 public Expression Expr {
3460 public Expression TrueExpr {
3466 public Expression FalseExpr {
3472 public override Expression DoResolve (EmitContext ec)
3474 expr = expr.Resolve (ec);
3479 if (expr.Type != TypeManager.bool_type){
3480 expr = Expression.ResolveBoolean (
3487 trueExpr = trueExpr.Resolve (ec);
3488 falseExpr = falseExpr.Resolve (ec);
3490 if (trueExpr == null || falseExpr == null)
3493 eclass = ExprClass.Value;
3494 if (trueExpr.Type == falseExpr.Type)
3495 type = trueExpr.Type;
3498 Type true_type = trueExpr.Type;
3499 Type false_type = falseExpr.Type;
3502 // First, if an implicit conversion exists from trueExpr
3503 // to falseExpr, then the result type is of type falseExpr.Type
3505 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3508 // Check if both can convert implicitl to each other's type
3510 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3512 "Can not compute type of conditional expression " +
3513 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3514 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3515 "' convert implicitly to each other");
3520 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3524 Error (173, "The type of the conditional expression can " +
3525 "not be computed because there is no implicit conversion" +
3526 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3527 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3532 // Dead code optimalization
3533 if (expr is BoolConstant){
3534 BoolConstant bc = (BoolConstant) expr;
3536 Report.Warning (429, 4, bc.Value ? falseExpr.Location : trueExpr.Location, "Unreachable expression code detected");
3537 return bc.Value ? trueExpr : falseExpr;
3543 public override void Emit (EmitContext ec)
3545 ILGenerator ig = ec.ig;
3546 Label false_target = ig.DefineLabel ();
3547 Label end_target = ig.DefineLabel ();
3549 expr.EmitBranchable (ec, false_target, false);
3551 ig.Emit (OpCodes.Br, end_target);
3552 ig.MarkLabel (false_target);
3553 falseExpr.Emit (ec);
3554 ig.MarkLabel (end_target);
3562 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3563 public readonly string Name;
3564 public readonly Block Block;
3565 public LocalInfo local_info;
3568 LocalTemporary temp;
3570 public LocalVariableReference (Block block, string name, Location l)
3575 eclass = ExprClass.Variable;
3579 // Setting `is_readonly' to false will allow you to create a writable
3580 // reference to a read-only variable. This is used by foreach and using.
3582 public LocalVariableReference (Block block, string name, Location l,
3583 LocalInfo local_info, bool is_readonly)
3584 : this (block, name, l)
3586 this.local_info = local_info;
3587 this.is_readonly = is_readonly;
3590 public VariableInfo VariableInfo {
3592 return local_info.VariableInfo;
3596 public bool IsReadOnly {
3602 protected Expression DoResolveBase (EmitContext ec, Expression lvalue_right_side)
3604 if (local_info == null) {
3605 local_info = Block.GetLocalInfo (Name);
3608 if (lvalue_right_side == EmptyExpression.Null)
3609 local_info.Used = true;
3611 is_readonly = local_info.ReadOnly;
3614 type = local_info.VariableType;
3616 VariableInfo variable_info = local_info.VariableInfo;
3617 if (lvalue_right_side != null){
3619 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3623 if (variable_info != null)
3624 variable_info.SetAssigned (ec);
3627 Expression e = Block.GetConstantExpression (Name);
3629 local_info.Used = true;
3630 eclass = ExprClass.Value;
3631 return e.Resolve (ec);
3634 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3637 if (lvalue_right_side == null)
3638 local_info.Used = true;
3640 if (ec.CurrentAnonymousMethod != null){
3642 // If we are referencing a variable from the external block
3643 // flag it for capturing
3645 if (local_info.Block.Toplevel != ec.CurrentBlock.Toplevel){
3646 if (local_info.AddressTaken){
3647 AnonymousMethod.Error_AddressOfCapturedVar (local_info.Name, loc);
3650 ec.CaptureVariable (local_info);
3657 public override Expression DoResolve (EmitContext ec)
3659 return DoResolveBase (ec, null);
3662 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3664 Expression ret = DoResolveBase (ec, right_side);
3666 CheckObsoleteAttribute (ret.Type);
3671 public bool VerifyFixed (bool is_expression)
3673 return !is_expression || local_info.IsFixed;
3676 public override void Emit (EmitContext ec)
3678 ILGenerator ig = ec.ig;
3680 if (local_info.FieldBuilder == null){
3682 // A local variable on the local CLR stack
3684 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3687 // A local variable captured by anonymous methods.
3690 ec.EmitCapturedVariableInstance (local_info);
3692 ig.Emit (OpCodes.Ldfld, local_info.FieldBuilder);
3696 public void Emit (EmitContext ec, bool leave_copy)
3700 ec.ig.Emit (OpCodes.Dup);
3701 if (local_info.FieldBuilder != null){
3702 temp = new LocalTemporary (ec, Type);
3708 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3710 ILGenerator ig = ec.ig;
3711 prepared = prepare_for_load;
3713 if (local_info.FieldBuilder == null){
3715 // A local variable on the local CLR stack
3717 if (local_info.LocalBuilder == null)
3718 throw new Exception ("This should not happen: both Field and Local are null");
3722 ec.ig.Emit (OpCodes.Dup);
3723 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3726 // A local variable captured by anonymous methods or itereators.
3728 ec.EmitCapturedVariableInstance (local_info);
3730 if (prepare_for_load)
3731 ig.Emit (OpCodes.Dup);
3734 ig.Emit (OpCodes.Dup);
3735 temp = new LocalTemporary (ec, Type);
3738 ig.Emit (OpCodes.Stfld, local_info.FieldBuilder);
3744 public void AddressOf (EmitContext ec, AddressOp mode)
3746 ILGenerator ig = ec.ig;
3748 if (local_info.FieldBuilder == null){
3750 // A local variable on the local CLR stack
3752 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3755 // A local variable captured by anonymous methods or iterators
3757 ec.EmitCapturedVariableInstance (local_info);
3758 ig.Emit (OpCodes.Ldflda, local_info.FieldBuilder);
3762 public override string ToString ()
3764 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3769 /// This represents a reference to a parameter in the intermediate
3772 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3778 public Parameter.Modifier mod;
3779 public bool is_ref, is_out, prepared;
3793 LocalTemporary temp;
3795 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3802 eclass = ExprClass.Variable;
3805 public VariableInfo VariableInfo {
3809 public bool VerifyFixed (bool is_expression)
3811 return !is_expression || TypeManager.IsValueType (type);
3814 public bool IsAssigned (EmitContext ec, Location loc)
3816 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsAssigned (vi))
3819 Report.Error (165, loc,
3820 "Use of unassigned parameter `" + name + "'");
3824 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3826 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3829 Report.Error (170, loc,
3830 "Use of possibly unassigned field `" + field_name + "'");
3834 public void SetAssigned (EmitContext ec)
3836 if (is_out && ec.DoFlowAnalysis)
3837 ec.CurrentBranching.SetAssigned (vi);
3840 public void SetFieldAssigned (EmitContext ec, string field_name)
3842 if (is_out && ec.DoFlowAnalysis)
3843 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3846 protected void DoResolveBase (EmitContext ec)
3848 type = pars.GetParameterInfo (ec, idx, out mod);
3849 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3850 is_out = (mod & Parameter.Modifier.OUT) != 0;
3851 eclass = ExprClass.Variable;
3854 vi = block.ParameterMap [idx];
3856 if (ec.CurrentAnonymousMethod != null){
3858 Report.Error (1628, Location,
3859 "Can not reference a ref or out parameter in an anonymous method");
3864 // If we are referencing the parameter from the external block
3865 // flag it for capturing
3867 //Console.WriteLine ("Is parameter `{0}' local? {1}", name, block.IsLocalParameter (name));
3868 if (!block.IsLocalParameter (name)){
3869 ec.CaptureParameter (name, type, idx);
3875 // Notice that for ref/out parameters, the type exposed is not the
3876 // same type exposed externally.
3879 // externally we expose "int&"
3880 // here we expose "int".
3882 // We record this in "is_ref". This means that the type system can treat
3883 // the type as it is expected, but when we generate the code, we generate
3884 // the alternate kind of code.
3886 public override Expression DoResolve (EmitContext ec)
3890 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3893 if (ec.RemapToProxy)
3894 return ec.RemapParameter (idx);
3899 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3905 if (ec.RemapToProxy)
3906 return ec.RemapParameterLValue (idx, right_side);
3911 static public void EmitLdArg (ILGenerator ig, int x)
3915 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3916 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3917 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3918 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3919 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3922 ig.Emit (OpCodes.Ldarg, x);
3926 // This method is used by parameters that are references, that are
3927 // being passed as references: we only want to pass the pointer (that
3928 // is already stored in the parameter, not the address of the pointer,
3929 // and not the value of the variable).
3931 public void EmitLoad (EmitContext ec)
3933 ILGenerator ig = ec.ig;
3939 EmitLdArg (ig, arg_idx);
3942 // FIXME: Review for anonymous methods
3946 public override void Emit (EmitContext ec)
3948 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
3949 ec.EmitParameter (name);
3956 public void Emit (EmitContext ec, bool leave_copy)
3958 ILGenerator ig = ec.ig;
3964 EmitLdArg (ig, arg_idx);
3968 ec.ig.Emit (OpCodes.Dup);
3971 // If we are a reference, we loaded on the stack a pointer
3972 // Now lets load the real value
3974 LoadFromPtr (ig, type);
3978 ec.ig.Emit (OpCodes.Dup);
3981 temp = new LocalTemporary (ec, type);
3987 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3989 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
3990 ec.EmitAssignParameter (name, source, leave_copy, prepare_for_load);
3994 ILGenerator ig = ec.ig;
3997 prepared = prepare_for_load;
4002 if (is_ref && !prepared)
4003 EmitLdArg (ig, arg_idx);
4008 ec.ig.Emit (OpCodes.Dup);
4012 temp = new LocalTemporary (ec, type);
4016 StoreFromPtr (ig, type);
4022 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
4024 ig.Emit (OpCodes.Starg, arg_idx);
4028 public void AddressOf (EmitContext ec, AddressOp mode)
4030 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4031 ec.EmitAddressOfParameter (name);
4042 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
4044 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
4047 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
4049 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
4056 /// Used for arguments to New(), Invocation()
4058 public class Argument {
4059 public enum AType : byte {
4066 public readonly AType ArgType;
4067 public Expression Expr;
4069 public Argument (Expression expr, AType type)
4072 this.ArgType = type;
4075 public Argument (Expression expr)
4078 this.ArgType = AType.Expression;
4083 if (ArgType == AType.Ref || ArgType == AType.Out)
4084 return TypeManager.GetReferenceType (Expr.Type);
4090 public Parameter.Modifier GetParameterModifier ()
4094 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
4097 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
4100 return Parameter.Modifier.NONE;
4104 public static string FullDesc (Argument a)
4106 if (a.ArgType == AType.ArgList)
4109 return (a.ArgType == AType.Ref ? "ref " :
4110 (a.ArgType == AType.Out ? "out " : "")) +
4111 TypeManager.CSharpName (a.Expr.Type);
4114 public bool ResolveMethodGroup (EmitContext ec, Location loc)
4116 // FIXME: csc doesn't report any error if you try to use `ref' or
4117 // `out' in a delegate creation expression.
4118 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4125 public bool Resolve (EmitContext ec, Location loc)
4127 if (ArgType == AType.Ref) {
4128 Expr = Expr.Resolve (ec);
4132 if (!ec.IsConstructor) {
4133 FieldExpr fe = Expr as FieldExpr;
4134 if (fe != null && fe.FieldInfo.IsInitOnly) {
4135 if (fe.FieldInfo.IsStatic)
4136 Report.Error (199, loc, "A static readonly field cannot be passed ref or out (except in a static constructor)");
4138 Report.Error (192, loc, "A readonly field cannot be passed ref or out (except in a constructor)");
4142 Expr = Expr.ResolveLValue (ec, Expr);
4143 } else if (ArgType == AType.Out)
4144 Expr = Expr.ResolveLValue (ec, EmptyExpression.Null);
4146 Expr = Expr.Resolve (ec);
4151 if (ArgType == AType.Expression)
4155 // Catch errors where fields of a MarshalByRefObject are passed as ref or out
4156 // This is only allowed for `this'
4158 FieldExpr fe = Expr as FieldExpr;
4159 if (fe != null && !fe.IsStatic){
4160 Expression instance = fe.InstanceExpression;
4162 if (instance.GetType () != typeof (This)){
4163 if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
4164 Report.SymbolRelatedToPreviousError (fe.InstanceExpression.Type);
4165 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",
4173 if (Expr.eclass != ExprClass.Variable){
4175 // We just probe to match the CSC output
4177 if (Expr.eclass == ExprClass.PropertyAccess ||
4178 Expr.eclass == ExprClass.IndexerAccess){
4181 "A property or indexer can not be passed as an out or ref " +
4186 "An lvalue is required as an argument to out or ref");
4194 public void Emit (EmitContext ec)
4197 // Ref and Out parameters need to have their addresses taken.
4199 // ParameterReferences might already be references, so we want
4200 // to pass just the value
4202 if (ArgType == AType.Ref || ArgType == AType.Out){
4203 AddressOp mode = AddressOp.Store;
4205 if (ArgType == AType.Ref)
4206 mode |= AddressOp.Load;
4208 if (Expr is ParameterReference){
4209 ParameterReference pr = (ParameterReference) Expr;
4215 pr.AddressOf (ec, mode);
4218 if (Expr is IMemoryLocation)
4219 ((IMemoryLocation) Expr).AddressOf (ec, mode);
4222 1510, Expr.Location,
4223 "An lvalue is required as an argument to out or ref");
4233 /// Invocation of methods or delegates.
4235 public class Invocation : ExpressionStatement {
4236 public readonly ArrayList Arguments;
4239 MethodBase method = null;
4241 static Hashtable method_parameter_cache;
4243 static Invocation ()
4245 method_parameter_cache = new PtrHashtable ();
4249 // arguments is an ArrayList, but we do not want to typecast,
4250 // as it might be null.
4252 // FIXME: only allow expr to be a method invocation or a
4253 // delegate invocation (7.5.5)
4255 public Invocation (Expression expr, ArrayList arguments, Location l)
4258 Arguments = arguments;
4262 public Expression Expr {
4269 /// Returns the Parameters (a ParameterData interface) for the
4272 public static ParameterData GetParameterData (MethodBase mb)
4274 object pd = method_parameter_cache [mb];
4278 return (ParameterData) pd;
4281 ip = TypeManager.LookupParametersByBuilder (mb);
4283 method_parameter_cache [mb] = ip;
4285 return (ParameterData) ip;
4287 ReflectionParameters rp = new ReflectionParameters (mb);
4288 method_parameter_cache [mb] = rp;
4290 return (ParameterData) rp;
4295 /// Determines "better conversion" as specified in 7.4.2.3
4297 /// Returns : p if a->p is better,
4298 /// q if a->q is better,
4299 /// null if neither is better
4301 static Type BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
4303 Type argument_type = a.Type;
4304 Expression argument_expr = a.Expr;
4306 if (argument_type == null)
4307 throw new Exception ("Expression of type " + a.Expr +
4308 " does not resolve its type");
4310 if (p == null || q == null)
4311 throw new InternalErrorException ("BetterConversion Got a null conversion");
4316 if (argument_expr is NullLiteral) {
4318 // If the argument is null and one of the types to compare is 'object' and
4319 // the other is a reference type, we prefer the other.
4321 // This follows from the usual rules:
4322 // * There is an implicit conversion from 'null' to type 'object'
4323 // * There is an implicit conversion from 'null' to any reference type
4324 // * There is an implicit conversion from any reference type to type 'object'
4325 // * There is no implicit conversion from type 'object' to other reference types
4326 // => Conversion of 'null' to a reference type is better than conversion to 'object'
4328 // FIXME: This probably isn't necessary, since the type of a NullLiteral is the
4329 // null type. I think it used to be 'object' and thus needed a special
4330 // case to avoid the immediately following two checks.
4332 if (!p.IsValueType && q == TypeManager.object_type)
4334 if (!q.IsValueType && p == TypeManager.object_type)
4338 if (argument_type == p)
4341 if (argument_type == q)
4344 Expression p_tmp = new EmptyExpression (p);
4345 Expression q_tmp = new EmptyExpression (q);
4347 bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
4348 bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
4350 if (p_to_q && !q_to_p)
4353 if (q_to_p && !p_to_q)
4356 if (p == TypeManager.sbyte_type)
4357 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4358 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4360 if (q == TypeManager.sbyte_type)
4361 if (p == TypeManager.byte_type || p == TypeManager.ushort_type ||
4362 p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4365 if (p == TypeManager.short_type)
4366 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4367 q == TypeManager.uint64_type)
4369 if (q == TypeManager.short_type)
4370 if (p == TypeManager.ushort_type || p == TypeManager.uint32_type ||
4371 p == TypeManager.uint64_type)
4374 if (p == TypeManager.int32_type)
4375 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4377 if (q == TypeManager.int32_type)
4378 if (p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4381 if (p == TypeManager.int64_type)
4382 if (q == TypeManager.uint64_type)
4384 if (q == TypeManager.int64_type)
4385 if (p == TypeManager.uint64_type)
4392 /// Determines "Better function" between candidate
4393 /// and the current best match
4396 /// Returns an integer indicating :
4397 /// false if candidate ain't better
4398 /// true if candidate is better than the current best match
4400 static bool BetterFunction (EmitContext ec, ArrayList args, int argument_count,
4401 MethodBase candidate, bool candidate_params,
4402 MethodBase best, bool best_params, Location loc)
4404 ParameterData candidate_pd = GetParameterData (candidate);
4405 ParameterData best_pd = GetParameterData (best);
4407 int cand_count = candidate_pd.Count;
4410 // If there is no best method, than this one
4411 // is better, however, if we already found a
4412 // best method, we cant tell. This happens
4423 // interface IFooBar : IFoo, IBar {}
4425 // We cant tell if IFoo.DoIt is better than IBar.DoIt
4427 // However, we have to consider that
4428 // Trim (); is better than Trim (params char[] chars);
4430 if (cand_count == 0 && argument_count == 0)
4431 return !candidate_params && best_params;
4433 if ((candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS) &&
4434 (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.ARGLIST))
4435 if (cand_count != argument_count)
4438 bool better_at_least_one = false;
4439 for (int j = 0; j < argument_count; ++j) {
4440 Argument a = (Argument) args [j];
4442 Type ct = TypeManager.TypeToCoreType (candidate_pd.ParameterType (j));
4443 Type bt = TypeManager.TypeToCoreType (best_pd.ParameterType (j));
4445 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4446 if (candidate_params)
4447 ct = TypeManager.GetElementType (ct);
4449 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4451 bt = TypeManager.GetElementType (bt);
4453 Type better = BetterConversion (ec, a, ct, bt, loc);
4455 // for each argument, the conversion to 'ct' should be no worse than
4456 // the conversion to 'bt'.
4460 // for at least one argument, the conversion to 'ct' should be better than
4461 // the conversion to 'bt'.
4463 better_at_least_one = true;
4467 // If a method (in the normal form) with the
4468 // same signature as the expanded form of the
4469 // current best params method already exists,
4470 // the expanded form is not applicable so we
4471 // force it to select the candidate
4473 if (!candidate_params && best_params && cand_count == argument_count)
4476 return better_at_least_one;
4479 public static string FullMethodDesc (MethodBase mb)
4481 string ret_type = "";
4486 if (mb is MethodInfo)
4487 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
4489 StringBuilder sb = new StringBuilder (ret_type);
4491 sb.Append (mb.ReflectedType.ToString ());
4493 sb.Append (mb.Name);
4495 ParameterData pd = GetParameterData (mb);
4497 int count = pd.Count;
4500 for (int i = count; i > 0; ) {
4503 sb.Append (pd.ParameterDesc (count - i - 1));
4509 return sb.ToString ();
4512 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4514 MemberInfo [] miset;
4515 MethodGroupExpr union;
4520 return (MethodGroupExpr) mg2;
4523 return (MethodGroupExpr) mg1;
4526 MethodGroupExpr left_set = null, right_set = null;
4527 int length1 = 0, length2 = 0;
4529 left_set = (MethodGroupExpr) mg1;
4530 length1 = left_set.Methods.Length;
4532 right_set = (MethodGroupExpr) mg2;
4533 length2 = right_set.Methods.Length;
4535 ArrayList common = new ArrayList ();
4537 foreach (MethodBase r in right_set.Methods){
4538 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
4542 miset = new MemberInfo [length1 + length2 - common.Count];
4543 left_set.Methods.CopyTo (miset, 0);
4547 foreach (MethodBase r in right_set.Methods) {
4548 if (!common.Contains (r))
4552 union = new MethodGroupExpr (miset, loc);
4557 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4558 ArrayList arguments, int arg_count,
4559 ref MethodBase candidate)
4561 return IsParamsMethodApplicable (
4562 ec, me, arguments, arg_count, false, ref candidate) ||
4563 IsParamsMethodApplicable (
4564 ec, me, arguments, arg_count, true, ref candidate);
4569 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4570 ArrayList arguments, int arg_count,
4571 bool do_varargs, ref MethodBase candidate)
4573 return IsParamsMethodApplicable (
4574 ec, arguments, arg_count, candidate, do_varargs);
4578 /// Determines if the candidate method, if a params method, is applicable
4579 /// in its expanded form to the given set of arguments
4581 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
4582 int arg_count, MethodBase candidate,
4585 ParameterData pd = GetParameterData (candidate);
4587 int pd_count = pd.Count;
4591 int count = pd_count - 1;
4593 if (pd.ParameterModifier (count) != Parameter.Modifier.ARGLIST)
4595 if (pd_count != arg_count)
4598 if (pd.ParameterModifier (count) != Parameter.Modifier.PARAMS)
4602 if (count > arg_count)
4605 if (pd_count == 1 && arg_count == 0)
4609 // If we have come this far, the case which
4610 // remains is when the number of parameters is
4611 // less than or equal to the argument count.
4613 for (int i = 0; i < count; ++i) {
4615 Argument a = (Argument) arguments [i];
4617 Parameter.Modifier a_mod = a.GetParameterModifier () &
4618 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4619 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4620 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4622 if (a_mod == p_mod) {
4624 if (a_mod == Parameter.Modifier.NONE)
4625 if (!Convert.ImplicitConversionExists (ec,
4627 pd.ParameterType (i)))
4630 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4631 Type pt = pd.ParameterType (i);
4634 pt = TypeManager.GetReferenceType (pt);
4645 Argument a = (Argument) arguments [count];
4646 if (!(a.Expr is Arglist))
4652 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4654 for (int i = pd_count - 1; i < arg_count; i++) {
4655 Argument a = (Argument) arguments [i];
4657 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4664 static bool IsApplicable (EmitContext ec, MethodGroupExpr me,
4665 ArrayList arguments, int arg_count,
4666 ref MethodBase candidate)
4668 return IsApplicable (ec, arguments, arg_count, candidate);
4672 /// Determines if the candidate method is applicable (section 14.4.2.1)
4673 /// to the given set of arguments
4675 static bool IsApplicable (EmitContext ec, ArrayList arguments, int arg_count,
4676 MethodBase candidate)
4678 ParameterData pd = GetParameterData (candidate);
4680 if (arg_count != pd.Count)
4683 for (int i = arg_count; i > 0; ) {
4686 Argument a = (Argument) arguments [i];
4688 Parameter.Modifier a_mod = a.GetParameterModifier () &
4689 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4690 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4691 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4694 if (a_mod == p_mod ||
4695 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4696 if (a_mod == Parameter.Modifier.NONE) {
4697 if (!Convert.ImplicitConversionExists (ec,
4699 pd.ParameterType (i)))
4703 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4704 Type pt = pd.ParameterType (i);
4707 pt = TypeManager.GetReferenceType (pt);
4719 static private bool IsAncestralType (Type first_type, Type second_type)
4721 return first_type != second_type &&
4722 (second_type.IsSubclassOf (first_type) ||
4723 TypeManager.ImplementsInterface (second_type, first_type));
4727 /// Find the Applicable Function Members (7.4.2.1)
4729 /// me: Method Group expression with the members to select.
4730 /// it might contain constructors or methods (or anything
4731 /// that maps to a method).
4733 /// Arguments: ArrayList containing resolved Argument objects.
4735 /// loc: The location if we want an error to be reported, or a Null
4736 /// location for "probing" purposes.
4738 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4739 /// that is the best match of me on Arguments.
4742 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4743 ArrayList Arguments, bool may_fail,
4746 MethodBase method = null;
4747 bool method_params = false;
4748 Type applicable_type = null;
4750 ArrayList candidates = new ArrayList ();
4753 // Used to keep a map between the candidate
4754 // and whether it is being considered in its
4755 // normal or expanded form
4757 // false is normal form, true is expanded form
4759 Hashtable candidate_to_form = null;
4761 if (Arguments != null)
4762 arg_count = Arguments.Count;
4764 if ((me.Name == "Invoke") &&
4765 TypeManager.IsDelegateType (me.DeclaringType)) {
4766 Error_InvokeOnDelegate (loc);
4770 MethodBase[] methods = me.Methods;
4773 // First we construct the set of applicable methods
4775 bool is_sorted = true;
4776 for (int i = 0; i < methods.Length; i++){
4777 Type decl_type = methods [i].DeclaringType;
4780 // If we have already found an applicable method
4781 // we eliminate all base types (Section 14.5.5.1)
4783 if ((applicable_type != null) &&
4784 IsAncestralType (decl_type, applicable_type))
4788 // Check if candidate is applicable (section 14.4.2.1)
4789 // Is candidate applicable in normal form?
4791 bool is_applicable = IsApplicable (
4792 ec, me, Arguments, arg_count, ref methods [i]);
4794 if (!is_applicable &&
4795 (IsParamsMethodApplicable (
4796 ec, me, Arguments, arg_count, ref methods [i]))) {
4797 MethodBase candidate = methods [i];
4798 if (candidate_to_form == null)
4799 candidate_to_form = new PtrHashtable ();
4800 candidate_to_form [candidate] = candidate;
4801 // Candidate is applicable in expanded form
4802 is_applicable = true;
4808 candidates.Add (methods [i]);
4810 if (applicable_type == null)
4811 applicable_type = decl_type;
4812 else if (applicable_type != decl_type) {
4814 if (IsAncestralType (applicable_type, decl_type))
4815 applicable_type = decl_type;
4819 int candidate_top = candidates.Count;
4821 if (candidate_top == 0) {
4823 // Okay so we have failed to find anything so we
4824 // return by providing info about the closest match
4826 for (int i = 0; i < methods.Length; ++i) {
4827 MethodBase c = (MethodBase) methods [i];
4828 ParameterData pd = GetParameterData (c);
4830 if (pd.Count != arg_count)
4833 VerifyArgumentsCompat (ec, Arguments, arg_count,
4834 c, false, null, may_fail, loc);
4839 string report_name = me.Name;
4840 if (report_name == ".ctor")
4841 report_name = me.DeclaringType.ToString ();
4843 Error_WrongNumArguments (
4844 loc, report_name, arg_count);
4853 // At this point, applicable_type is _one_ of the most derived types
4854 // in the set of types containing the methods in this MethodGroup.
4855 // Filter the candidates so that they only contain methods from the
4856 // most derived types.
4859 int finalized = 0; // Number of finalized candidates
4862 // Invariant: applicable_type is a most derived type
4864 // We'll try to complete Section 14.5.5.1 for 'applicable_type' by
4865 // eliminating all it's base types. At the same time, we'll also move
4866 // every unrelated type to the end of the array, and pick the next
4867 // 'applicable_type'.
4869 Type next_applicable_type = null;
4870 int j = finalized; // where to put the next finalized candidate
4871 int k = finalized; // where to put the next undiscarded candidate
4872 for (int i = finalized; i < candidate_top; ++i) {
4873 Type decl_type = ((MethodBase) candidates[i]).DeclaringType;
4875 if (decl_type == applicable_type) {
4876 candidates[k++] = candidates[j];
4877 candidates[j++] = candidates[i];
4881 if (IsAncestralType (decl_type, applicable_type))
4884 if (next_applicable_type != null &&
4885 IsAncestralType (decl_type, next_applicable_type))
4888 candidates[k++] = candidates[i];
4890 if (next_applicable_type == null ||
4891 IsAncestralType (next_applicable_type, decl_type))
4892 next_applicable_type = decl_type;
4895 applicable_type = next_applicable_type;
4898 } while (applicable_type != null);
4902 // Now we actually find the best method
4905 method = (MethodBase) candidates[0];
4906 method_params = candidate_to_form != null && candidate_to_form.Contains (method);
4907 for (int ix = 1; ix < candidate_top; ix++){
4908 MethodBase candidate = (MethodBase) candidates [ix];
4909 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4911 if (BetterFunction (ec, Arguments, arg_count,
4912 candidate, cand_params,
4913 method, method_params, loc)) {
4915 method_params = cand_params;
4920 // Now check that there are no ambiguities i.e the selected method
4921 // should be better than all the others
4923 bool ambiguous = false;
4924 for (int ix = 0; ix < candidate_top; ix++){
4925 MethodBase candidate = (MethodBase) candidates [ix];
4927 if (candidate == method)
4930 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4931 if (!BetterFunction (ec, Arguments, arg_count,
4932 method, method_params,
4933 candidate, cand_params,
4935 Report.SymbolRelatedToPreviousError (candidate);
4941 Report.SymbolRelatedToPreviousError (method);
4942 Report.Error (121, loc, "Ambiguous call when selecting function due to implicit casts");
4948 // And now check if the arguments are all
4949 // compatible, perform conversions if
4950 // necessary etc. and return if everything is
4953 if (!VerifyArgumentsCompat (ec, Arguments, arg_count, method,
4954 method_params, null, may_fail, loc))
4960 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
4962 Report.Error (1501, loc,
4963 "No overload for method `" + name + "' takes `" +
4964 arg_count + "' arguments");
4967 static void Error_InvokeOnDelegate (Location loc)
4969 Report.Error (1533, loc,
4970 "Invoke cannot be called directly on a delegate");
4973 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
4974 Type delegate_type, string arg_sig, string par_desc)
4976 if (delegate_type == null)
4977 Report.Error (1502, loc,
4978 "The best overloaded match for method '" +
4979 FullMethodDesc (method) +
4980 "' has some invalid arguments");
4982 Report.Error (1594, loc,
4983 "Delegate '" + delegate_type.ToString () +
4984 "' has some invalid arguments.");
4985 Report.Error (1503, loc,
4986 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
4987 idx, arg_sig, par_desc));
4990 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
4991 int arg_count, MethodBase method,
4992 bool chose_params_expanded,
4993 Type delegate_type, bool may_fail,
4996 ParameterData pd = GetParameterData (method);
4997 int pd_count = pd.Count;
4999 for (int j = 0; j < arg_count; j++) {
5000 Argument a = (Argument) Arguments [j];
5001 Expression a_expr = a.Expr;
5002 Type parameter_type = pd.ParameterType (j);
5003 Parameter.Modifier pm = pd.ParameterModifier (j);
5005 if (pm == Parameter.Modifier.PARAMS){
5006 if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
5008 Error_InvalidArguments (
5009 loc, j, method, delegate_type,
5010 Argument.FullDesc (a), pd.ParameterDesc (j));
5014 if (chose_params_expanded)
5015 parameter_type = TypeManager.GetElementType (parameter_type);
5016 } else if (pm == Parameter.Modifier.ARGLIST){
5022 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
5024 Error_InvalidArguments (
5025 loc, j, method, delegate_type,
5026 Argument.FullDesc (a), pd.ParameterDesc (j));
5034 if (!a.Type.Equals (parameter_type)){
5037 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
5041 Error_InvalidArguments (
5042 loc, j, method, delegate_type,
5043 Argument.FullDesc (a), pd.ParameterDesc (j));
5048 // Update the argument with the implicit conversion
5054 if (parameter_type.IsPointer){
5061 Parameter.Modifier a_mod = a.GetParameterModifier () &
5062 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5063 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
5064 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5066 if (a_mod != p_mod &&
5067 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
5069 Report.Error (1502, loc,
5070 "The best overloaded match for method '" + FullMethodDesc (method)+
5071 "' has some invalid arguments");
5072 Report.Error (1503, loc,
5073 "Argument " + (j+1) +
5074 ": Cannot convert from '" + Argument.FullDesc (a)
5075 + "' to '" + pd.ParameterDesc (j) + "'");
5085 public override Expression DoResolve (EmitContext ec)
5088 // First, resolve the expression that is used to
5089 // trigger the invocation
5091 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
5095 if (!(expr is MethodGroupExpr)) {
5096 Type expr_type = expr.Type;
5098 if (expr_type != null){
5099 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
5101 return (new DelegateInvocation (
5102 this.expr, Arguments, loc)).Resolve (ec);
5106 if (!(expr is MethodGroupExpr)){
5107 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup, loc);
5112 // Next, evaluate all the expressions in the argument list
5114 if (Arguments != null){
5115 foreach (Argument a in Arguments){
5116 if (!a.Resolve (ec, loc))
5121 MethodGroupExpr mg = (MethodGroupExpr) expr;
5122 method = OverloadResolve (ec, mg, Arguments, false, loc);
5127 MethodInfo mi = method as MethodInfo;
5129 type = TypeManager.TypeToCoreType (mi.ReturnType);
5130 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null)) {
5131 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
5135 Expression iexpr = mg.InstanceExpression;
5136 if (mi.IsStatic && (iexpr != null) && !(iexpr is This)) {
5137 if (mg.IdenticalTypeName)
5138 mg.InstanceExpression = null;
5140 MemberAccess.error176 (loc, mi.Name);
5146 if (type.IsPointer){
5154 // Only base will allow this invocation to happen.
5156 if (mg.IsBase && method.IsAbstract){
5157 Report.Error (205, loc, "Cannot call an abstract base member: " +
5158 FullMethodDesc (method));
5162 if (method.Name == "Finalize" && Arguments == null) {
5164 Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
5166 Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
5170 if ((method.Attributes & MethodAttributes.SpecialName) != 0) {
5171 if (TypeManager.LookupDeclSpace (method.DeclaringType) != null || TypeManager.IsSpecialMethod (method)) {
5172 Report.Error (571, loc, TypeManager.CSharpSignature (method) + ": can not call operator or accessor");
5177 if (mg.InstanceExpression != null)
5178 mg.InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
5180 eclass = ExprClass.Value;
5185 // Emits the list of arguments as an array
5187 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
5189 ILGenerator ig = ec.ig;
5190 int count = arguments.Count - idx;
5191 Argument a = (Argument) arguments [idx];
5192 Type t = a.Expr.Type;
5194 IntConstant.EmitInt (ig, count);
5195 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
5197 int top = arguments.Count;
5198 for (int j = idx; j < top; j++){
5199 a = (Argument) arguments [j];
5201 ig.Emit (OpCodes.Dup);
5202 IntConstant.EmitInt (ig, j - idx);
5205 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj);
5207 ig.Emit (OpCodes.Ldelema, t);
5212 ig.Emit (OpCodes.Stobj, t);
5219 /// Emits a list of resolved Arguments that are in the arguments
5222 /// The MethodBase argument might be null if the
5223 /// emission of the arguments is known not to contain
5224 /// a `params' field (for example in constructors or other routines
5225 /// that keep their arguments in this structure)
5227 /// if `dup_args' is true, a copy of the arguments will be left
5228 /// on the stack. If `dup_args' is true, you can specify `this_arg'
5229 /// which will be duplicated before any other args. Only EmitCall
5230 /// should be using this interface.
5232 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments, bool dup_args, LocalTemporary this_arg)
5236 pd = GetParameterData (mb);
5240 LocalTemporary [] temps = null;
5243 temps = new LocalTemporary [arguments.Count];
5246 // If we are calling a params method with no arguments, special case it
5248 if (arguments == null){
5249 if (pd != null && pd.Count > 0 &&
5250 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
5251 ILGenerator ig = ec.ig;
5253 IntConstant.EmitInt (ig, 0);
5254 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
5260 int top = arguments.Count;
5262 for (int i = 0; i < top; i++){
5263 Argument a = (Argument) arguments [i];
5266 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
5268 // Special case if we are passing the same data as the
5269 // params argument, do not put it in an array.
5271 if (pd.ParameterType (i) == a.Type)
5274 EmitParams (ec, i, arguments);
5281 ec.ig.Emit (OpCodes.Dup);
5282 (temps [i] = new LocalTemporary (ec, a.Type)).Store (ec);
5287 if (this_arg != null)
5290 for (int i = 0; i < top; i ++)
5291 temps [i].Emit (ec);
5294 if (pd != null && pd.Count > top &&
5295 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
5296 ILGenerator ig = ec.ig;
5298 IntConstant.EmitInt (ig, 0);
5299 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
5303 static Type[] GetVarargsTypes (EmitContext ec, MethodBase mb,
5304 ArrayList arguments)
5306 ParameterData pd = GetParameterData (mb);
5308 if (arguments == null)
5309 return new Type [0];
5311 Argument a = (Argument) arguments [pd.Count - 1];
5312 Arglist list = (Arglist) a.Expr;
5314 return list.ArgumentTypes;
5318 /// This checks the ConditionalAttribute on the method
5320 static bool IsMethodExcluded (MethodBase method, EmitContext ec)
5322 if (method.IsConstructor)
5325 IMethodData md = TypeManager.GetMethod (method);
5327 return md.IsExcluded (ec);
5329 // For some methods (generated by delegate class) GetMethod returns null
5330 // because they are not included in builder_to_method table
5331 if (method.DeclaringType is TypeBuilder)
5334 return AttributeTester.IsConditionalMethodExcluded (method);
5338 /// is_base tells whether we want to force the use of the `call'
5339 /// opcode instead of using callvirt. Call is required to call
5340 /// a specific method, while callvirt will always use the most
5341 /// recent method in the vtable.
5343 /// is_static tells whether this is an invocation on a static method
5345 /// instance_expr is an expression that represents the instance
5346 /// it must be non-null if is_static is false.
5348 /// method is the method to invoke.
5350 /// Arguments is the list of arguments to pass to the method or constructor.
5352 public static void EmitCall (EmitContext ec, bool is_base,
5353 bool is_static, Expression instance_expr,
5354 MethodBase method, ArrayList Arguments, Location loc)
5356 EmitCall (ec, is_base, is_static, instance_expr, method, Arguments, loc, false, false);
5359 // `dup_args' leaves an extra copy of the arguments on the stack
5360 // `omit_args' does not leave any arguments at all.
5361 // So, basically, you could make one call with `dup_args' set to true,
5362 // and then another with `omit_args' set to true, and the two calls
5363 // would have the same set of arguments. However, each argument would
5364 // only have been evaluated once.
5365 public static void EmitCall (EmitContext ec, bool is_base,
5366 bool is_static, Expression instance_expr,
5367 MethodBase method, ArrayList Arguments, Location loc,
5368 bool dup_args, bool omit_args)
5370 ILGenerator ig = ec.ig;
5371 bool struct_call = false;
5372 bool this_call = false;
5373 LocalTemporary this_arg = null;
5375 Type decl_type = method.DeclaringType;
5377 if (!RootContext.StdLib) {
5378 // Replace any calls to the system's System.Array type with calls to
5379 // the newly created one.
5380 if (method == TypeManager.system_int_array_get_length)
5381 method = TypeManager.int_array_get_length;
5382 else if (method == TypeManager.system_int_array_get_rank)
5383 method = TypeManager.int_array_get_rank;
5384 else if (method == TypeManager.system_object_array_clone)
5385 method = TypeManager.object_array_clone;
5386 else if (method == TypeManager.system_int_array_get_length_int)
5387 method = TypeManager.int_array_get_length_int;
5388 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5389 method = TypeManager.int_array_get_lower_bound_int;
5390 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5391 method = TypeManager.int_array_get_upper_bound_int;
5392 else if (method == TypeManager.system_void_array_copyto_array_int)
5393 method = TypeManager.void_array_copyto_array_int;
5396 if (ec.TestObsoleteMethodUsage) {
5398 // This checks ObsoleteAttribute on the method and on the declaring type
5400 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
5402 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
5405 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
5407 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
5411 if (IsMethodExcluded (method, ec))
5415 this_call = instance_expr == null;
5416 if (decl_type.IsValueType || (!this_call && instance_expr.Type.IsValueType))
5420 // If this is ourselves, push "this"
5425 ig.Emit (OpCodes.Ldarg_0);
5429 // Push the instance expression
5431 if (instance_expr.Type.IsValueType) {
5433 // Special case: calls to a function declared in a
5434 // reference-type with a value-type argument need
5435 // to have their value boxed.
5436 if (decl_type.IsValueType) {
5438 // If the expression implements IMemoryLocation, then
5439 // we can optimize and use AddressOf on the
5442 // If not we have to use some temporary storage for
5444 if (instance_expr is IMemoryLocation) {
5445 ((IMemoryLocation)instance_expr).
5446 AddressOf (ec, AddressOp.LoadStore);
5448 LocalTemporary temp = new LocalTemporary (ec, instance_expr.Type);
5449 instance_expr.Emit (ec);
5451 temp.AddressOf (ec, AddressOp.Load);
5454 // avoid the overhead of doing this all the time.
5456 t = TypeManager.GetReferenceType (instance_expr.Type);
5458 instance_expr.Emit (ec);
5459 ig.Emit (OpCodes.Box, instance_expr.Type);
5460 t = TypeManager.object_type;
5463 instance_expr.Emit (ec);
5464 t = instance_expr.Type;
5469 this_arg = new LocalTemporary (ec, t);
5470 ig.Emit (OpCodes.Dup);
5471 this_arg.Store (ec);
5477 EmitArguments (ec, method, Arguments, dup_args, this_arg);
5480 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
5481 call_op = OpCodes.Call;
5483 call_op = OpCodes.Callvirt;
5485 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
5486 Type[] varargs_types = GetVarargsTypes (ec, method, Arguments);
5487 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
5494 // and DoFoo is not virtual, you can omit the callvirt,
5495 // because you don't need the null checking behavior.
5497 if (method is MethodInfo)
5498 ig.Emit (call_op, (MethodInfo) method);
5500 ig.Emit (call_op, (ConstructorInfo) method);
5503 public override void Emit (EmitContext ec)
5505 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5507 EmitCall (ec, mg.IsBase, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5510 public override void EmitStatement (EmitContext ec)
5515 // Pop the return value if there is one
5517 if (method is MethodInfo){
5518 Type ret = ((MethodInfo)method).ReturnType;
5519 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5520 ec.ig.Emit (OpCodes.Pop);
5525 public class InvocationOrCast : ExpressionStatement
5528 Expression argument;
5530 public InvocationOrCast (Expression expr, Expression argument, Location loc)
5533 this.argument = argument;
5537 public override Expression DoResolve (EmitContext ec)
5540 // First try to resolve it as a cast.
5542 TypeExpr te = expr.ResolveAsTypeTerminal (ec, true);
5544 Cast cast = new Cast (te, argument, loc);
5545 return cast.Resolve (ec);
5549 // This can either be a type or a delegate invocation.
5550 // Let's just resolve it and see what we'll get.
5552 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5557 // Ok, so it's a Cast.
5559 if (expr.eclass == ExprClass.Type) {
5560 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
5561 return cast.Resolve (ec);
5565 // It's a delegate invocation.
5567 if (!TypeManager.IsDelegateType (expr.Type)) {
5568 Error (149, "Method name expected");
5572 ArrayList args = new ArrayList ();
5573 args.Add (new Argument (argument, Argument.AType.Expression));
5574 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5575 return invocation.Resolve (ec);
5580 Error (201, "Only assignment, call, increment, decrement and new object " +
5581 "expressions can be used as a statement");
5584 public override ExpressionStatement ResolveStatement (EmitContext ec)
5587 // First try to resolve it as a cast.
5589 TypeExpr te = expr.ResolveAsTypeTerminal (ec, true);
5596 // This can either be a type or a delegate invocation.
5597 // Let's just resolve it and see what we'll get.
5599 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5600 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5606 // It's a delegate invocation.
5608 if (!TypeManager.IsDelegateType (expr.Type)) {
5609 Error (149, "Method name expected");
5613 ArrayList args = new ArrayList ();
5614 args.Add (new Argument (argument, Argument.AType.Expression));
5615 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5616 return invocation.ResolveStatement (ec);
5619 public override void Emit (EmitContext ec)
5621 throw new Exception ("Cannot happen");
5624 public override void EmitStatement (EmitContext ec)
5626 throw new Exception ("Cannot happen");
5631 // This class is used to "disable" the code generation for the
5632 // temporary variable when initializing value types.
5634 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5635 public void AddressOf (EmitContext ec, AddressOp Mode)
5642 /// Implements the new expression
5644 public class New : ExpressionStatement, IMemoryLocation {
5645 public readonly ArrayList Arguments;
5648 // During bootstrap, it contains the RequestedType,
5649 // but if `type' is not null, it *might* contain a NewDelegate
5650 // (because of field multi-initialization)
5652 public Expression RequestedType;
5654 MethodBase method = null;
5657 // If set, the new expression is for a value_target, and
5658 // we will not leave anything on the stack.
5660 Expression value_target;
5661 bool value_target_set = false;
5663 public New (Expression requested_type, ArrayList arguments, Location l)
5665 RequestedType = requested_type;
5666 Arguments = arguments;
5670 public bool SetValueTypeVariable (Expression value)
5672 value_target = value;
5673 value_target_set = true;
5674 if (!(value_target is IMemoryLocation)){
5675 Error_UnexpectedKind ("variable", loc);
5682 // This function is used to disable the following code sequence for
5683 // value type initialization:
5685 // AddressOf (temporary)
5689 // Instead the provide will have provided us with the address on the
5690 // stack to store the results.
5692 static Expression MyEmptyExpression;
5694 public void DisableTemporaryValueType ()
5696 if (MyEmptyExpression == null)
5697 MyEmptyExpression = new EmptyAddressOf ();
5700 // To enable this, look into:
5701 // test-34 and test-89 and self bootstrapping.
5703 // For instance, we can avoid a copy by using `newobj'
5704 // instead of Call + Push-temp on value types.
5705 // value_target = MyEmptyExpression;
5708 public override Expression DoResolve (EmitContext ec)
5711 // The New DoResolve might be called twice when initializing field
5712 // expressions (see EmitFieldInitializers, the call to
5713 // GetInitializerExpression will perform a resolve on the expression,
5714 // and later the assign will trigger another resolution
5716 // This leads to bugs (#37014)
5719 if (RequestedType is NewDelegate)
5720 return RequestedType;
5724 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec, false);
5728 type = texpr.ResolveType (ec);
5730 CheckObsoleteAttribute (type);
5732 bool IsDelegate = TypeManager.IsDelegateType (type);
5735 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5736 if (RequestedType != null)
5737 if (!(RequestedType is DelegateCreation))
5738 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
5739 return RequestedType;
5742 if (type.IsAbstract && type.IsSealed) {
5743 Report.Error (712, loc, "Cannot create an instance of the static class '{0}'", TypeManager.CSharpName (type));
5747 if (type.IsInterface || type.IsAbstract){
5748 Error (144, "It is not possible to create instances of interfaces or abstract classes");
5752 bool is_struct = type.IsValueType;
5753 eclass = ExprClass.Value;
5756 // SRE returns a match for .ctor () on structs (the object constructor),
5757 // so we have to manually ignore it.
5759 if (is_struct && Arguments == null)
5763 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
5764 ml = MemberLookupFinal (ec, type, type, ".ctor",
5765 MemberTypes.Constructor,
5766 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5771 if (! (ml is MethodGroupExpr)){
5773 ml.Error_UnexpectedKind ("method group", loc);
5779 if (Arguments != null){
5780 foreach (Argument a in Arguments){
5781 if (!a.Resolve (ec, loc))
5786 method = Invocation.OverloadResolve (
5787 ec, (MethodGroupExpr) ml, Arguments, false, loc);
5791 if (method == null) {
5792 if (!is_struct || Arguments.Count > 0) {
5793 Error (1501, String.Format (
5794 "New invocation: Can not find a constructor in `{0}' for this argument list",
5795 TypeManager.CSharpName (type)));
5804 // This DoEmit can be invoked in two contexts:
5805 // * As a mechanism that will leave a value on the stack (new object)
5806 // * As one that wont (init struct)
5808 // You can control whether a value is required on the stack by passing
5809 // need_value_on_stack. The code *might* leave a value on the stack
5810 // so it must be popped manually
5812 // If we are dealing with a ValueType, we have a few
5813 // situations to deal with:
5815 // * The target is a ValueType, and we have been provided
5816 // the instance (this is easy, we are being assigned).
5818 // * The target of New is being passed as an argument,
5819 // to a boxing operation or a function that takes a
5822 // In this case, we need to create a temporary variable
5823 // that is the argument of New.
5825 // Returns whether a value is left on the stack
5827 bool DoEmit (EmitContext ec, bool need_value_on_stack)
5829 bool is_value_type = type.IsValueType;
5830 ILGenerator ig = ec.ig;
5835 // Allow DoEmit() to be called multiple times.
5836 // We need to create a new LocalTemporary each time since
5837 // you can't share LocalBuilders among ILGeneators.
5838 if (!value_target_set)
5839 value_target = new LocalTemporary (ec, type);
5841 ml = (IMemoryLocation) value_target;
5842 ml.AddressOf (ec, AddressOp.Store);
5846 Invocation.EmitArguments (ec, method, Arguments, false, null);
5850 ig.Emit (OpCodes.Initobj, type);
5852 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5853 if (need_value_on_stack){
5854 value_target.Emit (ec);
5859 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
5864 public override void Emit (EmitContext ec)
5869 public override void EmitStatement (EmitContext ec)
5871 if (DoEmit (ec, false))
5872 ec.ig.Emit (OpCodes.Pop);
5875 public void AddressOf (EmitContext ec, AddressOp Mode)
5877 if (!type.IsValueType){
5879 // We throw an exception. So far, I believe we only need to support
5881 // foreach (int j in new StructType ())
5884 throw new Exception ("AddressOf should not be used for classes");
5887 if (!value_target_set)
5888 value_target = new LocalTemporary (ec, type);
5890 IMemoryLocation ml = (IMemoryLocation) value_target;
5891 ml.AddressOf (ec, AddressOp.Store);
5893 Invocation.EmitArguments (ec, method, Arguments, false, null);
5896 ec.ig.Emit (OpCodes.Initobj, type);
5898 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5900 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
5905 /// 14.5.10.2: Represents an array creation expression.
5909 /// There are two possible scenarios here: one is an array creation
5910 /// expression that specifies the dimensions and optionally the
5911 /// initialization data and the other which does not need dimensions
5912 /// specified but where initialization data is mandatory.
5914 public class ArrayCreation : Expression {
5915 Expression requested_base_type;
5916 ArrayList initializers;
5919 // The list of Argument types.
5920 // This is used to construct the `newarray' or constructor signature
5922 ArrayList arguments;
5925 // Method used to create the array object.
5927 MethodBase new_method = null;
5929 Type array_element_type;
5930 Type underlying_type;
5931 bool is_one_dimensional = false;
5932 bool is_builtin_type = false;
5933 bool expect_initializers = false;
5934 int num_arguments = 0;
5938 ArrayList array_data;
5943 // The number of array initializers that we can handle
5944 // via the InitializeArray method - through EmitStaticInitializers
5946 int num_automatic_initializers;
5948 const int max_automatic_initializers = 6;
5950 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
5952 this.requested_base_type = requested_base_type;
5953 this.initializers = initializers;
5957 arguments = new ArrayList ();
5959 foreach (Expression e in exprs) {
5960 arguments.Add (new Argument (e, Argument.AType.Expression));
5965 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
5967 this.requested_base_type = requested_base_type;
5968 this.initializers = initializers;
5972 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
5974 //string tmp = rank.Substring (rank.LastIndexOf ('['));
5976 //dimensions = tmp.Length - 1;
5977 expect_initializers = true;
5980 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
5982 StringBuilder sb = new StringBuilder (rank);
5985 for (int i = 1; i < idx_count; i++)
5990 return new ComposedCast (base_type, sb.ToString (), loc);
5993 void Error_IncorrectArrayInitializer ()
5995 Error (178, "Incorrectly structured array initializer");
5998 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
6000 if (specified_dims) {
6001 Argument a = (Argument) arguments [idx];
6003 if (!a.Resolve (ec, loc))
6006 if (!(a.Expr is Constant)) {
6007 Error (150, "A constant value is expected");
6011 int value = (int) ((Constant) a.Expr).GetValue ();
6013 if (value != probe.Count) {
6014 Error_IncorrectArrayInitializer ();
6018 bounds [idx] = value;
6021 int child_bounds = -1;
6022 foreach (object o in probe) {
6023 if (o is ArrayList) {
6024 int current_bounds = ((ArrayList) o).Count;
6026 if (child_bounds == -1)
6027 child_bounds = current_bounds;
6029 else if (child_bounds != current_bounds){
6030 Error_IncorrectArrayInitializer ();
6033 if (specified_dims && (idx + 1 >= arguments.Count)){
6034 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
6038 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
6042 if (child_bounds != -1){
6043 Error_IncorrectArrayInitializer ();
6047 Expression tmp = (Expression) o;
6048 tmp = tmp.Resolve (ec);
6052 // Console.WriteLine ("I got: " + tmp);
6053 // Handle initialization from vars, fields etc.
6055 Expression conv = Convert.ImplicitConversionRequired (
6056 ec, tmp, underlying_type, loc);
6061 if (conv is StringConstant || conv is DecimalConstant || conv is NullCast) {
6062 // These are subclasses of Constant that can appear as elements of an
6063 // array that cannot be statically initialized (with num_automatic_initializers
6064 // > max_automatic_initializers), so num_automatic_initializers should be left as zero.
6065 array_data.Add (conv);
6066 } else if (conv is Constant) {
6067 // These are the types of Constant that can appear in arrays that can be
6068 // statically allocated.
6069 array_data.Add (conv);
6070 num_automatic_initializers++;
6072 array_data.Add (conv);
6079 public void UpdateIndices (EmitContext ec)
6082 for (ArrayList probe = initializers; probe != null;) {
6083 if (probe.Count > 0 && probe [0] is ArrayList) {
6084 Expression e = new IntConstant (probe.Count);
6085 arguments.Add (new Argument (e, Argument.AType.Expression));
6087 bounds [i++] = probe.Count;
6089 probe = (ArrayList) probe [0];
6092 Expression e = new IntConstant (probe.Count);
6093 arguments.Add (new Argument (e, Argument.AType.Expression));
6095 bounds [i++] = probe.Count;
6102 public bool ValidateInitializers (EmitContext ec, Type array_type)
6104 if (initializers == null) {
6105 if (expect_initializers)
6111 if (underlying_type == null)
6115 // We use this to store all the date values in the order in which we
6116 // will need to store them in the byte blob later
6118 array_data = new ArrayList ();
6119 bounds = new Hashtable ();
6123 if (arguments != null) {
6124 ret = CheckIndices (ec, initializers, 0, true);
6127 arguments = new ArrayList ();
6129 ret = CheckIndices (ec, initializers, 0, false);
6136 if (arguments.Count != dimensions) {
6137 Error_IncorrectArrayInitializer ();
6146 // Converts `source' to an int, uint, long or ulong.
6148 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
6152 bool old_checked = ec.CheckState;
6153 ec.CheckState = true;
6155 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
6156 if (target == null){
6157 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
6158 if (target == null){
6159 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
6160 if (target == null){
6161 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
6163 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
6167 ec.CheckState = old_checked;
6170 // Only positive constants are allowed at compile time
6172 if (target is Constant){
6173 if (target is IntConstant){
6174 if (((IntConstant) target).Value < 0){
6175 Expression.Error_NegativeArrayIndex (loc);
6180 if (target is LongConstant){
6181 if (((LongConstant) target).Value < 0){
6182 Expression.Error_NegativeArrayIndex (loc);
6193 // Creates the type of the array
6195 bool LookupType (EmitContext ec)
6197 StringBuilder array_qualifier = new StringBuilder (rank);
6200 // `In the first form allocates an array instace of the type that results
6201 // from deleting each of the individual expression from the expression list'
6203 if (num_arguments > 0) {
6204 array_qualifier.Append ("[");
6205 for (int i = num_arguments-1; i > 0; i--)
6206 array_qualifier.Append (",");
6207 array_qualifier.Append ("]");
6213 TypeExpr array_type_expr;
6214 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
6215 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec, false);
6216 if (array_type_expr == null)
6219 type = array_type_expr.ResolveType (ec);
6221 if (!type.IsArray) {
6222 Error (622, "Can only use array initializer expressions to assign to array types. Try using a new expression instead.");
6225 underlying_type = TypeManager.GetElementType (type);
6226 dimensions = type.GetArrayRank ();
6231 public override Expression DoResolve (EmitContext ec)
6235 if (!LookupType (ec))
6239 // First step is to validate the initializers and fill
6240 // in any missing bits
6242 if (!ValidateInitializers (ec, type))
6245 if (arguments == null)
6248 arg_count = arguments.Count;
6249 foreach (Argument a in arguments){
6250 if (!a.Resolve (ec, loc))
6253 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
6254 if (real_arg == null)
6261 array_element_type = TypeManager.GetElementType (type);
6263 if (array_element_type.IsAbstract && array_element_type.IsSealed) {
6264 Report.Error (719, loc, "'{0}': array elements cannot be of static type", TypeManager.CSharpName (array_element_type));
6268 if (arg_count == 1) {
6269 is_one_dimensional = true;
6270 eclass = ExprClass.Value;
6274 is_builtin_type = TypeManager.IsBuiltinType (type);
6276 if (is_builtin_type) {
6279 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
6280 AllBindingFlags, loc);
6282 if (!(ml is MethodGroupExpr)) {
6283 ml.Error_UnexpectedKind ("method group", loc);
6288 Error (-6, "New invocation: Can not find a constructor for " +
6289 "this argument list");
6293 new_method = Invocation.OverloadResolve (
6294 ec, (MethodGroupExpr) ml, arguments, false, loc);
6296 if (new_method == null) {
6297 Error (-6, "New invocation: Can not find a constructor for " +
6298 "this argument list");
6302 eclass = ExprClass.Value;
6305 ModuleBuilder mb = CodeGen.Module.Builder;
6306 ArrayList args = new ArrayList ();
6308 if (arguments != null) {
6309 for (int i = 0; i < arg_count; i++)
6310 args.Add (TypeManager.int32_type);
6313 Type [] arg_types = null;
6316 arg_types = new Type [args.Count];
6318 args.CopyTo (arg_types, 0);
6320 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
6323 if (new_method == null) {
6324 Error (-6, "New invocation: Can not find a constructor for " +
6325 "this argument list");
6329 eclass = ExprClass.Value;
6334 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
6339 int count = array_data.Count;
6341 if (underlying_type.IsEnum)
6342 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
6344 factor = GetTypeSize (underlying_type);
6346 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
6348 data = new byte [(count * factor + 4) & ~3];
6351 for (int i = 0; i < count; ++i) {
6352 object v = array_data [i];
6354 if (v is EnumConstant)
6355 v = ((EnumConstant) v).Child;
6357 if (v is Constant && !(v is StringConstant))
6358 v = ((Constant) v).GetValue ();
6364 if (underlying_type == TypeManager.int64_type){
6365 if (!(v is Expression)){
6366 long val = (long) v;
6368 for (int j = 0; j < factor; ++j) {
6369 data [idx + j] = (byte) (val & 0xFF);
6373 } else if (underlying_type == TypeManager.uint64_type){
6374 if (!(v is Expression)){
6375 ulong val = (ulong) v;
6377 for (int j = 0; j < factor; ++j) {
6378 data [idx + j] = (byte) (val & 0xFF);
6382 } else if (underlying_type == TypeManager.float_type) {
6383 if (!(v is Expression)){
6384 element = BitConverter.GetBytes ((float) v);
6386 for (int j = 0; j < factor; ++j)
6387 data [idx + j] = element [j];
6389 } else if (underlying_type == TypeManager.double_type) {
6390 if (!(v is Expression)){
6391 element = BitConverter.GetBytes ((double) v);
6393 for (int j = 0; j < factor; ++j)
6394 data [idx + j] = element [j];
6396 } else if (underlying_type == TypeManager.char_type){
6397 if (!(v is Expression)){
6398 int val = (int) ((char) v);
6400 data [idx] = (byte) (val & 0xff);
6401 data [idx+1] = (byte) (val >> 8);
6403 } else if (underlying_type == TypeManager.short_type){
6404 if (!(v is Expression)){
6405 int val = (int) ((short) v);
6407 data [idx] = (byte) (val & 0xff);
6408 data [idx+1] = (byte) (val >> 8);
6410 } else if (underlying_type == TypeManager.ushort_type){
6411 if (!(v is Expression)){
6412 int val = (int) ((ushort) v);
6414 data [idx] = (byte) (val & 0xff);
6415 data [idx+1] = (byte) (val >> 8);
6417 } else if (underlying_type == TypeManager.int32_type) {
6418 if (!(v is Expression)){
6421 data [idx] = (byte) (val & 0xff);
6422 data [idx+1] = (byte) ((val >> 8) & 0xff);
6423 data [idx+2] = (byte) ((val >> 16) & 0xff);
6424 data [idx+3] = (byte) (val >> 24);
6426 } else if (underlying_type == TypeManager.uint32_type) {
6427 if (!(v is Expression)){
6428 uint val = (uint) v;
6430 data [idx] = (byte) (val & 0xff);
6431 data [idx+1] = (byte) ((val >> 8) & 0xff);
6432 data [idx+2] = (byte) ((val >> 16) & 0xff);
6433 data [idx+3] = (byte) (val >> 24);
6435 } else if (underlying_type == TypeManager.sbyte_type) {
6436 if (!(v is Expression)){
6437 sbyte val = (sbyte) v;
6438 data [idx] = (byte) val;
6440 } else if (underlying_type == TypeManager.byte_type) {
6441 if (!(v is Expression)){
6442 byte val = (byte) v;
6443 data [idx] = (byte) val;
6445 } else if (underlying_type == TypeManager.bool_type) {
6446 if (!(v is Expression)){
6447 bool val = (bool) v;
6448 data [idx] = (byte) (val ? 1 : 0);
6450 } else if (underlying_type == TypeManager.decimal_type){
6451 if (!(v is Expression)){
6452 int [] bits = Decimal.GetBits ((decimal) v);
6455 // FIXME: For some reason, this doesn't work on the MS runtime.
6456 int [] nbits = new int [4];
6457 nbits [0] = bits [3];
6458 nbits [1] = bits [2];
6459 nbits [2] = bits [0];
6460 nbits [3] = bits [1];
6462 for (int j = 0; j < 4; j++){
6463 data [p++] = (byte) (nbits [j] & 0xff);
6464 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6465 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6466 data [p++] = (byte) (nbits [j] >> 24);
6470 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6479 // Emits the initializers for the array
6481 void EmitStaticInitializers (EmitContext ec)
6484 // First, the static data
6487 ILGenerator ig = ec.ig;
6489 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6491 fb = RootContext.MakeStaticData (data);
6493 ig.Emit (OpCodes.Dup);
6494 ig.Emit (OpCodes.Ldtoken, fb);
6495 ig.Emit (OpCodes.Call,
6496 TypeManager.void_initializearray_array_fieldhandle);
6500 // Emits pieces of the array that can not be computed at compile
6501 // time (variables and string locations).
6503 // This always expect the top value on the stack to be the array
6505 void EmitDynamicInitializers (EmitContext ec)
6507 ILGenerator ig = ec.ig;
6508 int dims = bounds.Count;
6509 int [] current_pos = new int [dims];
6510 int top = array_data.Count;
6512 MethodInfo set = null;
6516 ModuleBuilder mb = null;
6517 mb = CodeGen.Module.Builder;
6518 args = new Type [dims + 1];
6521 for (j = 0; j < dims; j++)
6522 args [j] = TypeManager.int32_type;
6524 args [j] = array_element_type;
6526 set = mb.GetArrayMethod (
6528 CallingConventions.HasThis | CallingConventions.Standard,
6529 TypeManager.void_type, args);
6532 for (int i = 0; i < top; i++){
6534 Expression e = null;
6536 if (array_data [i] is Expression)
6537 e = (Expression) array_data [i];
6541 // Basically we do this for string literals and
6542 // other non-literal expressions
6544 if (e is EnumConstant){
6545 e = ((EnumConstant) e).Child;
6548 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6549 num_automatic_initializers <= max_automatic_initializers) {
6550 Type etype = e.Type;
6552 ig.Emit (OpCodes.Dup);
6554 for (int idx = 0; idx < dims; idx++)
6555 IntConstant.EmitInt (ig, current_pos [idx]);
6558 // If we are dealing with a struct, get the
6559 // address of it, so we can store it.
6562 etype.IsSubclassOf (TypeManager.value_type) &&
6563 (!TypeManager.IsBuiltinOrEnum (etype) ||
6564 etype == TypeManager.decimal_type)) {
6569 // Let new know that we are providing
6570 // the address where to store the results
6572 n.DisableTemporaryValueType ();
6575 ig.Emit (OpCodes.Ldelema, etype);
6582 OpCode op = ArrayAccess.GetStoreOpcode (etype, out is_stobj);
6584 ig.Emit (OpCodes.Stobj, etype);
6588 ig.Emit (OpCodes.Call, set);
6596 for (int j = dims - 1; j >= 0; j--){
6598 if (current_pos [j] < (int) bounds [j])
6600 current_pos [j] = 0;
6605 void EmitArrayArguments (EmitContext ec)
6607 ILGenerator ig = ec.ig;
6609 foreach (Argument a in arguments) {
6610 Type atype = a.Type;
6613 if (atype == TypeManager.uint64_type)
6614 ig.Emit (OpCodes.Conv_Ovf_U4);
6615 else if (atype == TypeManager.int64_type)
6616 ig.Emit (OpCodes.Conv_Ovf_I4);
6620 public override void Emit (EmitContext ec)
6622 ILGenerator ig = ec.ig;
6624 EmitArrayArguments (ec);
6625 if (is_one_dimensional)
6626 ig.Emit (OpCodes.Newarr, array_element_type);
6628 if (is_builtin_type)
6629 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6631 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6634 if (initializers != null){
6636 // FIXME: Set this variable correctly.
6638 bool dynamic_initializers = true;
6640 // This will never be true for array types that cannot be statically
6641 // initialized. num_automatic_initializers will always be zero. See
6643 if (num_automatic_initializers > max_automatic_initializers)
6644 EmitStaticInitializers (ec);
6646 if (dynamic_initializers)
6647 EmitDynamicInitializers (ec);
6651 public object EncodeAsAttribute ()
6653 if (!is_one_dimensional){
6654 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6658 if (array_data == null){
6659 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6663 object [] ret = new object [array_data.Count];
6665 foreach (Expression e in array_data){
6668 if (e is NullLiteral)
6671 if (!Attribute.GetAttributeArgumentExpression (e, Location, array_element_type, out v))
6681 /// Represents the `this' construct
6683 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6686 VariableInfo variable_info;
6688 public This (Block block, Location loc)
6694 public This (Location loc)
6699 public VariableInfo VariableInfo {
6700 get { return variable_info; }
6703 public bool VerifyFixed (bool is_expression)
6705 if ((variable_info == null) || (variable_info.LocalInfo == null))
6708 return variable_info.LocalInfo.IsFixed;
6711 public bool ResolveBase (EmitContext ec)
6713 eclass = ExprClass.Variable;
6714 type = ec.ContainerType;
6717 Error (26, "Keyword this not valid in static code");
6721 if ((block != null) && (block.ThisVariable != null))
6722 variable_info = block.ThisVariable.VariableInfo;
6727 public override Expression DoResolve (EmitContext ec)
6729 if (!ResolveBase (ec))
6732 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
6733 Error (188, "The this object cannot be used before all " +
6734 "of its fields are assigned to");
6735 variable_info.SetAssigned (ec);
6739 if (ec.IsFieldInitializer) {
6740 Error (27, "Keyword `this' can't be used outside a constructor, " +
6741 "a method or a property.");
6748 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6750 if (!ResolveBase (ec))
6753 if (variable_info != null)
6754 variable_info.SetAssigned (ec);
6756 if (ec.TypeContainer is Class){
6757 Error (1604, "Cannot assign to `this'");
6764 public void Emit (EmitContext ec, bool leave_copy)
6768 ec.ig.Emit (OpCodes.Dup);
6771 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
6773 ILGenerator ig = ec.ig;
6775 if (ec.TypeContainer is Struct){
6779 ec.ig.Emit (OpCodes.Dup);
6780 ig.Emit (OpCodes.Stobj, type);
6782 throw new Exception ("how did you get here");
6786 public override void Emit (EmitContext ec)
6788 ILGenerator ig = ec.ig;
6791 if (ec.TypeContainer is Struct)
6792 ig.Emit (OpCodes.Ldobj, type);
6795 public void AddressOf (EmitContext ec, AddressOp mode)
6800 // FIGURE OUT WHY LDARG_S does not work
6802 // consider: struct X { int val; int P { set { val = value; }}}
6804 // Yes, this looks very bad. Look at `NOTAS' for
6806 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
6811 /// Represents the `__arglist' construct
6813 public class ArglistAccess : Expression
6815 public ArglistAccess (Location loc)
6820 public bool ResolveBase (EmitContext ec)
6822 eclass = ExprClass.Variable;
6823 type = TypeManager.runtime_argument_handle_type;
6827 public override Expression DoResolve (EmitContext ec)
6829 if (!ResolveBase (ec))
6832 if (ec.IsFieldInitializer || !ec.CurrentBlock.HasVarargs) {
6833 Error (190, "The __arglist construct is valid only within " +
6834 "a variable argument method.");
6841 public override void Emit (EmitContext ec)
6843 ec.ig.Emit (OpCodes.Arglist);
6848 /// Represents the `__arglist (....)' construct
6850 public class Arglist : Expression
6852 public readonly Argument[] Arguments;
6854 public Arglist (Argument[] args, Location l)
6860 public Type[] ArgumentTypes {
6862 Type[] retval = new Type [Arguments.Length];
6863 for (int i = 0; i < Arguments.Length; i++)
6864 retval [i] = Arguments [i].Type;
6869 public override Expression DoResolve (EmitContext ec)
6871 eclass = ExprClass.Variable;
6872 type = TypeManager.runtime_argument_handle_type;
6874 foreach (Argument arg in Arguments) {
6875 if (!arg.Resolve (ec, loc))
6882 public override void Emit (EmitContext ec)
6884 foreach (Argument arg in Arguments)
6890 // This produces the value that renders an instance, used by the iterators code
6892 public class ProxyInstance : Expression, IMemoryLocation {
6893 public override Expression DoResolve (EmitContext ec)
6895 eclass = ExprClass.Variable;
6896 type = ec.ContainerType;
6900 public override void Emit (EmitContext ec)
6902 ec.ig.Emit (OpCodes.Ldarg_0);
6906 public void AddressOf (EmitContext ec, AddressOp mode)
6908 ec.ig.Emit (OpCodes.Ldarg_0);
6913 /// Implements the typeof operator
6915 public class TypeOf : Expression {
6916 public Expression QueriedType;
6917 protected Type typearg;
6919 public TypeOf (Expression queried_type, Location l)
6921 QueriedType = queried_type;
6925 public override Expression DoResolve (EmitContext ec)
6927 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
6931 typearg = texpr.ResolveType (ec);
6933 if (typearg == TypeManager.void_type) {
6934 Error (673, "System.Void cannot be used from C# - " +
6935 "use typeof (void) to get the void type object");
6939 if (typearg.IsPointer && !ec.InUnsafe){
6943 CheckObsoleteAttribute (typearg);
6945 type = TypeManager.type_type;
6946 eclass = ExprClass.Type;
6950 public override void Emit (EmitContext ec)
6952 ec.ig.Emit (OpCodes.Ldtoken, typearg);
6953 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6956 public Type TypeArg {
6957 get { return typearg; }
6962 /// Implements the `typeof (void)' operator
6964 public class TypeOfVoid : TypeOf {
6965 public TypeOfVoid (Location l) : base (null, l)
6970 public override Expression DoResolve (EmitContext ec)
6972 type = TypeManager.type_type;
6973 typearg = TypeManager.void_type;
6974 eclass = ExprClass.Type;
6980 /// Implements the sizeof expression
6982 public class SizeOf : Expression {
6983 public Expression QueriedType;
6986 public SizeOf (Expression queried_type, Location l)
6988 this.QueriedType = queried_type;
6992 public override Expression DoResolve (EmitContext ec)
6996 233, loc, "Sizeof may only be used in an unsafe context " +
6997 "(consider using System.Runtime.InteropServices.Marshal.SizeOf");
7001 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
7005 type_queried = texpr.ResolveType (ec);
7007 CheckObsoleteAttribute (type_queried);
7009 if (!TypeManager.IsUnmanagedType (type_queried)){
7010 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
7014 type = TypeManager.int32_type;
7015 eclass = ExprClass.Value;
7019 public override void Emit (EmitContext ec)
7021 int size = GetTypeSize (type_queried);
7024 ec.ig.Emit (OpCodes.Sizeof, type_queried);
7026 IntConstant.EmitInt (ec.ig, size);
7031 /// Implements the member access expression
7033 public class MemberAccess : Expression {
7034 public readonly string Identifier;
7037 public MemberAccess (Expression expr, string id, Location l)
7044 public Expression Expr {
7050 public static void error176 (Location loc, string name)
7052 Report.Error (176, loc, "Static member `" +
7053 name + "' cannot be accessed " +
7054 "with an instance reference, qualify with a " +
7055 "type name instead");
7058 public static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Expression left, Location loc)
7060 SimpleName sn = left_original as SimpleName;
7061 if (sn == null || left == null || left.Type.Name != sn.Name)
7064 return RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc) != null;
7067 // TODO: possible optimalization
7068 // Cache resolved constant result in FieldBuilder <-> expresion map
7069 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
7070 Expression left, Location loc,
7071 Expression left_original)
7073 bool left_is_type, left_is_explicit;
7075 // If `left' is null, then we're called from SimpleNameResolve and this is
7076 // a member in the currently defining class.
7078 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
7079 left_is_explicit = false;
7081 // Implicitly default to `this' unless we're static.
7082 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
7083 left = ec.GetThis (loc);
7085 left_is_type = left is TypeExpr;
7086 left_is_explicit = true;
7089 if (member_lookup is FieldExpr){
7090 FieldExpr fe = (FieldExpr) member_lookup;
7091 FieldInfo fi = fe.FieldInfo;
7092 Type decl_type = fi.DeclaringType;
7094 bool is_emitted = fi is FieldBuilder;
7095 Type t = fi.FieldType;
7098 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
7102 if (!c.LookupConstantValue (out o))
7105 object real_value = ((Constant) c.Expr).GetValue ();
7107 return Constantify (real_value, t);
7111 // IsInitOnly is because of MS compatibility, I don't know why but they emit decimal constant as InitOnly
7112 if (fi.IsInitOnly && !is_emitted && t == TypeManager.decimal_type) {
7113 object[] attrs = fi.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
7114 if (attrs.Length == 1)
7115 return new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
7122 o = TypeManager.GetValue ((FieldBuilder) fi);
7124 o = fi.GetValue (fi);
7126 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
7127 if (left_is_explicit && !left_is_type &&
7128 !IdenticalNameAndTypeName (ec, left_original, member_lookup, loc)) {
7129 error176 (loc, fe.FieldInfo.Name);
7133 Expression enum_member = MemberLookup (
7134 ec, decl_type, "value__", MemberTypes.Field,
7135 AllBindingFlags, loc);
7137 Enum en = TypeManager.LookupEnum (decl_type);
7141 c = Constantify (o, en.UnderlyingType);
7143 c = Constantify (o, enum_member.Type);
7145 return new EnumConstant (c, decl_type);
7148 Expression exp = Constantify (o, t);
7150 if (left_is_explicit && !left_is_type) {
7151 error176 (loc, fe.FieldInfo.Name);
7158 if (t.IsPointer && !ec.InUnsafe){
7164 if (member_lookup is EventExpr) {
7165 EventExpr ee = (EventExpr) member_lookup;
7168 // If the event is local to this class, we transform ourselves into
7172 if (ee.EventInfo.DeclaringType == ec.ContainerType ||
7173 TypeManager.IsNestedChildOf(ec.ContainerType, ee.EventInfo.DeclaringType)) {
7174 MemberInfo mi = GetFieldFromEvent (ee);
7178 // If this happens, then we have an event with its own
7179 // accessors and private field etc so there's no need
7180 // to transform ourselves.
7182 ee.InstanceExpression = left;
7186 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
7189 Report.Error (-200, loc, "Internal error!!");
7193 if (!left_is_explicit)
7196 ee.InstanceExpression = left;
7198 return ResolveMemberAccess (ec, ml, left, loc, left_original);
7202 if (member_lookup is IMemberExpr) {
7203 IMemberExpr me = (IMemberExpr) member_lookup;
7204 MethodGroupExpr mg = me as MethodGroupExpr;
7207 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
7208 mg.IsExplicitImpl = left_is_explicit;
7211 if ((ec.IsFieldInitializer || ec.IsStatic) &&
7212 IdenticalNameAndTypeName (ec, left_original, member_lookup, loc))
7213 return member_lookup;
7215 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
7220 if (!me.IsInstance) {
7221 if (IdenticalNameAndTypeName (ec, left_original, left, loc))
7222 return member_lookup;
7224 if (left_is_explicit) {
7225 error176 (loc, me.Name);
7231 // Since we can not check for instance objects in SimpleName,
7232 // becaue of the rule that allows types and variables to share
7233 // the name (as long as they can be de-ambiguated later, see
7234 // IdenticalNameAndTypeName), we have to check whether left
7235 // is an instance variable in a static context
7237 // However, if the left-hand value is explicitly given, then
7238 // it is already our instance expression, so we aren't in
7242 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
7243 IMemberExpr mexp = (IMemberExpr) left;
7245 if (!mexp.IsStatic){
7246 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
7251 if ((mg != null) && IdenticalNameAndTypeName (ec, left_original, left, loc))
7252 mg.IdenticalTypeName = true;
7254 me.InstanceExpression = left;
7257 return member_lookup;
7260 Console.WriteLine ("Left is: " + left);
7261 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
7262 Environment.Exit (1);
7266 public Expression DoResolve (EmitContext ec, Expression right_side, ResolveFlags flags)
7269 throw new Exception ();
7272 // Resolve the expression with flow analysis turned off, we'll do the definite
7273 // assignment checks later. This is because we don't know yet what the expression
7274 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7275 // definite assignment check on the actual field and not on the whole struct.
7278 Expression original = expr;
7279 expr = expr.Resolve (ec, flags | ResolveFlags.Intermediate | ResolveFlags.DisableFlowAnalysis);
7283 if (expr is SimpleName){
7284 SimpleName child_expr = (SimpleName) expr;
7286 Expression new_expr = new SimpleName (child_expr.Name, Identifier, loc);
7288 return new_expr.Resolve (ec, flags);
7292 // TODO: I mailed Ravi about this, and apparently we can get rid
7293 // of this and put it in the right place.
7295 // Handle enums here when they are in transit.
7296 // Note that we cannot afford to hit MemberLookup in this case because
7297 // it will fail to find any members at all
7300 Type expr_type = expr.Type;
7301 if (expr is TypeExpr){
7302 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
7303 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", expr_type);
7307 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
7308 Enum en = TypeManager.LookupEnum (expr_type);
7311 object value = en.LookupEnumValue (ec, Identifier, loc);
7314 MemberCore mc = en.GetDefinition (Identifier);
7315 ObsoleteAttribute oa = mc.GetObsoleteAttribute (en);
7317 AttributeTester.Report_ObsoleteMessage (oa, mc.GetSignatureForError (), Location);
7319 oa = en.GetObsoleteAttribute (en);
7321 AttributeTester.Report_ObsoleteMessage (oa, en.GetSignatureForError (), Location);
7324 Constant c = Constantify (value, en.UnderlyingType);
7325 return new EnumConstant (c, expr_type);
7328 CheckObsoleteAttribute (expr_type);
7330 FieldInfo fi = expr_type.GetField (Identifier);
7332 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
7334 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), Location);
7340 if (expr_type.IsPointer){
7341 Error (23, "The `.' operator can not be applied to pointer operands (" +
7342 TypeManager.CSharpName (expr_type) + ")");
7346 Expression member_lookup;
7347 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
7348 if (member_lookup == null)
7351 if (member_lookup is TypeExpr) {
7352 if (!(expr is TypeExpr) && !(expr is SimpleName)) {
7353 Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
7354 member_lookup.Type + "' instead");
7358 return member_lookup;
7361 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
7362 if (member_lookup == null)
7365 // The following DoResolve/DoResolveLValue will do the definite assignment
7368 if (right_side != null)
7369 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
7371 member_lookup = member_lookup.DoResolve (ec);
7373 return member_lookup;
7376 public override Expression DoResolve (EmitContext ec)
7378 return DoResolve (ec, null, ResolveFlags.VariableOrValue |
7379 ResolveFlags.SimpleName | ResolveFlags.Type);
7382 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7384 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
7385 ResolveFlags.SimpleName | ResolveFlags.Type);
7388 public override Expression ResolveAsTypeStep (EmitContext ec)
7390 string fname = null;
7391 MemberAccess full_expr = this;
7392 while (full_expr != null) {
7394 fname = String.Concat (full_expr.Identifier, ".", fname);
7396 fname = full_expr.Identifier;
7398 if (full_expr.Expr is SimpleName) {
7399 string full_name = String.Concat (((SimpleName) full_expr.Expr).Name, ".", fname);
7400 Type fully_qualified = ec.DeclSpace.FindType (loc, full_name);
7401 if (fully_qualified != null)
7402 return new TypeExpression (fully_qualified, loc);
7405 full_expr = full_expr.Expr as MemberAccess;
7408 Expression new_expr = expr.ResolveAsTypeStep (ec);
7410 if (new_expr == null)
7413 if (new_expr is SimpleName){
7414 SimpleName child_expr = (SimpleName) new_expr;
7416 new_expr = new SimpleName (child_expr.Name, Identifier, loc);
7418 return new_expr.ResolveAsTypeStep (ec);
7421 Type expr_type = new_expr.Type;
7423 if (expr_type.IsPointer){
7424 Error (23, "The `.' operator can not be applied to pointer operands (" +
7425 TypeManager.CSharpName (expr_type) + ")");
7429 Expression member_lookup;
7430 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
7431 if (member_lookup == null)
7434 if (member_lookup is TypeExpr){
7435 member_lookup.Resolve (ec, ResolveFlags.Type);
7436 return member_lookup;
7442 public override void Emit (EmitContext ec)
7444 throw new Exception ("Should not happen");
7447 public override string ToString ()
7449 return expr + "." + Identifier;
7454 /// Implements checked expressions
7456 public class CheckedExpr : Expression {
7458 public Expression Expr;
7460 public CheckedExpr (Expression e, Location l)
7466 public override Expression DoResolve (EmitContext ec)
7468 bool last_check = ec.CheckState;
7469 bool last_const_check = ec.ConstantCheckState;
7471 ec.CheckState = true;
7472 ec.ConstantCheckState = true;
7473 Expr = Expr.Resolve (ec);
7474 ec.CheckState = last_check;
7475 ec.ConstantCheckState = last_const_check;
7480 if (Expr is Constant)
7483 eclass = Expr.eclass;
7488 public override void Emit (EmitContext ec)
7490 bool last_check = ec.CheckState;
7491 bool last_const_check = ec.ConstantCheckState;
7493 ec.CheckState = true;
7494 ec.ConstantCheckState = true;
7496 ec.CheckState = last_check;
7497 ec.ConstantCheckState = last_const_check;
7503 /// Implements the unchecked expression
7505 public class UnCheckedExpr : Expression {
7507 public Expression Expr;
7509 public UnCheckedExpr (Expression e, Location l)
7515 public override Expression DoResolve (EmitContext ec)
7517 bool last_check = ec.CheckState;
7518 bool last_const_check = ec.ConstantCheckState;
7520 ec.CheckState = false;
7521 ec.ConstantCheckState = false;
7522 Expr = Expr.Resolve (ec);
7523 ec.CheckState = last_check;
7524 ec.ConstantCheckState = last_const_check;
7529 if (Expr is Constant)
7532 eclass = Expr.eclass;
7537 public override void Emit (EmitContext ec)
7539 bool last_check = ec.CheckState;
7540 bool last_const_check = ec.ConstantCheckState;
7542 ec.CheckState = false;
7543 ec.ConstantCheckState = false;
7545 ec.CheckState = last_check;
7546 ec.ConstantCheckState = last_const_check;
7552 /// An Element Access expression.
7554 /// During semantic analysis these are transformed into
7555 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7557 public class ElementAccess : Expression {
7558 public ArrayList Arguments;
7559 public Expression Expr;
7561 public ElementAccess (Expression e, ArrayList e_list, Location l)
7570 Arguments = new ArrayList ();
7571 foreach (Expression tmp in e_list)
7572 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7576 bool CommonResolve (EmitContext ec)
7578 Expr = Expr.Resolve (ec);
7583 if (Arguments == null)
7586 foreach (Argument a in Arguments){
7587 if (!a.Resolve (ec, loc))
7594 Expression MakePointerAccess (EmitContext ec)
7598 if (t == TypeManager.void_ptr_type){
7599 Error (242, "The array index operation is not valid for void pointers");
7602 if (Arguments.Count != 1){
7603 Error (196, "A pointer must be indexed by a single value");
7608 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc).Resolve (ec);
7611 return new Indirection (p, loc).Resolve (ec);
7614 public override Expression DoResolve (EmitContext ec)
7616 if (!CommonResolve (ec))
7620 // We perform some simple tests, and then to "split" the emit and store
7621 // code we create an instance of a different class, and return that.
7623 // I am experimenting with this pattern.
7627 if (t == TypeManager.array_type){
7628 Report.Error (21, loc, "Cannot use indexer on System.Array");
7633 return (new ArrayAccess (this, loc)).Resolve (ec);
7634 else if (t.IsPointer)
7635 return MakePointerAccess (ec);
7637 return (new IndexerAccess (this, loc)).Resolve (ec);
7640 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7642 if (!CommonResolve (ec))
7647 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
7648 else if (t.IsPointer)
7649 return MakePointerAccess (ec);
7651 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
7654 public override void Emit (EmitContext ec)
7656 throw new Exception ("Should never be reached");
7661 /// Implements array access
7663 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7665 // Points to our "data" repository
7669 LocalTemporary temp;
7672 public ArrayAccess (ElementAccess ea_data, Location l)
7675 eclass = ExprClass.Variable;
7679 public override Expression DoResolve (EmitContext ec)
7682 ExprClass eclass = ea.Expr.eclass;
7684 // As long as the type is valid
7685 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7686 eclass == ExprClass.Value)) {
7687 ea.Expr.Error_UnexpectedKind ("variable or value");
7692 Type t = ea.Expr.Type;
7693 if (t.GetArrayRank () != ea.Arguments.Count){
7695 "Incorrect number of indexes for array " +
7696 " expected: " + t.GetArrayRank () + " got: " +
7697 ea.Arguments.Count);
7701 type = TypeManager.GetElementType (t);
7702 if (type.IsPointer && !ec.InUnsafe){
7703 UnsafeError (ea.Location);
7707 foreach (Argument a in ea.Arguments){
7708 Type argtype = a.Type;
7710 if (argtype == TypeManager.int32_type ||
7711 argtype == TypeManager.uint32_type ||
7712 argtype == TypeManager.int64_type ||
7713 argtype == TypeManager.uint64_type) {
7714 Constant c = a.Expr as Constant;
7715 if (c != null && c.IsNegative) {
7716 Report.Warning (251, 2, a.Expr.Location, "Indexing an array with a negative index (array indices always start at zero)");
7722 // Mhm. This is strage, because the Argument.Type is not the same as
7723 // Argument.Expr.Type: the value changes depending on the ref/out setting.
7725 // Wonder if I will run into trouble for this.
7727 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
7732 eclass = ExprClass.Variable;
7738 /// Emits the right opcode to load an object of Type `t'
7739 /// from an array of T
7741 static public void EmitLoadOpcode (ILGenerator ig, Type type)
7743 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7744 ig.Emit (OpCodes.Ldelem_U1);
7745 else if (type == TypeManager.sbyte_type)
7746 ig.Emit (OpCodes.Ldelem_I1);
7747 else if (type == TypeManager.short_type)
7748 ig.Emit (OpCodes.Ldelem_I2);
7749 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7750 ig.Emit (OpCodes.Ldelem_U2);
7751 else if (type == TypeManager.int32_type)
7752 ig.Emit (OpCodes.Ldelem_I4);
7753 else if (type == TypeManager.uint32_type)
7754 ig.Emit (OpCodes.Ldelem_U4);
7755 else if (type == TypeManager.uint64_type)
7756 ig.Emit (OpCodes.Ldelem_I8);
7757 else if (type == TypeManager.int64_type)
7758 ig.Emit (OpCodes.Ldelem_I8);
7759 else if (type == TypeManager.float_type)
7760 ig.Emit (OpCodes.Ldelem_R4);
7761 else if (type == TypeManager.double_type)
7762 ig.Emit (OpCodes.Ldelem_R8);
7763 else if (type == TypeManager.intptr_type)
7764 ig.Emit (OpCodes.Ldelem_I);
7765 else if (TypeManager.IsEnumType (type)){
7766 EmitLoadOpcode (ig, TypeManager.EnumToUnderlying (type));
7767 } else if (type.IsValueType){
7768 ig.Emit (OpCodes.Ldelema, type);
7769 ig.Emit (OpCodes.Ldobj, type);
7771 ig.Emit (OpCodes.Ldelem_Ref);
7775 /// Returns the right opcode to store an object of Type `t'
7776 /// from an array of T.
7778 static public OpCode GetStoreOpcode (Type t, out bool is_stobj)
7780 //Console.WriteLine (new System.Diagnostics.StackTrace ());
7782 t = TypeManager.TypeToCoreType (t);
7783 if (TypeManager.IsEnumType (t))
7784 t = TypeManager.EnumToUnderlying (t);
7785 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
7786 t == TypeManager.bool_type)
7787 return OpCodes.Stelem_I1;
7788 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
7789 t == TypeManager.char_type)
7790 return OpCodes.Stelem_I2;
7791 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
7792 return OpCodes.Stelem_I4;
7793 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
7794 return OpCodes.Stelem_I8;
7795 else if (t == TypeManager.float_type)
7796 return OpCodes.Stelem_R4;
7797 else if (t == TypeManager.double_type)
7798 return OpCodes.Stelem_R8;
7799 else if (t == TypeManager.intptr_type) {
7801 return OpCodes.Stobj;
7802 } else if (t.IsValueType) {
7804 return OpCodes.Stobj;
7806 return OpCodes.Stelem_Ref;
7809 MethodInfo FetchGetMethod ()
7811 ModuleBuilder mb = CodeGen.Module.Builder;
7812 int arg_count = ea.Arguments.Count;
7813 Type [] args = new Type [arg_count];
7816 for (int i = 0; i < arg_count; i++){
7817 //args [i++] = a.Type;
7818 args [i] = TypeManager.int32_type;
7821 get = mb.GetArrayMethod (
7822 ea.Expr.Type, "Get",
7823 CallingConventions.HasThis |
7824 CallingConventions.Standard,
7830 MethodInfo FetchAddressMethod ()
7832 ModuleBuilder mb = CodeGen.Module.Builder;
7833 int arg_count = ea.Arguments.Count;
7834 Type [] args = new Type [arg_count];
7838 ret_type = TypeManager.GetReferenceType (type);
7840 for (int i = 0; i < arg_count; i++){
7841 //args [i++] = a.Type;
7842 args [i] = TypeManager.int32_type;
7845 address = mb.GetArrayMethod (
7846 ea.Expr.Type, "Address",
7847 CallingConventions.HasThis |
7848 CallingConventions.Standard,
7855 // Load the array arguments into the stack.
7857 // If we have been requested to cache the values (cached_locations array
7858 // initialized), then load the arguments the first time and store them
7859 // in locals. otherwise load from local variables.
7861 void LoadArrayAndArguments (EmitContext ec)
7863 ILGenerator ig = ec.ig;
7866 foreach (Argument a in ea.Arguments){
7867 Type argtype = a.Expr.Type;
7871 if (argtype == TypeManager.int64_type)
7872 ig.Emit (OpCodes.Conv_Ovf_I);
7873 else if (argtype == TypeManager.uint64_type)
7874 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7878 public void Emit (EmitContext ec, bool leave_copy)
7880 int rank = ea.Expr.Type.GetArrayRank ();
7881 ILGenerator ig = ec.ig;
7884 LoadArrayAndArguments (ec);
7887 EmitLoadOpcode (ig, type);
7891 method = FetchGetMethod ();
7892 ig.Emit (OpCodes.Call, method);
7895 LoadFromPtr (ec.ig, this.type);
7898 ec.ig.Emit (OpCodes.Dup);
7899 temp = new LocalTemporary (ec, this.type);
7904 public override void Emit (EmitContext ec)
7909 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
7911 int rank = ea.Expr.Type.GetArrayRank ();
7912 ILGenerator ig = ec.ig;
7913 Type t = source.Type;
7914 prepared = prepare_for_load;
7916 if (prepare_for_load) {
7917 AddressOf (ec, AddressOp.LoadStore);
7918 ec.ig.Emit (OpCodes.Dup);
7921 ec.ig.Emit (OpCodes.Dup);
7922 temp = new LocalTemporary (ec, this.type);
7925 StoreFromPtr (ec.ig, t);
7933 LoadArrayAndArguments (ec);
7937 OpCode op = GetStoreOpcode (t, out is_stobj);
7939 // The stobj opcode used by value types will need
7940 // an address on the stack, not really an array/array
7944 ig.Emit (OpCodes.Ldelema, t);
7948 ec.ig.Emit (OpCodes.Dup);
7949 temp = new LocalTemporary (ec, this.type);
7954 ig.Emit (OpCodes.Stobj, t);
7958 ModuleBuilder mb = CodeGen.Module.Builder;
7959 int arg_count = ea.Arguments.Count;
7960 Type [] args = new Type [arg_count + 1];
7965 ec.ig.Emit (OpCodes.Dup);
7966 temp = new LocalTemporary (ec, this.type);
7970 for (int i = 0; i < arg_count; i++){
7971 //args [i++] = a.Type;
7972 args [i] = TypeManager.int32_type;
7975 args [arg_count] = type;
7977 set = mb.GetArrayMethod (
7978 ea.Expr.Type, "Set",
7979 CallingConventions.HasThis |
7980 CallingConventions.Standard,
7981 TypeManager.void_type, args);
7983 ig.Emit (OpCodes.Call, set);
7990 public void AddressOf (EmitContext ec, AddressOp mode)
7992 int rank = ea.Expr.Type.GetArrayRank ();
7993 ILGenerator ig = ec.ig;
7995 LoadArrayAndArguments (ec);
7998 ig.Emit (OpCodes.Ldelema, type);
8000 MethodInfo address = FetchAddressMethod ();
8001 ig.Emit (OpCodes.Call, address);
8008 public ArrayList Properties;
8009 static Hashtable map;
8011 public struct Indexer {
8012 public readonly Type Type;
8013 public readonly MethodInfo Getter, Setter;
8015 public Indexer (Type type, MethodInfo get, MethodInfo set)
8025 map = new Hashtable ();
8030 Properties = new ArrayList ();
8033 void Append (MemberInfo [] mi)
8035 foreach (PropertyInfo property in mi){
8036 MethodInfo get, set;
8038 get = property.GetGetMethod (true);
8039 set = property.GetSetMethod (true);
8040 Properties.Add (new Indexer (property.PropertyType, get, set));
8044 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
8046 string p_name = TypeManager.IndexerPropertyName (lookup_type);
8048 MemberInfo [] mi = TypeManager.MemberLookup (
8049 caller_type, caller_type, lookup_type, MemberTypes.Property,
8050 BindingFlags.Public | BindingFlags.Instance |
8051 BindingFlags.DeclaredOnly, p_name, null);
8053 if (mi == null || mi.Length == 0)
8059 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
8061 Indexers ix = (Indexers) map [lookup_type];
8066 Type copy = lookup_type;
8067 while (copy != TypeManager.object_type && copy != null){
8068 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
8072 ix = new Indexers ();
8077 copy = copy.BaseType;
8080 if (!lookup_type.IsInterface)
8083 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
8084 if (ifaces != null) {
8085 foreach (Type itype in ifaces) {
8086 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
8089 ix = new Indexers ();
8101 /// Expressions that represent an indexer call.
8103 public class IndexerAccess : Expression, IAssignMethod {
8105 // Points to our "data" repository
8107 MethodInfo get, set;
8108 ArrayList set_arguments;
8109 bool is_base_indexer;
8111 protected Type indexer_type;
8112 protected Type current_type;
8113 protected Expression instance_expr;
8114 protected ArrayList arguments;
8116 public IndexerAccess (ElementAccess ea, Location loc)
8117 : this (ea.Expr, false, loc)
8119 this.arguments = ea.Arguments;
8122 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
8125 this.instance_expr = instance_expr;
8126 this.is_base_indexer = is_base_indexer;
8127 this.eclass = ExprClass.Value;
8131 protected virtual bool CommonResolve (EmitContext ec)
8133 indexer_type = instance_expr.Type;
8134 current_type = ec.ContainerType;
8139 public override Expression DoResolve (EmitContext ec)
8141 ArrayList AllGetters = new ArrayList();
8142 if (!CommonResolve (ec))
8146 // Step 1: Query for all `Item' *properties*. Notice
8147 // that the actual methods are pointed from here.
8149 // This is a group of properties, piles of them.
8151 bool found_any = false, found_any_getters = false;
8152 Type lookup_type = indexer_type;
8155 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
8156 if (ilist != null) {
8158 if (ilist.Properties != null) {
8159 foreach (Indexers.Indexer ix in ilist.Properties) {
8160 if (ix.Getter != null)
8161 AllGetters.Add(ix.Getter);
8166 if (AllGetters.Count > 0) {
8167 found_any_getters = true;
8168 get = (MethodInfo) Invocation.OverloadResolve (
8169 ec, new MethodGroupExpr (AllGetters, loc),
8170 arguments, false, loc);
8174 Report.Error (21, loc,
8175 "Type `" + TypeManager.CSharpName (indexer_type) +
8176 "' does not have any indexers defined");
8180 if (!found_any_getters) {
8181 Error (154, "indexer can not be used in this context, because " +
8182 "it lacks a `get' accessor");
8187 Error (1501, "No Overload for method `this' takes `" +
8188 arguments.Count + "' arguments");
8193 // Only base will allow this invocation to happen.
8195 if (get.IsAbstract && this is BaseIndexerAccess){
8196 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
8200 type = get.ReturnType;
8201 if (type.IsPointer && !ec.InUnsafe){
8206 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8208 eclass = ExprClass.IndexerAccess;
8212 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8214 ArrayList AllSetters = new ArrayList();
8215 if (!CommonResolve (ec))
8218 bool found_any = false, found_any_setters = false;
8220 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
8221 if (ilist != null) {
8223 if (ilist.Properties != null) {
8224 foreach (Indexers.Indexer ix in ilist.Properties) {
8225 if (ix.Setter != null)
8226 AllSetters.Add(ix.Setter);
8230 if (AllSetters.Count > 0) {
8231 found_any_setters = true;
8232 set_arguments = (ArrayList) arguments.Clone ();
8233 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
8234 set = (MethodInfo) Invocation.OverloadResolve (
8235 ec, new MethodGroupExpr (AllSetters, loc),
8236 set_arguments, false, loc);
8240 Report.Error (21, loc,
8241 "Type `" + TypeManager.CSharpName (indexer_type) +
8242 "' does not have any indexers defined");
8246 if (!found_any_setters) {
8247 Error (154, "indexer can not be used in this context, because " +
8248 "it lacks a `set' accessor");
8253 Error (1501, "No Overload for method `this' takes `" +
8254 arguments.Count + "' arguments");
8259 // Only base will allow this invocation to happen.
8261 if (set.IsAbstract && this is BaseIndexerAccess){
8262 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
8267 // Now look for the actual match in the list of indexers to set our "return" type
8269 type = TypeManager.void_type; // default value
8270 foreach (Indexers.Indexer ix in ilist.Properties){
8271 if (ix.Setter == set){
8277 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8279 eclass = ExprClass.IndexerAccess;
8283 bool prepared = false;
8284 LocalTemporary temp;
8286 public void Emit (EmitContext ec, bool leave_copy)
8288 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc, prepared, false);
8290 ec.ig.Emit (OpCodes.Dup);
8291 temp = new LocalTemporary (ec, Type);
8297 // source is ignored, because we already have a copy of it from the
8298 // LValue resolution and we have already constructed a pre-cached
8299 // version of the arguments (ea.set_arguments);
8301 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8303 prepared = prepare_for_load;
8304 Argument a = (Argument) set_arguments [set_arguments.Count - 1];
8309 ec.ig.Emit (OpCodes.Dup);
8310 temp = new LocalTemporary (ec, Type);
8313 } else if (leave_copy) {
8314 temp = new LocalTemporary (ec, Type);
8320 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc, false, prepared);
8327 public override void Emit (EmitContext ec)
8334 /// The base operator for method names
8336 public class BaseAccess : Expression {
8339 public BaseAccess (string member, Location l)
8341 this.member = member;
8345 public override Expression DoResolve (EmitContext ec)
8347 Expression c = CommonResolve (ec);
8353 // MethodGroups use this opportunity to flag an error on lacking ()
8355 if (!(c is MethodGroupExpr))
8356 return c.Resolve (ec);
8360 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8362 Expression c = CommonResolve (ec);
8368 // MethodGroups use this opportunity to flag an error on lacking ()
8370 if (! (c is MethodGroupExpr))
8371 return c.DoResolveLValue (ec, right_side);
8376 Expression CommonResolve (EmitContext ec)
8378 Expression member_lookup;
8379 Type current_type = ec.ContainerType;
8380 Type base_type = current_type.BaseType;
8384 Error (1511, "Keyword base is not allowed in static method");
8388 if (ec.IsFieldInitializer){
8389 Error (1512, "Keyword base is not available in the current context");
8393 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type, member,
8394 AllMemberTypes, AllBindingFlags, loc);
8395 if (member_lookup == null) {
8396 MemberLookupFailed (ec, base_type, base_type, member, null, loc);
8403 left = new TypeExpression (base_type, loc);
8405 left = ec.GetThis (loc);
8407 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
8409 if (e is PropertyExpr){
8410 PropertyExpr pe = (PropertyExpr) e;
8415 if (e is MethodGroupExpr)
8416 ((MethodGroupExpr) e).IsBase = true;
8421 public override void Emit (EmitContext ec)
8423 throw new Exception ("Should never be called");
8428 /// The base indexer operator
8430 public class BaseIndexerAccess : IndexerAccess {
8431 public BaseIndexerAccess (ArrayList args, Location loc)
8432 : base (null, true, loc)
8434 arguments = new ArrayList ();
8435 foreach (Expression tmp in args)
8436 arguments.Add (new Argument (tmp, Argument.AType.Expression));
8439 protected override bool CommonResolve (EmitContext ec)
8441 instance_expr = ec.GetThis (loc);
8443 current_type = ec.ContainerType.BaseType;
8444 indexer_type = current_type;
8446 foreach (Argument a in arguments){
8447 if (!a.Resolve (ec, loc))
8456 /// This class exists solely to pass the Type around and to be a dummy
8457 /// that can be passed to the conversion functions (this is used by
8458 /// foreach implementation to typecast the object return value from
8459 /// get_Current into the proper type. All code has been generated and
8460 /// we only care about the side effect conversions to be performed
8462 /// This is also now used as a placeholder where a no-action expression
8463 /// is needed (the `New' class).
8465 public class EmptyExpression : Expression {
8466 public static readonly EmptyExpression Null = new EmptyExpression ();
8468 // TODO: should be protected
8469 public EmptyExpression ()
8471 type = TypeManager.object_type;
8472 eclass = ExprClass.Value;
8473 loc = Location.Null;
8476 public EmptyExpression (Type t)
8479 eclass = ExprClass.Value;
8480 loc = Location.Null;
8483 public override Expression DoResolve (EmitContext ec)
8488 public override void Emit (EmitContext ec)
8490 // nothing, as we only exist to not do anything.
8494 // This is just because we might want to reuse this bad boy
8495 // instead of creating gazillions of EmptyExpressions.
8496 // (CanImplicitConversion uses it)
8498 public void SetType (Type t)
8504 public class UserCast : Expression {
8508 public UserCast (MethodInfo method, Expression source, Location l)
8510 this.method = method;
8511 this.source = source;
8512 type = method.ReturnType;
8513 eclass = ExprClass.Value;
8517 public Expression Source {
8523 public override Expression DoResolve (EmitContext ec)
8526 // We are born fully resolved
8531 public override void Emit (EmitContext ec)
8533 ILGenerator ig = ec.ig;
8537 if (method is MethodInfo)
8538 ig.Emit (OpCodes.Call, (MethodInfo) method);
8540 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
8546 // This class is used to "construct" the type during a typecast
8547 // operation. Since the Type.GetType class in .NET can parse
8548 // the type specification, we just use this to construct the type
8549 // one bit at a time.
8551 public class ComposedCast : TypeExpr {
8555 public ComposedCast (Expression left, string dim, Location l)
8562 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
8564 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec, false);
8568 Type ltype = lexpr.ResolveType (ec);
8570 if ((ltype == TypeManager.void_type) && (dim != "*")) {
8571 Report.Error (1547, Location,
8572 "Keyword 'void' cannot be used in this context");
8577 // ltype.Fullname is already fully qualified, so we can skip
8578 // a lot of probes, and go directly to TypeManager.LookupType
8580 string cname = ltype.FullName + dim;
8581 type = TypeManager.LookupTypeDirect (cname);
8584 // For arrays of enumerations we are having a problem
8585 // with the direct lookup. Need to investigate.
8587 // For now, fall back to the full lookup in that case.
8589 type = RootContext.LookupType (ec.DeclSpace, cname, false, loc);
8594 if (!ec.InUnsafe && type.IsPointer){
8599 if (type.IsArray && (type.GetElementType () == TypeManager.arg_iterator_type ||
8600 type.GetElementType () == TypeManager.typed_reference_type)) {
8601 Report.Error (611, loc, "Array elements cannot be of type '{0}'", TypeManager.CSharpName (type.GetElementType ()));
8605 eclass = ExprClass.Type;
8609 public override string Name {
8617 // This class is used to represent the address of an array, used
8618 // only by the Fixed statement, this is like the C "&a [0]" construct.
8620 public class ArrayPtr : Expression {
8623 public ArrayPtr (Expression array, Location l)
8625 Type array_type = TypeManager.GetElementType (array.Type);
8629 type = TypeManager.GetPointerType (array_type);
8630 eclass = ExprClass.Value;
8634 public override void Emit (EmitContext ec)
8636 ILGenerator ig = ec.ig;
8639 IntLiteral.EmitInt (ig, 0);
8640 ig.Emit (OpCodes.Ldelema, TypeManager.GetElementType (array.Type));
8643 public override Expression DoResolve (EmitContext ec)
8646 // We are born fully resolved
8653 // Used by the fixed statement
8655 public class StringPtr : Expression {
8658 public StringPtr (LocalBuilder b, Location l)
8661 eclass = ExprClass.Value;
8662 type = TypeManager.char_ptr_type;
8666 public override Expression DoResolve (EmitContext ec)
8668 // This should never be invoked, we are born in fully
8669 // initialized state.
8674 public override void Emit (EmitContext ec)
8676 ILGenerator ig = ec.ig;
8678 ig.Emit (OpCodes.Ldloc, b);
8679 ig.Emit (OpCodes.Conv_I);
8680 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
8681 ig.Emit (OpCodes.Add);
8686 // Implements the `stackalloc' keyword
8688 public class StackAlloc : Expression {
8693 public StackAlloc (Expression type, Expression count, Location l)
8700 public override Expression DoResolve (EmitContext ec)
8702 count = count.Resolve (ec);
8706 if (count.Type != TypeManager.int32_type){
8707 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8712 Constant c = count as Constant;
8713 if (c != null && c.IsNegative) {
8714 Report.Error (247, loc, "Cannot use a negative size with stackalloc");
8718 if (ec.CurrentBranching.InCatch () ||
8719 ec.CurrentBranching.InFinally (true)) {
8721 "stackalloc can not be used in a catch or finally block");
8725 TypeExpr texpr = t.ResolveAsTypeTerminal (ec, false);
8729 otype = texpr.ResolveType (ec);
8731 if (!TypeManager.VerifyUnManaged (otype, loc))
8734 type = TypeManager.GetPointerType (otype);
8735 eclass = ExprClass.Value;
8740 public override void Emit (EmitContext ec)
8742 int size = GetTypeSize (otype);
8743 ILGenerator ig = ec.ig;
8746 ig.Emit (OpCodes.Sizeof, otype);
8748 IntConstant.EmitInt (ig, size);
8750 ig.Emit (OpCodes.Mul);
8751 ig.Emit (OpCodes.Localloc);