2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
8 // (C) 2003, 2004 Novell, Inc.
12 namespace Mono.CSharp {
14 using System.Collections;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// This is just a helper class, it is generated by Unary, UnaryMutator
21 /// when an overloaded method has been found. It just emits the code for a
24 public class StaticCallExpr : ExpressionStatement {
28 public StaticCallExpr (MethodInfo m, ArrayList a, Location l)
34 eclass = ExprClass.Value;
38 public override Expression DoResolve (EmitContext ec)
41 // We are born fully resolved
46 public override void Emit (EmitContext ec)
49 Invocation.EmitArguments (ec, mi, args, false, null);
51 ec.ig.Emit (OpCodes.Call, mi);
55 static public StaticCallExpr MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
56 Expression e, Location loc)
61 args = new ArrayList (1);
62 Argument a = new Argument (e, Argument.AType.Expression);
64 // We need to resolve the arguments before sending them in !
65 if (!a.Resolve (ec, loc))
69 method = Invocation.OverloadResolve (
70 ec, (MethodGroupExpr) mg, args, false, loc);
75 return new StaticCallExpr ((MethodInfo) method, args, loc);
78 public override void EmitStatement (EmitContext ec)
81 if (TypeManager.TypeToCoreType (type) != TypeManager.void_type)
82 ec.ig.Emit (OpCodes.Pop);
85 public MethodInfo Method {
90 public class ParenthesizedExpression : Expression
92 public Expression Expr;
94 public ParenthesizedExpression (Expression expr)
99 public override Expression DoResolve (EmitContext ec)
101 Expr = Expr.Resolve (ec);
105 public override void Emit (EmitContext ec)
107 throw new Exception ("Should not happen");
112 /// Unary expressions.
116 /// Unary implements unary expressions. It derives from
117 /// ExpressionStatement becuase the pre/post increment/decrement
118 /// operators can be used in a statement context.
120 public class Unary : Expression {
121 public enum Operator : byte {
122 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
123 Indirection, AddressOf, TOP
126 public Operator Oper;
127 public Expression Expr;
129 public Unary (Operator op, Expression expr, Location loc)
137 /// Returns a stringified representation of the Operator
139 static public string OperName (Operator oper)
142 case Operator.UnaryPlus:
144 case Operator.UnaryNegation:
146 case Operator.LogicalNot:
148 case Operator.OnesComplement:
150 case Operator.AddressOf:
152 case Operator.Indirection:
156 return oper.ToString ();
159 public static readonly string [] oper_names;
163 oper_names = new string [(int)Operator.TOP];
165 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
166 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
167 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
168 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
169 oper_names [(int) Operator.Indirection] = "op_Indirection";
170 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
173 void Error23 (Type t)
175 Report.Error (23, loc, "Operator `{0}' cannot be applied to operand of type `{1}'",
176 OperName (Oper), TypeManager.CSharpName (t));
180 /// The result has been already resolved:
182 /// FIXME: a minus constant -128 sbyte cant be turned into a
185 static Expression TryReduceNegative (Constant expr)
189 if (expr is IntConstant)
190 e = new IntConstant (-((IntConstant) expr).Value);
191 else if (expr is UIntConstant){
192 uint value = ((UIntConstant) expr).Value;
194 if (value < 2147483649)
195 return new IntConstant (-(int)value);
197 e = new LongConstant (-value);
199 else if (expr is LongConstant)
200 e = new LongConstant (-((LongConstant) expr).Value);
201 else if (expr is ULongConstant){
202 ulong value = ((ULongConstant) expr).Value;
204 if (value < 9223372036854775809)
205 return new LongConstant(-(long)value);
207 else if (expr is FloatConstant)
208 e = new FloatConstant (-((FloatConstant) expr).Value);
209 else if (expr is DoubleConstant)
210 e = new DoubleConstant (-((DoubleConstant) expr).Value);
211 else if (expr is DecimalConstant)
212 e = new DecimalConstant (-((DecimalConstant) expr).Value);
213 else if (expr is ShortConstant)
214 e = new IntConstant (-((ShortConstant) expr).Value);
215 else if (expr is UShortConstant)
216 e = new IntConstant (-((UShortConstant) expr).Value);
217 else if (expr is SByteConstant)
218 e = new IntConstant (-((SByteConstant) expr).Value);
219 else if (expr is ByteConstant)
220 e = new IntConstant (-((ByteConstant) expr).Value);
225 // This routine will attempt to simplify the unary expression when the
226 // argument is a constant. The result is returned in `result' and the
227 // function returns true or false depending on whether a reduction
228 // was performed or not
230 bool Reduce (EmitContext ec, Constant e, out Expression result)
232 Type expr_type = e.Type;
235 case Operator.UnaryPlus:
236 if (expr_type == TypeManager.bool_type){
245 case Operator.UnaryNegation:
246 result = TryReduceNegative (e);
247 return result != null;
249 case Operator.LogicalNot:
250 if (expr_type != TypeManager.bool_type) {
256 BoolConstant b = (BoolConstant) e;
257 result = new BoolConstant (!(b.Value));
260 case Operator.OnesComplement:
261 if (!((expr_type == TypeManager.int32_type) ||
262 (expr_type == TypeManager.uint32_type) ||
263 (expr_type == TypeManager.int64_type) ||
264 (expr_type == TypeManager.uint64_type) ||
265 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
268 if (Convert.ImplicitConversionExists (ec, e, TypeManager.int32_type)){
269 result = new Cast (new TypeExpression (TypeManager.int32_type, loc), e, loc);
270 result = result.Resolve (ec);
271 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint32_type)){
272 result = new Cast (new TypeExpression (TypeManager.uint32_type, loc), e, loc);
273 result = result.Resolve (ec);
274 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.int64_type)){
275 result = new Cast (new TypeExpression (TypeManager.int64_type, loc), e, loc);
276 result = result.Resolve (ec);
277 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint64_type)){
278 result = new Cast (new TypeExpression (TypeManager.uint64_type, loc), e, loc);
279 result = result.Resolve (ec);
282 if (result == null || !(result is Constant)){
288 expr_type = result.Type;
289 e = (Constant) result;
292 if (e is EnumConstant){
293 EnumConstant enum_constant = (EnumConstant) e;
296 if (Reduce (ec, enum_constant.Child, out reduced)){
297 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
305 if (expr_type == TypeManager.int32_type){
306 result = new IntConstant (~ ((IntConstant) e).Value);
307 } else if (expr_type == TypeManager.uint32_type){
308 result = new UIntConstant (~ ((UIntConstant) e).Value);
309 } else if (expr_type == TypeManager.int64_type){
310 result = new LongConstant (~ ((LongConstant) e).Value);
311 } else if (expr_type == TypeManager.uint64_type){
312 result = new ULongConstant (~ ((ULongConstant) e).Value);
320 case Operator.AddressOf:
324 case Operator.Indirection:
328 throw new Exception ("Can not constant fold: " + Oper.ToString());
331 Expression ResolveOperator (EmitContext ec)
334 // Step 1: Default operations on CLI native types.
337 // Attempt to use a constant folding operation.
338 if (Expr is Constant){
341 if (Reduce (ec, (Constant) Expr, out result))
346 // Step 2: Perform Operator Overload location
348 Type expr_type = Expr.Type;
352 op_name = oper_names [(int) Oper];
354 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
357 Expression e = StaticCallExpr.MakeSimpleCall (
358 ec, (MethodGroupExpr) mg, Expr, loc);
368 // Only perform numeric promotions on:
371 if (expr_type == null)
375 case Operator.LogicalNot:
376 if (expr_type != TypeManager.bool_type) {
377 Expr = ResolveBoolean (ec, Expr, loc);
384 type = TypeManager.bool_type;
387 case Operator.OnesComplement:
388 if (!((expr_type == TypeManager.int32_type) ||
389 (expr_type == TypeManager.uint32_type) ||
390 (expr_type == TypeManager.int64_type) ||
391 (expr_type == TypeManager.uint64_type) ||
392 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
395 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
397 type = TypeManager.int32_type;
400 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint32_type, loc);
402 type = TypeManager.uint32_type;
405 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
407 type = TypeManager.int64_type;
410 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint64_type, loc);
412 type = TypeManager.uint64_type;
421 case Operator.AddressOf:
427 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
431 IVariable variable = Expr as IVariable;
432 bool is_fixed = variable != null && variable.VerifyFixed ();
434 if (!ec.InFixedInitializer && !is_fixed) {
435 Error (212, "You can only take the address of unfixed expression inside " +
436 "of a fixed statement initializer");
440 if (ec.InFixedInitializer && is_fixed) {
441 Error (213, "You cannot use the fixed statement to take the address of 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 must be applied to a pointer");
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.DoResolveLValue (ec, new EmptyExpression ());
580 if (Expr == null || Expr.eclass != ExprClass.Variable){
581 Error (211, "Cannot take the address of the given expression");
586 Expr = Expr.Resolve (ec);
591 eclass = ExprClass.Value;
592 return ResolveOperator (ec);
595 public override Expression DoResolveLValue (EmitContext ec, Expression right)
597 if (Oper == Operator.Indirection)
598 return DoResolve (ec);
603 public override void Emit (EmitContext ec)
605 ILGenerator ig = ec.ig;
608 case Operator.UnaryPlus:
609 throw new Exception ("This should be caught by Resolve");
611 case Operator.UnaryNegation:
613 ig.Emit (OpCodes.Ldc_I4_0);
614 if (type == TypeManager.int64_type)
615 ig.Emit (OpCodes.Conv_U8);
617 ig.Emit (OpCodes.Sub_Ovf);
620 ig.Emit (OpCodes.Neg);
625 case Operator.LogicalNot:
627 ig.Emit (OpCodes.Ldc_I4_0);
628 ig.Emit (OpCodes.Ceq);
631 case Operator.OnesComplement:
633 ig.Emit (OpCodes.Not);
636 case Operator.AddressOf:
637 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
641 throw new Exception ("This should not happen: Operator = "
646 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
648 if (Oper == Operator.LogicalNot)
649 Expr.EmitBranchable (ec, target, !onTrue);
651 base.EmitBranchable (ec, target, onTrue);
654 public override string ToString ()
656 return "Unary (" + Oper + ", " + Expr + ")";
662 // Unary operators are turned into Indirection expressions
663 // after semantic analysis (this is so we can take the address
664 // of an indirection).
666 public class Indirection : Expression, IMemoryLocation, IAssignMethod, IVariable {
668 LocalTemporary temporary;
671 public Indirection (Expression expr, Location l)
674 type = TypeManager.HasElementType (expr.Type) ? TypeManager.GetElementType (expr.Type) : expr.Type;
675 eclass = ExprClass.Variable;
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 DoResolveLValue (EmitContext ec, Expression right_side)
726 return DoResolve (ec);
729 public override Expression DoResolve (EmitContext ec)
732 // Born fully resolved
737 public override string ToString ()
739 return "*(" + expr + ")";
742 #region IVariable Members
744 public VariableInfo VariableInfo {
750 public bool VerifyFixed ()
752 // A pointer-indirection is always fixed.
760 /// Unary Mutator expressions (pre and post ++ and --)
764 /// UnaryMutator implements ++ and -- expressions. It derives from
765 /// ExpressionStatement becuase the pre/post increment/decrement
766 /// operators can be used in a statement context.
768 /// FIXME: Idea, we could split this up in two classes, one simpler
769 /// for the common case, and one with the extra fields for more complex
770 /// classes (indexers require temporary access; overloaded require method)
773 public class UnaryMutator : ExpressionStatement {
775 public enum Mode : byte {
782 PreDecrement = IsDecrement,
783 PostIncrement = IsPost,
784 PostDecrement = IsPost | IsDecrement
788 bool is_expr = false;
789 bool recurse = false;
794 // This is expensive for the simplest case.
796 StaticCallExpr method;
798 public UnaryMutator (Mode m, Expression e, Location l)
805 static string OperName (Mode mode)
807 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
812 /// Returns whether an object of type `t' can be incremented
813 /// or decremented with add/sub (ie, basically whether we can
814 /// use pre-post incr-decr operations on it, but it is not a
815 /// System.Decimal, which we require operator overloading to catch)
817 static bool IsIncrementableNumber (Type t)
819 return (t == TypeManager.sbyte_type) ||
820 (t == TypeManager.byte_type) ||
821 (t == TypeManager.short_type) ||
822 (t == TypeManager.ushort_type) ||
823 (t == TypeManager.int32_type) ||
824 (t == TypeManager.uint32_type) ||
825 (t == TypeManager.int64_type) ||
826 (t == TypeManager.uint64_type) ||
827 (t == TypeManager.char_type) ||
828 (t.IsSubclassOf (TypeManager.enum_type)) ||
829 (t == TypeManager.float_type) ||
830 (t == TypeManager.double_type) ||
831 (t.IsPointer && t != TypeManager.void_ptr_type);
834 Expression ResolveOperator (EmitContext ec)
836 Type expr_type = expr.Type;
839 // Step 1: Perform Operator Overload location
844 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
845 op_name = "op_Increment";
847 op_name = "op_Decrement";
849 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
852 method = StaticCallExpr.MakeSimpleCall (
853 ec, (MethodGroupExpr) mg, expr, loc);
856 } else if (!IsIncrementableNumber (expr_type)) {
857 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
858 TypeManager.CSharpName (expr_type) + "'");
863 // The operand of the prefix/postfix increment decrement operators
864 // should be an expression that is classified as a variable,
865 // a property access or an indexer access
868 if (expr.eclass == ExprClass.Variable){
869 LocalVariableReference var = expr as LocalVariableReference;
870 if ((var != null) && var.IsReadOnly) {
871 Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
874 } else if (expr.eclass == ExprClass.IndexerAccess || expr.eclass == ExprClass.PropertyAccess){
875 expr = expr.ResolveLValue (ec, this, Location);
879 expr.Error_UnexpectedKind (ec, "variable, indexer or property access", loc);
886 public override Expression DoResolve (EmitContext ec)
888 expr = expr.Resolve (ec);
893 eclass = ExprClass.Value;
894 return ResolveOperator (ec);
897 static int PtrTypeSize (Type t)
899 return GetTypeSize (TypeManager.GetElementType (t));
903 // Loads the proper "1" into the stack based on the type, then it emits the
904 // opcode for the operation requested
906 void LoadOneAndEmitOp (EmitContext ec, Type t)
909 // Measure if getting the typecode and using that is more/less efficient
910 // that comparing types. t.GetTypeCode() is an internal call.
912 ILGenerator ig = ec.ig;
914 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
915 LongConstant.EmitLong (ig, 1);
916 else if (t == TypeManager.double_type)
917 ig.Emit (OpCodes.Ldc_R8, 1.0);
918 else if (t == TypeManager.float_type)
919 ig.Emit (OpCodes.Ldc_R4, 1.0F);
920 else if (t.IsPointer){
921 int n = PtrTypeSize (t);
924 ig.Emit (OpCodes.Sizeof, t);
926 IntConstant.EmitInt (ig, n);
928 ig.Emit (OpCodes.Ldc_I4_1);
931 // Now emit the operation
934 if (t == TypeManager.int32_type ||
935 t == TypeManager.int64_type){
936 if ((mode & Mode.IsDecrement) != 0)
937 ig.Emit (OpCodes.Sub_Ovf);
939 ig.Emit (OpCodes.Add_Ovf);
940 } else if (t == TypeManager.uint32_type ||
941 t == TypeManager.uint64_type){
942 if ((mode & Mode.IsDecrement) != 0)
943 ig.Emit (OpCodes.Sub_Ovf_Un);
945 ig.Emit (OpCodes.Add_Ovf_Un);
947 if ((mode & Mode.IsDecrement) != 0)
948 ig.Emit (OpCodes.Sub_Ovf);
950 ig.Emit (OpCodes.Add_Ovf);
953 if ((mode & Mode.IsDecrement) != 0)
954 ig.Emit (OpCodes.Sub);
956 ig.Emit (OpCodes.Add);
959 if (t == TypeManager.sbyte_type){
961 ig.Emit (OpCodes.Conv_Ovf_I1);
963 ig.Emit (OpCodes.Conv_I1);
964 } else if (t == TypeManager.byte_type){
966 ig.Emit (OpCodes.Conv_Ovf_U1);
968 ig.Emit (OpCodes.Conv_U1);
969 } else if (t == TypeManager.short_type){
971 ig.Emit (OpCodes.Conv_Ovf_I2);
973 ig.Emit (OpCodes.Conv_I2);
974 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
976 ig.Emit (OpCodes.Conv_Ovf_U2);
978 ig.Emit (OpCodes.Conv_U2);
983 void EmitCode (EmitContext ec, bool is_expr)
986 this.is_expr = is_expr;
987 ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
991 public override void Emit (EmitContext ec)
994 // We use recurse to allow ourselfs to be the source
995 // of an assignment. This little hack prevents us from
996 // having to allocate another expression
999 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
1001 LoadOneAndEmitOp (ec, expr.Type);
1003 ec.ig.Emit (OpCodes.Call, method.Method);
1008 EmitCode (ec, true);
1011 public override void EmitStatement (EmitContext ec)
1013 EmitCode (ec, false);
1018 /// Base class for the `Is' and `As' classes.
1022 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1025 public abstract class Probe : Expression {
1026 public Expression ProbeType;
1027 protected Expression expr;
1028 protected Type probe_type;
1030 public Probe (Expression expr, Expression probe_type, Location l)
1032 ProbeType = probe_type;
1037 public Expression Expr {
1043 public override Expression DoResolve (EmitContext ec)
1045 TypeExpr texpr = ProbeType.ResolveAsTypeTerminal (ec, false);
1048 probe_type = texpr.ResolveType (ec);
1050 CheckObsoleteAttribute (probe_type);
1052 expr = expr.Resolve (ec);
1056 if (expr.Type.IsPointer) {
1057 Report.Error (244, loc, "\"is\" or \"as\" are not valid on pointer types");
1065 /// Implementation of the `is' operator.
1067 public class Is : Probe {
1068 public Is (Expression expr, Expression probe_type, Location l)
1069 : base (expr, probe_type, l)
1074 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1079 public override void Emit (EmitContext ec)
1081 ILGenerator ig = ec.ig;
1086 case Action.AlwaysFalse:
1087 ig.Emit (OpCodes.Pop);
1088 IntConstant.EmitInt (ig, 0);
1090 case Action.AlwaysTrue:
1091 ig.Emit (OpCodes.Pop);
1092 IntConstant.EmitInt (ig, 1);
1094 case Action.LeaveOnStack:
1095 // the `e != null' rule.
1096 ig.Emit (OpCodes.Ldnull);
1097 ig.Emit (OpCodes.Ceq);
1098 ig.Emit (OpCodes.Ldc_I4_0);
1099 ig.Emit (OpCodes.Ceq);
1102 ig.Emit (OpCodes.Isinst, probe_type);
1103 ig.Emit (OpCodes.Ldnull);
1104 ig.Emit (OpCodes.Cgt_Un);
1107 throw new Exception ("never reached");
1110 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
1112 ILGenerator ig = ec.ig;
1115 case Action.AlwaysFalse:
1117 ig.Emit (OpCodes.Br, target);
1120 case Action.AlwaysTrue:
1122 ig.Emit (OpCodes.Br, target);
1125 case Action.LeaveOnStack:
1126 // the `e != null' rule.
1128 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1132 ig.Emit (OpCodes.Isinst, probe_type);
1133 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1136 throw new Exception ("never reached");
1139 public override Expression DoResolve (EmitContext ec)
1141 Expression e = base.DoResolve (ec);
1143 if ((e == null) || (expr == null))
1146 Type etype = expr.Type;
1147 bool warning_always_matches = false;
1148 bool warning_never_matches = false;
1150 type = TypeManager.bool_type;
1151 eclass = ExprClass.Value;
1154 // First case, if at compile time, there is an implicit conversion
1155 // then e != null (objects) or true (value types)
1157 e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1158 if (e != null && !(e is NullCast)){
1160 if (etype.IsValueType)
1161 action = Action.AlwaysTrue;
1163 action = Action.LeaveOnStack;
1165 warning_always_matches = true;
1166 } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1168 // Second case: explicit reference convresion
1170 if (expr is NullLiteral)
1171 action = Action.AlwaysFalse;
1173 action = Action.Probe;
1175 action = Action.AlwaysFalse;
1176 warning_never_matches = true;
1179 if (warning_always_matches)
1180 Report.Warning (183, 1, loc, "The given expression is always of the provided (`{0}') type", TypeManager.CSharpName (probe_type));
1181 else if (warning_never_matches){
1182 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1183 Report.Warning (184, 1, loc, "The given expression is never of the provided (`{0}') type", TypeManager.CSharpName (probe_type));
1191 /// Implementation of the `as' operator.
1193 public class As : Probe {
1194 public As (Expression expr, Expression probe_type, Location l)
1195 : base (expr, probe_type, l)
1199 bool do_isinst = false;
1201 public override void Emit (EmitContext ec)
1203 ILGenerator ig = ec.ig;
1208 ig.Emit (OpCodes.Isinst, probe_type);
1211 static void Error_CannotConvertType (Type source, Type target, Location loc)
1213 Report.Error (39, loc, "Cannot convert type `{0}' to `{1}' via a built-in conversion",
1214 TypeManager.CSharpName (source),
1215 TypeManager.CSharpName (target));
1218 public override Expression DoResolve (EmitContext ec)
1220 Expression e = base.DoResolve (ec);
1226 eclass = ExprClass.Value;
1227 Type etype = expr.Type;
1229 if (TypeManager.IsValueType (probe_type)){
1230 Report.Error (77, loc, "The as operator must be used with a reference type (`" +
1231 TypeManager.CSharpName (probe_type) + "' is a value type)");
1236 e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1243 if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1248 Error_CannotConvertType (etype, probe_type, loc);
1254 /// This represents a typecast in the source language.
1256 /// FIXME: Cast expressions have an unusual set of parsing
1257 /// rules, we need to figure those out.
1259 public class Cast : Expression {
1260 Expression target_type;
1263 public Cast (Expression cast_type, Expression expr)
1264 : this (cast_type, expr, cast_type.Location)
1268 public Cast (Expression cast_type, Expression expr, Location loc)
1270 this.target_type = cast_type;
1275 public Expression TargetType {
1281 public Expression Expr {
1290 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1292 if (!ec.ConstantCheckState)
1295 if ((value < min) || (value > max)) {
1296 Error (221, "Constant value `" + value + "' cannot be converted " +
1297 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1298 "syntax to override)");
1305 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1307 if (!ec.ConstantCheckState)
1311 Error (221, "Constant value `" + value + "' cannot be converted " +
1312 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1313 "syntax to override)");
1320 bool CheckUnsigned (EmitContext ec, long value, Type type)
1322 if (!ec.ConstantCheckState)
1326 Error (221, "Constant value `" + value + "' cannot be converted " +
1327 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1328 "syntax to override)");
1335 // TODO: move to constant
1337 /// Attempts to do a compile-time folding of a constant cast.
1339 Expression TryReduce (EmitContext ec, Type target_type)
1341 if (expr.Type == target_type)
1344 if (TypeManager.IsEnumType (target_type))
1345 return new EnumConstant ((Constant)expr, target_type);
1347 Expression real_expr = expr;
1348 if (real_expr is EnumConstant)
1349 real_expr = ((EnumConstant) real_expr).Child;
1351 if (real_expr is ByteConstant){
1352 byte v = ((ByteConstant) real_expr).Value;
1354 if (target_type == TypeManager.sbyte_type) {
1355 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1357 return new SByteConstant ((sbyte) v);
1359 if (target_type == TypeManager.short_type)
1360 return new ShortConstant ((short) v);
1361 if (target_type == TypeManager.ushort_type)
1362 return new UShortConstant ((ushort) v);
1363 if (target_type == TypeManager.int32_type)
1364 return new IntConstant ((int) v);
1365 if (target_type == TypeManager.uint32_type)
1366 return new UIntConstant ((uint) v);
1367 if (target_type == TypeManager.int64_type)
1368 return new LongConstant ((long) v);
1369 if (target_type == TypeManager.uint64_type)
1370 return new ULongConstant ((ulong) v);
1371 if (target_type == TypeManager.float_type)
1372 return new FloatConstant ((float) v);
1373 if (target_type == TypeManager.double_type)
1374 return new DoubleConstant ((double) v);
1375 if (target_type == TypeManager.char_type)
1376 return new CharConstant ((char) v);
1377 if (target_type == TypeManager.decimal_type)
1378 return new DecimalConstant ((decimal) v);
1380 if (real_expr is SByteConstant){
1381 sbyte v = ((SByteConstant) real_expr).Value;
1383 if (target_type == TypeManager.byte_type) {
1384 if (!CheckUnsigned (ec, v, target_type))
1386 return new ByteConstant ((byte) v);
1388 if (target_type == TypeManager.short_type)
1389 return new ShortConstant ((short) v);
1390 if (target_type == TypeManager.ushort_type) {
1391 if (!CheckUnsigned (ec, v, target_type))
1393 return new UShortConstant ((ushort) v);
1394 } if (target_type == TypeManager.int32_type)
1395 return new IntConstant ((int) v);
1396 if (target_type == TypeManager.uint32_type) {
1397 if (!CheckUnsigned (ec, v, target_type))
1399 return new UIntConstant ((uint) v);
1400 } if (target_type == TypeManager.int64_type)
1401 return new LongConstant ((long) v);
1402 if (target_type == TypeManager.uint64_type) {
1403 if (!CheckUnsigned (ec, v, target_type))
1405 return new ULongConstant ((ulong) v);
1407 if (target_type == TypeManager.float_type)
1408 return new FloatConstant ((float) v);
1409 if (target_type == TypeManager.double_type)
1410 return new DoubleConstant ((double) v);
1411 if (target_type == TypeManager.char_type) {
1412 if (!CheckUnsigned (ec, v, target_type))
1414 return new CharConstant ((char) v);
1416 if (target_type == TypeManager.decimal_type)
1417 return new DecimalConstant ((decimal) v);
1419 if (real_expr is ShortConstant){
1420 short v = ((ShortConstant) real_expr).Value;
1422 if (target_type == TypeManager.byte_type) {
1423 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1425 return new ByteConstant ((byte) v);
1427 if (target_type == TypeManager.sbyte_type) {
1428 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1430 return new SByteConstant ((sbyte) v);
1432 if (target_type == TypeManager.ushort_type) {
1433 if (!CheckUnsigned (ec, v, target_type))
1435 return new UShortConstant ((ushort) v);
1437 if (target_type == TypeManager.int32_type)
1438 return new IntConstant ((int) v);
1439 if (target_type == TypeManager.uint32_type) {
1440 if (!CheckUnsigned (ec, v, target_type))
1442 return new UIntConstant ((uint) v);
1444 if (target_type == TypeManager.int64_type)
1445 return new LongConstant ((long) v);
1446 if (target_type == TypeManager.uint64_type) {
1447 if (!CheckUnsigned (ec, v, target_type))
1449 return new ULongConstant ((ulong) v);
1451 if (target_type == TypeManager.float_type)
1452 return new FloatConstant ((float) v);
1453 if (target_type == TypeManager.double_type)
1454 return new DoubleConstant ((double) v);
1455 if (target_type == TypeManager.char_type) {
1456 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1458 return new CharConstant ((char) v);
1460 if (target_type == TypeManager.decimal_type)
1461 return new DecimalConstant ((decimal) v);
1463 if (real_expr is UShortConstant){
1464 ushort v = ((UShortConstant) real_expr).Value;
1466 if (target_type == TypeManager.byte_type) {
1467 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1469 return new ByteConstant ((byte) v);
1471 if (target_type == TypeManager.sbyte_type) {
1472 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1474 return new SByteConstant ((sbyte) v);
1476 if (target_type == TypeManager.short_type) {
1477 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1479 return new ShortConstant ((short) v);
1481 if (target_type == TypeManager.int32_type)
1482 return new IntConstant ((int) v);
1483 if (target_type == TypeManager.uint32_type)
1484 return new UIntConstant ((uint) v);
1485 if (target_type == TypeManager.int64_type)
1486 return new LongConstant ((long) v);
1487 if (target_type == TypeManager.uint64_type)
1488 return new ULongConstant ((ulong) v);
1489 if (target_type == TypeManager.float_type)
1490 return new FloatConstant ((float) v);
1491 if (target_type == TypeManager.double_type)
1492 return new DoubleConstant ((double) v);
1493 if (target_type == TypeManager.char_type) {
1494 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1496 return new CharConstant ((char) v);
1498 if (target_type == TypeManager.decimal_type)
1499 return new DecimalConstant ((decimal) v);
1501 if (real_expr is IntConstant){
1502 int v = ((IntConstant) real_expr).Value;
1504 if (target_type == TypeManager.byte_type) {
1505 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1507 return new ByteConstant ((byte) v);
1509 if (target_type == TypeManager.sbyte_type) {
1510 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1512 return new SByteConstant ((sbyte) v);
1514 if (target_type == TypeManager.short_type) {
1515 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1517 return new ShortConstant ((short) v);
1519 if (target_type == TypeManager.ushort_type) {
1520 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1522 return new UShortConstant ((ushort) v);
1524 if (target_type == TypeManager.uint32_type) {
1525 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1527 return new UIntConstant ((uint) v);
1529 if (target_type == TypeManager.int64_type)
1530 return new LongConstant ((long) v);
1531 if (target_type == TypeManager.uint64_type) {
1532 if (!CheckUnsigned (ec, v, target_type))
1534 return new ULongConstant ((ulong) v);
1536 if (target_type == TypeManager.float_type)
1537 return new FloatConstant ((float) v);
1538 if (target_type == TypeManager.double_type)
1539 return new DoubleConstant ((double) v);
1540 if (target_type == TypeManager.char_type) {
1541 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1543 return new CharConstant ((char) v);
1545 if (target_type == TypeManager.decimal_type)
1546 return new DecimalConstant ((decimal) v);
1548 if (real_expr is UIntConstant){
1549 uint v = ((UIntConstant) real_expr).Value;
1551 if (target_type == TypeManager.byte_type) {
1552 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1554 return new ByteConstant ((byte) v);
1556 if (target_type == TypeManager.sbyte_type) {
1557 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1559 return new SByteConstant ((sbyte) v);
1561 if (target_type == TypeManager.short_type) {
1562 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1564 return new ShortConstant ((short) v);
1566 if (target_type == TypeManager.ushort_type) {
1567 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1569 return new UShortConstant ((ushort) v);
1571 if (target_type == TypeManager.int32_type) {
1572 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1574 return new IntConstant ((int) v);
1576 if (target_type == TypeManager.int64_type)
1577 return new LongConstant ((long) v);
1578 if (target_type == TypeManager.uint64_type)
1579 return new ULongConstant ((ulong) v);
1580 if (target_type == TypeManager.float_type)
1581 return new FloatConstant ((float) v);
1582 if (target_type == TypeManager.double_type)
1583 return new DoubleConstant ((double) v);
1584 if (target_type == TypeManager.char_type) {
1585 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1587 return new CharConstant ((char) v);
1589 if (target_type == TypeManager.decimal_type)
1590 return new DecimalConstant ((decimal) v);
1592 if (real_expr is LongConstant){
1593 long v = ((LongConstant) real_expr).Value;
1595 if (target_type == TypeManager.byte_type) {
1596 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1598 return new ByteConstant ((byte) v);
1600 if (target_type == TypeManager.sbyte_type) {
1601 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1603 return new SByteConstant ((sbyte) v);
1605 if (target_type == TypeManager.short_type) {
1606 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1608 return new ShortConstant ((short) v);
1610 if (target_type == TypeManager.ushort_type) {
1611 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1613 return new UShortConstant ((ushort) v);
1615 if (target_type == TypeManager.int32_type) {
1616 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1618 return new IntConstant ((int) v);
1620 if (target_type == TypeManager.uint32_type) {
1621 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1623 return new UIntConstant ((uint) v);
1625 if (target_type == TypeManager.uint64_type) {
1626 if (!CheckUnsigned (ec, v, target_type))
1628 return new ULongConstant ((ulong) v);
1630 if (target_type == TypeManager.float_type)
1631 return new FloatConstant ((float) v);
1632 if (target_type == TypeManager.double_type)
1633 return new DoubleConstant ((double) v);
1634 if (target_type == TypeManager.char_type) {
1635 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1637 return new CharConstant ((char) v);
1639 if (target_type == TypeManager.decimal_type)
1640 return new DecimalConstant ((decimal) v);
1642 if (real_expr is ULongConstant){
1643 ulong v = ((ULongConstant) real_expr).Value;
1645 if (target_type == TypeManager.byte_type) {
1646 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1648 return new ByteConstant ((byte) v);
1650 if (target_type == TypeManager.sbyte_type) {
1651 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1653 return new SByteConstant ((sbyte) v);
1655 if (target_type == TypeManager.short_type) {
1656 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1658 return new ShortConstant ((short) v);
1660 if (target_type == TypeManager.ushort_type) {
1661 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1663 return new UShortConstant ((ushort) v);
1665 if (target_type == TypeManager.int32_type) {
1666 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1668 return new IntConstant ((int) v);
1670 if (target_type == TypeManager.uint32_type) {
1671 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1673 return new UIntConstant ((uint) v);
1675 if (target_type == TypeManager.int64_type) {
1676 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1678 return new LongConstant ((long) v);
1680 if (target_type == TypeManager.float_type)
1681 return new FloatConstant ((float) v);
1682 if (target_type == TypeManager.double_type)
1683 return new DoubleConstant ((double) v);
1684 if (target_type == TypeManager.char_type) {
1685 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1687 return new CharConstant ((char) v);
1689 if (target_type == TypeManager.decimal_type)
1690 return new DecimalConstant ((decimal) v);
1692 if (real_expr is FloatConstant){
1693 float v = ((FloatConstant) real_expr).Value;
1695 if (target_type == TypeManager.byte_type)
1696 return new ByteConstant ((byte) v);
1697 if (target_type == TypeManager.sbyte_type)
1698 return new SByteConstant ((sbyte) v);
1699 if (target_type == TypeManager.short_type)
1700 return new ShortConstant ((short) v);
1701 if (target_type == TypeManager.ushort_type)
1702 return new UShortConstant ((ushort) v);
1703 if (target_type == TypeManager.int32_type)
1704 return new IntConstant ((int) v);
1705 if (target_type == TypeManager.uint32_type)
1706 return new UIntConstant ((uint) v);
1707 if (target_type == TypeManager.int64_type)
1708 return new LongConstant ((long) v);
1709 if (target_type == TypeManager.uint64_type)
1710 return new ULongConstant ((ulong) v);
1711 if (target_type == TypeManager.double_type)
1712 return new DoubleConstant ((double) v);
1713 if (target_type == TypeManager.char_type)
1714 return new CharConstant ((char) v);
1715 if (target_type == TypeManager.decimal_type)
1716 return new DecimalConstant ((decimal) v);
1718 if (real_expr is DoubleConstant){
1719 double v = ((DoubleConstant) real_expr).Value;
1721 if (target_type == TypeManager.byte_type){
1722 return new ByteConstant ((byte) v);
1723 } if (target_type == TypeManager.sbyte_type)
1724 return new SByteConstant ((sbyte) v);
1725 if (target_type == TypeManager.short_type)
1726 return new ShortConstant ((short) v);
1727 if (target_type == TypeManager.ushort_type)
1728 return new UShortConstant ((ushort) v);
1729 if (target_type == TypeManager.int32_type)
1730 return new IntConstant ((int) v);
1731 if (target_type == TypeManager.uint32_type)
1732 return new UIntConstant ((uint) v);
1733 if (target_type == TypeManager.int64_type)
1734 return new LongConstant ((long) v);
1735 if (target_type == TypeManager.uint64_type)
1736 return new ULongConstant ((ulong) v);
1737 if (target_type == TypeManager.float_type)
1738 return new FloatConstant ((float) v);
1739 if (target_type == TypeManager.char_type)
1740 return new CharConstant ((char) v);
1741 if (target_type == TypeManager.decimal_type)
1742 return new DecimalConstant ((decimal) v);
1745 if (real_expr is CharConstant){
1746 char v = ((CharConstant) real_expr).Value;
1748 if (target_type == TypeManager.byte_type) {
1749 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1751 return new ByteConstant ((byte) v);
1753 if (target_type == TypeManager.sbyte_type) {
1754 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1756 return new SByteConstant ((sbyte) v);
1758 if (target_type == TypeManager.short_type) {
1759 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1761 return new ShortConstant ((short) v);
1763 if (target_type == TypeManager.int32_type)
1764 return new IntConstant ((int) v);
1765 if (target_type == TypeManager.uint32_type)
1766 return new UIntConstant ((uint) v);
1767 if (target_type == TypeManager.int64_type)
1768 return new LongConstant ((long) v);
1769 if (target_type == TypeManager.uint64_type)
1770 return new ULongConstant ((ulong) v);
1771 if (target_type == TypeManager.float_type)
1772 return new FloatConstant ((float) v);
1773 if (target_type == TypeManager.double_type)
1774 return new DoubleConstant ((double) v);
1775 if (target_type == TypeManager.char_type) {
1776 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1778 return new CharConstant ((char) v);
1780 if (target_type == TypeManager.decimal_type)
1781 return new DecimalConstant ((decimal) v);
1787 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1789 expr = expr.DoResolveLValue (ec, right_side);
1793 return ResolveRest (ec);
1796 public override Expression DoResolve (EmitContext ec)
1798 expr = expr.Resolve (ec);
1802 return ResolveRest (ec);
1805 Expression ResolveRest (EmitContext ec)
1807 TypeExpr target = target_type.ResolveAsTypeTerminal (ec, false);
1811 type = target.ResolveType (ec);
1813 CheckObsoleteAttribute (type);
1815 if (type.IsAbstract && type.IsSealed) {
1816 Report.Error (716, loc, "Cannot convert to static type `{0}'", TypeManager.CSharpName (type));
1820 eclass = ExprClass.Value;
1822 if (expr is Constant){
1823 Expression e = TryReduce (ec, type);
1829 if (type.IsPointer && !ec.InUnsafe) {
1833 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1837 public override void Emit (EmitContext ec)
1840 // This one will never happen
1842 throw new Exception ("Should not happen");
1847 /// Binary operators
1849 public class Binary : Expression {
1850 public enum Operator : byte {
1851 Multiply, Division, Modulus,
1852 Addition, Subtraction,
1853 LeftShift, RightShift,
1854 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1855 Equality, Inequality,
1865 Expression left, right;
1867 // This must be kept in sync with Operator!!!
1868 public static readonly string [] oper_names;
1872 oper_names = new string [(int) Operator.TOP];
1874 oper_names [(int) Operator.Multiply] = "op_Multiply";
1875 oper_names [(int) Operator.Division] = "op_Division";
1876 oper_names [(int) Operator.Modulus] = "op_Modulus";
1877 oper_names [(int) Operator.Addition] = "op_Addition";
1878 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1879 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1880 oper_names [(int) Operator.RightShift] = "op_RightShift";
1881 oper_names [(int) Operator.LessThan] = "op_LessThan";
1882 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1883 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1884 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1885 oper_names [(int) Operator.Equality] = "op_Equality";
1886 oper_names [(int) Operator.Inequality] = "op_Inequality";
1887 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1888 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1889 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1890 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1891 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1894 public Binary (Operator oper, Expression left, Expression right)
1899 this.loc = left.Location;
1902 public Operator Oper {
1911 public Expression Left {
1920 public Expression Right {
1931 /// Returns a stringified representation of the Operator
1933 static string OperName (Operator oper)
1936 case Operator.Multiply:
1938 case Operator.Division:
1940 case Operator.Modulus:
1942 case Operator.Addition:
1944 case Operator.Subtraction:
1946 case Operator.LeftShift:
1948 case Operator.RightShift:
1950 case Operator.LessThan:
1952 case Operator.GreaterThan:
1954 case Operator.LessThanOrEqual:
1956 case Operator.GreaterThanOrEqual:
1958 case Operator.Equality:
1960 case Operator.Inequality:
1962 case Operator.BitwiseAnd:
1964 case Operator.BitwiseOr:
1966 case Operator.ExclusiveOr:
1968 case Operator.LogicalOr:
1970 case Operator.LogicalAnd:
1974 return oper.ToString ();
1977 public override string ToString ()
1979 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1980 right.ToString () + ")";
1983 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1985 if (expr.Type == target_type)
1988 return Convert.ImplicitConversion (ec, expr, target_type, loc);
1991 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1994 34, loc, "Operator `" + OperName (oper)
1995 + "' is ambiguous on operands of type `"
1996 + TypeManager.CSharpName (l) + "' "
1997 + "and `" + TypeManager.CSharpName (r)
2001 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
2003 if ((l == t) || (r == t))
2006 if (!check_user_conversions)
2009 if (Convert.ImplicitUserConversionExists (ec, l, t))
2011 else if (Convert.ImplicitUserConversionExists (ec, r, t))
2018 // Note that handling the case l == Decimal || r == Decimal
2019 // is taken care of by the Step 1 Operator Overload resolution.
2021 // If `check_user_conv' is true, we also check whether a user-defined conversion
2022 // exists. Note that we only need to do this if both arguments are of a user-defined
2023 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
2024 // so we don't explicitly check for performance reasons.
2026 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
2028 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
2030 // If either operand is of type double, the other operand is
2031 // conveted to type double.
2033 if (r != TypeManager.double_type)
2034 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
2035 if (l != TypeManager.double_type)
2036 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
2038 type = TypeManager.double_type;
2039 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
2041 // if either operand is of type float, the other operand is
2042 // converted to type float.
2044 if (r != TypeManager.double_type)
2045 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
2046 if (l != TypeManager.double_type)
2047 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
2048 type = TypeManager.float_type;
2049 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2053 // If either operand is of type ulong, the other operand is
2054 // converted to type ulong. or an error ocurrs if the other
2055 // operand is of type sbyte, short, int or long
2057 if (l == TypeManager.uint64_type){
2058 if (r != TypeManager.uint64_type){
2059 if (right is IntConstant){
2060 IntConstant ic = (IntConstant) right;
2062 e = Convert.TryImplicitIntConversion (l, ic);
2065 } else if (right is LongConstant){
2066 long ll = ((LongConstant) right).Value;
2069 right = new ULongConstant ((ulong) ll);
2071 e = Convert.ImplicitNumericConversion (ec, right, l, loc);
2078 if (left is IntConstant){
2079 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
2082 } else if (left is LongConstant){
2083 long ll = ((LongConstant) left).Value;
2086 left = new ULongConstant ((ulong) ll);
2088 e = Convert.ImplicitNumericConversion (ec, left, r, loc);
2095 if ((other == TypeManager.sbyte_type) ||
2096 (other == TypeManager.short_type) ||
2097 (other == TypeManager.int32_type) ||
2098 (other == TypeManager.int64_type))
2099 Error_OperatorAmbiguous (loc, oper, l, r);
2101 left = ForceConversion (ec, left, TypeManager.uint64_type);
2102 right = ForceConversion (ec, right, TypeManager.uint64_type);
2104 type = TypeManager.uint64_type;
2105 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2107 // If either operand is of type long, the other operand is converted
2110 if (l != TypeManager.int64_type)
2111 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
2112 if (r != TypeManager.int64_type)
2113 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
2115 type = TypeManager.int64_type;
2116 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2118 // If either operand is of type uint, and the other
2119 // operand is of type sbyte, short or int, othe operands are
2120 // converted to type long (unless we have an int constant).
2124 if (l == TypeManager.uint32_type){
2125 if (right is IntConstant){
2126 IntConstant ic = (IntConstant) right;
2130 right = new UIntConstant ((uint) val);
2137 } else if (r == TypeManager.uint32_type){
2138 if (left is IntConstant){
2139 IntConstant ic = (IntConstant) left;
2143 left = new UIntConstant ((uint) val);
2152 if ((other == TypeManager.sbyte_type) ||
2153 (other == TypeManager.short_type) ||
2154 (other == TypeManager.int32_type)){
2155 left = ForceConversion (ec, left, TypeManager.int64_type);
2156 right = ForceConversion (ec, right, TypeManager.int64_type);
2157 type = TypeManager.int64_type;
2160 // if either operand is of type uint, the other
2161 // operand is converd to type uint
2163 left = ForceConversion (ec, left, TypeManager.uint32_type);
2164 right = ForceConversion (ec, right, TypeManager.uint32_type);
2165 type = TypeManager.uint32_type;
2167 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2168 if (l != TypeManager.decimal_type)
2169 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
2171 if (r != TypeManager.decimal_type)
2172 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
2173 type = TypeManager.decimal_type;
2175 left = ForceConversion (ec, left, TypeManager.int32_type);
2176 right = ForceConversion (ec, right, TypeManager.int32_type);
2178 type = TypeManager.int32_type;
2181 return (left != null) && (right != null);
2184 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2186 Report.Error (19, loc, "Operator `{0}' cannot be applied to operands of type `{1}' and `{2}'",
2187 name, TypeManager.CSharpName (l), TypeManager.CSharpName (r));
2190 void Error_OperatorCannotBeApplied ()
2192 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2195 static bool is_unsigned (Type t)
2197 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2198 t == TypeManager.short_type || t == TypeManager.byte_type);
2201 static bool is_user_defined (Type t)
2203 if (t.IsSubclassOf (TypeManager.value_type) &&
2204 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2210 Expression Make32or64 (EmitContext ec, Expression e)
2214 if (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2215 t == TypeManager.int64_type || t == TypeManager.uint64_type)
2217 Expression ee = Convert.ImplicitConversion (ec, e, TypeManager.int32_type, loc);
2220 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint32_type, loc);
2223 ee = Convert.ImplicitConversion (ec, e, TypeManager.int64_type, loc);
2226 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint64_type, loc);
2232 Expression CheckShiftArguments (EmitContext ec)
2236 e = ForceConversion (ec, right, TypeManager.int32_type);
2238 Error_OperatorCannotBeApplied ();
2243 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
2244 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
2245 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
2246 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
2250 if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
2251 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (31));
2252 right = right.DoResolve (ec);
2254 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (63));
2255 right = right.DoResolve (ec);
2260 Error_OperatorCannotBeApplied ();
2265 // This is used to check if a test 'x == null' can be optimized to a reference equals,
2266 // i.e., not invoke op_Equality.
2268 static bool EqualsNullIsReferenceEquals (Type t)
2270 return t == TypeManager.object_type || t == TypeManager.string_type ||
2271 t == TypeManager.delegate_type || t.IsSubclassOf (TypeManager.delegate_type);
2274 static void Warning_UnintendedReferenceComparison (Location loc, string side, Type type)
2276 Report.Warning ((side == "left" ? 252 : 253), 2, loc,
2277 "Possible unintended reference comparison; to get a value comparison, " +
2278 "cast the {0} hand side to type `{1}'.", side, TypeManager.CSharpName (type));
2281 Expression ResolveOperator (EmitContext ec)
2284 Type r = right.Type;
2286 if (oper == Operator.Equality || oper == Operator.Inequality){
2288 // Optimize out call to op_Equality in a few cases.
2290 if ((l == TypeManager.null_type && EqualsNullIsReferenceEquals (r)) ||
2291 (r == TypeManager.null_type && EqualsNullIsReferenceEquals (l))) {
2293 Type = TypeManager.bool_type;
2299 if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
2300 Type = TypeManager.bool_type;
2307 // Do not perform operator overload resolution when both sides are
2310 Expression left_operators = null, right_operators = null;
2311 if (!(TypeManager.IsPrimitiveType (l) && TypeManager.IsPrimitiveType (r))){
2313 // Step 1: Perform Operator Overload location
2315 string op = oper_names [(int) oper];
2317 MethodGroupExpr union;
2318 left_operators = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2320 right_operators = MemberLookup (
2321 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2322 union = Invocation.MakeUnionSet (left_operators, right_operators, loc);
2324 union = (MethodGroupExpr) left_operators;
2326 if (union != null) {
2327 ArrayList args = new ArrayList (2);
2328 args.Add (new Argument (left, Argument.AType.Expression));
2329 args.Add (new Argument (right, Argument.AType.Expression));
2331 MethodBase method = Invocation.OverloadResolve (
2332 ec, union, args, true, Location.Null);
2334 if (method != null) {
2335 MethodInfo mi = (MethodInfo) method;
2337 return new BinaryMethod (mi.ReturnType, method, args);
2343 // Step 0: String concatenation (because overloading will get this wrong)
2345 if (oper == Operator.Addition){
2347 // If any of the arguments is a string, cast to string
2350 // Simple constant folding
2351 if (left is StringConstant && right is StringConstant)
2352 return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value);
2354 if (l == TypeManager.string_type || r == TypeManager.string_type) {
2356 if (r == TypeManager.void_type || l == TypeManager.void_type) {
2357 Error_OperatorCannotBeApplied ();
2361 // try to fold it in on the left
2362 if (left is StringConcat) {
2365 // We have to test here for not-null, since we can be doubly-resolved
2366 // take care of not appending twice
2369 type = TypeManager.string_type;
2370 ((StringConcat) left).Append (ec, right);
2371 return left.Resolve (ec);
2377 // Otherwise, start a new concat expression
2378 return new StringConcat (ec, loc, left, right).Resolve (ec);
2382 // Transform a + ( - b) into a - b
2384 if (right is Unary){
2385 Unary right_unary = (Unary) right;
2387 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2388 oper = Operator.Subtraction;
2389 right = right_unary.Expr;
2395 if (oper == Operator.Equality || oper == Operator.Inequality){
2396 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2397 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2398 Error_OperatorCannotBeApplied ();
2402 type = TypeManager.bool_type;
2406 if (l.IsPointer || r.IsPointer) {
2407 if (l.IsPointer && r.IsPointer) {
2408 type = TypeManager.bool_type;
2412 if (l.IsPointer && r == TypeManager.null_type) {
2413 right = new EmptyCast (NullPointer.Null, l);
2414 type = TypeManager.bool_type;
2418 if (r.IsPointer && l == TypeManager.null_type) {
2419 left = new EmptyCast (NullPointer.Null, r);
2420 type = TypeManager.bool_type;
2426 // operator != (object a, object b)
2427 // operator == (object a, object b)
2429 // For this to be used, both arguments have to be reference-types.
2430 // Read the rationale on the spec (14.9.6)
2432 if (!(l.IsValueType || r.IsValueType)){
2433 type = TypeManager.bool_type;
2439 // Also, a standard conversion must exist from either one
2441 bool left_to_right =
2442 Convert.ImplicitStandardConversionExists (ec, left, r);
2443 bool right_to_left = !left_to_right &&
2444 Convert.ImplicitStandardConversionExists (ec, right, l);
2446 if (!left_to_right && !right_to_left) {
2447 Error_OperatorCannotBeApplied ();
2451 if (left_to_right && left_operators != null &&
2452 RootContext.WarningLevel >= 2) {
2453 ArrayList args = new ArrayList (2);
2454 args.Add (new Argument (left, Argument.AType.Expression));
2455 args.Add (new Argument (left, Argument.AType.Expression));
2456 MethodBase method = Invocation.OverloadResolve (
2457 ec, (MethodGroupExpr) left_operators, args, true, Location.Null);
2459 Warning_UnintendedReferenceComparison (loc, "right", l);
2462 if (right_to_left && right_operators != null &&
2463 RootContext.WarningLevel >= 2) {
2464 ArrayList args = new ArrayList (2);
2465 args.Add (new Argument (right, Argument.AType.Expression));
2466 args.Add (new Argument (right, Argument.AType.Expression));
2467 MethodBase method = Invocation.OverloadResolve (
2468 ec, (MethodGroupExpr) right_operators, args, true, Location.Null);
2470 Warning_UnintendedReferenceComparison (loc, "left", r);
2474 // We are going to have to convert to an object to compare
2476 if (l != TypeManager.object_type)
2477 left = new EmptyCast (left, TypeManager.object_type);
2478 if (r != TypeManager.object_type)
2479 right = new EmptyCast (right, TypeManager.object_type);
2482 // FIXME: CSC here catches errors cs254 and cs252
2488 // One of them is a valuetype, but the other one is not.
2490 if (!l.IsValueType || !r.IsValueType) {
2491 Error_OperatorCannotBeApplied ();
2496 // Only perform numeric promotions on:
2497 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2499 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2500 if (l.IsSubclassOf (TypeManager.delegate_type)){
2501 if (((right.eclass == ExprClass.MethodGroup) ||
2502 (r == TypeManager.anonymous_method_type))){
2503 if ((RootContext.Version != LanguageVersion.ISO_1)){
2504 Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2512 if (r.IsSubclassOf (TypeManager.delegate_type)){
2514 ArrayList args = new ArrayList (2);
2516 args = new ArrayList (2);
2517 args.Add (new Argument (left, Argument.AType.Expression));
2518 args.Add (new Argument (right, Argument.AType.Expression));
2520 if (oper == Operator.Addition)
2521 method = TypeManager.delegate_combine_delegate_delegate;
2523 method = TypeManager.delegate_remove_delegate_delegate;
2526 Error_OperatorCannotBeApplied ();
2530 return new BinaryDelegate (l, method, args);
2535 // Pointer arithmetic:
2537 // T* operator + (T* x, int y);
2538 // T* operator + (T* x, uint y);
2539 // T* operator + (T* x, long y);
2540 // T* operator + (T* x, ulong y);
2542 // T* operator + (int y, T* x);
2543 // T* operator + (uint y, T *x);
2544 // T* operator + (long y, T *x);
2545 // T* operator + (ulong y, T *x);
2547 // T* operator - (T* x, int y);
2548 // T* operator - (T* x, uint y);
2549 // T* operator - (T* x, long y);
2550 // T* operator - (T* x, ulong y);
2552 // long operator - (T* x, T *y)
2555 if (r.IsPointer && oper == Operator.Subtraction){
2557 return new PointerArithmetic (
2558 false, left, right, TypeManager.int64_type,
2561 Expression t = Make32or64 (ec, right);
2563 return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc).Resolve (ec);
2565 } else if (r.IsPointer && oper == Operator.Addition){
2566 Expression t = Make32or64 (ec, left);
2568 return new PointerArithmetic (true, right, t, r, loc).Resolve (ec);
2573 // Enumeration operators
2575 bool lie = TypeManager.IsEnumType (l);
2576 bool rie = TypeManager.IsEnumType (r);
2580 // U operator - (E e, E f)
2582 if (oper == Operator.Subtraction){
2584 type = TypeManager.EnumToUnderlying (l);
2587 Error_OperatorCannotBeApplied ();
2593 // operator + (E e, U x)
2594 // operator - (E e, U x)
2596 if (oper == Operator.Addition || oper == Operator.Subtraction){
2597 Type enum_type = lie ? l : r;
2598 Type other_type = lie ? r : l;
2599 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2601 if (underlying_type != other_type){
2602 temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
2612 Error_OperatorCannotBeApplied ();
2621 temp = Convert.ImplicitConversion (ec, right, l, loc);
2625 Error_OperatorCannotBeApplied ();
2629 temp = Convert.ImplicitConversion (ec, left, r, loc);
2634 Error_OperatorCannotBeApplied ();
2639 if (oper == Operator.Equality || oper == Operator.Inequality ||
2640 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2641 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2642 if (left.Type != right.Type){
2643 Error_OperatorCannotBeApplied ();
2646 type = TypeManager.bool_type;
2650 if (oper == Operator.BitwiseAnd ||
2651 oper == Operator.BitwiseOr ||
2652 oper == Operator.ExclusiveOr){
2653 if (left.Type != right.Type){
2654 Error_OperatorCannotBeApplied ();
2660 Error_OperatorCannotBeApplied ();
2664 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2665 return CheckShiftArguments (ec);
2667 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2668 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2669 type = TypeManager.bool_type;
2674 Error_OperatorCannotBeApplied ();
2678 Expression e = new ConditionalLogicalOperator (
2679 oper == Operator.LogicalAnd, left, right, l, loc);
2680 return e.Resolve (ec);
2684 // operator & (bool x, bool y)
2685 // operator | (bool x, bool y)
2686 // operator ^ (bool x, bool y)
2688 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2689 if (oper == Operator.BitwiseAnd ||
2690 oper == Operator.BitwiseOr ||
2691 oper == Operator.ExclusiveOr){
2698 // Pointer comparison
2700 if (l.IsPointer && r.IsPointer){
2701 if (oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2702 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2703 type = TypeManager.bool_type;
2709 // This will leave left or right set to null if there is an error
2711 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2712 DoNumericPromotions (ec, l, r, check_user_conv);
2713 if (left == null || right == null){
2714 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2719 // reload our cached types if required
2724 if (oper == Operator.BitwiseAnd ||
2725 oper == Operator.BitwiseOr ||
2726 oper == Operator.ExclusiveOr){
2728 if (((l == TypeManager.int32_type) ||
2729 (l == TypeManager.uint32_type) ||
2730 (l == TypeManager.short_type) ||
2731 (l == TypeManager.ushort_type) ||
2732 (l == TypeManager.int64_type) ||
2733 (l == TypeManager.uint64_type))){
2736 Error_OperatorCannotBeApplied ();
2740 Error_OperatorCannotBeApplied ();
2745 if (oper == Operator.Equality ||
2746 oper == Operator.Inequality ||
2747 oper == Operator.LessThanOrEqual ||
2748 oper == Operator.LessThan ||
2749 oper == Operator.GreaterThanOrEqual ||
2750 oper == Operator.GreaterThan){
2751 type = TypeManager.bool_type;
2757 public override Expression DoResolve (EmitContext ec)
2759 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2760 left = ((ParenthesizedExpression) left).Expr;
2761 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2765 if (left.eclass == ExprClass.Type) {
2766 Error (75, "To cast a negative value, you must enclose the value in parentheses");
2770 left = left.Resolve (ec);
2775 Constant lc = left as Constant;
2776 if (lc != null && lc.Type == TypeManager.bool_type &&
2777 ((oper == Operator.LogicalAnd && (bool)lc.GetValue () == false) ||
2778 (oper == Operator.LogicalOr && (bool)lc.GetValue () == true))) {
2780 // TODO: make a sense to resolve unreachable expression as we do for statement
2781 Report.Warning (429, 4, loc, "Unreachable expression code detected");
2785 right = right.Resolve (ec);
2789 eclass = ExprClass.Value;
2791 Constant rc = right as Constant;
2793 if (oper == Operator.BitwiseAnd) {
2794 if (rc != null && rc.IsZeroInteger) {
2795 return lc is EnumConstant ?
2796 new EnumConstant (rc, lc.Type):
2800 if (lc != null && lc.IsZeroInteger) {
2801 return rc is EnumConstant ?
2802 new EnumConstant (lc, rc.Type):
2807 if (rc != null && lc != null){
2808 int prev_e = Report.Errors;
2809 Expression e = ConstantFold.BinaryFold (
2810 ec, oper, lc, rc, loc);
2811 if (e != null || Report.Errors != prev_e)
2815 return ResolveOperator (ec);
2819 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2820 /// context of a conditional bool expression. This function will return
2821 /// false if it is was possible to use EmitBranchable, or true if it was.
2823 /// The expression's code is generated, and we will generate a branch to `target'
2824 /// if the resulting expression value is equal to isTrue
2826 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2828 ILGenerator ig = ec.ig;
2831 // This is more complicated than it looks, but its just to avoid
2832 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2833 // but on top of that we want for == and != to use a special path
2834 // if we are comparing against null
2836 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
2837 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2840 // put the constant on the rhs, for simplicity
2842 if (left is Constant) {
2843 Expression swap = right;
2848 if (((Constant) right).IsZeroInteger) {
2851 ig.Emit (OpCodes.Brtrue, target);
2853 ig.Emit (OpCodes.Brfalse, target);
2856 } else if (right is BoolConstant) {
2858 if (my_on_true != ((BoolConstant) right).Value)
2859 ig.Emit (OpCodes.Brtrue, target);
2861 ig.Emit (OpCodes.Brfalse, target);
2866 } else if (oper == Operator.LogicalAnd) {
2869 Label tests_end = ig.DefineLabel ();
2871 left.EmitBranchable (ec, tests_end, false);
2872 right.EmitBranchable (ec, target, true);
2873 ig.MarkLabel (tests_end);
2875 left.EmitBranchable (ec, target, false);
2876 right.EmitBranchable (ec, target, false);
2881 } else if (oper == Operator.LogicalOr){
2883 left.EmitBranchable (ec, target, true);
2884 right.EmitBranchable (ec, target, true);
2887 Label tests_end = ig.DefineLabel ();
2888 left.EmitBranchable (ec, tests_end, true);
2889 right.EmitBranchable (ec, target, false);
2890 ig.MarkLabel (tests_end);
2895 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2896 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2897 oper == Operator.Equality || oper == Operator.Inequality)) {
2898 base.EmitBranchable (ec, target, onTrue);
2906 bool isUnsigned = is_unsigned (t) || t == TypeManager.double_type || t == TypeManager.float_type;
2909 case Operator.Equality:
2911 ig.Emit (OpCodes.Beq, target);
2913 ig.Emit (OpCodes.Bne_Un, target);
2916 case Operator.Inequality:
2918 ig.Emit (OpCodes.Bne_Un, target);
2920 ig.Emit (OpCodes.Beq, target);
2923 case Operator.LessThan:
2926 ig.Emit (OpCodes.Blt_Un, target);
2928 ig.Emit (OpCodes.Blt, target);
2931 ig.Emit (OpCodes.Bge_Un, target);
2933 ig.Emit (OpCodes.Bge, target);
2936 case Operator.GreaterThan:
2939 ig.Emit (OpCodes.Bgt_Un, target);
2941 ig.Emit (OpCodes.Bgt, target);
2944 ig.Emit (OpCodes.Ble_Un, target);
2946 ig.Emit (OpCodes.Ble, target);
2949 case Operator.LessThanOrEqual:
2952 ig.Emit (OpCodes.Ble_Un, target);
2954 ig.Emit (OpCodes.Ble, target);
2957 ig.Emit (OpCodes.Bgt_Un, target);
2959 ig.Emit (OpCodes.Bgt, target);
2963 case Operator.GreaterThanOrEqual:
2966 ig.Emit (OpCodes.Bge_Un, target);
2968 ig.Emit (OpCodes.Bge, target);
2971 ig.Emit (OpCodes.Blt_Un, target);
2973 ig.Emit (OpCodes.Blt, target);
2976 Console.WriteLine (oper);
2977 throw new Exception ("what is THAT");
2981 public override void Emit (EmitContext ec)
2983 ILGenerator ig = ec.ig;
2988 // Handle short-circuit operators differently
2991 if (oper == Operator.LogicalAnd) {
2992 Label load_zero = ig.DefineLabel ();
2993 Label end = ig.DefineLabel ();
2995 left.EmitBranchable (ec, load_zero, false);
2997 ig.Emit (OpCodes.Br, end);
2999 ig.MarkLabel (load_zero);
3000 ig.Emit (OpCodes.Ldc_I4_0);
3003 } else if (oper == Operator.LogicalOr) {
3004 Label load_one = ig.DefineLabel ();
3005 Label end = ig.DefineLabel ();
3007 left.EmitBranchable (ec, load_one, true);
3009 ig.Emit (OpCodes.Br, end);
3011 ig.MarkLabel (load_one);
3012 ig.Emit (OpCodes.Ldc_I4_1);
3020 bool isUnsigned = is_unsigned (left.Type);
3023 case Operator.Multiply:
3025 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3026 opcode = OpCodes.Mul_Ovf;
3027 else if (isUnsigned)
3028 opcode = OpCodes.Mul_Ovf_Un;
3030 opcode = OpCodes.Mul;
3032 opcode = OpCodes.Mul;
3036 case Operator.Division:
3038 opcode = OpCodes.Div_Un;
3040 opcode = OpCodes.Div;
3043 case Operator.Modulus:
3045 opcode = OpCodes.Rem_Un;
3047 opcode = OpCodes.Rem;
3050 case Operator.Addition:
3052 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3053 opcode = OpCodes.Add_Ovf;
3054 else if (isUnsigned)
3055 opcode = OpCodes.Add_Ovf_Un;
3057 opcode = OpCodes.Add;
3059 opcode = OpCodes.Add;
3062 case Operator.Subtraction:
3064 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3065 opcode = OpCodes.Sub_Ovf;
3066 else if (isUnsigned)
3067 opcode = OpCodes.Sub_Ovf_Un;
3069 opcode = OpCodes.Sub;
3071 opcode = OpCodes.Sub;
3074 case Operator.RightShift:
3076 opcode = OpCodes.Shr_Un;
3078 opcode = OpCodes.Shr;
3081 case Operator.LeftShift:
3082 opcode = OpCodes.Shl;
3085 case Operator.Equality:
3086 opcode = OpCodes.Ceq;
3089 case Operator.Inequality:
3090 ig.Emit (OpCodes.Ceq);
3091 ig.Emit (OpCodes.Ldc_I4_0);
3093 opcode = OpCodes.Ceq;
3096 case Operator.LessThan:
3098 opcode = OpCodes.Clt_Un;
3100 opcode = OpCodes.Clt;
3103 case Operator.GreaterThan:
3105 opcode = OpCodes.Cgt_Un;
3107 opcode = OpCodes.Cgt;
3110 case Operator.LessThanOrEqual:
3111 Type lt = left.Type;
3113 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
3114 ig.Emit (OpCodes.Cgt_Un);
3116 ig.Emit (OpCodes.Cgt);
3117 ig.Emit (OpCodes.Ldc_I4_0);
3119 opcode = OpCodes.Ceq;
3122 case Operator.GreaterThanOrEqual:
3123 Type le = left.Type;
3125 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3126 ig.Emit (OpCodes.Clt_Un);
3128 ig.Emit (OpCodes.Clt);
3130 ig.Emit (OpCodes.Ldc_I4_0);
3132 opcode = OpCodes.Ceq;
3135 case Operator.BitwiseOr:
3136 opcode = OpCodes.Or;
3139 case Operator.BitwiseAnd:
3140 opcode = OpCodes.And;
3143 case Operator.ExclusiveOr:
3144 opcode = OpCodes.Xor;
3148 throw new Exception ("This should not happen: Operator = "
3149 + oper.ToString ());
3157 // Object created by Binary when the binary operator uses an method instead of being
3158 // a binary operation that maps to a CIL binary operation.
3160 public class BinaryMethod : Expression {
3161 public MethodBase method;
3162 public ArrayList Arguments;
3164 public BinaryMethod (Type t, MethodBase m, ArrayList args)
3169 eclass = ExprClass.Value;
3172 public override Expression DoResolve (EmitContext ec)
3177 public override void Emit (EmitContext ec)
3179 ILGenerator ig = ec.ig;
3181 if (Arguments != null)
3182 Invocation.EmitArguments (ec, method, Arguments, false, null);
3184 if (method is MethodInfo)
3185 ig.Emit (OpCodes.Call, (MethodInfo) method);
3187 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3192 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3193 // b, c, d... may be strings or objects.
3195 public class StringConcat : Expression {
3197 bool invalid = false;
3198 bool emit_conv_done = false;
3200 // Are we also concating objects?
3202 bool is_strings_only = true;
3204 public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
3207 type = TypeManager.string_type;
3208 eclass = ExprClass.Value;
3210 operands = new ArrayList (2);
3215 public override Expression DoResolve (EmitContext ec)
3223 public void Append (EmitContext ec, Expression operand)
3228 if (operand is StringConstant && operands.Count != 0) {
3229 StringConstant last_operand = operands [operands.Count - 1] as StringConstant;
3230 if (last_operand != null) {
3231 operands [operands.Count - 1] = new StringConstant (last_operand.Value + ((StringConstant) operand).Value);
3237 // Conversion to object
3239 if (operand.Type != TypeManager.string_type) {
3240 Expression no = Convert.ImplicitConversion (ec, operand, TypeManager.object_type, loc);
3243 Binary.Error_OperatorCannotBeApplied (loc, "+", TypeManager.string_type, operand.Type);
3249 operands.Add (operand);
3252 public override void Emit (EmitContext ec)
3254 MethodInfo concat_method = null;
3257 // Do conversion to arguments; check for strings only
3260 // This can get called multiple times, so we have to deal with that.
3261 if (!emit_conv_done) {
3262 emit_conv_done = true;
3263 for (int i = 0; i < operands.Count; i ++) {
3264 Expression e = (Expression) operands [i];
3265 is_strings_only &= e.Type == TypeManager.string_type;
3268 for (int i = 0; i < operands.Count; i ++) {
3269 Expression e = (Expression) operands [i];
3271 if (! is_strings_only && e.Type == TypeManager.string_type) {
3272 // need to make sure this is an object, because the EmitParams
3273 // method might look at the type of this expression, see it is a
3274 // string and emit a string [] when we want an object [];
3276 e = new EmptyCast (e, TypeManager.object_type);
3278 operands [i] = new Argument (e, Argument.AType.Expression);
3283 // Find the right method
3285 switch (operands.Count) {
3288 // This should not be possible, because simple constant folding
3289 // is taken care of in the Binary code.
3291 throw new Exception ("how did you get here?");
3294 concat_method = is_strings_only ?
3295 TypeManager.string_concat_string_string :
3296 TypeManager.string_concat_object_object ;
3299 concat_method = is_strings_only ?
3300 TypeManager.string_concat_string_string_string :
3301 TypeManager.string_concat_object_object_object ;
3305 // There is not a 4 param overlaod for object (the one that there is
3306 // is actually a varargs methods, and is only in corlib because it was
3307 // introduced there before.).
3309 if (!is_strings_only)
3312 concat_method = TypeManager.string_concat_string_string_string_string;
3315 concat_method = is_strings_only ?
3316 TypeManager.string_concat_string_dot_dot_dot :
3317 TypeManager.string_concat_object_dot_dot_dot ;
3321 Invocation.EmitArguments (ec, concat_method, operands, false, null);
3322 ec.ig.Emit (OpCodes.Call, concat_method);
3327 // Object created with +/= on delegates
3329 public class BinaryDelegate : Expression {
3333 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3338 eclass = ExprClass.Value;
3341 public override Expression DoResolve (EmitContext ec)
3346 public override void Emit (EmitContext ec)
3348 ILGenerator ig = ec.ig;
3350 Invocation.EmitArguments (ec, method, args, false, null);
3352 ig.Emit (OpCodes.Call, (MethodInfo) method);
3353 ig.Emit (OpCodes.Castclass, type);
3356 public Expression Right {
3358 Argument arg = (Argument) args [1];
3363 public bool IsAddition {
3365 return method == TypeManager.delegate_combine_delegate_delegate;
3371 // User-defined conditional logical operator
3372 public class ConditionalLogicalOperator : Expression {
3373 Expression left, right;
3376 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3379 eclass = ExprClass.Value;
3383 this.is_and = is_and;
3386 protected void Error19 ()
3388 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3391 protected void Error218 ()
3393 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3394 "declarations of operator true and operator false");
3397 Expression op_true, op_false, op;
3398 LocalTemporary left_temp;
3400 public override Expression DoResolve (EmitContext ec)
3403 Expression operator_group;
3405 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3406 if (operator_group == null) {
3411 left_temp = new LocalTemporary (ec, type);
3413 ArrayList arguments = new ArrayList ();
3414 arguments.Add (new Argument (left_temp, Argument.AType.Expression));
3415 arguments.Add (new Argument (right, Argument.AType.Expression));
3416 method = Invocation.OverloadResolve (
3417 ec, (MethodGroupExpr) operator_group, arguments, false, loc)
3419 if (method == null) {
3424 if (method.ReturnType != type) {
3425 Report.Error (217, loc, "In order to be applicable as a short circuit operator a user-defined logical operator `{0}' " +
3426 "must have the same return type as the type of its 2 parameters", TypeManager.CSharpSignature (method));
3430 op = new StaticCallExpr (method, arguments, loc);
3432 op_true = GetOperatorTrue (ec, left_temp, loc);
3433 op_false = GetOperatorFalse (ec, left_temp, loc);
3434 if ((op_true == null) || (op_false == null)) {
3442 public override void Emit (EmitContext ec)
3444 ILGenerator ig = ec.ig;
3445 Label false_target = ig.DefineLabel ();
3446 Label end_target = ig.DefineLabel ();
3449 left_temp.Store (ec);
3451 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
3452 left_temp.Emit (ec);
3453 ig.Emit (OpCodes.Br, end_target);
3454 ig.MarkLabel (false_target);
3456 ig.MarkLabel (end_target);
3460 public class PointerArithmetic : Expression {
3461 Expression left, right;
3465 // We assume that `l' is always a pointer
3467 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3473 is_add = is_addition;
3476 public override Expression DoResolve (EmitContext ec)
3478 eclass = ExprClass.Variable;
3480 if (left.Type == TypeManager.void_ptr_type) {
3481 Error (242, "The operation in question is undefined on void pointers");
3488 public override void Emit (EmitContext ec)
3490 Type op_type = left.Type;
3491 ILGenerator ig = ec.ig;
3493 // It must be either array or fixed buffer
3494 Type element = TypeManager.HasElementType (op_type) ?
3495 element = TypeManager.GetElementType (op_type) :
3496 element = AttributeTester.GetFixedBuffer (((FieldExpr)left).FieldInfo).ElementType;
3498 int size = GetTypeSize (element);
3499 Type rtype = right.Type;
3501 if (rtype.IsPointer){
3503 // handle (pointer - pointer)
3507 ig.Emit (OpCodes.Sub);
3511 ig.Emit (OpCodes.Sizeof, element);
3513 IntLiteral.EmitInt (ig, size);
3514 ig.Emit (OpCodes.Div);
3516 ig.Emit (OpCodes.Conv_I8);
3519 // handle + and - on (pointer op int)
3522 ig.Emit (OpCodes.Conv_I);
3524 Constant right_const = right as Constant;
3525 if (right_const != null && size != 0) {
3526 Expression ex = ConstantFold.BinaryFold (ec, Binary.Operator.Multiply, new IntConstant (size), right_const, loc);
3534 ig.Emit (OpCodes.Sizeof, element);
3536 IntLiteral.EmitInt (ig, size);
3537 if (rtype == TypeManager.int64_type)
3538 ig.Emit (OpCodes.Conv_I8);
3539 else if (rtype == TypeManager.uint64_type)
3540 ig.Emit (OpCodes.Conv_U8);
3541 ig.Emit (OpCodes.Mul);
3545 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
3546 ig.Emit (OpCodes.Conv_I);
3549 ig.Emit (OpCodes.Add);
3551 ig.Emit (OpCodes.Sub);
3557 /// Implements the ternary conditional operator (?:)
3559 public class Conditional : Expression {
3560 Expression expr, trueExpr, falseExpr;
3562 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr)
3565 this.trueExpr = trueExpr;
3566 this.falseExpr = falseExpr;
3567 this.loc = expr.Location;
3570 public Expression Expr {
3576 public Expression TrueExpr {
3582 public Expression FalseExpr {
3588 public override Expression DoResolve (EmitContext ec)
3590 expr = expr.Resolve (ec);
3595 if (expr.Type != TypeManager.bool_type){
3596 expr = Expression.ResolveBoolean (
3603 trueExpr = trueExpr.Resolve (ec);
3604 falseExpr = falseExpr.Resolve (ec);
3606 if (trueExpr == null || falseExpr == null)
3609 eclass = ExprClass.Value;
3610 if (trueExpr.Type == falseExpr.Type)
3611 type = trueExpr.Type;
3614 Type true_type = trueExpr.Type;
3615 Type false_type = falseExpr.Type;
3618 // First, if an implicit conversion exists from trueExpr
3619 // to falseExpr, then the result type is of type falseExpr.Type
3621 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3624 // Check if both can convert implicitl to each other's type
3626 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3628 "Can not compute type of conditional expression " +
3629 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3630 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3631 "' convert implicitly to each other");
3636 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3640 Report.Error (173, loc, "Type of conditional expression cannot be determined because there is no implicit conversion between `{0}' and `{1}'",
3641 trueExpr.GetSignatureForError (), falseExpr.GetSignatureForError ());
3646 // Dead code optimalization
3647 if (expr is BoolConstant){
3648 BoolConstant bc = (BoolConstant) expr;
3650 Report.Warning (429, 4, bc.Value ? falseExpr.Location : trueExpr.Location, "Unreachable expression code detected");
3651 return bc.Value ? trueExpr : falseExpr;
3657 public override void Emit (EmitContext ec)
3659 ILGenerator ig = ec.ig;
3660 Label false_target = ig.DefineLabel ();
3661 Label end_target = ig.DefineLabel ();
3663 expr.EmitBranchable (ec, false_target, false);
3665 ig.Emit (OpCodes.Br, end_target);
3666 ig.MarkLabel (false_target);
3667 falseExpr.Emit (ec);
3668 ig.MarkLabel (end_target);
3676 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3677 public readonly string Name;
3678 public readonly Block Block;
3679 public LocalInfo local_info;
3682 LocalTemporary temp;
3684 public LocalVariableReference (Block block, string name, Location l)
3689 eclass = ExprClass.Variable;
3693 // Setting `is_readonly' to false will allow you to create a writable
3694 // reference to a read-only variable. This is used by foreach and using.
3696 public LocalVariableReference (Block block, string name, Location l,
3697 LocalInfo local_info, bool is_readonly)
3698 : this (block, name, l)
3700 this.local_info = local_info;
3701 this.is_readonly = is_readonly;
3704 public VariableInfo VariableInfo {
3706 return local_info.VariableInfo;
3710 public bool IsReadOnly {
3716 protected Expression DoResolveBase (EmitContext ec, Expression lvalue_right_side)
3718 if (local_info == null) {
3719 local_info = Block.GetLocalInfo (Name);
3722 if (lvalue_right_side == EmptyExpression.Null)
3723 local_info.Used = true;
3725 is_readonly = local_info.ReadOnly;
3728 type = local_info.VariableType;
3730 VariableInfo variable_info = local_info.VariableInfo;
3731 if (lvalue_right_side != null){
3733 if (lvalue_right_side is LocalVariableReference || lvalue_right_side == EmptyExpression.Null)
3734 Report.Error (1657, loc, "Cannot pass `{0}' as a ref or out argument because it is a `{1}'",
3735 Name, local_info.GetReadOnlyContext ());
3737 Report.Error (1656, loc, "Cannot assign to `{0}' because it is a `{1}'",
3738 Name, local_info.GetReadOnlyContext ());
3742 if (variable_info != null)
3743 variable_info.SetAssigned (ec);
3746 Expression e = Block.GetConstantExpression (Name);
3748 local_info.Used = true;
3749 eclass = ExprClass.Value;
3750 return e.Resolve (ec);
3753 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3756 if (lvalue_right_side == null)
3757 local_info.Used = true;
3759 if (ec.CurrentAnonymousMethod != null){
3761 // If we are referencing a variable from the external block
3762 // flag it for capturing
3764 if ((local_info.Block.Toplevel != ec.CurrentBlock.Toplevel) ||
3765 ec.CurrentAnonymousMethod.IsIterator)
3767 if (local_info.AddressTaken){
3768 AnonymousMethod.Error_AddressOfCapturedVar (local_info.Name, loc);
3771 ec.CaptureVariable (local_info);
3778 public override Expression DoResolve (EmitContext ec)
3780 return DoResolveBase (ec, null);
3783 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3785 Expression ret = DoResolveBase (ec, right_side);
3787 CheckObsoleteAttribute (ret.Type);
3792 public bool VerifyFixed ()
3794 // A local Variable is always fixed.
3798 public override int GetHashCode()
3800 return Name.GetHashCode ();
3803 public override bool Equals (object obj)
3805 LocalVariableReference lvr = obj as LocalVariableReference;
3809 return Name == lvr.Name && Block == lvr.Block;
3812 public override void Emit (EmitContext ec)
3814 ILGenerator ig = ec.ig;
3816 if (local_info.FieldBuilder == null){
3818 // A local variable on the local CLR stack
3820 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3823 // A local variable captured by anonymous methods.
3826 ec.EmitCapturedVariableInstance (local_info);
3828 ig.Emit (OpCodes.Ldfld, local_info.FieldBuilder);
3832 public void Emit (EmitContext ec, bool leave_copy)
3836 ec.ig.Emit (OpCodes.Dup);
3837 if (local_info.FieldBuilder != null){
3838 temp = new LocalTemporary (ec, Type);
3844 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3846 ILGenerator ig = ec.ig;
3847 prepared = prepare_for_load;
3849 if (local_info.FieldBuilder == null){
3851 // A local variable on the local CLR stack
3853 if (local_info.LocalBuilder == null)
3854 throw new Exception ("This should not happen: both Field and Local are null");
3858 ec.ig.Emit (OpCodes.Dup);
3859 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3862 // A local variable captured by anonymous methods or itereators.
3864 ec.EmitCapturedVariableInstance (local_info);
3866 if (prepare_for_load)
3867 ig.Emit (OpCodes.Dup);
3870 ig.Emit (OpCodes.Dup);
3871 temp = new LocalTemporary (ec, Type);
3874 ig.Emit (OpCodes.Stfld, local_info.FieldBuilder);
3880 public void AddressOf (EmitContext ec, AddressOp mode)
3882 ILGenerator ig = ec.ig;
3884 if (local_info.FieldBuilder == null){
3886 // A local variable on the local CLR stack
3888 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3891 // A local variable captured by anonymous methods or iterators
3893 ec.EmitCapturedVariableInstance (local_info);
3894 ig.Emit (OpCodes.Ldflda, local_info.FieldBuilder);
3898 public override string ToString ()
3900 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3905 /// This represents a reference to a parameter in the intermediate
3908 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3914 public Parameter.Modifier mod;
3915 public bool is_ref, is_out, prepared;
3929 LocalTemporary temp;
3931 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3938 eclass = ExprClass.Variable;
3941 public ParameterReference (InternalParameters pars, Block block, int idx, Location loc)
3942 : this (pars.Parameters, block, idx, pars.ParameterName (idx), loc)
3945 public VariableInfo VariableInfo {
3949 public bool VerifyFixed ()
3951 // A parameter is fixed if it's a value parameter (i.e., no modifier like out, ref, param).
3952 return mod == Parameter.Modifier.NONE;
3955 public bool IsAssigned (EmitContext ec, Location loc)
3957 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsAssigned (vi))
3960 Report.Error (269, loc,
3961 "Use of unassigned out parameter `{0}'", name);
3965 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3967 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3970 Report.Error (170, loc,
3971 "Use of possibly unassigned field `" + field_name + "'");
3975 public void SetAssigned (EmitContext ec)
3977 if (is_out && ec.DoFlowAnalysis)
3978 ec.CurrentBranching.SetAssigned (vi);
3981 public void SetFieldAssigned (EmitContext ec, string field_name)
3983 if (is_out && ec.DoFlowAnalysis)
3984 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3987 protected void DoResolveBase (EmitContext ec)
3989 type = pars.GetParameterInfo (ec, idx, out mod);
3990 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3991 is_out = (mod & Parameter.Modifier.OUT) != 0;
3992 eclass = ExprClass.Variable;
3995 vi = block.ParameterMap [idx];
3997 if (ec.CurrentAnonymousMethod != null){
3999 Report.Error (1628, Location, "Cannot use ref or out parameter `{0}' inside an anonymous method block",
4005 // If we are referencing the parameter from the external block
4006 // flag it for capturing
4008 //Console.WriteLine ("Is parameter `{0}' local? {1}", name, block.IsLocalParameter (name));
4009 if (!block.Toplevel.IsLocalParameter (name)){
4010 ec.CaptureParameter (name, type, idx);
4015 public override int GetHashCode()
4017 return name.GetHashCode ();
4020 public override bool Equals (object obj)
4022 ParameterReference pr = obj as ParameterReference;
4026 return name == pr.name && block == pr.block;
4030 // Notice that for ref/out parameters, the type exposed is not the
4031 // same type exposed externally.
4034 // externally we expose "int&"
4035 // here we expose "int".
4037 // We record this in "is_ref". This means that the type system can treat
4038 // the type as it is expected, but when we generate the code, we generate
4039 // the alternate kind of code.
4041 public override Expression DoResolve (EmitContext ec)
4045 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
4051 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4060 static public void EmitLdArg (ILGenerator ig, int x)
4064 case 0: ig.Emit (OpCodes.Ldarg_0); break;
4065 case 1: ig.Emit (OpCodes.Ldarg_1); break;
4066 case 2: ig.Emit (OpCodes.Ldarg_2); break;
4067 case 3: ig.Emit (OpCodes.Ldarg_3); break;
4068 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
4071 ig.Emit (OpCodes.Ldarg, x);
4075 // This method is used by parameters that are references, that are
4076 // being passed as references: we only want to pass the pointer (that
4077 // is already stored in the parameter, not the address of the pointer,
4078 // and not the value of the variable).
4080 public void EmitLoad (EmitContext ec)
4082 ILGenerator ig = ec.ig;
4085 if (!ec.MethodIsStatic)
4088 EmitLdArg (ig, arg_idx);
4091 // FIXME: Review for anonymous methods
4095 public override void Emit (EmitContext ec)
4100 public void Emit (EmitContext ec, bool leave_copy)
4102 ILGenerator ig = ec.ig;
4105 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4107 throw new InternalErrorException ();
4109 ec.EmitParameter (name);
4113 if (!ec.MethodIsStatic)
4116 EmitLdArg (ig, arg_idx);
4120 ec.ig.Emit (OpCodes.Dup);
4123 // If we are a reference, we loaded on the stack a pointer
4124 // Now lets load the real value
4126 LoadFromPtr (ig, type);
4130 ec.ig.Emit (OpCodes.Dup);
4133 temp = new LocalTemporary (ec, type);
4139 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
4141 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4142 ec.EmitAssignParameter (name, source, leave_copy, prepare_for_load);
4146 ILGenerator ig = ec.ig;
4149 prepared = prepare_for_load;
4151 if (!ec.MethodIsStatic)
4154 if (is_ref && !prepared)
4155 EmitLdArg (ig, arg_idx);
4160 ec.ig.Emit (OpCodes.Dup);
4164 temp = new LocalTemporary (ec, type);
4168 StoreFromPtr (ig, type);
4174 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
4176 ig.Emit (OpCodes.Starg, arg_idx);
4180 public void AddressOf (EmitContext ec, AddressOp mode)
4182 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4183 ec.EmitAddressOfParameter (name);
4189 if (!ec.MethodIsStatic)
4194 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
4196 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
4199 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
4201 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
4208 /// Used for arguments to New(), Invocation()
4210 public class Argument {
4211 public enum AType : byte {
4218 public readonly AType ArgType;
4219 public Expression Expr;
4221 public Argument (Expression expr, AType type)
4224 this.ArgType = type;
4227 public Argument (Expression expr)
4230 this.ArgType = AType.Expression;
4235 if (ArgType == AType.Ref || ArgType == AType.Out)
4236 return TypeManager.GetReferenceType (Expr.Type);
4242 public Parameter.Modifier Modifier
4247 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
4250 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
4253 return Parameter.Modifier.NONE;
4258 public static string FullDesc (Argument a)
4260 if (a.ArgType == AType.ArgList)
4263 return (a.ArgType == AType.Ref ? "ref " :
4264 (a.ArgType == AType.Out ? "out " : "")) +
4265 TypeManager.CSharpName (a.Expr.Type);
4268 public bool ResolveMethodGroup (EmitContext ec, Location loc)
4270 // FIXME: csc doesn't report any error if you try to use `ref' or
4271 // `out' in a delegate creation expression.
4272 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4279 void Error_LValueRequired (Location loc)
4281 Report.Error (1510, loc, "A ref or out argument must be an assignable variable");
4284 public bool Resolve (EmitContext ec, Location loc)
4286 bool old_do_flow_analysis = ec.DoFlowAnalysis;
4287 ec.DoFlowAnalysis = true;
4289 if (ArgType == AType.Ref) {
4290 ec.InRefOutArgumentResolving = true;
4291 Expr = Expr.Resolve (ec);
4292 ec.InRefOutArgumentResolving = false;
4294 ec.DoFlowAnalysis = old_do_flow_analysis;
4298 Expr = Expr.DoResolveLValue (ec, Expr);
4300 Error_LValueRequired (loc);
4301 } else if (ArgType == AType.Out) {
4302 ec.InRefOutArgumentResolving = true;
4303 Expr = Expr.DoResolveLValue (ec, EmptyExpression.Null);
4304 ec.InRefOutArgumentResolving = false;
4307 Error_LValueRequired (loc);
4310 Expr = Expr.Resolve (ec);
4312 ec.DoFlowAnalysis = old_do_flow_analysis;
4317 if (ArgType == AType.Expression)
4321 // Catch errors where fields of a MarshalByRefObject are passed as ref or out
4322 // This is only allowed for `this'
4324 FieldExpr fe = Expr as FieldExpr;
4325 if (fe != null && !fe.IsStatic){
4326 Expression instance = fe.InstanceExpression;
4328 if (instance.GetType () != typeof (This)){
4329 if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
4330 Report.SymbolRelatedToPreviousError (fe.InstanceExpression.Type);
4331 Report.Warning (197, 1, loc,
4332 "Passing `{0}' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class",
4333 fe.GetSignatureForError ());
4340 if (Expr.eclass != ExprClass.Variable){
4342 // We just probe to match the CSC output
4344 if (Expr.eclass == ExprClass.PropertyAccess ||
4345 Expr.eclass == ExprClass.IndexerAccess){
4346 Report.Error (206, loc, "A property or indexer `{0}' may not be passed as an out or ref parameter",
4347 Expr.GetSignatureForError ());
4349 Error_LValueRequired (loc);
4357 public void Emit (EmitContext ec)
4360 // Ref and Out parameters need to have their addresses taken.
4362 // ParameterReferences might already be references, so we want
4363 // to pass just the value
4365 if (ArgType == AType.Ref || ArgType == AType.Out){
4366 AddressOp mode = AddressOp.Store;
4368 if (ArgType == AType.Ref)
4369 mode |= AddressOp.Load;
4371 if (Expr is ParameterReference){
4372 ParameterReference pr = (ParameterReference) Expr;
4378 pr.AddressOf (ec, mode);
4381 if (Expr is IMemoryLocation)
4382 ((IMemoryLocation) Expr).AddressOf (ec, mode);
4384 Error_LValueRequired (Expr.Location);
4394 /// Invocation of methods or delegates.
4396 public class Invocation : ExpressionStatement {
4397 public readonly ArrayList Arguments;
4400 MethodBase method = null;
4403 // arguments is an ArrayList, but we do not want to typecast,
4404 // as it might be null.
4406 // FIXME: only allow expr to be a method invocation or a
4407 // delegate invocation (7.5.5)
4409 public Invocation (Expression expr, ArrayList arguments)
4412 Arguments = arguments;
4413 loc = expr.Location;
4416 public Expression Expr {
4423 /// Determines "better conversion" as specified in 14.4.2.3
4425 /// Returns : p if a->p is better,
4426 /// q if a->q is better,
4427 /// null if neither is better
4429 static Type BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
4431 Type argument_type = a.Type;
4432 Expression argument_expr = a.Expr;
4434 if (argument_type == null)
4435 throw new Exception ("Expression of type " + a.Expr +
4436 " does not resolve its type");
4438 if (p == null || q == null)
4439 throw new InternalErrorException ("BetterConversion Got a null conversion");
4444 if (argument_expr is NullLiteral) {
4446 // If the argument is null and one of the types to compare is 'object' and
4447 // the other is a reference type, we prefer the other.
4449 // This follows from the usual rules:
4450 // * There is an implicit conversion from 'null' to type 'object'
4451 // * There is an implicit conversion from 'null' to any reference type
4452 // * There is an implicit conversion from any reference type to type 'object'
4453 // * There is no implicit conversion from type 'object' to other reference types
4454 // => Conversion of 'null' to a reference type is better than conversion to 'object'
4456 // FIXME: This probably isn't necessary, since the type of a NullLiteral is the
4457 // null type. I think it used to be 'object' and thus needed a special
4458 // case to avoid the immediately following two checks.
4460 if (!p.IsValueType && q == TypeManager.object_type)
4462 if (!q.IsValueType && p == TypeManager.object_type)
4466 if (argument_type == p)
4469 if (argument_type == q)
4472 Expression p_tmp = new EmptyExpression (p);
4473 Expression q_tmp = new EmptyExpression (q);
4475 bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
4476 bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
4478 if (p_to_q && !q_to_p)
4481 if (q_to_p && !p_to_q)
4484 if (p == TypeManager.sbyte_type)
4485 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4486 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4488 if (q == TypeManager.sbyte_type)
4489 if (p == TypeManager.byte_type || p == TypeManager.ushort_type ||
4490 p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4493 if (p == TypeManager.short_type)
4494 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4495 q == TypeManager.uint64_type)
4497 if (q == TypeManager.short_type)
4498 if (p == TypeManager.ushort_type || p == TypeManager.uint32_type ||
4499 p == TypeManager.uint64_type)
4502 if (p == TypeManager.int32_type)
4503 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4505 if (q == TypeManager.int32_type)
4506 if (p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4509 if (p == TypeManager.int64_type)
4510 if (q == TypeManager.uint64_type)
4512 if (q == TypeManager.int64_type)
4513 if (p == TypeManager.uint64_type)
4520 /// Determines "Better function" between candidate
4521 /// and the current best match
4524 /// Returns an integer indicating :
4525 /// false if candidate ain't better
4526 /// true if candidate is better than the current best match
4528 static bool BetterFunction (EmitContext ec, ArrayList args, int argument_count,
4529 MethodBase candidate, bool candidate_params,
4530 MethodBase best, bool best_params, Location loc)
4532 ParameterData candidate_pd = TypeManager.GetParameterData (candidate);
4533 ParameterData best_pd = TypeManager.GetParameterData (best);
4535 bool better_at_least_one = false;
4537 for (int j = 0; j < argument_count; ++j) {
4538 Argument a = (Argument) args [j];
4540 Type ct = TypeManager.TypeToCoreType (candidate_pd.ParameterType (j));
4541 Type bt = TypeManager.TypeToCoreType (best_pd.ParameterType (j));
4543 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4544 if (candidate_params)
4545 ct = TypeManager.GetElementType (ct);
4547 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4549 bt = TypeManager.GetElementType (bt);
4555 Type better = BetterConversion (ec, a, ct, bt, loc);
4557 // for each argument, the conversion to 'ct' should be no worse than
4558 // the conversion to 'bt'.
4562 // for at least one argument, the conversion to 'ct' should be better than
4563 // the conversion to 'bt'.
4565 better_at_least_one = true;
4568 if (better_at_least_one)
4572 // This handles the case
4574 // Add (float f1, float f2, float f3);
4575 // Add (params decimal [] foo);
4577 // The call Add (3, 4, 5) should be ambiguous. Without this check, the
4578 // first candidate would've chosen as better.
4584 // This handles the following cases:
4586 // Trim () is better than Trim (params char[] chars)
4587 // Concat (string s1, string s2, string s3) is better than
4588 // Concat (string s1, params string [] srest)
4590 return !candidate_params && best_params;
4593 static bool IsOverride (MethodBase cand_method, MethodBase base_method)
4595 if (!IsAncestralType (base_method.DeclaringType, cand_method.DeclaringType))
4598 ParameterData cand_pd = TypeManager.GetParameterData (cand_method);
4599 ParameterData base_pd = TypeManager.GetParameterData (base_method);
4601 if (cand_pd.Count != base_pd.Count)
4604 for (int j = 0; j < cand_pd.Count; ++j) {
4605 Parameter.Modifier cm = cand_pd.ParameterModifier (j);
4606 Parameter.Modifier bm = base_pd.ParameterModifier (j);
4607 Type ct = TypeManager.TypeToCoreType (cand_pd.ParameterType (j));
4608 Type bt = TypeManager.TypeToCoreType (base_pd.ParameterType (j));
4610 if (cm != bm || ct != bt)
4617 public static string FullMethodDesc (MethodBase mb)
4623 if (mb is MethodInfo) {
4624 sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
4628 sb = new StringBuilder ();
4630 sb.Append (TypeManager.CSharpSignature (mb));
4631 return sb.ToString ();
4634 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4636 MemberInfo [] miset;
4637 MethodGroupExpr union;
4642 return (MethodGroupExpr) mg2;
4645 return (MethodGroupExpr) mg1;
4648 MethodGroupExpr left_set = null, right_set = null;
4649 int length1 = 0, length2 = 0;
4651 left_set = (MethodGroupExpr) mg1;
4652 length1 = left_set.Methods.Length;
4654 right_set = (MethodGroupExpr) mg2;
4655 length2 = right_set.Methods.Length;
4657 ArrayList common = new ArrayList ();
4659 foreach (MethodBase r in right_set.Methods){
4660 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
4664 miset = new MemberInfo [length1 + length2 - common.Count];
4665 left_set.Methods.CopyTo (miset, 0);
4669 foreach (MethodBase r in right_set.Methods) {
4670 if (!common.Contains (r))
4674 union = new MethodGroupExpr (miset, loc);
4679 public static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4680 ArrayList arguments, int arg_count,
4681 ref MethodBase candidate)
4683 return IsParamsMethodApplicable (
4684 ec, me, arguments, arg_count, false, ref candidate) ||
4685 IsParamsMethodApplicable (
4686 ec, me, arguments, arg_count, true, ref candidate);
4691 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4692 ArrayList arguments, int arg_count,
4693 bool do_varargs, ref MethodBase candidate)
4695 return IsParamsMethodApplicable (
4696 ec, arguments, arg_count, candidate, do_varargs);
4700 /// Determines if the candidate method, if a params method, is applicable
4701 /// in its expanded form to the given set of arguments
4703 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
4704 int arg_count, MethodBase candidate,
4707 ParameterData pd = TypeManager.GetParameterData (candidate);
4709 int pd_count = pd.Count;
4713 int count = pd_count - 1;
4715 if (pd.ParameterModifier (count) != Parameter.Modifier.ARGLIST)
4717 if (pd_count != arg_count)
4720 if (pd.ParameterModifier (count) != Parameter.Modifier.PARAMS)
4724 if (count > arg_count)
4727 if (pd_count == 1 && arg_count == 0)
4731 // If we have come this far, the case which
4732 // remains is when the number of parameters is
4733 // less than or equal to the argument count.
4735 for (int i = 0; i < count; ++i) {
4737 Argument a = (Argument) arguments [i];
4739 Parameter.Modifier a_mod = a.Modifier &
4740 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4741 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4742 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4744 if (a_mod == p_mod) {
4746 if (a_mod == Parameter.Modifier.NONE)
4747 if (!Convert.ImplicitConversionExists (ec,
4749 pd.ParameterType (i)))
4752 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4753 Type pt = pd.ParameterType (i);
4756 pt = TypeManager.GetReferenceType (pt);
4767 Argument a = (Argument) arguments [count];
4768 if (!(a.Expr is Arglist))
4774 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4776 for (int i = pd_count - 1; i < arg_count; i++) {
4777 Argument a = (Argument) arguments [i];
4779 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4786 public static bool IsApplicable (EmitContext ec, MethodGroupExpr me,
4787 ArrayList arguments, int arg_count,
4788 ref MethodBase candidate)
4790 return IsApplicable (ec, arguments, arg_count, candidate);
4794 /// Determines if the candidate method is applicable (section 14.4.2.1)
4795 /// to the given set of arguments
4797 static bool IsApplicable (EmitContext ec, ArrayList arguments, int arg_count,
4798 MethodBase candidate)
4800 ParameterData pd = TypeManager.GetParameterData (candidate);
4802 if (arg_count != pd.Count)
4805 for (int i = arg_count; i > 0; ) {
4808 Argument a = (Argument) arguments [i];
4810 Parameter.Modifier a_mod = a.Modifier &
4811 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4812 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4813 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4815 if (a_mod == p_mod ||
4816 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4817 if (a_mod == Parameter.Modifier.NONE) {
4818 if (!Convert.ImplicitConversionExists (ec,
4820 pd.ParameterType (i)))
4824 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4825 Type pt = pd.ParameterType (i);
4828 pt = TypeManager.GetReferenceType (pt);
4840 static private bool IsAncestralType (Type first_type, Type second_type)
4842 return first_type != second_type &&
4843 (second_type.IsSubclassOf (first_type) ||
4844 TypeManager.ImplementsInterface (second_type, first_type));
4848 /// Find the Applicable Function Members (7.4.2.1)
4850 /// me: Method Group expression with the members to select.
4851 /// it might contain constructors or methods (or anything
4852 /// that maps to a method).
4854 /// Arguments: ArrayList containing resolved Argument objects.
4856 /// loc: The location if we want an error to be reported, or a Null
4857 /// location for "probing" purposes.
4859 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4860 /// that is the best match of me on Arguments.
4863 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4864 ArrayList Arguments, bool may_fail,
4867 MethodBase method = null;
4868 bool method_params = false;
4869 Type applicable_type = null;
4871 ArrayList candidates = new ArrayList (2);
4872 ArrayList candidate_overrides = null;
4875 // Used to keep a map between the candidate
4876 // and whether it is being considered in its
4877 // normal or expanded form
4879 // false is normal form, true is expanded form
4881 Hashtable candidate_to_form = null;
4883 if (Arguments != null)
4884 arg_count = Arguments.Count;
4886 if ((me.Name == "Invoke") &&
4887 TypeManager.IsDelegateType (me.DeclaringType)) {
4888 Error_InvokeOnDelegate (loc);
4892 MethodBase[] methods = me.Methods;
4895 // First we construct the set of applicable methods
4897 bool is_sorted = true;
4898 for (int i = 0; i < methods.Length; i++){
4899 Type decl_type = methods [i].DeclaringType;
4902 // If we have already found an applicable method
4903 // we eliminate all base types (Section 14.5.5.1)
4905 if ((applicable_type != null) &&
4906 IsAncestralType (decl_type, applicable_type))
4910 // Methods marked 'override' don't take part in 'applicable_type'
4911 // computation, nor in the actual overload resolution.
4912 // However, they still need to be emitted instead of a base virtual method.
4913 // We avoid doing the 'applicable' test here, since it'll anyway be applied
4914 // to the base virtual function, and IsOverride is much faster than IsApplicable.
4916 if (!me.IsBase && TypeManager.IsOverride (methods [i])) {
4917 if (candidate_overrides == null)
4918 candidate_overrides = new ArrayList ();
4919 candidate_overrides.Add (methods [i]);
4924 // Check if candidate is applicable (section 14.4.2.1)
4925 // Is candidate applicable in normal form?
4927 bool is_applicable = IsApplicable (
4928 ec, me, Arguments, arg_count, ref methods [i]);
4930 if (!is_applicable &&
4931 (IsParamsMethodApplicable (
4932 ec, me, Arguments, arg_count, ref methods [i]))) {
4933 MethodBase candidate = methods [i];
4934 if (candidate_to_form == null)
4935 candidate_to_form = new PtrHashtable ();
4936 candidate_to_form [candidate] = candidate;
4937 // Candidate is applicable in expanded form
4938 is_applicable = true;
4944 candidates.Add (methods [i]);
4946 if (applicable_type == null)
4947 applicable_type = decl_type;
4948 else if (applicable_type != decl_type) {
4950 if (IsAncestralType (applicable_type, decl_type))
4951 applicable_type = decl_type;
4955 int candidate_top = candidates.Count;
4957 if (applicable_type == null) {
4959 // Okay so we have failed to find anything so we
4960 // return by providing info about the closest match
4962 int errors = Report.Errors;
4963 for (int i = 0; i < methods.Length; ++i) {
4964 MethodBase c = (MethodBase) methods [i];
4965 ParameterData pd = TypeManager.GetParameterData (c);
4967 if (pd.Count != arg_count)
4970 VerifyArgumentsCompat (ec, Arguments, arg_count,
4971 c, false, null, may_fail, loc);
4975 if (!may_fail && errors == Report.Errors) {
4976 string report_name = me.Name;
4977 if (report_name == ".ctor")
4978 report_name = me.DeclaringType.ToString ();
4979 Error_WrongNumArguments (loc, report_name, arg_count);
4987 // At this point, applicable_type is _one_ of the most derived types
4988 // in the set of types containing the methods in this MethodGroup.
4989 // Filter the candidates so that they only contain methods from the
4990 // most derived types.
4993 int finalized = 0; // Number of finalized candidates
4996 // Invariant: applicable_type is a most derived type
4998 // We'll try to complete Section 14.5.5.1 for 'applicable_type' by
4999 // eliminating all it's base types. At the same time, we'll also move
5000 // every unrelated type to the end of the array, and pick the next
5001 // 'applicable_type'.
5003 Type next_applicable_type = null;
5004 int j = finalized; // where to put the next finalized candidate
5005 int k = finalized; // where to put the next undiscarded candidate
5006 for (int i = finalized; i < candidate_top; ++i) {
5007 MethodBase candidate = (MethodBase) candidates [i];
5008 Type decl_type = candidate.DeclaringType;
5010 if (decl_type == applicable_type) {
5011 candidates [k++] = candidates [j];
5012 candidates [j++] = candidates [i];
5016 if (IsAncestralType (decl_type, applicable_type))
5019 if (next_applicable_type != null &&
5020 IsAncestralType (decl_type, next_applicable_type))
5023 candidates [k++] = candidates [i];
5025 if (next_applicable_type == null ||
5026 IsAncestralType (next_applicable_type, decl_type))
5027 next_applicable_type = decl_type;
5030 applicable_type = next_applicable_type;
5033 } while (applicable_type != null);
5037 // Now we actually find the best method
5040 method = (MethodBase) candidates [0];
5041 method_params = candidate_to_form != null && candidate_to_form.Contains (method);
5042 for (int ix = 1; ix < candidate_top; ix++){
5043 MethodBase candidate = (MethodBase) candidates [ix];
5045 if (candidate == method)
5048 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
5050 if (BetterFunction (ec, Arguments, arg_count,
5051 candidate, cand_params,
5052 method, method_params, loc)) {
5054 method_params = cand_params;
5059 // Now check that there are no ambiguities i.e the selected method
5060 // should be better than all the others
5062 MethodBase ambiguous = null;
5063 for (int ix = 0; ix < candidate_top; ix++){
5064 MethodBase candidate = (MethodBase) candidates [ix];
5066 if (candidate == method)
5069 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
5070 if (!BetterFunction (ec, Arguments, arg_count,
5071 method, method_params,
5072 candidate, cand_params,
5074 Report.SymbolRelatedToPreviousError (candidate);
5075 ambiguous = candidate;
5079 if (ambiguous != null) {
5080 Report.SymbolRelatedToPreviousError (method);
5081 Report.Error (121, loc, "The call is ambiguous between the following methods or properties: `{0}' and `{1}'",
5082 TypeManager.CSharpSignature (ambiguous), TypeManager.CSharpSignature (method));
5087 // If the method is a virtual function, pick an override closer to the LHS type.
5089 if (!me.IsBase && method.IsVirtual) {
5090 if (TypeManager.IsOverride (method))
5091 throw new InternalErrorException (
5092 "Should not happen. An 'override' method took part in overload resolution: " + method);
5094 if (candidate_overrides != null)
5095 foreach (MethodBase candidate in candidate_overrides) {
5096 if (IsOverride (candidate, method))
5102 // And now check if the arguments are all
5103 // compatible, perform conversions if
5104 // necessary etc. and return if everything is
5107 if (!VerifyArgumentsCompat (ec, Arguments, arg_count, method,
5108 method_params, null, may_fail, loc))
5111 if (method != null) {
5112 IMethodData data = TypeManager.GetMethod (method);
5114 data.SetMemberIsUsed ();
5119 public static void Error_WrongNumArguments (Location loc, String name, int arg_count)
5121 Report.Error (1501, loc, "No overload for method `{0}' takes `{1}' arguments",
5125 static void Error_InvokeOnDelegate (Location loc)
5127 Report.Error (1533, loc,
5128 "Invoke cannot be called directly on a delegate");
5131 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
5132 Type delegate_type, Argument a, ParameterData expected_par)
5134 if (delegate_type == null)
5135 Report.Error (1502, loc, "The best overloaded method match for `{0}' has some invalid arguments",
5136 TypeManager.CSharpSignature (method));
5138 Report.Error (1594, loc, "Delegate `{0}' has some invalid arguments",
5139 TypeManager.CSharpName (delegate_type));
5141 string par_desc = expected_par.ParameterDesc (idx);
5143 if (a.Modifier != expected_par.ParameterModifier (idx)) {
5144 if ((expected_par.ParameterModifier (idx) & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) == 0)
5145 Report.Error (1615, loc, "Argument `{0}' should not be passed with the `{1}' keyword",
5146 idx + 1, Parameter.GetModifierSignature (a.Modifier));
5148 Report.Error (1620, loc, "Argument `{0}' must be passed with the `{1}' keyword",
5149 idx + 1, Parameter.GetModifierSignature (expected_par.ParameterModifier (idx)));
5153 Report.Error (1503, loc,
5154 String.Format ("Argument {0}: Cannot convert from `{1}' to `{2}'",
5155 idx + 1, Argument.FullDesc (a), par_desc));
5158 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
5159 int arg_count, MethodBase method,
5160 bool chose_params_expanded,
5161 Type delegate_type, bool may_fail,
5164 ParameterData pd = TypeManager.GetParameterData (method);
5165 int pd_count = pd.Count;
5167 for (int j = 0; j < arg_count; j++) {
5168 Argument a = (Argument) Arguments [j];
5169 Expression a_expr = a.Expr;
5170 Type parameter_type = pd.ParameterType (j);
5171 Parameter.Modifier pm = pd.ParameterModifier (j);
5173 if (pm == Parameter.Modifier.PARAMS){
5174 if ((pm & ~Parameter.Modifier.PARAMS) != a.Modifier) {
5176 Error_InvalidArguments (
5177 loc, j, method, delegate_type,
5182 if (chose_params_expanded)
5183 parameter_type = TypeManager.GetElementType (parameter_type);
5184 } else if (pm == Parameter.Modifier.ARGLIST){
5190 if (pd.ParameterModifier (j) != a.Modifier){
5192 Error_InvalidArguments (
5193 loc, j, method, delegate_type,
5202 if (!a.Type.Equals (parameter_type)){
5205 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
5209 Error_InvalidArguments (loc, j, method, delegate_type, a, pd);
5214 // Update the argument with the implicit conversion
5220 if (parameter_type.IsPointer){
5227 Parameter.Modifier a_mod = a.Modifier &
5228 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5229 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
5230 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5232 if (a_mod != p_mod &&
5233 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
5235 Invocation.Error_InvalidArguments (loc, j, method, null, a, pd);
5245 public override Expression DoResolve (EmitContext ec)
5248 // First, resolve the expression that is used to
5249 // trigger the invocation
5251 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
5255 if (!(expr is MethodGroupExpr)) {
5256 Type expr_type = expr.Type;
5258 if (expr_type != null){
5259 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
5261 return (new DelegateInvocation (
5262 this.expr, Arguments, loc)).Resolve (ec);
5266 if (!(expr is MethodGroupExpr)){
5267 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup, loc);
5272 // Next, evaluate all the expressions in the argument list
5274 if (Arguments != null){
5275 foreach (Argument a in Arguments){
5276 if (!a.Resolve (ec, loc))
5281 MethodGroupExpr mg = (MethodGroupExpr) expr;
5282 method = OverloadResolve (ec, mg, Arguments, false, loc);
5287 MethodInfo mi = method as MethodInfo;
5289 type = TypeManager.TypeToCoreType (mi.ReturnType);
5290 Expression iexpr = mg.InstanceExpression;
5292 if (iexpr == null ||
5293 iexpr is This || iexpr is EmptyExpression ||
5294 mg.IdenticalTypeName) {
5295 mg.InstanceExpression = null;
5297 MemberExpr.error176 (loc, TypeManager.CSharpSignature (mi));
5301 if (iexpr == null || iexpr is EmptyExpression) {
5302 SimpleName.Error_ObjectRefRequired (ec, loc, TypeManager.CSharpSignature (mi));
5308 if (type.IsPointer){
5316 // Only base will allow this invocation to happen.
5318 if (mg.IsBase && method.IsAbstract){
5319 Error_CannotCallAbstractBase (TypeManager.CSharpSignature (method));
5323 if (Arguments == null && method.Name == "Finalize") {
5325 Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
5327 Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
5331 if ((method.Attributes & MethodAttributes.SpecialName) != 0) {
5332 if (TypeManager.LookupDeclSpace (method.DeclaringType) != null || TypeManager.IsSpecialMethod (method)) {
5333 Report.Error (571, loc, "`{0}': cannot explicitly call operator or accessor",
5334 TypeManager.CSharpSignature (method, true));
5339 if (mg.InstanceExpression != null)
5340 mg.InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
5342 eclass = ExprClass.Value;
5347 // Emits the list of arguments as an array
5349 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
5351 ILGenerator ig = ec.ig;
5352 int count = arguments.Count - idx;
5353 Argument a = (Argument) arguments [idx];
5354 Type t = a.Expr.Type;
5356 IntConstant.EmitInt (ig, count);
5357 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
5359 int top = arguments.Count;
5360 for (int j = idx; j < top; j++){
5361 a = (Argument) arguments [j];
5363 ig.Emit (OpCodes.Dup);
5364 IntConstant.EmitInt (ig, j - idx);
5367 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj);
5369 ig.Emit (OpCodes.Ldelema, t);
5374 ig.Emit (OpCodes.Stobj, t);
5381 /// Emits a list of resolved Arguments that are in the arguments
5384 /// The MethodBase argument might be null if the
5385 /// emission of the arguments is known not to contain
5386 /// a `params' field (for example in constructors or other routines
5387 /// that keep their arguments in this structure)
5389 /// if `dup_args' is true, a copy of the arguments will be left
5390 /// on the stack. If `dup_args' is true, you can specify `this_arg'
5391 /// which will be duplicated before any other args. Only EmitCall
5392 /// should be using this interface.
5394 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments, bool dup_args, LocalTemporary this_arg)
5398 pd = TypeManager.GetParameterData (mb);
5402 LocalTemporary [] temps = null;
5405 temps = new LocalTemporary [arguments.Count];
5408 // If we are calling a params method with no arguments, special case it
5410 if (arguments == null){
5411 if (pd != null && pd.Count > 0 &&
5412 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
5413 ILGenerator ig = ec.ig;
5415 IntConstant.EmitInt (ig, 0);
5416 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
5422 int top = arguments.Count;
5424 for (int i = 0; i < top; i++){
5425 Argument a = (Argument) arguments [i];
5428 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
5430 // Special case if we are passing the same data as the
5431 // params argument, do not put it in an array.
5433 if (pd.ParameterType (i) == a.Type)
5436 EmitParams (ec, i, arguments);
5443 ec.ig.Emit (OpCodes.Dup);
5444 (temps [i] = new LocalTemporary (ec, a.Type)).Store (ec);
5449 if (this_arg != null)
5452 for (int i = 0; i < top; i ++)
5453 temps [i].Emit (ec);
5456 if (pd != null && pd.Count > top &&
5457 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
5458 ILGenerator ig = ec.ig;
5460 IntConstant.EmitInt (ig, 0);
5461 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
5465 static Type[] GetVarargsTypes (EmitContext ec, MethodBase mb,
5466 ArrayList arguments)
5468 ParameterData pd = TypeManager.GetParameterData (mb);
5470 if (arguments == null)
5471 return new Type [0];
5473 Argument a = (Argument) arguments [pd.Count - 1];
5474 Arglist list = (Arglist) a.Expr;
5476 return list.ArgumentTypes;
5480 /// This checks the ConditionalAttribute on the method
5482 static bool IsMethodExcluded (MethodBase method, EmitContext ec)
5484 if (method.IsConstructor)
5487 IMethodData md = TypeManager.GetMethod (method);
5489 return md.IsExcluded (ec);
5491 // For some methods (generated by delegate class) GetMethod returns null
5492 // because they are not included in builder_to_method table
5493 if (method.DeclaringType is TypeBuilder)
5496 return AttributeTester.IsConditionalMethodExcluded (method);
5500 /// is_base tells whether we want to force the use of the `call'
5501 /// opcode instead of using callvirt. Call is required to call
5502 /// a specific method, while callvirt will always use the most
5503 /// recent method in the vtable.
5505 /// is_static tells whether this is an invocation on a static method
5507 /// instance_expr is an expression that represents the instance
5508 /// it must be non-null if is_static is false.
5510 /// method is the method to invoke.
5512 /// Arguments is the list of arguments to pass to the method or constructor.
5514 public static void EmitCall (EmitContext ec, bool is_base,
5515 bool is_static, Expression instance_expr,
5516 MethodBase method, ArrayList Arguments, Location loc)
5518 EmitCall (ec, is_base, is_static, instance_expr, method, Arguments, loc, false, false);
5521 // `dup_args' leaves an extra copy of the arguments on the stack
5522 // `omit_args' does not leave any arguments at all.
5523 // So, basically, you could make one call with `dup_args' set to true,
5524 // and then another with `omit_args' set to true, and the two calls
5525 // would have the same set of arguments. However, each argument would
5526 // only have been evaluated once.
5527 public static void EmitCall (EmitContext ec, bool is_base,
5528 bool is_static, Expression instance_expr,
5529 MethodBase method, ArrayList Arguments, Location loc,
5530 bool dup_args, bool omit_args)
5532 ILGenerator ig = ec.ig;
5533 bool struct_call = false;
5534 bool this_call = false;
5535 LocalTemporary this_arg = null;
5537 Type decl_type = method.DeclaringType;
5539 if (!RootContext.StdLib) {
5540 // Replace any calls to the system's System.Array type with calls to
5541 // the newly created one.
5542 if (method == TypeManager.system_int_array_get_length)
5543 method = TypeManager.int_array_get_length;
5544 else if (method == TypeManager.system_int_array_get_rank)
5545 method = TypeManager.int_array_get_rank;
5546 else if (method == TypeManager.system_object_array_clone)
5547 method = TypeManager.object_array_clone;
5548 else if (method == TypeManager.system_int_array_get_length_int)
5549 method = TypeManager.int_array_get_length_int;
5550 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5551 method = TypeManager.int_array_get_lower_bound_int;
5552 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5553 method = TypeManager.int_array_get_upper_bound_int;
5554 else if (method == TypeManager.system_void_array_copyto_array_int)
5555 method = TypeManager.void_array_copyto_array_int;
5558 if (ec.TestObsoleteMethodUsage) {
5560 // This checks ObsoleteAttribute on the method and on the declaring type
5562 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
5564 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
5567 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
5569 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
5573 if (IsMethodExcluded (method, ec))
5577 if (instance_expr == EmptyExpression.Null) {
5578 SimpleName.Error_ObjectRefRequired (ec, loc, TypeManager.CSharpSignature (method));
5582 this_call = instance_expr is This;
5583 if (decl_type.IsValueType || (!this_call && instance_expr.Type.IsValueType))
5589 // Push the instance expression
5591 if (instance_expr.Type.IsValueType) {
5593 // Special case: calls to a function declared in a
5594 // reference-type with a value-type argument need
5595 // to have their value boxed.
5596 if (decl_type.IsValueType) {
5598 // If the expression implements IMemoryLocation, then
5599 // we can optimize and use AddressOf on the
5602 // If not we have to use some temporary storage for
5604 if (instance_expr is IMemoryLocation) {
5605 ((IMemoryLocation)instance_expr).
5606 AddressOf (ec, AddressOp.LoadStore);
5608 LocalTemporary temp = new LocalTemporary (ec, instance_expr.Type);
5609 instance_expr.Emit (ec);
5611 temp.AddressOf (ec, AddressOp.Load);
5614 // avoid the overhead of doing this all the time.
5616 t = TypeManager.GetReferenceType (instance_expr.Type);
5618 instance_expr.Emit (ec);
5619 ig.Emit (OpCodes.Box, instance_expr.Type);
5620 t = TypeManager.object_type;
5623 instance_expr.Emit (ec);
5624 t = instance_expr.Type;
5628 this_arg = new LocalTemporary (ec, t);
5629 ig.Emit (OpCodes.Dup);
5630 this_arg.Store (ec);
5636 EmitArguments (ec, method, Arguments, dup_args, this_arg);
5639 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
5640 call_op = OpCodes.Call;
5642 call_op = OpCodes.Callvirt;
5644 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
5645 Type[] varargs_types = GetVarargsTypes (ec, method, Arguments);
5646 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
5653 // and DoFoo is not virtual, you can omit the callvirt,
5654 // because you don't need the null checking behavior.
5656 if (method is MethodInfo)
5657 ig.Emit (call_op, (MethodInfo) method);
5659 ig.Emit (call_op, (ConstructorInfo) method);
5662 public override void Emit (EmitContext ec)
5664 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5666 EmitCall (ec, mg.IsBase, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5669 public override void EmitStatement (EmitContext ec)
5674 // Pop the return value if there is one
5676 if (method is MethodInfo){
5677 Type ret = ((MethodInfo)method).ReturnType;
5678 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5679 ec.ig.Emit (OpCodes.Pop);
5684 public class InvocationOrCast : ExpressionStatement
5687 Expression argument;
5689 public InvocationOrCast (Expression expr, Expression argument)
5692 this.argument = argument;
5693 this.loc = expr.Location;
5696 public override Expression DoResolve (EmitContext ec)
5699 // First try to resolve it as a cast.
5701 TypeExpr te = expr.ResolveAsTypeTerminal (ec, true);
5703 Cast cast = new Cast (te, argument, loc);
5704 return cast.Resolve (ec);
5708 // This can either be a type or a delegate invocation.
5709 // Let's just resolve it and see what we'll get.
5711 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5716 // Ok, so it's a Cast.
5718 if (expr.eclass == ExprClass.Type) {
5719 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
5720 return cast.Resolve (ec);
5724 // It's a delegate invocation.
5726 if (!TypeManager.IsDelegateType (expr.Type)) {
5727 Error (149, "Method name expected");
5731 ArrayList args = new ArrayList ();
5732 args.Add (new Argument (argument, Argument.AType.Expression));
5733 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5734 return invocation.Resolve (ec);
5739 Error (201, "Only assignment, call, increment, decrement and new object " +
5740 "expressions can be used as a statement");
5743 public override ExpressionStatement ResolveStatement (EmitContext ec)
5746 // First try to resolve it as a cast.
5748 TypeExpr te = expr.ResolveAsTypeTerminal (ec, true);
5755 // This can either be a type or a delegate invocation.
5756 // Let's just resolve it and see what we'll get.
5758 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5759 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5765 // It's a delegate invocation.
5767 if (!TypeManager.IsDelegateType (expr.Type)) {
5768 Error (149, "Method name expected");
5772 ArrayList args = new ArrayList ();
5773 args.Add (new Argument (argument, Argument.AType.Expression));
5774 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5775 return invocation.ResolveStatement (ec);
5778 public override void Emit (EmitContext ec)
5780 throw new Exception ("Cannot happen");
5783 public override void EmitStatement (EmitContext ec)
5785 throw new Exception ("Cannot happen");
5790 // This class is used to "disable" the code generation for the
5791 // temporary variable when initializing value types.
5793 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5794 public void AddressOf (EmitContext ec, AddressOp Mode)
5801 /// Implements the new expression
5803 public class New : ExpressionStatement, IMemoryLocation {
5804 public readonly ArrayList Arguments;
5807 // During bootstrap, it contains the RequestedType,
5808 // but if `type' is not null, it *might* contain a NewDelegate
5809 // (because of field multi-initialization)
5811 public Expression RequestedType;
5813 MethodBase method = null;
5816 // If set, the new expression is for a value_target, and
5817 // we will not leave anything on the stack.
5819 Expression value_target;
5820 bool value_target_set = false;
5822 public New (Expression requested_type, ArrayList arguments, Location l)
5824 RequestedType = requested_type;
5825 Arguments = arguments;
5829 public bool SetValueTypeVariable (Expression value)
5831 value_target = value;
5832 value_target_set = true;
5833 if (!(value_target is IMemoryLocation)){
5834 Error_UnexpectedKind (null, "variable", loc);
5841 // This function is used to disable the following code sequence for
5842 // value type initialization:
5844 // AddressOf (temporary)
5848 // Instead the provide will have provided us with the address on the
5849 // stack to store the results.
5851 static Expression MyEmptyExpression;
5853 public void DisableTemporaryValueType ()
5855 if (MyEmptyExpression == null)
5856 MyEmptyExpression = new EmptyAddressOf ();
5859 // To enable this, look into:
5860 // test-34 and test-89 and self bootstrapping.
5862 // For instance, we can avoid a copy by using `newobj'
5863 // instead of Call + Push-temp on value types.
5864 // value_target = MyEmptyExpression;
5869 /// Converts complex core type syntax like 'new int ()' to simple constant
5871 public static Constant Constantify (Type t)
5873 if (t == TypeManager.int32_type)
5874 return new IntConstant (0);
5875 if (t == TypeManager.uint32_type)
5876 return new UIntConstant (0);
5877 if (t == TypeManager.int64_type)
5878 return new LongConstant (0);
5879 if (t == TypeManager.uint64_type)
5880 return new ULongConstant (0);
5881 if (t == TypeManager.float_type)
5882 return new FloatConstant (0);
5883 if (t == TypeManager.double_type)
5884 return new DoubleConstant (0);
5885 if (t == TypeManager.short_type)
5886 return new ShortConstant (0);
5887 if (t == TypeManager.ushort_type)
5888 return new UShortConstant (0);
5889 if (t == TypeManager.sbyte_type)
5890 return new SByteConstant (0);
5891 if (t == TypeManager.byte_type)
5892 return new ByteConstant (0);
5893 if (t == TypeManager.char_type)
5894 return new CharConstant ('\0');
5895 if (t == TypeManager.bool_type)
5896 return new BoolConstant (false);
5897 if (t == TypeManager.decimal_type)
5898 return new DecimalConstant (0);
5903 public override Expression DoResolve (EmitContext ec)
5906 // The New DoResolve might be called twice when initializing field
5907 // expressions (see EmitFieldInitializers, the call to
5908 // GetInitializerExpression will perform a resolve on the expression,
5909 // and later the assign will trigger another resolution
5911 // This leads to bugs (#37014)
5914 if (RequestedType is NewDelegate)
5915 return RequestedType;
5919 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec, false);
5923 type = texpr.ResolveType (ec);
5925 if (Arguments == null) {
5926 Expression c = Constantify (type);
5931 CheckObsoleteAttribute (type);
5933 if (TypeManager.IsDelegateType (type)) {
5934 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5935 if (RequestedType != null)
5936 if (!(RequestedType is DelegateCreation))
5937 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
5938 return RequestedType;
5941 if (type.IsAbstract && type.IsSealed) {
5942 Report.Error (712, loc, "Cannot create an instance of the static class `{0}'", TypeManager.CSharpName (type));
5946 if (type.IsInterface || type.IsAbstract){
5947 Report.Error (144, loc, "Cannot create an instance of the abstract class or interface `{0}'", TypeManager.CSharpName (type));
5951 bool is_struct = type.IsValueType;
5952 eclass = ExprClass.Value;
5955 // SRE returns a match for .ctor () on structs (the object constructor),
5956 // so we have to manually ignore it.
5958 if (is_struct && Arguments == null)
5961 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
5962 Expression ml = MemberLookupFinal (ec, type, type, ".ctor",
5963 MemberTypes.Constructor, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5968 MethodGroupExpr mg = ml as MethodGroupExpr;
5971 ml.Error_UnexpectedKind (ec, "method group", loc);
5975 if (Arguments != null){
5976 foreach (Argument a in Arguments){
5977 if (!a.Resolve (ec, loc))
5982 method = Invocation.OverloadResolve (ec, mg, Arguments, false, loc);
5983 if (method == null) {
5984 if (almostMatchedMembers.Count != 0)
5985 MemberLookupFailed (ec, type, type, ".ctor", null, true, loc);
5993 // This DoEmit can be invoked in two contexts:
5994 // * As a mechanism that will leave a value on the stack (new object)
5995 // * As one that wont (init struct)
5997 // You can control whether a value is required on the stack by passing
5998 // need_value_on_stack. The code *might* leave a value on the stack
5999 // so it must be popped manually
6001 // If we are dealing with a ValueType, we have a few
6002 // situations to deal with:
6004 // * The target is a ValueType, and we have been provided
6005 // the instance (this is easy, we are being assigned).
6007 // * The target of New is being passed as an argument,
6008 // to a boxing operation or a function that takes a
6011 // In this case, we need to create a temporary variable
6012 // that is the argument of New.
6014 // Returns whether a value is left on the stack
6016 bool DoEmit (EmitContext ec, bool need_value_on_stack)
6018 bool is_value_type = type.IsValueType;
6019 ILGenerator ig = ec.ig;
6024 // Allow DoEmit() to be called multiple times.
6025 // We need to create a new LocalTemporary each time since
6026 // you can't share LocalBuilders among ILGeneators.
6027 if (!value_target_set)
6028 value_target = new LocalTemporary (ec, type);
6030 ml = (IMemoryLocation) value_target;
6031 ml.AddressOf (ec, AddressOp.Store);
6035 Invocation.EmitArguments (ec, method, Arguments, false, null);
6039 ig.Emit (OpCodes.Initobj, type);
6041 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6042 if (need_value_on_stack){
6043 value_target.Emit (ec);
6048 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
6053 public override void Emit (EmitContext ec)
6058 public override void EmitStatement (EmitContext ec)
6060 if (DoEmit (ec, false))
6061 ec.ig.Emit (OpCodes.Pop);
6064 public void AddressOf (EmitContext ec, AddressOp Mode)
6066 if (!type.IsValueType){
6068 // We throw an exception. So far, I believe we only need to support
6070 // foreach (int j in new StructType ())
6073 throw new Exception ("AddressOf should not be used for classes");
6076 if (!value_target_set)
6077 value_target = new LocalTemporary (ec, type);
6079 IMemoryLocation ml = (IMemoryLocation) value_target;
6080 ml.AddressOf (ec, AddressOp.Store);
6082 Invocation.EmitArguments (ec, method, Arguments, false, null);
6085 ec.ig.Emit (OpCodes.Initobj, type);
6087 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6089 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
6094 /// 14.5.10.2: Represents an array creation expression.
6098 /// There are two possible scenarios here: one is an array creation
6099 /// expression that specifies the dimensions and optionally the
6100 /// initialization data and the other which does not need dimensions
6101 /// specified but where initialization data is mandatory.
6103 public class ArrayCreation : Expression {
6104 Expression requested_base_type;
6105 ArrayList initializers;
6108 // The list of Argument types.
6109 // This is used to construct the `newarray' or constructor signature
6111 ArrayList arguments;
6114 // Method used to create the array object.
6116 MethodBase new_method = null;
6118 Type array_element_type;
6119 Type underlying_type;
6120 bool is_one_dimensional = false;
6121 bool is_builtin_type = false;
6122 bool expect_initializers = false;
6123 int num_arguments = 0;
6127 ArrayList array_data;
6132 // The number of array initializers that we can handle
6133 // via the InitializeArray method - through EmitStaticInitializers
6135 int num_automatic_initializers;
6137 const int max_automatic_initializers = 6;
6139 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
6141 this.requested_base_type = requested_base_type;
6142 this.initializers = initializers;
6146 arguments = new ArrayList ();
6148 foreach (Expression e in exprs) {
6149 arguments.Add (new Argument (e, Argument.AType.Expression));
6154 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
6156 this.requested_base_type = requested_base_type;
6157 this.initializers = initializers;
6161 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
6163 //string tmp = rank.Substring (rank.LastIndexOf ('['));
6165 //dimensions = tmp.Length - 1;
6166 expect_initializers = true;
6169 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
6171 StringBuilder sb = new StringBuilder (rank);
6174 for (int i = 1; i < idx_count; i++)
6179 return new ComposedCast (base_type, sb.ToString (), loc);
6182 void Error_IncorrectArrayInitializer ()
6184 Error (178, "Invalid rank specifier: expected `,' or `]'");
6187 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
6189 if (specified_dims) {
6190 Argument a = (Argument) arguments [idx];
6192 if (!a.Resolve (ec, loc))
6195 if (!(a.Expr is Constant)) {
6196 Error (150, "A constant value is expected");
6200 int value = (int) ((Constant) a.Expr).GetValue ();
6202 if (value != probe.Count) {
6203 Error_IncorrectArrayInitializer ();
6207 bounds [idx] = value;
6210 int child_bounds = -1;
6211 for (int i = 0; i < probe.Count; ++i) {
6212 object o = probe [i];
6213 if (o is ArrayList) {
6214 ArrayList sub_probe = o as ArrayList;
6215 int current_bounds = sub_probe.Count;
6217 if (child_bounds == -1)
6218 child_bounds = current_bounds;
6220 else if (child_bounds != current_bounds){
6221 Error_IncorrectArrayInitializer ();
6224 if (specified_dims && (idx + 1 >= arguments.Count)){
6225 Error (623, "Array initializers can only be used in a variable or field initializer. Try using a new expression instead");
6229 bool ret = CheckIndices (ec, sub_probe, idx + 1, specified_dims);
6233 if (child_bounds != -1){
6234 Error_IncorrectArrayInitializer ();
6238 Expression tmp = (Expression) o;
6239 tmp = tmp.Resolve (ec);
6244 // Console.WriteLine ("I got: " + tmp);
6245 // Handle initialization from vars, fields etc.
6247 Expression conv = Convert.ImplicitConversionRequired (
6248 ec, tmp, underlying_type, loc);
6253 if (conv is StringConstant || conv is DecimalConstant || conv is NullCast) {
6254 // These are subclasses of Constant that can appear as elements of an
6255 // array that cannot be statically initialized (with num_automatic_initializers
6256 // > max_automatic_initializers), so num_automatic_initializers should be left as zero.
6257 array_data.Add (conv);
6258 } else if (conv is Constant) {
6259 // These are the types of Constant that can appear in arrays that can be
6260 // statically allocated.
6261 array_data.Add (conv);
6262 num_automatic_initializers++;
6264 array_data.Add (conv);
6271 public void UpdateIndices (EmitContext ec)
6274 for (ArrayList probe = initializers; probe != null;) {
6275 if (probe.Count > 0 && probe [0] is ArrayList) {
6276 Expression e = new IntConstant (probe.Count);
6277 arguments.Add (new Argument (e, Argument.AType.Expression));
6279 bounds [i++] = probe.Count;
6281 probe = (ArrayList) probe [0];
6284 Expression e = new IntConstant (probe.Count);
6285 arguments.Add (new Argument (e, Argument.AType.Expression));
6287 bounds [i++] = probe.Count;
6294 public bool ValidateInitializers (EmitContext ec, Type array_type)
6296 if (initializers == null) {
6297 if (expect_initializers)
6303 if (underlying_type == null)
6307 // We use this to store all the date values in the order in which we
6308 // will need to store them in the byte blob later
6310 array_data = new ArrayList ();
6311 bounds = new Hashtable ();
6315 if (arguments != null) {
6316 ret = CheckIndices (ec, initializers, 0, true);
6319 arguments = new ArrayList ();
6321 ret = CheckIndices (ec, initializers, 0, false);
6328 if (arguments.Count != dimensions) {
6329 Error_IncorrectArrayInitializer ();
6338 // Creates the type of the array
6340 bool LookupType (EmitContext ec)
6342 StringBuilder array_qualifier = new StringBuilder (rank);
6345 // `In the first form allocates an array instace of the type that results
6346 // from deleting each of the individual expression from the expression list'
6348 if (num_arguments > 0) {
6349 array_qualifier.Append ("[");
6350 for (int i = num_arguments-1; i > 0; i--)
6351 array_qualifier.Append (",");
6352 array_qualifier.Append ("]");
6358 TypeExpr array_type_expr;
6359 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
6360 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec, false);
6361 if (array_type_expr == null)
6364 type = array_type_expr.ResolveType (ec);
6366 if (!type.IsArray) {
6367 Error (622, "Can only use array initializer expressions to assign to array types. Try using a new expression instead.");
6370 underlying_type = TypeManager.GetElementType (type);
6371 dimensions = type.GetArrayRank ();
6376 public override Expression DoResolve (EmitContext ec)
6380 if (!LookupType (ec))
6384 // First step is to validate the initializers and fill
6385 // in any missing bits
6387 if (!ValidateInitializers (ec, type))
6390 if (arguments == null)
6393 arg_count = arguments.Count;
6394 foreach (Argument a in arguments){
6395 if (!a.Resolve (ec, loc))
6398 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
6399 if (real_arg == null)
6406 array_element_type = TypeManager.GetElementType (type);
6408 if (array_element_type.IsAbstract && array_element_type.IsSealed) {
6409 Report.Error (719, loc, "`{0}': array elements cannot be of static type", TypeManager.CSharpName (array_element_type));
6413 if (arg_count == 1) {
6414 is_one_dimensional = true;
6415 eclass = ExprClass.Value;
6419 is_builtin_type = TypeManager.IsBuiltinType (type);
6421 if (is_builtin_type) {
6424 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
6425 AllBindingFlags, loc);
6427 if (!(ml is MethodGroupExpr)) {
6428 ml.Error_UnexpectedKind (ec, "method group", loc);
6433 Error (-6, "New invocation: Can not find a constructor for " +
6434 "this argument list");
6438 new_method = Invocation.OverloadResolve (
6439 ec, (MethodGroupExpr) ml, arguments, false, loc);
6441 if (new_method == null) {
6442 Error (-6, "New invocation: Can not find a constructor for " +
6443 "this argument list");
6447 eclass = ExprClass.Value;
6450 ModuleBuilder mb = CodeGen.Module.Builder;
6451 ArrayList args = new ArrayList ();
6453 if (arguments != null) {
6454 for (int i = 0; i < arg_count; i++)
6455 args.Add (TypeManager.int32_type);
6458 Type [] arg_types = null;
6461 arg_types = new Type [args.Count];
6463 args.CopyTo (arg_types, 0);
6465 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
6468 if (new_method == null) {
6469 Error (-6, "New invocation: Can not find a constructor for " +
6470 "this argument list");
6474 eclass = ExprClass.Value;
6479 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
6484 int count = array_data.Count;
6486 if (underlying_type.IsEnum)
6487 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
6489 factor = GetTypeSize (underlying_type);
6491 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
6493 data = new byte [(count * factor + 4) & ~3];
6496 for (int i = 0; i < count; ++i) {
6497 object v = array_data [i];
6499 if (v is EnumConstant)
6500 v = ((EnumConstant) v).Child;
6502 if (v is Constant && !(v is StringConstant))
6503 v = ((Constant) v).GetValue ();
6509 if (underlying_type == TypeManager.int64_type){
6510 if (!(v is Expression)){
6511 long val = (long) v;
6513 for (int j = 0; j < factor; ++j) {
6514 data [idx + j] = (byte) (val & 0xFF);
6518 } else if (underlying_type == TypeManager.uint64_type){
6519 if (!(v is Expression)){
6520 ulong val = (ulong) v;
6522 for (int j = 0; j < factor; ++j) {
6523 data [idx + j] = (byte) (val & 0xFF);
6527 } else if (underlying_type == TypeManager.float_type) {
6528 if (!(v is Expression)){
6529 element = BitConverter.GetBytes ((float) v);
6531 for (int j = 0; j < factor; ++j)
6532 data [idx + j] = element [j];
6534 } else if (underlying_type == TypeManager.double_type) {
6535 if (!(v is Expression)){
6536 element = BitConverter.GetBytes ((double) v);
6538 for (int j = 0; j < factor; ++j)
6539 data [idx + j] = element [j];
6541 } else if (underlying_type == TypeManager.char_type){
6542 if (!(v is Expression)){
6543 int val = (int) ((char) v);
6545 data [idx] = (byte) (val & 0xff);
6546 data [idx+1] = (byte) (val >> 8);
6548 } else if (underlying_type == TypeManager.short_type){
6549 if (!(v is Expression)){
6550 int val = (int) ((short) v);
6552 data [idx] = (byte) (val & 0xff);
6553 data [idx+1] = (byte) (val >> 8);
6555 } else if (underlying_type == TypeManager.ushort_type){
6556 if (!(v is Expression)){
6557 int val = (int) ((ushort) v);
6559 data [idx] = (byte) (val & 0xff);
6560 data [idx+1] = (byte) (val >> 8);
6562 } else if (underlying_type == TypeManager.int32_type) {
6563 if (!(v is Expression)){
6566 data [idx] = (byte) (val & 0xff);
6567 data [idx+1] = (byte) ((val >> 8) & 0xff);
6568 data [idx+2] = (byte) ((val >> 16) & 0xff);
6569 data [idx+3] = (byte) (val >> 24);
6571 } else if (underlying_type == TypeManager.uint32_type) {
6572 if (!(v is Expression)){
6573 uint val = (uint) v;
6575 data [idx] = (byte) (val & 0xff);
6576 data [idx+1] = (byte) ((val >> 8) & 0xff);
6577 data [idx+2] = (byte) ((val >> 16) & 0xff);
6578 data [idx+3] = (byte) (val >> 24);
6580 } else if (underlying_type == TypeManager.sbyte_type) {
6581 if (!(v is Expression)){
6582 sbyte val = (sbyte) v;
6583 data [idx] = (byte) val;
6585 } else if (underlying_type == TypeManager.byte_type) {
6586 if (!(v is Expression)){
6587 byte val = (byte) v;
6588 data [idx] = (byte) val;
6590 } else if (underlying_type == TypeManager.bool_type) {
6591 if (!(v is Expression)){
6592 bool val = (bool) v;
6593 data [idx] = (byte) (val ? 1 : 0);
6595 } else if (underlying_type == TypeManager.decimal_type){
6596 if (!(v is Expression)){
6597 int [] bits = Decimal.GetBits ((decimal) v);
6600 // FIXME: For some reason, this doesn't work on the MS runtime.
6601 int [] nbits = new int [4];
6602 nbits [0] = bits [3];
6603 nbits [1] = bits [2];
6604 nbits [2] = bits [0];
6605 nbits [3] = bits [1];
6607 for (int j = 0; j < 4; j++){
6608 data [p++] = (byte) (nbits [j] & 0xff);
6609 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6610 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6611 data [p++] = (byte) (nbits [j] >> 24);
6615 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6624 // Emits the initializers for the array
6626 void EmitStaticInitializers (EmitContext ec)
6629 // First, the static data
6632 ILGenerator ig = ec.ig;
6634 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6636 fb = RootContext.MakeStaticData (data);
6638 ig.Emit (OpCodes.Dup);
6639 ig.Emit (OpCodes.Ldtoken, fb);
6640 ig.Emit (OpCodes.Call,
6641 TypeManager.void_initializearray_array_fieldhandle);
6645 // Emits pieces of the array that can not be computed at compile
6646 // time (variables and string locations).
6648 // This always expect the top value on the stack to be the array
6650 void EmitDynamicInitializers (EmitContext ec)
6652 ILGenerator ig = ec.ig;
6653 int dims = bounds.Count;
6654 int [] current_pos = new int [dims];
6655 int top = array_data.Count;
6657 MethodInfo set = null;
6661 ModuleBuilder mb = null;
6662 mb = CodeGen.Module.Builder;
6663 args = new Type [dims + 1];
6666 for (j = 0; j < dims; j++)
6667 args [j] = TypeManager.int32_type;
6669 args [j] = array_element_type;
6671 set = mb.GetArrayMethod (
6673 CallingConventions.HasThis | CallingConventions.Standard,
6674 TypeManager.void_type, args);
6677 for (int i = 0; i < top; i++){
6679 Expression e = null;
6681 if (array_data [i] is Expression)
6682 e = (Expression) array_data [i];
6686 // Basically we do this for string literals and
6687 // other non-literal expressions
6689 if (e is EnumConstant){
6690 e = ((EnumConstant) e).Child;
6693 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6694 num_automatic_initializers <= max_automatic_initializers) {
6695 Type etype = e.Type;
6697 ig.Emit (OpCodes.Dup);
6699 for (int idx = 0; idx < dims; idx++)
6700 IntConstant.EmitInt (ig, current_pos [idx]);
6703 // If we are dealing with a struct, get the
6704 // address of it, so we can store it.
6707 etype.IsSubclassOf (TypeManager.value_type) &&
6708 (!TypeManager.IsBuiltinOrEnum (etype) ||
6709 etype == TypeManager.decimal_type)) {
6714 // Let new know that we are providing
6715 // the address where to store the results
6717 n.DisableTemporaryValueType ();
6720 ig.Emit (OpCodes.Ldelema, etype);
6727 OpCode op = ArrayAccess.GetStoreOpcode (etype, out is_stobj);
6729 ig.Emit (OpCodes.Stobj, etype);
6733 ig.Emit (OpCodes.Call, set);
6741 for (int j = dims - 1; j >= 0; j--){
6743 if (current_pos [j] < (int) bounds [j])
6745 current_pos [j] = 0;
6750 void EmitArrayArguments (EmitContext ec)
6752 ILGenerator ig = ec.ig;
6754 foreach (Argument a in arguments) {
6755 Type atype = a.Type;
6758 if (atype == TypeManager.uint64_type)
6759 ig.Emit (OpCodes.Conv_Ovf_U4);
6760 else if (atype == TypeManager.int64_type)
6761 ig.Emit (OpCodes.Conv_Ovf_I4);
6765 public override void Emit (EmitContext ec)
6767 ILGenerator ig = ec.ig;
6769 EmitArrayArguments (ec);
6770 if (is_one_dimensional)
6771 ig.Emit (OpCodes.Newarr, array_element_type);
6773 if (is_builtin_type)
6774 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6776 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6779 if (initializers != null){
6781 // FIXME: Set this variable correctly.
6783 bool dynamic_initializers = true;
6785 // This will never be true for array types that cannot be statically
6786 // initialized. num_automatic_initializers will always be zero. See
6788 if (num_automatic_initializers > max_automatic_initializers)
6789 EmitStaticInitializers (ec);
6791 if (dynamic_initializers)
6792 EmitDynamicInitializers (ec);
6796 public object EncodeAsAttribute ()
6798 if (!is_one_dimensional){
6799 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6803 if (array_data == null){
6804 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6808 object [] ret = new object [array_data.Count];
6810 foreach (Expression e in array_data){
6813 if (e is NullLiteral)
6816 if (!Attribute.GetAttributeArgumentExpression (e, Location, array_element_type, out v))
6826 /// Represents the `this' construct
6828 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6831 VariableInfo variable_info;
6833 public This (Block block, Location loc)
6839 public This (Location loc)
6844 public VariableInfo VariableInfo {
6845 get { return variable_info; }
6848 public bool VerifyFixed ()
6850 // Treat 'this' as a value parameter for the purpose of fixed variable determination.
6854 public bool ResolveBase (EmitContext ec)
6856 eclass = ExprClass.Variable;
6857 type = ec.ContainerType;
6860 Error (26, "Keyword `this' is not valid in a static property, static method, or static field initializer");
6864 if (block != null && block.Toplevel.ThisVariable != null)
6865 variable_info = block.Toplevel.ThisVariable.VariableInfo;
6867 if (ec.CurrentAnonymousMethod != null)
6873 public override Expression DoResolve (EmitContext ec)
6875 if (!ResolveBase (ec))
6878 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
6879 Error (188, "The `this' object cannot be used before all of its fields are assigned to");
6880 variable_info.SetAssigned (ec);
6884 if (ec.IsFieldInitializer) {
6885 Error (27, "Keyword `this' is not available in the current context");
6892 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6894 if (!ResolveBase (ec))
6897 if (variable_info != null)
6898 variable_info.SetAssigned (ec);
6900 if (ec.TypeContainer is Class){
6901 Error (1604, "Cannot assign to 'this' because it is read-only");
6908 public void Emit (EmitContext ec, bool leave_copy)
6912 ec.ig.Emit (OpCodes.Dup);
6915 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
6917 ILGenerator ig = ec.ig;
6919 if (ec.TypeContainer is Struct){
6923 ec.ig.Emit (OpCodes.Dup);
6924 ig.Emit (OpCodes.Stobj, type);
6926 throw new Exception ("how did you get here");
6930 public override void Emit (EmitContext ec)
6932 ILGenerator ig = ec.ig;
6935 if (ec.TypeContainer is Struct)
6936 ig.Emit (OpCodes.Ldobj, type);
6939 public override int GetHashCode()
6941 return block.GetHashCode ();
6944 public override bool Equals (object obj)
6946 This t = obj as This;
6950 return block == t.block;
6953 public void AddressOf (EmitContext ec, AddressOp mode)
6958 // FIGURE OUT WHY LDARG_S does not work
6960 // consider: struct X { int val; int P { set { val = value; }}}
6962 // Yes, this looks very bad. Look at `NOTAS' for
6964 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
6969 /// Represents the `__arglist' construct
6971 public class ArglistAccess : Expression
6973 public ArglistAccess (Location loc)
6978 public bool ResolveBase (EmitContext ec)
6980 eclass = ExprClass.Variable;
6981 type = TypeManager.runtime_argument_handle_type;
6985 public override Expression DoResolve (EmitContext ec)
6987 if (!ResolveBase (ec))
6990 if (ec.IsFieldInitializer || !ec.CurrentBlock.Toplevel.HasVarargs) {
6991 Error (190, "The __arglist construct is valid only within " +
6992 "a variable argument method.");
6999 public override void Emit (EmitContext ec)
7001 ec.ig.Emit (OpCodes.Arglist);
7006 /// Represents the `__arglist (....)' construct
7008 public class Arglist : Expression
7010 public readonly Argument[] Arguments;
7012 public Arglist (Argument[] args, Location l)
7018 public Type[] ArgumentTypes {
7020 Type[] retval = new Type [Arguments.Length];
7021 for (int i = 0; i < Arguments.Length; i++)
7022 retval [i] = Arguments [i].Type;
7027 public override Expression DoResolve (EmitContext ec)
7029 eclass = ExprClass.Variable;
7030 type = TypeManager.runtime_argument_handle_type;
7032 foreach (Argument arg in Arguments) {
7033 if (!arg.Resolve (ec, loc))
7040 public override void Emit (EmitContext ec)
7042 foreach (Argument arg in Arguments)
7048 // This produces the value that renders an instance, used by the iterators code
7050 public class ProxyInstance : Expression, IMemoryLocation {
7051 public override Expression DoResolve (EmitContext ec)
7053 eclass = ExprClass.Variable;
7054 type = ec.ContainerType;
7058 public override void Emit (EmitContext ec)
7060 ec.ig.Emit (OpCodes.Ldarg_0);
7064 public void AddressOf (EmitContext ec, AddressOp mode)
7066 ec.ig.Emit (OpCodes.Ldarg_0);
7071 /// Implements the typeof operator
7073 public class TypeOf : Expression {
7074 public Expression QueriedType;
7075 protected Type typearg;
7077 public TypeOf (Expression queried_type, Location l)
7079 QueriedType = queried_type;
7083 public override Expression DoResolve (EmitContext ec)
7085 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
7089 typearg = texpr.ResolveType (ec);
7091 if (typearg == TypeManager.void_type) {
7092 Error (673, "System.Void cannot be used from C#. Use typeof (void) to get the void type object");
7096 if (typearg.IsPointer && !ec.InUnsafe){
7100 CheckObsoleteAttribute (typearg);
7102 type = TypeManager.type_type;
7103 // Even though what is returned is a type object, it's treated as a value by the compiler.
7104 // In particular, 'typeof (Foo).X' is something totally different from 'Foo.X'.
7105 eclass = ExprClass.Value;
7109 public override void Emit (EmitContext ec)
7111 ec.ig.Emit (OpCodes.Ldtoken, typearg);
7112 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
7115 public Type TypeArg {
7116 get { return typearg; }
7121 /// Implements the `typeof (void)' operator
7123 public class TypeOfVoid : TypeOf {
7124 public TypeOfVoid (Location l) : base (null, l)
7129 public override Expression DoResolve (EmitContext ec)
7131 type = TypeManager.type_type;
7132 typearg = TypeManager.void_type;
7133 // See description in TypeOf.
7134 eclass = ExprClass.Value;
7140 /// Implements the sizeof expression
7142 public class SizeOf : Expression {
7143 public Expression QueriedType;
7146 public SizeOf (Expression queried_type, Location l)
7148 this.QueriedType = queried_type;
7152 public override Expression DoResolve (EmitContext ec)
7154 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
7158 type_queried = texpr.ResolveType (ec);
7160 int size_of = GetTypeSize (type_queried);
7162 return new IntConstant (size_of);
7166 Report.Error (233, loc, "`{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)",
7167 TypeManager.CSharpName (type_queried));
7171 CheckObsoleteAttribute (type_queried);
7173 if (!TypeManager.VerifyUnManaged (type_queried, loc)){
7177 type = TypeManager.int32_type;
7178 eclass = ExprClass.Value;
7182 public override void Emit (EmitContext ec)
7184 int size = GetTypeSize (type_queried);
7187 ec.ig.Emit (OpCodes.Sizeof, type_queried);
7189 IntConstant.EmitInt (ec.ig, size);
7194 /// Implements the qualified-alias-member (::) expression.
7196 public class QualifiedAliasMember : Expression
7198 string alias, identifier;
7200 public QualifiedAliasMember (string alias, string identifier, Location l)
7203 this.identifier = identifier;
7207 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
7209 if (alias == "global")
7210 return new MemberAccess (Namespace.Root, identifier, loc).ResolveAsTypeStep (ec, silent);
7212 int errors = Report.Errors;
7213 FullNamedExpression fne = ec.DeclSpace.NamespaceEntry.LookupAlias (alias);
7215 if (errors == Report.Errors)
7216 Report.Error (432, loc, "Alias `{0}' not found", alias);
7219 if (fne.eclass != ExprClass.Namespace) {
7221 Report.Error (431, loc, "`{0}' cannot be used with '::' since it denotes a type", alias);
7224 return new MemberAccess (fne, identifier, loc).ResolveAsTypeStep (ec, silent);
7227 public override Expression DoResolve (EmitContext ec)
7229 FullNamedExpression fne;
7230 if (alias == "global") {
7231 fne = Namespace.Root;
7233 int errors = Report.Errors;
7234 fne = ec.DeclSpace.NamespaceEntry.LookupAlias (alias);
7236 if (errors == Report.Errors)
7237 Report.Error (432, loc, "Alias `{0}' not found", alias);
7242 Expression retval = new MemberAccess (fne, identifier, loc).DoResolve (ec);
7246 if (!(retval is FullNamedExpression)) {
7247 Report.Error (687, loc, "The expression `{0}::{1}' did not resolve to a namespace or a type", alias, identifier);
7251 // We defer this check till the end to match the behaviour of CSC
7252 if (fne.eclass != ExprClass.Namespace) {
7253 Report.Error (431, loc, "`{0}' cannot be used with '::' since it denotes a type", alias);
7259 public override void Emit (EmitContext ec)
7261 throw new InternalErrorException ("QualifiedAliasMember found in resolved tree");
7265 public override string ToString ()
7267 return alias + "::" + identifier;
7270 public override string GetSignatureForError ()
7277 /// Implements the member access expression
7279 public class MemberAccess : Expression {
7280 public readonly string Identifier; // TODO: LocatedToken
7283 public MemberAccess (Expression expr, string id, Location l)
7290 public Expression Expr {
7291 get { return expr; }
7294 // TODO: this method has very poor performace for Enum fields and
7295 // probably for other constants as well
7296 Expression DoResolve (EmitContext ec, Expression right_side)
7299 throw new Exception ();
7302 // Resolve the expression with flow analysis turned off, we'll do the definite
7303 // assignment checks later. This is because we don't know yet what the expression
7304 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7305 // definite assignment check on the actual field and not on the whole struct.
7308 SimpleName original = expr as SimpleName;
7309 Expression new_expr = expr.Resolve (ec,
7310 ResolveFlags.VariableOrValue | ResolveFlags.Type |
7311 ResolveFlags.Intermediate | ResolveFlags.DisableFlowAnalysis);
7313 if (new_expr == null)
7316 if (new_expr is Namespace) {
7317 Namespace ns = (Namespace) new_expr;
7318 FullNamedExpression retval = ns.Lookup (ec.DeclSpace, Identifier, loc);
7320 Report.Error (234, loc, "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
7321 Identifier, ns.FullName);
7325 Type expr_type = new_expr.Type;
7326 if (expr_type.IsPointer){
7327 Error (23, "The `.' operator can not be applied to pointer operands (" +
7328 TypeManager.CSharpName (expr_type) + ")");
7332 Expression member_lookup;
7333 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
7334 if (member_lookup == null)
7337 if (member_lookup is TypeExpr) {
7338 if (!(new_expr is TypeExpr) &&
7339 (original == null || !original.IdenticalNameAndTypeName (ec, new_expr, loc))) {
7340 Report.Error (572, loc, "`{0}': cannot reference a type through an expression; try `{1}' instead",
7341 Identifier, member_lookup.GetSignatureForError ());
7345 return member_lookup;
7348 MemberExpr me = (MemberExpr) member_lookup;
7349 member_lookup = me.ResolveMemberAccess (ec, new_expr, loc, original);
7350 if (member_lookup == null)
7353 // The following DoResolve/DoResolveLValue will do the definite assignment
7356 if (right_side != null)
7357 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
7359 member_lookup = member_lookup.DoResolve (ec);
7361 return member_lookup;
7364 public override Expression DoResolve (EmitContext ec)
7366 return DoResolve (ec, null);
7369 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7371 return DoResolve (ec, right_side);
7374 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
7376 return ResolveNamespaceOrType (ec, silent);
7379 public FullNamedExpression ResolveNamespaceOrType (EmitContext ec, bool silent)
7381 FullNamedExpression new_expr = expr.ResolveAsTypeStep (ec, silent);
7383 if (new_expr == null) {
7384 Report.Error (234, "No such name or typespace {0}", expr);
7388 if (new_expr is Namespace) {
7389 Namespace ns = (Namespace) new_expr;
7390 FullNamedExpression retval = ns.Lookup (ec.DeclSpace, Identifier, loc);
7391 if (!silent && retval == null)
7392 Report.Error (234, loc, "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
7393 Identifier, ns.FullName);
7397 Type expr_type = new_expr.Type;
7399 if (expr_type.IsPointer){
7400 Error (23, "The `.' operator can not be applied to pointer operands (" +
7401 TypeManager.CSharpName (expr_type) + ")");
7405 Expression member_lookup = MemberLookup (ec, expr_type, expr_type, Identifier, loc);
7406 if (member_lookup == null) {
7407 int errors = Report.Errors;
7408 MemberLookupFailed (ec, expr_type, expr_type, Identifier, null, false, loc);
7410 if (!silent && errors == Report.Errors) {
7411 Report.Error (426, loc, "The nested type `{0}' does not exist in the type `{1}'",
7412 Identifier, new_expr.GetSignatureForError ());
7417 if (!(member_lookup is TypeExpr)) {
7418 new_expr.Error_UnexpectedKind (ec, "type", loc);
7422 member_lookup = member_lookup.Resolve (ec, ResolveFlags.Type);
7423 return (member_lookup as TypeExpr);
7426 public override void Emit (EmitContext ec)
7428 throw new Exception ("Should not happen");
7431 public override string ToString ()
7433 return expr + "." + Identifier;
7436 public override string GetSignatureForError ()
7438 return expr.GetSignatureForError () + "." + Identifier;
7443 /// Implements checked expressions
7445 public class CheckedExpr : Expression {
7447 public Expression Expr;
7449 public CheckedExpr (Expression e, Location l)
7455 public override Expression DoResolve (EmitContext ec)
7457 bool last_check = ec.CheckState;
7458 bool last_const_check = ec.ConstantCheckState;
7460 ec.CheckState = true;
7461 ec.ConstantCheckState = true;
7462 Expr = Expr.Resolve (ec);
7463 ec.CheckState = last_check;
7464 ec.ConstantCheckState = last_const_check;
7469 if (Expr is Constant)
7472 eclass = Expr.eclass;
7477 public override void Emit (EmitContext ec)
7479 bool last_check = ec.CheckState;
7480 bool last_const_check = ec.ConstantCheckState;
7482 ec.CheckState = true;
7483 ec.ConstantCheckState = true;
7485 ec.CheckState = last_check;
7486 ec.ConstantCheckState = last_const_check;
7492 /// Implements the unchecked expression
7494 public class UnCheckedExpr : Expression {
7496 public Expression Expr;
7498 public UnCheckedExpr (Expression e, Location l)
7504 public override Expression DoResolve (EmitContext ec)
7506 bool last_check = ec.CheckState;
7507 bool last_const_check = ec.ConstantCheckState;
7509 ec.CheckState = false;
7510 ec.ConstantCheckState = false;
7511 Expr = Expr.Resolve (ec);
7512 ec.CheckState = last_check;
7513 ec.ConstantCheckState = last_const_check;
7518 if (Expr is Constant)
7521 eclass = Expr.eclass;
7526 public override void Emit (EmitContext ec)
7528 bool last_check = ec.CheckState;
7529 bool last_const_check = ec.ConstantCheckState;
7531 ec.CheckState = false;
7532 ec.ConstantCheckState = false;
7534 ec.CheckState = last_check;
7535 ec.ConstantCheckState = last_const_check;
7541 /// An Element Access expression.
7543 /// During semantic analysis these are transformed into
7544 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7546 public class ElementAccess : Expression {
7547 public ArrayList Arguments;
7548 public Expression Expr;
7550 public ElementAccess (Expression e, ArrayList e_list)
7559 Arguments = new ArrayList ();
7560 foreach (Expression tmp in e_list)
7561 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7565 bool CommonResolve (EmitContext ec)
7567 Expr = Expr.Resolve (ec);
7572 if (Arguments == null)
7575 foreach (Argument a in Arguments){
7576 if (!a.Resolve (ec, loc))
7583 Expression MakePointerAccess (EmitContext ec, Type t)
7585 if (t == TypeManager.void_ptr_type){
7586 Error (242, "The array index operation is not valid on void pointers");
7589 if (Arguments.Count != 1){
7590 Error (196, "A pointer must be indexed by only one value");
7595 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc).Resolve (ec);
7598 return new Indirection (p, loc).Resolve (ec);
7601 public override Expression DoResolve (EmitContext ec)
7603 if (!CommonResolve (ec))
7607 // We perform some simple tests, and then to "split" the emit and store
7608 // code we create an instance of a different class, and return that.
7610 // I am experimenting with this pattern.
7614 if (t == TypeManager.array_type){
7615 Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `System.Array'");
7620 return (new ArrayAccess (this, loc)).Resolve (ec);
7622 return MakePointerAccess (ec, Expr.Type);
7624 FieldExpr fe = Expr as FieldExpr;
7626 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
7628 return MakePointerAccess (ec, ff.ElementType);
7631 return (new IndexerAccess (this, loc)).Resolve (ec);
7634 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7636 if (!CommonResolve (ec))
7641 return (new ArrayAccess (this, loc)).DoResolveLValue (ec, right_side);
7644 return MakePointerAccess (ec, Expr.Type);
7646 FieldExpr fe = Expr as FieldExpr;
7648 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
7650 if (!(fe.InstanceExpression is LocalVariableReference) &&
7651 !(fe.InstanceExpression is This)) {
7652 Report.Error (1708, loc, "Fixed size buffers can only be accessed through locals or fields");
7655 // TODO: not sure whether it is correct
7656 // if (!ec.InFixedInitializer) {
7657 // Error (1666, "You cannot use fixed sized buffers contained in unfixed expressions. Try using the fixed statement");
7660 return MakePointerAccess (ec, ff.ElementType);
7663 return (new IndexerAccess (this, loc)).DoResolveLValue (ec, right_side);
7666 public override void Emit (EmitContext ec)
7668 throw new Exception ("Should never be reached");
7673 /// Implements array access
7675 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7677 // Points to our "data" repository
7681 LocalTemporary temp;
7684 public ArrayAccess (ElementAccess ea_data, Location l)
7687 eclass = ExprClass.Variable;
7691 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7693 return DoResolve (ec);
7696 public override Expression DoResolve (EmitContext ec)
7699 ExprClass eclass = ea.Expr.eclass;
7701 // As long as the type is valid
7702 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7703 eclass == ExprClass.Value)) {
7704 ea.Expr.Error_UnexpectedKind ("variable or value");
7709 Type t = ea.Expr.Type;
7710 if (t.GetArrayRank () != ea.Arguments.Count){
7711 Report.Error (22, ea.Location, "Wrong number of indexes `{0}' inside [], expected `{1}'",
7712 ea.Arguments.Count, t.GetArrayRank ());
7716 type = TypeManager.GetElementType (t);
7717 if (type.IsPointer && !ec.InUnsafe){
7718 UnsafeError (ea.Location);
7722 foreach (Argument a in ea.Arguments){
7723 Type argtype = a.Type;
7725 if (argtype == TypeManager.int32_type ||
7726 argtype == TypeManager.uint32_type ||
7727 argtype == TypeManager.int64_type ||
7728 argtype == TypeManager.uint64_type) {
7729 Constant c = a.Expr as Constant;
7730 if (c != null && c.IsNegative) {
7731 Report.Warning (251, 2, ea.Location, "Indexing an array with a negative index (array indices always start at zero)");
7737 // Mhm. This is strage, because the Argument.Type is not the same as
7738 // Argument.Expr.Type: the value changes depending on the ref/out setting.
7740 // Wonder if I will run into trouble for this.
7742 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
7747 eclass = ExprClass.Variable;
7753 /// Emits the right opcode to load an object of Type `t'
7754 /// from an array of T
7756 static public void EmitLoadOpcode (ILGenerator ig, Type type)
7758 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7759 ig.Emit (OpCodes.Ldelem_U1);
7760 else if (type == TypeManager.sbyte_type)
7761 ig.Emit (OpCodes.Ldelem_I1);
7762 else if (type == TypeManager.short_type)
7763 ig.Emit (OpCodes.Ldelem_I2);
7764 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7765 ig.Emit (OpCodes.Ldelem_U2);
7766 else if (type == TypeManager.int32_type)
7767 ig.Emit (OpCodes.Ldelem_I4);
7768 else if (type == TypeManager.uint32_type)
7769 ig.Emit (OpCodes.Ldelem_U4);
7770 else if (type == TypeManager.uint64_type)
7771 ig.Emit (OpCodes.Ldelem_I8);
7772 else if (type == TypeManager.int64_type)
7773 ig.Emit (OpCodes.Ldelem_I8);
7774 else if (type == TypeManager.float_type)
7775 ig.Emit (OpCodes.Ldelem_R4);
7776 else if (type == TypeManager.double_type)
7777 ig.Emit (OpCodes.Ldelem_R8);
7778 else if (type == TypeManager.intptr_type)
7779 ig.Emit (OpCodes.Ldelem_I);
7780 else if (TypeManager.IsEnumType (type)){
7781 EmitLoadOpcode (ig, TypeManager.EnumToUnderlying (type));
7782 } else if (type.IsValueType){
7783 ig.Emit (OpCodes.Ldelema, type);
7784 ig.Emit (OpCodes.Ldobj, type);
7786 ig.Emit (OpCodes.Ldelem_Ref);
7790 /// Returns the right opcode to store an object of Type `t'
7791 /// from an array of T.
7793 static public OpCode GetStoreOpcode (Type t, out bool is_stobj)
7795 //Console.WriteLine (new System.Diagnostics.StackTrace ());
7797 t = TypeManager.TypeToCoreType (t);
7798 if (TypeManager.IsEnumType (t))
7799 t = TypeManager.EnumToUnderlying (t);
7800 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
7801 t == TypeManager.bool_type)
7802 return OpCodes.Stelem_I1;
7803 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
7804 t == TypeManager.char_type)
7805 return OpCodes.Stelem_I2;
7806 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
7807 return OpCodes.Stelem_I4;
7808 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
7809 return OpCodes.Stelem_I8;
7810 else if (t == TypeManager.float_type)
7811 return OpCodes.Stelem_R4;
7812 else if (t == TypeManager.double_type)
7813 return OpCodes.Stelem_R8;
7814 else if (t == TypeManager.intptr_type) {
7816 return OpCodes.Stobj;
7817 } else if (t.IsValueType) {
7819 return OpCodes.Stobj;
7821 return OpCodes.Stelem_Ref;
7824 MethodInfo FetchGetMethod ()
7826 ModuleBuilder mb = CodeGen.Module.Builder;
7827 int arg_count = ea.Arguments.Count;
7828 Type [] args = new Type [arg_count];
7831 for (int i = 0; i < arg_count; i++){
7832 //args [i++] = a.Type;
7833 args [i] = TypeManager.int32_type;
7836 get = mb.GetArrayMethod (
7837 ea.Expr.Type, "Get",
7838 CallingConventions.HasThis |
7839 CallingConventions.Standard,
7845 MethodInfo FetchAddressMethod ()
7847 ModuleBuilder mb = CodeGen.Module.Builder;
7848 int arg_count = ea.Arguments.Count;
7849 Type [] args = new Type [arg_count];
7853 ret_type = TypeManager.GetReferenceType (type);
7855 for (int i = 0; i < arg_count; i++){
7856 //args [i++] = a.Type;
7857 args [i] = TypeManager.int32_type;
7860 address = mb.GetArrayMethod (
7861 ea.Expr.Type, "Address",
7862 CallingConventions.HasThis |
7863 CallingConventions.Standard,
7870 // Load the array arguments into the stack.
7872 // If we have been requested to cache the values (cached_locations array
7873 // initialized), then load the arguments the first time and store them
7874 // in locals. otherwise load from local variables.
7876 void LoadArrayAndArguments (EmitContext ec)
7878 ILGenerator ig = ec.ig;
7881 foreach (Argument a in ea.Arguments){
7882 Type argtype = a.Expr.Type;
7886 if (argtype == TypeManager.int64_type)
7887 ig.Emit (OpCodes.Conv_Ovf_I);
7888 else if (argtype == TypeManager.uint64_type)
7889 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7893 public void Emit (EmitContext ec, bool leave_copy)
7895 int rank = ea.Expr.Type.GetArrayRank ();
7896 ILGenerator ig = ec.ig;
7899 LoadArrayAndArguments (ec);
7902 EmitLoadOpcode (ig, type);
7906 method = FetchGetMethod ();
7907 ig.Emit (OpCodes.Call, method);
7910 LoadFromPtr (ec.ig, this.type);
7913 ec.ig.Emit (OpCodes.Dup);
7914 temp = new LocalTemporary (ec, this.type);
7919 public override void Emit (EmitContext ec)
7924 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
7926 int rank = ea.Expr.Type.GetArrayRank ();
7927 ILGenerator ig = ec.ig;
7928 Type t = source.Type;
7929 prepared = prepare_for_load;
7931 if (prepare_for_load) {
7932 AddressOf (ec, AddressOp.LoadStore);
7933 ec.ig.Emit (OpCodes.Dup);
7936 ec.ig.Emit (OpCodes.Dup);
7937 temp = new LocalTemporary (ec, this.type);
7940 StoreFromPtr (ec.ig, t);
7948 LoadArrayAndArguments (ec);
7952 OpCode op = GetStoreOpcode (t, out is_stobj);
7954 // The stobj opcode used by value types will need
7955 // an address on the stack, not really an array/array
7959 ig.Emit (OpCodes.Ldelema, t);
7963 ec.ig.Emit (OpCodes.Dup);
7964 temp = new LocalTemporary (ec, this.type);
7969 ig.Emit (OpCodes.Stobj, t);
7973 ModuleBuilder mb = CodeGen.Module.Builder;
7974 int arg_count = ea.Arguments.Count;
7975 Type [] args = new Type [arg_count + 1];
7980 ec.ig.Emit (OpCodes.Dup);
7981 temp = new LocalTemporary (ec, this.type);
7985 for (int i = 0; i < arg_count; i++){
7986 //args [i++] = a.Type;
7987 args [i] = TypeManager.int32_type;
7990 args [arg_count] = type;
7992 set = mb.GetArrayMethod (
7993 ea.Expr.Type, "Set",
7994 CallingConventions.HasThis |
7995 CallingConventions.Standard,
7996 TypeManager.void_type, args);
7998 ig.Emit (OpCodes.Call, set);
8005 public void AddressOf (EmitContext ec, AddressOp mode)
8007 int rank = ea.Expr.Type.GetArrayRank ();
8008 ILGenerator ig = ec.ig;
8010 LoadArrayAndArguments (ec);
8013 ig.Emit (OpCodes.Ldelema, type);
8015 MethodInfo address = FetchAddressMethod ();
8016 ig.Emit (OpCodes.Call, address);
8020 public void EmitGetLength (EmitContext ec, int dim)
8022 int rank = ea.Expr.Type.GetArrayRank ();
8023 ILGenerator ig = ec.ig;
8027 ig.Emit (OpCodes.Ldlen);
8028 ig.Emit (OpCodes.Conv_I4);
8030 IntLiteral.EmitInt (ig, dim);
8031 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
8037 // note that the ArrayList itself in mutable. We just can't assign to 'Properties' again.
8038 public readonly ArrayList Properties;
8039 static Indexers empty;
8041 public struct Indexer {
8042 public readonly PropertyInfo PropertyInfo;
8043 public readonly MethodInfo Getter, Setter;
8045 public Indexer (PropertyInfo property_info, MethodInfo get, MethodInfo set)
8047 this.PropertyInfo = property_info;
8055 empty = new Indexers (null);
8058 Indexers (ArrayList array)
8063 static void Append (ref Indexers ix, Type caller_type, MemberInfo [] mi)
8068 foreach (PropertyInfo property in mi){
8069 MethodInfo get, set;
8071 get = property.GetGetMethod (true);
8072 set = property.GetSetMethod (true);
8073 if (get != null && !Expression.IsAccessorAccessible (caller_type, get, out dummy))
8075 if (set != null && !Expression.IsAccessorAccessible (caller_type, set, out dummy))
8077 if (get != null || set != null) {
8079 ix = new Indexers (new ArrayList ());
8080 ix.Properties.Add (new Indexer (property, get, set));
8085 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
8087 string p_name = TypeManager.IndexerPropertyName (lookup_type);
8089 return TypeManager.MemberLookup (
8090 caller_type, caller_type, lookup_type, MemberTypes.Property,
8091 BindingFlags.Public | BindingFlags.Instance |
8092 BindingFlags.DeclaredOnly, p_name, null);
8095 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
8097 Indexers ix = empty;
8099 Type copy = lookup_type;
8100 while (copy != TypeManager.object_type && copy != null){
8101 Append (ref ix, caller_type, GetIndexersForTypeOrInterface (caller_type, copy));
8102 copy = copy.BaseType;
8105 if (lookup_type.IsInterface) {
8106 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
8107 if (ifaces != null) {
8108 foreach (Type itype in ifaces)
8109 Append (ref ix, caller_type, GetIndexersForTypeOrInterface (caller_type, itype));
8118 /// Expressions that represent an indexer call.
8120 public class IndexerAccess : Expression, IAssignMethod {
8122 // Points to our "data" repository
8124 MethodInfo get, set;
8125 ArrayList set_arguments;
8126 bool is_base_indexer;
8128 protected Type indexer_type;
8129 protected Type current_type;
8130 protected Expression instance_expr;
8131 protected ArrayList arguments;
8133 public IndexerAccess (ElementAccess ea, Location loc)
8134 : this (ea.Expr, false, loc)
8136 this.arguments = ea.Arguments;
8139 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
8142 this.instance_expr = instance_expr;
8143 this.is_base_indexer = is_base_indexer;
8144 this.eclass = ExprClass.Value;
8148 protected virtual bool CommonResolve (EmitContext ec)
8150 indexer_type = instance_expr.Type;
8151 current_type = ec.ContainerType;
8156 public override Expression DoResolve (EmitContext ec)
8158 ArrayList AllGetters = new ArrayList();
8159 if (!CommonResolve (ec))
8163 // Step 1: Query for all `Item' *properties*. Notice
8164 // that the actual methods are pointed from here.
8166 // This is a group of properties, piles of them.
8168 bool found_any = false, found_any_getters = false;
8169 Type lookup_type = indexer_type;
8171 Indexers ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
8172 if (ilist.Properties != null) {
8174 foreach (Indexers.Indexer ix in ilist.Properties) {
8175 if (ix.Getter != null)
8176 AllGetters.Add (ix.Getter);
8180 if (AllGetters.Count > 0) {
8181 found_any_getters = true;
8182 get = (MethodInfo) Invocation.OverloadResolve (
8183 ec, new MethodGroupExpr (AllGetters, loc),
8184 arguments, false, loc);
8188 Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
8189 TypeManager.CSharpName (indexer_type));
8193 if (!found_any_getters) {
8194 Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
8200 Invocation.Error_WrongNumArguments (loc, "this", arguments.Count);
8205 // Only base will allow this invocation to happen.
8207 if (get.IsAbstract && this is BaseIndexerAccess){
8208 Error_CannotCallAbstractBase (TypeManager.CSharpSignature (get));
8212 type = get.ReturnType;
8213 if (type.IsPointer && !ec.InUnsafe){
8218 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8220 eclass = ExprClass.IndexerAccess;
8224 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8226 ArrayList AllSetters = new ArrayList();
8227 if (!CommonResolve (ec))
8230 bool found_any = false, found_any_setters = false;
8232 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
8233 if (ilist.Properties != null) {
8235 foreach (Indexers.Indexer ix in ilist.Properties) {
8236 if (ix.Setter != null)
8237 AllSetters.Add (ix.Setter);
8240 if (AllSetters.Count > 0) {
8241 found_any_setters = true;
8242 set_arguments = (ArrayList) arguments.Clone ();
8243 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
8244 set = (MethodInfo) Invocation.OverloadResolve (
8245 ec, new MethodGroupExpr (AllSetters, loc),
8246 set_arguments, false, loc);
8250 Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
8251 TypeManager.CSharpName (indexer_type));
8255 if (!found_any_setters) {
8256 Error (154, "indexer can not be used in this context, because " +
8257 "it lacks a `set' accessor");
8262 Invocation.Error_WrongNumArguments (loc, "this", arguments.Count);
8267 // Only base will allow this invocation to happen.
8269 if (set.IsAbstract && this is BaseIndexerAccess){
8270 Error_CannotCallAbstractBase (TypeManager.CSharpSignature (set));
8275 // Now look for the actual match in the list of indexers to set our "return" type
8277 type = TypeManager.void_type; // default value
8278 foreach (Indexers.Indexer ix in ilist.Properties){
8279 if (ix.Setter == set){
8280 type = ix.PropertyInfo.PropertyType;
8285 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8287 eclass = ExprClass.IndexerAccess;
8291 bool prepared = false;
8292 LocalTemporary temp;
8294 public void Emit (EmitContext ec, bool leave_copy)
8296 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc, prepared, false);
8298 ec.ig.Emit (OpCodes.Dup);
8299 temp = new LocalTemporary (ec, Type);
8305 // source is ignored, because we already have a copy of it from the
8306 // LValue resolution and we have already constructed a pre-cached
8307 // version of the arguments (ea.set_arguments);
8309 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8311 prepared = prepare_for_load;
8312 Argument a = (Argument) set_arguments [set_arguments.Count - 1];
8317 ec.ig.Emit (OpCodes.Dup);
8318 temp = new LocalTemporary (ec, Type);
8321 } else if (leave_copy) {
8322 temp = new LocalTemporary (ec, Type);
8328 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc, false, prepared);
8335 public override void Emit (EmitContext ec)
8342 /// The base operator for method names
8344 public class BaseAccess : Expression {
8347 public BaseAccess (string member, Location l)
8349 this.member = member;
8353 public override Expression DoResolve (EmitContext ec)
8355 Expression c = CommonResolve (ec);
8361 // MethodGroups use this opportunity to flag an error on lacking ()
8363 if (!(c is MethodGroupExpr))
8364 return c.Resolve (ec);
8368 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8370 Expression c = CommonResolve (ec);
8376 // MethodGroups use this opportunity to flag an error on lacking ()
8378 if (! (c is MethodGroupExpr))
8379 return c.DoResolveLValue (ec, right_side);
8384 Expression CommonResolve (EmitContext ec)
8386 Expression member_lookup;
8387 Type current_type = ec.ContainerType;
8388 Type base_type = current_type.BaseType;
8391 Error (1511, "Keyword `base' is not available in a static method");
8395 if (ec.IsFieldInitializer){
8396 Error (1512, "Keyword `base' is not available in the current context");
8400 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type, member,
8401 AllMemberTypes, AllBindingFlags, loc);
8402 if (member_lookup == null) {
8403 MemberLookupFailed (ec, base_type, base_type, member, null, true, loc);
8410 left = new TypeExpression (base_type, loc);
8412 left = ec.GetThis (loc);
8414 MemberExpr me = (MemberExpr) member_lookup;
8416 Expression e = me.ResolveMemberAccess (ec, left, loc, null);
8418 if (e is PropertyExpr) {
8419 PropertyExpr pe = (PropertyExpr) e;
8424 if (e is MethodGroupExpr)
8425 ((MethodGroupExpr) e).IsBase = true;
8430 public override void Emit (EmitContext ec)
8432 throw new Exception ("Should never be called");
8437 /// The base indexer operator
8439 public class BaseIndexerAccess : IndexerAccess {
8440 public BaseIndexerAccess (ArrayList args, Location loc)
8441 : base (null, true, loc)
8443 arguments = new ArrayList ();
8444 foreach (Expression tmp in args)
8445 arguments.Add (new Argument (tmp, Argument.AType.Expression));
8448 protected override bool CommonResolve (EmitContext ec)
8450 instance_expr = ec.GetThis (loc);
8452 current_type = ec.ContainerType.BaseType;
8453 indexer_type = current_type;
8455 foreach (Argument a in arguments){
8456 if (!a.Resolve (ec, loc))
8465 /// This class exists solely to pass the Type around and to be a dummy
8466 /// that can be passed to the conversion functions (this is used by
8467 /// foreach implementation to typecast the object return value from
8468 /// get_Current into the proper type. All code has been generated and
8469 /// we only care about the side effect conversions to be performed
8471 /// This is also now used as a placeholder where a no-action expression
8472 /// is needed (the `New' class).
8474 public class EmptyExpression : Expression {
8475 public static readonly EmptyExpression Null = new EmptyExpression ();
8477 static EmptyExpression temp = new EmptyExpression ();
8478 public static EmptyExpression Grab ()
8481 throw new InternalErrorException ("Nested Grab");
8482 EmptyExpression retval = temp;
8487 public static void Release (EmptyExpression e)
8490 throw new InternalErrorException ("Already released");
8494 // TODO: should be protected
8495 public EmptyExpression ()
8497 type = TypeManager.object_type;
8498 eclass = ExprClass.Value;
8499 loc = Location.Null;
8502 public EmptyExpression (Type t)
8505 eclass = ExprClass.Value;
8506 loc = Location.Null;
8509 public override Expression DoResolve (EmitContext ec)
8514 public override void Emit (EmitContext ec)
8516 // nothing, as we only exist to not do anything.
8520 // This is just because we might want to reuse this bad boy
8521 // instead of creating gazillions of EmptyExpressions.
8522 // (CanImplicitConversion uses it)
8524 public void SetType (Type t)
8530 public class UserCast : Expression {
8534 public UserCast (MethodInfo method, Expression source, Location l)
8536 this.method = method;
8537 this.source = source;
8538 type = method.ReturnType;
8539 eclass = ExprClass.Value;
8543 public Expression Source {
8549 public override Expression DoResolve (EmitContext ec)
8552 // We are born fully resolved
8557 public override void Emit (EmitContext ec)
8559 ILGenerator ig = ec.ig;
8563 if (method is MethodInfo)
8564 ig.Emit (OpCodes.Call, (MethodInfo) method);
8566 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
8572 // This class is used to "construct" the type during a typecast
8573 // operation. Since the Type.GetType class in .NET can parse
8574 // the type specification, we just use this to construct the type
8575 // one bit at a time.
8577 public class ComposedCast : TypeExpr {
8581 public ComposedCast (Expression left, string dim)
8582 : this (left, dim, left.Location)
8586 public ComposedCast (Expression left, string dim, Location l)
8593 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
8595 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec, false);
8599 Type ltype = lexpr.ResolveType (ec);
8601 if ((ltype == TypeManager.void_type) && (dim != "*")) {
8602 Report.Error (1547, Location,
8603 "Keyword 'void' cannot be used in this context");
8607 if (dim == "*" && !TypeManager.VerifyUnManaged (ltype, loc)) {
8611 type = TypeManager.GetConstructedType (ltype, dim);
8613 throw new InternalErrorException ("Couldn't create computed type " + ltype + dim);
8616 if (!ec.InUnsafe && type.IsPointer){
8621 if (type.IsArray && (type.GetElementType () == TypeManager.arg_iterator_type ||
8622 type.GetElementType () == TypeManager.typed_reference_type)) {
8623 Report.Error (611, loc, "Array elements cannot be of type `{0}'", TypeManager.CSharpName (type.GetElementType ()));
8627 eclass = ExprClass.Type;
8631 public override string Name {
8637 public override string FullName {
8639 return type.FullName;
8644 public class FixedBufferPtr: Expression {
8647 public FixedBufferPtr (Expression array, Type array_type, Location l)
8652 type = TypeManager.GetPointerType (array_type);
8653 eclass = ExprClass.Value;
8656 public override void Emit(EmitContext ec)
8661 public override Expression DoResolve (EmitContext ec)
8664 // We are born fully resolved
8672 // This class is used to represent the address of an array, used
8673 // only by the Fixed statement, this generates "&a [0]" construct
8674 // for fixed (char *pa = a)
8676 public class ArrayPtr : FixedBufferPtr {
8679 public ArrayPtr (Expression array, Type array_type, Location l):
8680 base (array, array_type, l)
8682 this.array_type = array_type;
8685 public override void Emit (EmitContext ec)
8689 ILGenerator ig = ec.ig;
8690 IntLiteral.EmitInt (ig, 0);
8691 ig.Emit (OpCodes.Ldelema, array_type);
8696 // Used by the fixed statement
8698 public class StringPtr : Expression {
8701 public StringPtr (LocalBuilder b, Location l)
8704 eclass = ExprClass.Value;
8705 type = TypeManager.char_ptr_type;
8709 public override Expression DoResolve (EmitContext ec)
8711 // This should never be invoked, we are born in fully
8712 // initialized state.
8717 public override void Emit (EmitContext ec)
8719 ILGenerator ig = ec.ig;
8721 ig.Emit (OpCodes.Ldloc, b);
8722 ig.Emit (OpCodes.Conv_I);
8723 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
8724 ig.Emit (OpCodes.Add);
8729 // Implements the `stackalloc' keyword
8731 public class StackAlloc : Expression {
8736 public StackAlloc (Expression type, Expression count, Location l)
8743 public override Expression DoResolve (EmitContext ec)
8745 count = count.Resolve (ec);
8749 if (count.Type != TypeManager.int32_type){
8750 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8755 Constant c = count as Constant;
8756 if (c != null && c.IsNegative) {
8757 Report.Error (247, loc, "Cannot use a negative size with stackalloc");
8761 if (ec.InCatch || ec.InFinally) {
8762 Error (255, "Cannot use stackalloc in finally or catch");
8766 TypeExpr texpr = t.ResolveAsTypeTerminal (ec, false);
8770 otype = texpr.ResolveType (ec);
8772 if (!TypeManager.VerifyUnManaged (otype, loc))
8775 type = TypeManager.GetPointerType (otype);
8776 eclass = ExprClass.Value;
8781 public override void Emit (EmitContext ec)
8783 int size = GetTypeSize (otype);
8784 ILGenerator ig = ec.ig;
8787 ig.Emit (OpCodes.Sizeof, otype);
8789 IntConstant.EmitInt (ig, size);
8791 ig.Emit (OpCodes.Mul);
8792 ig.Emit (OpCodes.Localloc);