2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
8 // (C) 2003, 2004 Novell, Inc.
12 namespace Mono.CSharp {
14 using System.Collections;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// This is just a helper class, it is generated by Unary, UnaryMutator
21 /// when an overloaded method has been found. It just emits the code for a
24 public class StaticCallExpr : ExpressionStatement {
28 public StaticCallExpr (MethodInfo m, ArrayList a, Location l)
34 eclass = ExprClass.Value;
38 public override Expression DoResolve (EmitContext ec)
41 // We are born fully resolved
46 public override void Emit (EmitContext ec)
49 Invocation.EmitArguments (ec, mi, args, false, null);
51 ec.ig.Emit (OpCodes.Call, mi);
55 static public StaticCallExpr MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
56 Expression e, Location loc)
61 args = new ArrayList (1);
62 Argument a = new Argument (e, Argument.AType.Expression);
64 // We need to resolve the arguments before sending them in !
65 if (!a.Resolve (ec, loc))
69 method = Invocation.OverloadResolve (
70 ec, (MethodGroupExpr) mg, args, false, loc);
75 return new StaticCallExpr ((MethodInfo) method, args, loc);
78 public override void EmitStatement (EmitContext ec)
81 if (TypeManager.TypeToCoreType (type) != TypeManager.void_type)
82 ec.ig.Emit (OpCodes.Pop);
85 public MethodInfo Method {
90 public class ParenthesizedExpression : Expression
92 public Expression Expr;
94 public ParenthesizedExpression (Expression expr, Location loc)
100 public override Expression DoResolve (EmitContext ec)
102 Expr = Expr.Resolve (ec);
106 public override void Emit (EmitContext ec)
108 throw new Exception ("Should not happen");
113 /// Unary expressions.
117 /// Unary implements unary expressions. It derives from
118 /// ExpressionStatement becuase the pre/post increment/decrement
119 /// operators can be used in a statement context.
121 public class Unary : Expression {
122 public enum Operator : byte {
123 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
124 Indirection, AddressOf, TOP
127 public Operator Oper;
128 public Expression Expr;
130 public Unary (Operator op, Expression expr, Location loc)
138 /// Returns a stringified representation of the Operator
140 static public string OperName (Operator oper)
143 case Operator.UnaryPlus:
145 case Operator.UnaryNegation:
147 case Operator.LogicalNot:
149 case Operator.OnesComplement:
151 case Operator.AddressOf:
153 case Operator.Indirection:
157 return oper.ToString ();
160 public static readonly string [] oper_names;
164 oper_names = new string [(int)Operator.TOP];
166 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
167 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
168 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
169 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
170 oper_names [(int) Operator.Indirection] = "op_Indirection";
171 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
174 void Error23 (Type t)
177 23, "Operator " + OperName (Oper) +
178 " cannot be applied to operand of type `" +
179 TypeManager.CSharpName (t) + "'");
183 /// The result has been already resolved:
185 /// FIXME: a minus constant -128 sbyte cant be turned into a
188 static Expression TryReduceNegative (Constant expr)
192 if (expr is IntConstant)
193 e = new IntConstant (-((IntConstant) expr).Value);
194 else if (expr is UIntConstant){
195 uint value = ((UIntConstant) expr).Value;
197 if (value < 2147483649)
198 return new IntConstant (-(int)value);
200 e = new LongConstant (-value);
202 else if (expr is LongConstant)
203 e = new LongConstant (-((LongConstant) expr).Value);
204 else if (expr is ULongConstant){
205 ulong value = ((ULongConstant) expr).Value;
207 if (value < 9223372036854775809)
208 return new LongConstant(-(long)value);
210 else if (expr is FloatConstant)
211 e = new FloatConstant (-((FloatConstant) expr).Value);
212 else if (expr is DoubleConstant)
213 e = new DoubleConstant (-((DoubleConstant) expr).Value);
214 else if (expr is DecimalConstant)
215 e = new DecimalConstant (-((DecimalConstant) expr).Value);
216 else if (expr is ShortConstant)
217 e = new IntConstant (-((ShortConstant) expr).Value);
218 else if (expr is UShortConstant)
219 e = new IntConstant (-((UShortConstant) expr).Value);
224 // This routine will attempt to simplify the unary expression when the
225 // argument is a constant. The result is returned in `result' and the
226 // function returns true or false depending on whether a reduction
227 // was performed or not
229 bool Reduce (EmitContext ec, Constant e, out Expression result)
231 Type expr_type = e.Type;
234 case Operator.UnaryPlus:
238 case Operator.UnaryNegation:
239 result = TryReduceNegative (e);
242 case Operator.LogicalNot:
243 if (expr_type != TypeManager.bool_type) {
249 BoolConstant b = (BoolConstant) e;
250 result = new BoolConstant (!(b.Value));
253 case Operator.OnesComplement:
254 if (!((expr_type == TypeManager.int32_type) ||
255 (expr_type == TypeManager.uint32_type) ||
256 (expr_type == TypeManager.int64_type) ||
257 (expr_type == TypeManager.uint64_type) ||
258 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
261 if (Convert.ImplicitConversionExists (ec, e, TypeManager.int32_type)){
262 result = new Cast (new TypeExpression (TypeManager.int32_type, loc), e, loc);
263 result = result.Resolve (ec);
264 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint32_type)){
265 result = new Cast (new TypeExpression (TypeManager.uint32_type, loc), e, loc);
266 result = result.Resolve (ec);
267 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.int64_type)){
268 result = new Cast (new TypeExpression (TypeManager.int64_type, loc), e, loc);
269 result = result.Resolve (ec);
270 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint64_type)){
271 result = new Cast (new TypeExpression (TypeManager.uint64_type, loc), e, loc);
272 result = result.Resolve (ec);
275 if (result == null || !(result is Constant)){
281 expr_type = result.Type;
282 e = (Constant) result;
285 if (e is EnumConstant){
286 EnumConstant enum_constant = (EnumConstant) e;
289 if (Reduce (ec, enum_constant.Child, out reduced)){
290 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
298 if (expr_type == TypeManager.int32_type){
299 result = new IntConstant (~ ((IntConstant) e).Value);
300 } else if (expr_type == TypeManager.uint32_type){
301 result = new UIntConstant (~ ((UIntConstant) e).Value);
302 } else if (expr_type == TypeManager.int64_type){
303 result = new LongConstant (~ ((LongConstant) e).Value);
304 } else if (expr_type == TypeManager.uint64_type){
305 result = new ULongConstant (~ ((ULongConstant) e).Value);
313 case Operator.AddressOf:
317 case Operator.Indirection:
321 throw new Exception ("Can not constant fold: " + Oper.ToString());
324 Expression ResolveOperator (EmitContext ec)
326 Type expr_type = Expr.Type;
329 // Step 1: Perform Operator Overload location
334 op_name = oper_names [(int) Oper];
336 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
339 Expression e = StaticCallExpr.MakeSimpleCall (
340 ec, (MethodGroupExpr) mg, Expr, loc);
350 // Only perform numeric promotions on:
353 if (expr_type == null)
357 // Step 2: Default operations on CLI native types.
360 // Attempt to use a constant folding operation.
361 if (Expr is Constant){
364 if (Reduce (ec, (Constant) Expr, out result))
369 case Operator.LogicalNot:
370 if (expr_type != TypeManager.bool_type) {
371 Expr = ResolveBoolean (ec, Expr, loc);
378 type = TypeManager.bool_type;
381 case Operator.OnesComplement:
382 if (!((expr_type == TypeManager.int32_type) ||
383 (expr_type == TypeManager.uint32_type) ||
384 (expr_type == TypeManager.int64_type) ||
385 (expr_type == TypeManager.uint64_type) ||
386 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
389 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
391 type = TypeManager.int32_type;
394 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint32_type, loc);
396 type = TypeManager.uint32_type;
399 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
401 type = TypeManager.int64_type;
404 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint64_type, loc);
406 type = TypeManager.uint64_type;
415 case Operator.AddressOf:
416 if (Expr.eclass != ExprClass.Variable){
417 Error (211, "Cannot take the address of non-variables");
426 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
430 IVariable variable = Expr as IVariable;
431 if (!ec.InFixedInitializer && ((variable == null) || !variable.VerifyFixed (false))) {
432 Error (212, "You can only take the address of an unfixed expression inside " +
433 "of a fixed statement initializer");
437 if (ec.InFixedInitializer && ((variable != null) && variable.VerifyFixed (false))) {
438 Error (213, "You can not fix an already fixed expression");
442 // According to the specs, a variable is considered definitely assigned if you take
444 if ((variable != null) && (variable.VariableInfo != null))
445 variable.VariableInfo.SetAssigned (ec);
447 type = TypeManager.GetPointerType (Expr.Type);
450 case Operator.Indirection:
456 if (!expr_type.IsPointer){
457 Error (193, "The * or -> operator can only be applied to pointers");
462 // We create an Indirection expression, because
463 // it can implement the IMemoryLocation.
465 return new Indirection (Expr, loc);
467 case Operator.UnaryPlus:
469 // A plus in front of something is just a no-op, so return the child.
473 case Operator.UnaryNegation:
475 // Deals with -literals
476 // int operator- (int x)
477 // long operator- (long x)
478 // float operator- (float f)
479 // double operator- (double d)
480 // decimal operator- (decimal d)
482 Expression expr = null;
485 // transform - - expr into expr
488 Unary unary = (Unary) Expr;
490 if (unary.Oper == Operator.UnaryNegation)
495 // perform numeric promotions to int,
499 // The following is inneficient, because we call
500 // ImplicitConversion too many times.
502 // It is also not clear if we should convert to Float
503 // or Double initially.
505 if (expr_type == TypeManager.uint32_type){
507 // FIXME: handle exception to this rule that
508 // permits the int value -2147483648 (-2^31) to
509 // bt wrote as a decimal interger literal
511 type = TypeManager.int64_type;
512 Expr = Convert.ImplicitConversion (ec, Expr, type, loc);
516 if (expr_type == TypeManager.uint64_type){
518 // FIXME: Handle exception of `long value'
519 // -92233720368547758087 (-2^63) to be wrote as
520 // decimal integer literal.
526 if (expr_type == TypeManager.float_type){
531 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
538 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
545 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.double_type, loc);
556 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
557 TypeManager.CSharpName (expr_type) + "'");
561 public override Expression DoResolve (EmitContext ec)
563 if (Oper == Operator.AddressOf)
564 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
566 Expr = Expr.Resolve (ec);
571 eclass = ExprClass.Value;
572 return ResolveOperator (ec);
575 public override Expression DoResolveLValue (EmitContext ec, Expression right)
577 if (Oper == Operator.Indirection)
578 return base.DoResolveLValue (ec, right);
580 Error (131, "The left-hand side of an assignment must be a " +
581 "variable, property or indexer");
585 public override void Emit (EmitContext ec)
587 ILGenerator ig = ec.ig;
590 case Operator.UnaryPlus:
591 throw new Exception ("This should be caught by Resolve");
593 case Operator.UnaryNegation:
595 ig.Emit (OpCodes.Ldc_I4_0);
596 if (type == TypeManager.int64_type)
597 ig.Emit (OpCodes.Conv_U8);
599 ig.Emit (OpCodes.Sub_Ovf);
602 ig.Emit (OpCodes.Neg);
607 case Operator.LogicalNot:
609 ig.Emit (OpCodes.Ldc_I4_0);
610 ig.Emit (OpCodes.Ceq);
613 case Operator.OnesComplement:
615 ig.Emit (OpCodes.Not);
618 case Operator.AddressOf:
619 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
623 throw new Exception ("This should not happen: Operator = "
628 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
630 if (Oper == Operator.LogicalNot)
631 Expr.EmitBranchable (ec, target, !onTrue);
633 base.EmitBranchable (ec, target, onTrue);
636 public override string ToString ()
638 return "Unary (" + Oper + ", " + Expr + ")";
644 // Unary operators are turned into Indirection expressions
645 // after semantic analysis (this is so we can take the address
646 // of an indirection).
648 public class Indirection : Expression, IMemoryLocation, IAssignMethod {
650 LocalTemporary temporary;
653 public Indirection (Expression expr, Location l)
656 this.type = TypeManager.GetElementType (expr.Type);
657 eclass = ExprClass.Variable;
661 void LoadExprValue (EmitContext ec)
665 public override void Emit (EmitContext ec)
670 LoadFromPtr (ec.ig, Type);
673 public void Emit (EmitContext ec, bool leave_copy)
677 ec.ig.Emit (OpCodes.Dup);
678 temporary = new LocalTemporary (ec, expr.Type);
679 temporary.Store (ec);
683 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
685 prepared = prepare_for_load;
689 if (prepare_for_load)
690 ec.ig.Emit (OpCodes.Dup);
694 ec.ig.Emit (OpCodes.Dup);
695 temporary = new LocalTemporary (ec, expr.Type);
696 temporary.Store (ec);
699 StoreFromPtr (ec.ig, type);
701 if (temporary != null)
705 public void AddressOf (EmitContext ec, AddressOp Mode)
710 public override Expression DoResolve (EmitContext ec)
713 // Born fully resolved
718 public override string ToString ()
720 return "*(" + expr + ")";
725 /// Unary Mutator expressions (pre and post ++ and --)
729 /// UnaryMutator implements ++ and -- expressions. It derives from
730 /// ExpressionStatement becuase the pre/post increment/decrement
731 /// operators can be used in a statement context.
733 /// FIXME: Idea, we could split this up in two classes, one simpler
734 /// for the common case, and one with the extra fields for more complex
735 /// classes (indexers require temporary access; overloaded require method)
738 public class UnaryMutator : ExpressionStatement {
740 public enum Mode : byte {
747 PreDecrement = IsDecrement,
748 PostIncrement = IsPost,
749 PostDecrement = IsPost | IsDecrement
753 bool is_expr = false;
754 bool recurse = false;
759 // This is expensive for the simplest case.
761 StaticCallExpr method;
763 public UnaryMutator (Mode m, Expression e, Location l)
770 static string OperName (Mode mode)
772 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
776 void Error23 (Type t)
779 23, "Operator " + OperName (mode) +
780 " cannot be applied to operand of type `" +
781 TypeManager.CSharpName (t) + "'");
785 /// Returns whether an object of type `t' can be incremented
786 /// or decremented with add/sub (ie, basically whether we can
787 /// use pre-post incr-decr operations on it, but it is not a
788 /// System.Decimal, which we require operator overloading to catch)
790 static bool IsIncrementableNumber (Type t)
792 return (t == TypeManager.sbyte_type) ||
793 (t == TypeManager.byte_type) ||
794 (t == TypeManager.short_type) ||
795 (t == TypeManager.ushort_type) ||
796 (t == TypeManager.int32_type) ||
797 (t == TypeManager.uint32_type) ||
798 (t == TypeManager.int64_type) ||
799 (t == TypeManager.uint64_type) ||
800 (t == TypeManager.char_type) ||
801 (t.IsSubclassOf (TypeManager.enum_type)) ||
802 (t == TypeManager.float_type) ||
803 (t == TypeManager.double_type) ||
804 (t.IsPointer && t != TypeManager.void_ptr_type);
807 Expression ResolveOperator (EmitContext ec)
809 Type expr_type = expr.Type;
812 // Step 1: Perform Operator Overload location
817 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
818 op_name = "op_Increment";
820 op_name = "op_Decrement";
822 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
824 if (mg == null && expr_type.BaseType != null)
825 mg = MemberLookup (ec, expr_type.BaseType, op_name,
826 MemberTypes.Method, AllBindingFlags, loc);
829 method = StaticCallExpr.MakeSimpleCall (
830 ec, (MethodGroupExpr) mg, expr, loc);
837 // The operand of the prefix/postfix increment decrement operators
838 // should be an expression that is classified as a variable,
839 // a property access or an indexer access
842 if (expr.eclass == ExprClass.Variable){
843 LocalVariableReference var = expr as LocalVariableReference;
844 if ((var != null) && var.IsReadOnly)
845 Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
846 if (IsIncrementableNumber (expr_type) ||
847 expr_type == TypeManager.decimal_type){
850 } else if (expr.eclass == ExprClass.IndexerAccess){
851 IndexerAccess ia = (IndexerAccess) expr;
853 expr = ia.ResolveLValue (ec, this);
858 } else if (expr.eclass == ExprClass.PropertyAccess){
859 PropertyExpr pe = (PropertyExpr) expr;
861 if (pe.VerifyAssignable ())
866 expr.Error_UnexpectedKind ("variable, indexer or property access", loc);
870 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
871 TypeManager.CSharpName (expr_type) + "'");
875 public override Expression DoResolve (EmitContext ec)
877 expr = expr.Resolve (ec);
882 eclass = ExprClass.Value;
883 return ResolveOperator (ec);
886 static int PtrTypeSize (Type t)
888 return GetTypeSize (TypeManager.GetElementType (t));
892 // Loads the proper "1" into the stack based on the type, then it emits the
893 // opcode for the operation requested
895 void LoadOneAndEmitOp (EmitContext ec, Type t)
898 // Measure if getting the typecode and using that is more/less efficient
899 // that comparing types. t.GetTypeCode() is an internal call.
901 ILGenerator ig = ec.ig;
903 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
904 LongConstant.EmitLong (ig, 1);
905 else if (t == TypeManager.double_type)
906 ig.Emit (OpCodes.Ldc_R8, 1.0);
907 else if (t == TypeManager.float_type)
908 ig.Emit (OpCodes.Ldc_R4, 1.0F);
909 else if (t.IsPointer){
910 int n = PtrTypeSize (t);
913 ig.Emit (OpCodes.Sizeof, t);
915 IntConstant.EmitInt (ig, n);
917 ig.Emit (OpCodes.Ldc_I4_1);
920 // Now emit the operation
923 if (t == TypeManager.int32_type ||
924 t == TypeManager.int64_type){
925 if ((mode & Mode.IsDecrement) != 0)
926 ig.Emit (OpCodes.Sub_Ovf);
928 ig.Emit (OpCodes.Add_Ovf);
929 } else if (t == TypeManager.uint32_type ||
930 t == TypeManager.uint64_type){
931 if ((mode & Mode.IsDecrement) != 0)
932 ig.Emit (OpCodes.Sub_Ovf_Un);
934 ig.Emit (OpCodes.Add_Ovf_Un);
936 if ((mode & Mode.IsDecrement) != 0)
937 ig.Emit (OpCodes.Sub_Ovf);
939 ig.Emit (OpCodes.Add_Ovf);
942 if ((mode & Mode.IsDecrement) != 0)
943 ig.Emit (OpCodes.Sub);
945 ig.Emit (OpCodes.Add);
948 if (t == TypeManager.sbyte_type){
950 ig.Emit (OpCodes.Conv_Ovf_I1);
952 ig.Emit (OpCodes.Conv_I1);
953 } else if (t == TypeManager.byte_type){
955 ig.Emit (OpCodes.Conv_Ovf_U1);
957 ig.Emit (OpCodes.Conv_U1);
958 } else if (t == TypeManager.short_type){
960 ig.Emit (OpCodes.Conv_Ovf_I2);
962 ig.Emit (OpCodes.Conv_I2);
963 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
965 ig.Emit (OpCodes.Conv_Ovf_U2);
967 ig.Emit (OpCodes.Conv_U2);
972 void EmitCode (EmitContext ec, bool is_expr)
975 this.is_expr = is_expr;
976 ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
980 public override void Emit (EmitContext ec)
983 // We use recurse to allow ourselfs to be the source
984 // of an assignment. This little hack prevents us from
985 // having to allocate another expression
988 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
990 LoadOneAndEmitOp (ec, expr.Type);
992 ec.ig.Emit (OpCodes.Call, method.Method);
1000 public override void EmitStatement (EmitContext ec)
1002 EmitCode (ec, false);
1007 /// Base class for the `Is' and `As' classes.
1011 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1014 public abstract class Probe : Expression {
1015 public Expression ProbeType;
1016 protected Expression expr;
1017 protected Type probe_type;
1019 public Probe (Expression expr, Expression probe_type, Location l)
1021 ProbeType = probe_type;
1026 public Expression Expr {
1032 public override Expression DoResolve (EmitContext ec)
1034 TypeExpr texpr = ProbeType.ResolveAsTypeTerminal (ec, false);
1037 probe_type = texpr.ResolveType (ec);
1039 CheckObsoleteAttribute (probe_type);
1041 expr = expr.Resolve (ec);
1045 if (expr.Type.IsPointer) {
1046 Report.Error (244, loc, "\"is\" or \"as\" are not valid on pointer types");
1054 /// Implementation of the `is' operator.
1056 public class Is : Probe {
1057 public Is (Expression expr, Expression probe_type, Location l)
1058 : base (expr, probe_type, l)
1063 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1068 public override void Emit (EmitContext ec)
1070 ILGenerator ig = ec.ig;
1075 case Action.AlwaysFalse:
1076 ig.Emit (OpCodes.Pop);
1077 IntConstant.EmitInt (ig, 0);
1079 case Action.AlwaysTrue:
1080 ig.Emit (OpCodes.Pop);
1081 IntConstant.EmitInt (ig, 1);
1083 case Action.LeaveOnStack:
1084 // the `e != null' rule.
1085 ig.Emit (OpCodes.Ldnull);
1086 ig.Emit (OpCodes.Ceq);
1087 ig.Emit (OpCodes.Ldc_I4_0);
1088 ig.Emit (OpCodes.Ceq);
1091 ig.Emit (OpCodes.Isinst, probe_type);
1092 ig.Emit (OpCodes.Ldnull);
1093 ig.Emit (OpCodes.Cgt_Un);
1096 throw new Exception ("never reached");
1099 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
1101 ILGenerator ig = ec.ig;
1104 case Action.AlwaysFalse:
1106 ig.Emit (OpCodes.Br, target);
1109 case Action.AlwaysTrue:
1111 ig.Emit (OpCodes.Br, target);
1114 case Action.LeaveOnStack:
1115 // the `e != null' rule.
1117 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1121 ig.Emit (OpCodes.Isinst, probe_type);
1122 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1125 throw new Exception ("never reached");
1128 public override Expression DoResolve (EmitContext ec)
1130 Expression e = base.DoResolve (ec);
1132 if ((e == null) || (expr == null))
1135 Type etype = expr.Type;
1136 bool warning_always_matches = false;
1137 bool warning_never_matches = false;
1139 type = TypeManager.bool_type;
1140 eclass = ExprClass.Value;
1143 // First case, if at compile time, there is an implicit conversion
1144 // then e != null (objects) or true (value types)
1146 e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1149 if (etype.IsValueType)
1150 action = Action.AlwaysTrue;
1152 action = Action.LeaveOnStack;
1154 warning_always_matches = true;
1155 } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1157 // Second case: explicit reference convresion
1159 if (expr is NullLiteral)
1160 action = Action.AlwaysFalse;
1162 action = Action.Probe;
1164 action = Action.AlwaysFalse;
1165 warning_never_matches = true;
1168 if (warning_always_matches)
1169 Warning (183, "The given expression is always of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1170 else if (warning_never_matches){
1171 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1172 Warning (184, "The given expression is never of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1180 /// Implementation of the `as' operator.
1182 public class As : Probe {
1183 public As (Expression expr, Expression probe_type, Location l)
1184 : base (expr, probe_type, l)
1188 bool do_isinst = false;
1190 public override void Emit (EmitContext ec)
1192 ILGenerator ig = ec.ig;
1197 ig.Emit (OpCodes.Isinst, probe_type);
1200 static void Error_CannotConvertType (Type source, Type target, Location loc)
1203 39, loc, "as operator can not convert from `" +
1204 TypeManager.CSharpName (source) + "' to `" +
1205 TypeManager.CSharpName (target) + "'");
1208 public override Expression DoResolve (EmitContext ec)
1210 Expression e = base.DoResolve (ec);
1216 eclass = ExprClass.Value;
1217 Type etype = expr.Type;
1219 if (TypeManager.IsValueType (probe_type)){
1220 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1221 TypeManager.CSharpName (probe_type) + " is a value type)");
1226 e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1233 if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1238 Error_CannotConvertType (etype, probe_type, loc);
1244 /// This represents a typecast in the source language.
1246 /// FIXME: Cast expressions have an unusual set of parsing
1247 /// rules, we need to figure those out.
1249 public class Cast : Expression {
1250 Expression target_type;
1253 public Cast (Expression cast_type, Expression expr, Location loc)
1255 this.target_type = cast_type;
1260 public Expression TargetType {
1266 public Expression Expr {
1275 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1277 if (!ec.ConstantCheckState)
1280 if ((value < min) || (value > max)) {
1281 Error (221, "Constant value `" + value + "' cannot be converted " +
1282 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1283 "syntax to override)");
1290 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1292 if (!ec.ConstantCheckState)
1296 Error (221, "Constant value `" + value + "' cannot be converted " +
1297 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1298 "syntax to override)");
1305 bool CheckUnsigned (EmitContext ec, long value, Type type)
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)");
1321 /// Attempts to do a compile-time folding of a constant cast.
1323 Expression TryReduce (EmitContext ec, Type target_type)
1325 Expression real_expr = expr;
1326 if (real_expr is EnumConstant)
1327 real_expr = ((EnumConstant) real_expr).Child;
1329 if (real_expr is ByteConstant){
1330 byte v = ((ByteConstant) real_expr).Value;
1332 if (target_type == TypeManager.sbyte_type) {
1333 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1335 return new SByteConstant ((sbyte) v);
1337 if (target_type == TypeManager.short_type)
1338 return new ShortConstant ((short) v);
1339 if (target_type == TypeManager.ushort_type)
1340 return new UShortConstant ((ushort) v);
1341 if (target_type == TypeManager.int32_type)
1342 return new IntConstant ((int) v);
1343 if (target_type == TypeManager.uint32_type)
1344 return new UIntConstant ((uint) v);
1345 if (target_type == TypeManager.int64_type)
1346 return new LongConstant ((long) v);
1347 if (target_type == TypeManager.uint64_type)
1348 return new ULongConstant ((ulong) v);
1349 if (target_type == TypeManager.float_type)
1350 return new FloatConstant ((float) v);
1351 if (target_type == TypeManager.double_type)
1352 return new DoubleConstant ((double) v);
1353 if (target_type == TypeManager.char_type)
1354 return new CharConstant ((char) v);
1355 if (target_type == TypeManager.decimal_type)
1356 return new DecimalConstant ((decimal) v);
1358 if (real_expr is SByteConstant){
1359 sbyte v = ((SByteConstant) real_expr).Value;
1361 if (target_type == TypeManager.byte_type) {
1362 if (!CheckUnsigned (ec, v, target_type))
1364 return new ByteConstant ((byte) v);
1366 if (target_type == TypeManager.short_type)
1367 return new ShortConstant ((short) v);
1368 if (target_type == TypeManager.ushort_type) {
1369 if (!CheckUnsigned (ec, v, target_type))
1371 return new UShortConstant ((ushort) v);
1372 } if (target_type == TypeManager.int32_type)
1373 return new IntConstant ((int) v);
1374 if (target_type == TypeManager.uint32_type) {
1375 if (!CheckUnsigned (ec, v, target_type))
1377 return new UIntConstant ((uint) v);
1378 } if (target_type == TypeManager.int64_type)
1379 return new LongConstant ((long) v);
1380 if (target_type == TypeManager.uint64_type) {
1381 if (!CheckUnsigned (ec, v, target_type))
1383 return new ULongConstant ((ulong) v);
1385 if (target_type == TypeManager.float_type)
1386 return new FloatConstant ((float) v);
1387 if (target_type == TypeManager.double_type)
1388 return new DoubleConstant ((double) v);
1389 if (target_type == TypeManager.char_type) {
1390 if (!CheckUnsigned (ec, v, target_type))
1392 return new CharConstant ((char) v);
1394 if (target_type == TypeManager.decimal_type)
1395 return new DecimalConstant ((decimal) v);
1397 if (real_expr is ShortConstant){
1398 short v = ((ShortConstant) real_expr).Value;
1400 if (target_type == TypeManager.byte_type) {
1401 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1403 return new ByteConstant ((byte) v);
1405 if (target_type == TypeManager.sbyte_type) {
1406 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1408 return new SByteConstant ((sbyte) v);
1410 if (target_type == TypeManager.ushort_type) {
1411 if (!CheckUnsigned (ec, v, target_type))
1413 return new UShortConstant ((ushort) v);
1415 if (target_type == TypeManager.int32_type)
1416 return new IntConstant ((int) v);
1417 if (target_type == TypeManager.uint32_type) {
1418 if (!CheckUnsigned (ec, v, target_type))
1420 return new UIntConstant ((uint) v);
1422 if (target_type == TypeManager.int64_type)
1423 return new LongConstant ((long) v);
1424 if (target_type == TypeManager.uint64_type) {
1425 if (!CheckUnsigned (ec, v, target_type))
1427 return new ULongConstant ((ulong) v);
1429 if (target_type == TypeManager.float_type)
1430 return new FloatConstant ((float) v);
1431 if (target_type == TypeManager.double_type)
1432 return new DoubleConstant ((double) v);
1433 if (target_type == TypeManager.char_type) {
1434 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1436 return new CharConstant ((char) v);
1438 if (target_type == TypeManager.decimal_type)
1439 return new DecimalConstant ((decimal) v);
1441 if (real_expr is UShortConstant){
1442 ushort v = ((UShortConstant) real_expr).Value;
1444 if (target_type == TypeManager.byte_type) {
1445 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1447 return new ByteConstant ((byte) v);
1449 if (target_type == TypeManager.sbyte_type) {
1450 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1452 return new SByteConstant ((sbyte) v);
1454 if (target_type == TypeManager.short_type) {
1455 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1457 return new ShortConstant ((short) v);
1459 if (target_type == TypeManager.int32_type)
1460 return new IntConstant ((int) v);
1461 if (target_type == TypeManager.uint32_type)
1462 return new UIntConstant ((uint) v);
1463 if (target_type == TypeManager.int64_type)
1464 return new LongConstant ((long) v);
1465 if (target_type == TypeManager.uint64_type)
1466 return new ULongConstant ((ulong) v);
1467 if (target_type == TypeManager.float_type)
1468 return new FloatConstant ((float) v);
1469 if (target_type == TypeManager.double_type)
1470 return new DoubleConstant ((double) v);
1471 if (target_type == TypeManager.char_type) {
1472 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1474 return new CharConstant ((char) v);
1476 if (target_type == TypeManager.decimal_type)
1477 return new DecimalConstant ((decimal) v);
1479 if (real_expr is IntConstant){
1480 int v = ((IntConstant) real_expr).Value;
1482 if (target_type == TypeManager.byte_type) {
1483 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1485 return new ByteConstant ((byte) v);
1487 if (target_type == TypeManager.sbyte_type) {
1488 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1490 return new SByteConstant ((sbyte) v);
1492 if (target_type == TypeManager.short_type) {
1493 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1495 return new ShortConstant ((short) v);
1497 if (target_type == TypeManager.ushort_type) {
1498 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1500 return new UShortConstant ((ushort) v);
1502 if (target_type == TypeManager.uint32_type) {
1503 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1505 return new UIntConstant ((uint) v);
1507 if (target_type == TypeManager.int64_type)
1508 return new LongConstant ((long) v);
1509 if (target_type == TypeManager.uint64_type) {
1510 if (!CheckUnsigned (ec, v, target_type))
1512 return new ULongConstant ((ulong) v);
1514 if (target_type == TypeManager.float_type)
1515 return new FloatConstant ((float) v);
1516 if (target_type == TypeManager.double_type)
1517 return new DoubleConstant ((double) v);
1518 if (target_type == TypeManager.char_type) {
1519 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1521 return new CharConstant ((char) v);
1523 if (target_type == TypeManager.decimal_type)
1524 return new DecimalConstant ((decimal) v);
1526 if (real_expr is UIntConstant){
1527 uint v = ((UIntConstant) real_expr).Value;
1529 if (target_type == TypeManager.byte_type) {
1530 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1532 return new ByteConstant ((byte) v);
1534 if (target_type == TypeManager.sbyte_type) {
1535 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1537 return new SByteConstant ((sbyte) v);
1539 if (target_type == TypeManager.short_type) {
1540 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1542 return new ShortConstant ((short) v);
1544 if (target_type == TypeManager.ushort_type) {
1545 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1547 return new UShortConstant ((ushort) v);
1549 if (target_type == TypeManager.int32_type) {
1550 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1552 return new IntConstant ((int) v);
1554 if (target_type == TypeManager.int64_type)
1555 return new LongConstant ((long) v);
1556 if (target_type == TypeManager.uint64_type)
1557 return new ULongConstant ((ulong) v);
1558 if (target_type == TypeManager.float_type)
1559 return new FloatConstant ((float) v);
1560 if (target_type == TypeManager.double_type)
1561 return new DoubleConstant ((double) v);
1562 if (target_type == TypeManager.char_type) {
1563 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1565 return new CharConstant ((char) v);
1567 if (target_type == TypeManager.decimal_type)
1568 return new DecimalConstant ((decimal) v);
1570 if (real_expr is LongConstant){
1571 long v = ((LongConstant) real_expr).Value;
1573 if (target_type == TypeManager.byte_type) {
1574 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1576 return new ByteConstant ((byte) v);
1578 if (target_type == TypeManager.sbyte_type) {
1579 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1581 return new SByteConstant ((sbyte) v);
1583 if (target_type == TypeManager.short_type) {
1584 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1586 return new ShortConstant ((short) v);
1588 if (target_type == TypeManager.ushort_type) {
1589 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1591 return new UShortConstant ((ushort) v);
1593 if (target_type == TypeManager.int32_type) {
1594 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1596 return new IntConstant ((int) v);
1598 if (target_type == TypeManager.uint32_type) {
1599 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1601 return new UIntConstant ((uint) v);
1603 if (target_type == TypeManager.uint64_type) {
1604 if (!CheckUnsigned (ec, v, target_type))
1606 return new ULongConstant ((ulong) v);
1608 if (target_type == TypeManager.float_type)
1609 return new FloatConstant ((float) v);
1610 if (target_type == TypeManager.double_type)
1611 return new DoubleConstant ((double) v);
1612 if (target_type == TypeManager.char_type) {
1613 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1615 return new CharConstant ((char) v);
1617 if (target_type == TypeManager.decimal_type)
1618 return new DecimalConstant ((decimal) v);
1620 if (real_expr is ULongConstant){
1621 ulong v = ((ULongConstant) real_expr).Value;
1623 if (target_type == TypeManager.byte_type) {
1624 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1626 return new ByteConstant ((byte) v);
1628 if (target_type == TypeManager.sbyte_type) {
1629 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1631 return new SByteConstant ((sbyte) v);
1633 if (target_type == TypeManager.short_type) {
1634 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1636 return new ShortConstant ((short) v);
1638 if (target_type == TypeManager.ushort_type) {
1639 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1641 return new UShortConstant ((ushort) v);
1643 if (target_type == TypeManager.int32_type) {
1644 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1646 return new IntConstant ((int) v);
1648 if (target_type == TypeManager.uint32_type) {
1649 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1651 return new UIntConstant ((uint) v);
1653 if (target_type == TypeManager.int64_type) {
1654 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1656 return new LongConstant ((long) v);
1658 if (target_type == TypeManager.float_type)
1659 return new FloatConstant ((float) v);
1660 if (target_type == TypeManager.double_type)
1661 return new DoubleConstant ((double) v);
1662 if (target_type == TypeManager.char_type) {
1663 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1665 return new CharConstant ((char) v);
1667 if (target_type == TypeManager.decimal_type)
1668 return new DecimalConstant ((decimal) v);
1670 if (real_expr is FloatConstant){
1671 float v = ((FloatConstant) real_expr).Value;
1673 if (target_type == TypeManager.byte_type)
1674 return new ByteConstant ((byte) v);
1675 if (target_type == TypeManager.sbyte_type)
1676 return new SByteConstant ((sbyte) v);
1677 if (target_type == TypeManager.short_type)
1678 return new ShortConstant ((short) v);
1679 if (target_type == TypeManager.ushort_type)
1680 return new UShortConstant ((ushort) v);
1681 if (target_type == TypeManager.int32_type)
1682 return new IntConstant ((int) v);
1683 if (target_type == TypeManager.uint32_type)
1684 return new UIntConstant ((uint) v);
1685 if (target_type == TypeManager.int64_type)
1686 return new LongConstant ((long) v);
1687 if (target_type == TypeManager.uint64_type)
1688 return new ULongConstant ((ulong) v);
1689 if (target_type == TypeManager.double_type)
1690 return new DoubleConstant ((double) v);
1691 if (target_type == TypeManager.char_type)
1692 return new CharConstant ((char) v);
1693 if (target_type == TypeManager.decimal_type)
1694 return new DecimalConstant ((decimal) v);
1696 if (real_expr is DoubleConstant){
1697 double v = ((DoubleConstant) real_expr).Value;
1699 if (target_type == TypeManager.byte_type){
1700 return new ByteConstant ((byte) v);
1701 } if (target_type == TypeManager.sbyte_type)
1702 return new SByteConstant ((sbyte) v);
1703 if (target_type == TypeManager.short_type)
1704 return new ShortConstant ((short) v);
1705 if (target_type == TypeManager.ushort_type)
1706 return new UShortConstant ((ushort) v);
1707 if (target_type == TypeManager.int32_type)
1708 return new IntConstant ((int) v);
1709 if (target_type == TypeManager.uint32_type)
1710 return new UIntConstant ((uint) v);
1711 if (target_type == TypeManager.int64_type)
1712 return new LongConstant ((long) v);
1713 if (target_type == TypeManager.uint64_type)
1714 return new ULongConstant ((ulong) v);
1715 if (target_type == TypeManager.float_type)
1716 return new FloatConstant ((float) v);
1717 if (target_type == TypeManager.char_type)
1718 return new CharConstant ((char) v);
1719 if (target_type == TypeManager.decimal_type)
1720 return new DecimalConstant ((decimal) v);
1723 if (real_expr is CharConstant){
1724 char v = ((CharConstant) real_expr).Value;
1726 if (target_type == TypeManager.byte_type) {
1727 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1729 return new ByteConstant ((byte) v);
1731 if (target_type == TypeManager.sbyte_type) {
1732 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1734 return new SByteConstant ((sbyte) v);
1736 if (target_type == TypeManager.short_type) {
1737 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1739 return new ShortConstant ((short) v);
1741 if (target_type == TypeManager.int32_type)
1742 return new IntConstant ((int) v);
1743 if (target_type == TypeManager.uint32_type)
1744 return new UIntConstant ((uint) v);
1745 if (target_type == TypeManager.int64_type)
1746 return new LongConstant ((long) v);
1747 if (target_type == TypeManager.uint64_type)
1748 return new ULongConstant ((ulong) v);
1749 if (target_type == TypeManager.float_type)
1750 return new FloatConstant ((float) v);
1751 if (target_type == TypeManager.double_type)
1752 return new DoubleConstant ((double) v);
1753 if (target_type == TypeManager.char_type) {
1754 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1756 return new CharConstant ((char) v);
1758 if (target_type == TypeManager.decimal_type)
1759 return new DecimalConstant ((decimal) v);
1765 public override Expression DoResolve (EmitContext ec)
1767 expr = expr.Resolve (ec);
1771 TypeExpr target = target_type.ResolveAsTypeTerminal (ec, false);
1775 type = target.ResolveType (ec);
1777 CheckObsoleteAttribute (type);
1779 if (type.IsAbstract && type.IsSealed) {
1780 Report.Error (716, loc, "Cannot convert to static type '{0}'", TypeManager.CSharpName (type));
1784 eclass = ExprClass.Value;
1786 if (expr is Constant){
1787 Expression e = TryReduce (ec, type);
1793 if (type.IsPointer && !ec.InUnsafe) {
1797 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1801 public override void Emit (EmitContext ec)
1804 // This one will never happen
1806 throw new Exception ("Should not happen");
1811 /// Binary operators
1813 public class Binary : Expression {
1814 public enum Operator : byte {
1815 Multiply, Division, Modulus,
1816 Addition, Subtraction,
1817 LeftShift, RightShift,
1818 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1819 Equality, Inequality,
1829 Expression left, right;
1831 // This must be kept in sync with Operator!!!
1832 public static readonly string [] oper_names;
1836 oper_names = new string [(int) Operator.TOP];
1838 oper_names [(int) Operator.Multiply] = "op_Multiply";
1839 oper_names [(int) Operator.Division] = "op_Division";
1840 oper_names [(int) Operator.Modulus] = "op_Modulus";
1841 oper_names [(int) Operator.Addition] = "op_Addition";
1842 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1843 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1844 oper_names [(int) Operator.RightShift] = "op_RightShift";
1845 oper_names [(int) Operator.LessThan] = "op_LessThan";
1846 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1847 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1848 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1849 oper_names [(int) Operator.Equality] = "op_Equality";
1850 oper_names [(int) Operator.Inequality] = "op_Inequality";
1851 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1852 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1853 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1854 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1855 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1858 public Binary (Operator oper, Expression left, Expression right, Location loc)
1866 public Operator Oper {
1875 public Expression Left {
1884 public Expression Right {
1895 /// Returns a stringified representation of the Operator
1897 static string OperName (Operator oper)
1900 case Operator.Multiply:
1902 case Operator.Division:
1904 case Operator.Modulus:
1906 case Operator.Addition:
1908 case Operator.Subtraction:
1910 case Operator.LeftShift:
1912 case Operator.RightShift:
1914 case Operator.LessThan:
1916 case Operator.GreaterThan:
1918 case Operator.LessThanOrEqual:
1920 case Operator.GreaterThanOrEqual:
1922 case Operator.Equality:
1924 case Operator.Inequality:
1926 case Operator.BitwiseAnd:
1928 case Operator.BitwiseOr:
1930 case Operator.ExclusiveOr:
1932 case Operator.LogicalOr:
1934 case Operator.LogicalAnd:
1938 return oper.ToString ();
1941 public override string ToString ()
1943 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1944 right.ToString () + ")";
1947 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1949 if (expr.Type == target_type)
1952 return Convert.ImplicitConversion (ec, expr, target_type, loc);
1955 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1958 34, loc, "Operator `" + OperName (oper)
1959 + "' is ambiguous on operands of type `"
1960 + TypeManager.CSharpName (l) + "' "
1961 + "and `" + TypeManager.CSharpName (r)
1965 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
1967 if ((l == t) || (r == t))
1970 if (!check_user_conversions)
1973 if (Convert.ImplicitUserConversionExists (ec, l, t))
1975 else if (Convert.ImplicitUserConversionExists (ec, r, t))
1982 // Note that handling the case l == Decimal || r == Decimal
1983 // is taken care of by the Step 1 Operator Overload resolution.
1985 // If `check_user_conv' is true, we also check whether a user-defined conversion
1986 // exists. Note that we only need to do this if both arguments are of a user-defined
1987 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
1988 // so we don't explicitly check for performance reasons.
1990 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
1992 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
1994 // If either operand is of type double, the other operand is
1995 // conveted to type double.
1997 if (r != TypeManager.double_type)
1998 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
1999 if (l != TypeManager.double_type)
2000 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
2002 type = TypeManager.double_type;
2003 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
2005 // if either operand is of type float, the other operand is
2006 // converted to type float.
2008 if (r != TypeManager.double_type)
2009 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
2010 if (l != TypeManager.double_type)
2011 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
2012 type = TypeManager.float_type;
2013 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2017 // If either operand is of type ulong, the other operand is
2018 // converted to type ulong. or an error ocurrs if the other
2019 // operand is of type sbyte, short, int or long
2021 if (l == TypeManager.uint64_type){
2022 if (r != TypeManager.uint64_type){
2023 if (right is IntConstant){
2024 IntConstant ic = (IntConstant) right;
2026 e = Convert.TryImplicitIntConversion (l, ic);
2029 } else if (right is LongConstant){
2030 long ll = ((LongConstant) right).Value;
2033 right = new ULongConstant ((ulong) ll);
2035 e = Convert.ImplicitNumericConversion (ec, right, l, loc);
2042 if (left is IntConstant){
2043 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
2046 } else if (left is LongConstant){
2047 long ll = ((LongConstant) left).Value;
2050 left = new ULongConstant ((ulong) ll);
2052 e = Convert.ImplicitNumericConversion (ec, left, r, loc);
2059 if ((other == TypeManager.sbyte_type) ||
2060 (other == TypeManager.short_type) ||
2061 (other == TypeManager.int32_type) ||
2062 (other == TypeManager.int64_type))
2063 Error_OperatorAmbiguous (loc, oper, l, r);
2065 left = ForceConversion (ec, left, TypeManager.uint64_type);
2066 right = ForceConversion (ec, right, TypeManager.uint64_type);
2068 type = TypeManager.uint64_type;
2069 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2071 // If either operand is of type long, the other operand is converted
2074 if (l != TypeManager.int64_type)
2075 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
2076 if (r != TypeManager.int64_type)
2077 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
2079 type = TypeManager.int64_type;
2080 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2082 // If either operand is of type uint, and the other
2083 // operand is of type sbyte, short or int, othe operands are
2084 // converted to type long (unless we have an int constant).
2088 if (l == TypeManager.uint32_type){
2089 if (right is IntConstant){
2090 IntConstant ic = (IntConstant) right;
2094 right = new UIntConstant ((uint) val);
2101 } else if (r == TypeManager.uint32_type){
2102 if (left is IntConstant){
2103 IntConstant ic = (IntConstant) left;
2107 left = new UIntConstant ((uint) val);
2116 if ((other == TypeManager.sbyte_type) ||
2117 (other == TypeManager.short_type) ||
2118 (other == TypeManager.int32_type)){
2119 left = ForceConversion (ec, left, TypeManager.int64_type);
2120 right = ForceConversion (ec, right, TypeManager.int64_type);
2121 type = TypeManager.int64_type;
2124 // if either operand is of type uint, the other
2125 // operand is converd to type uint
2127 left = ForceConversion (ec, left, TypeManager.uint32_type);
2128 right = ForceConversion (ec, right, TypeManager.uint32_type);
2129 type = TypeManager.uint32_type;
2131 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2132 if (l != TypeManager.decimal_type)
2133 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
2135 if (r != TypeManager.decimal_type)
2136 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
2137 type = TypeManager.decimal_type;
2139 left = ForceConversion (ec, left, TypeManager.int32_type);
2140 right = ForceConversion (ec, right, TypeManager.int32_type);
2142 type = TypeManager.int32_type;
2145 return (left != null) && (right != null);
2148 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2150 Report.Error (19, loc,
2151 "Operator " + name + " cannot be applied to operands of type `" +
2152 TypeManager.CSharpName (l) + "' and `" +
2153 TypeManager.CSharpName (r) + "'");
2156 void Error_OperatorCannotBeApplied ()
2158 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2161 static bool is_unsigned (Type t)
2163 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2164 t == TypeManager.short_type || t == TypeManager.byte_type);
2167 static bool is_user_defined (Type t)
2169 if (t.IsSubclassOf (TypeManager.value_type) &&
2170 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2176 Expression Make32or64 (EmitContext ec, Expression e)
2180 if (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2181 t == TypeManager.int64_type || t == TypeManager.uint64_type)
2183 Expression ee = Convert.ImplicitConversion (ec, e, TypeManager.int32_type, loc);
2186 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint32_type, loc);
2189 ee = Convert.ImplicitConversion (ec, e, TypeManager.int64_type, loc);
2192 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint64_type, loc);
2198 Expression CheckShiftArguments (EmitContext ec)
2202 e = ForceConversion (ec, right, TypeManager.int32_type);
2204 Error_OperatorCannotBeApplied ();
2209 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
2210 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
2211 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
2212 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
2216 if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
2217 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (31), loc);
2218 right = right.DoResolve (ec);
2220 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (63), loc);
2221 right = right.DoResolve (ec);
2226 Error_OperatorCannotBeApplied ();
2230 Expression ResolveOperator (EmitContext ec)
2233 Type r = right.Type;
2236 // Special cases: string comapred to null
2238 if (oper == Operator.Equality || oper == Operator.Inequality){
2239 if ((!TypeManager.IsValueType (l) && (right is NullLiteral)) ||
2240 (!TypeManager.IsValueType (r) && (left is NullLiteral))) {
2241 Type = TypeManager.bool_type;
2247 if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
2248 Type = TypeManager.bool_type;
2255 // Do not perform operator overload resolution when both sides are
2258 if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
2260 // Step 1: Perform Operator Overload location
2262 Expression left_expr, right_expr;
2264 string op = oper_names [(int) oper];
2266 MethodGroupExpr union;
2267 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2269 right_expr = MemberLookup (
2270 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2271 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2273 union = (MethodGroupExpr) left_expr;
2275 if (union != null) {
2276 ArrayList args = new ArrayList (2);
2277 args.Add (new Argument (left, Argument.AType.Expression));
2278 args.Add (new Argument (right, Argument.AType.Expression));
2280 MethodBase method = Invocation.OverloadResolve (
2281 ec, union, args, true, Location.Null);
2283 if (method != null) {
2284 MethodInfo mi = (MethodInfo) method;
2286 return new BinaryMethod (mi.ReturnType, method, args);
2292 // Step 0: String concatenation (because overloading will get this wrong)
2294 if (oper == Operator.Addition){
2296 // If any of the arguments is a string, cast to string
2299 // Simple constant folding
2300 if (left is StringConstant && right is StringConstant)
2301 return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value);
2303 if (l == TypeManager.string_type || r == TypeManager.string_type) {
2305 if (r == TypeManager.void_type || l == TypeManager.void_type) {
2306 Error_OperatorCannotBeApplied ();
2310 // try to fold it in on the left
2311 if (left is StringConcat) {
2314 // We have to test here for not-null, since we can be doubly-resolved
2315 // take care of not appending twice
2318 type = TypeManager.string_type;
2319 ((StringConcat) left).Append (ec, right);
2320 return left.Resolve (ec);
2326 // Otherwise, start a new concat expression
2327 return new StringConcat (ec, loc, left, right).Resolve (ec);
2331 // Transform a + ( - b) into a - b
2333 if (right is Unary){
2334 Unary right_unary = (Unary) right;
2336 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2337 oper = Operator.Subtraction;
2338 right = right_unary.Expr;
2344 if (oper == Operator.Equality || oper == Operator.Inequality){
2345 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2346 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2347 Error_OperatorCannotBeApplied ();
2351 type = TypeManager.bool_type;
2356 // operator != (object a, object b)
2357 // operator == (object a, object b)
2359 // For this to be used, both arguments have to be reference-types.
2360 // Read the rationale on the spec (14.9.6)
2362 // Also, if at compile time we know that the classes do not inherit
2363 // one from the other, then we catch the error there.
2365 if (!(l.IsValueType || r.IsValueType)){
2366 type = TypeManager.bool_type;
2371 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2375 // Also, a standard conversion must exist from either one
2377 if (!(Convert.ImplicitStandardConversionExists (ec, left, r) ||
2378 Convert.ImplicitStandardConversionExists (ec, right, l))){
2379 Error_OperatorCannotBeApplied ();
2383 // We are going to have to convert to an object to compare
2385 if (l != TypeManager.object_type)
2386 left = new EmptyCast (left, TypeManager.object_type);
2387 if (r != TypeManager.object_type)
2388 right = new EmptyCast (right, TypeManager.object_type);
2391 // FIXME: CSC here catches errors cs254 and cs252
2397 // One of them is a valuetype, but the other one is not.
2399 if (!l.IsValueType || !r.IsValueType) {
2400 Error_OperatorCannotBeApplied ();
2405 // Only perform numeric promotions on:
2406 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2408 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2409 if (l.IsSubclassOf (TypeManager.delegate_type)){
2410 if (((right.eclass == ExprClass.MethodGroup) ||
2411 (r == TypeManager.anonymous_method_type))){
2412 if ((RootContext.Version != LanguageVersion.ISO_1)){
2413 Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2421 if (r.IsSubclassOf (TypeManager.delegate_type)){
2423 ArrayList args = new ArrayList (2);
2425 args = new ArrayList (2);
2426 args.Add (new Argument (left, Argument.AType.Expression));
2427 args.Add (new Argument (right, Argument.AType.Expression));
2429 if (oper == Operator.Addition)
2430 method = TypeManager.delegate_combine_delegate_delegate;
2432 method = TypeManager.delegate_remove_delegate_delegate;
2435 Error_OperatorCannotBeApplied ();
2439 return new BinaryDelegate (l, method, args);
2444 // Pointer arithmetic:
2446 // T* operator + (T* x, int y);
2447 // T* operator + (T* x, uint y);
2448 // T* operator + (T* x, long y);
2449 // T* operator + (T* x, ulong y);
2451 // T* operator + (int y, T* x);
2452 // T* operator + (uint y, T *x);
2453 // T* operator + (long y, T *x);
2454 // T* operator + (ulong y, T *x);
2456 // T* operator - (T* x, int y);
2457 // T* operator - (T* x, uint y);
2458 // T* operator - (T* x, long y);
2459 // T* operator - (T* x, ulong y);
2461 // long operator - (T* x, T *y)
2464 if (r.IsPointer && oper == Operator.Subtraction){
2466 return new PointerArithmetic (
2467 false, left, right, TypeManager.int64_type,
2470 Expression t = Make32or64 (ec, right);
2472 return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc).Resolve (ec);
2474 } else if (r.IsPointer && oper == Operator.Addition){
2475 Expression t = Make32or64 (ec, left);
2477 return new PointerArithmetic (true, right, t, r, loc).Resolve (ec);
2482 // Enumeration operators
2484 bool lie = TypeManager.IsEnumType (l);
2485 bool rie = TypeManager.IsEnumType (r);
2489 // U operator - (E e, E f)
2491 if (oper == Operator.Subtraction){
2493 type = TypeManager.EnumToUnderlying (l);
2496 Error_OperatorCannotBeApplied ();
2502 // operator + (E e, U x)
2503 // operator - (E e, U x)
2505 if (oper == Operator.Addition || oper == Operator.Subtraction){
2506 Type enum_type = lie ? l : r;
2507 Type other_type = lie ? r : l;
2508 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2510 if (underlying_type != other_type){
2511 temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
2521 Error_OperatorCannotBeApplied ();
2530 temp = Convert.ImplicitConversion (ec, right, l, loc);
2534 Error_OperatorCannotBeApplied ();
2538 temp = Convert.ImplicitConversion (ec, left, r, loc);
2543 Error_OperatorCannotBeApplied ();
2548 if (oper == Operator.Equality || oper == Operator.Inequality ||
2549 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2550 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2551 if (left.Type != right.Type){
2552 Error_OperatorCannotBeApplied ();
2555 type = TypeManager.bool_type;
2559 if (oper == Operator.BitwiseAnd ||
2560 oper == Operator.BitwiseOr ||
2561 oper == Operator.ExclusiveOr){
2565 Error_OperatorCannotBeApplied ();
2569 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2570 return CheckShiftArguments (ec);
2572 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2573 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2574 type = TypeManager.bool_type;
2579 Error_OperatorCannotBeApplied ();
2583 Expression e = new ConditionalLogicalOperator (
2584 oper == Operator.LogicalAnd, left, right, l, loc);
2585 return e.Resolve (ec);
2589 // operator & (bool x, bool y)
2590 // operator | (bool x, bool y)
2591 // operator ^ (bool x, bool y)
2593 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2594 if (oper == Operator.BitwiseAnd ||
2595 oper == Operator.BitwiseOr ||
2596 oper == Operator.ExclusiveOr){
2603 // Pointer comparison
2605 if (l.IsPointer && r.IsPointer){
2606 if (oper == Operator.Equality || oper == Operator.Inequality ||
2607 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2608 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2609 type = TypeManager.bool_type;
2615 // This will leave left or right set to null if there is an error
2617 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2618 DoNumericPromotions (ec, l, r, check_user_conv);
2619 if (left == null || right == null){
2620 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2625 // reload our cached types if required
2630 if (oper == Operator.BitwiseAnd ||
2631 oper == Operator.BitwiseOr ||
2632 oper == Operator.ExclusiveOr){
2634 if (((l == TypeManager.int32_type) ||
2635 (l == TypeManager.uint32_type) ||
2636 (l == TypeManager.short_type) ||
2637 (l == TypeManager.ushort_type) ||
2638 (l == TypeManager.int64_type) ||
2639 (l == TypeManager.uint64_type))){
2642 Error_OperatorCannotBeApplied ();
2646 Error_OperatorCannotBeApplied ();
2651 if (oper == Operator.Equality ||
2652 oper == Operator.Inequality ||
2653 oper == Operator.LessThanOrEqual ||
2654 oper == Operator.LessThan ||
2655 oper == Operator.GreaterThanOrEqual ||
2656 oper == Operator.GreaterThan){
2657 type = TypeManager.bool_type;
2663 public override Expression DoResolve (EmitContext ec)
2665 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2666 left = ((ParenthesizedExpression) left).Expr;
2667 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2671 if (left.eclass == ExprClass.Type) {
2672 Error (75, "Casting a negative value needs to have the value in parentheses.");
2676 left = left.Resolve (ec);
2677 right = right.Resolve (ec);
2679 if (left == null || right == null)
2682 eclass = ExprClass.Value;
2684 Constant rc = right as Constant;
2685 Constant lc = left as Constant;
2687 if (rc != null & lc != null){
2688 Expression e = ConstantFold.BinaryFold (
2689 ec, oper, lc, rc, loc);
2694 return ResolveOperator (ec);
2698 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2699 /// context of a conditional bool expression. This function will return
2700 /// false if it is was possible to use EmitBranchable, or true if it was.
2702 /// The expression's code is generated, and we will generate a branch to `target'
2703 /// if the resulting expression value is equal to isTrue
2705 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2707 ILGenerator ig = ec.ig;
2710 // This is more complicated than it looks, but its just to avoid
2711 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2712 // but on top of that we want for == and != to use a special path
2713 // if we are comparing against null
2715 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
2716 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2719 // put the constant on the rhs, for simplicity
2721 if (left is Constant) {
2722 Expression swap = right;
2727 if (((Constant) right).IsZeroInteger) {
2730 ig.Emit (OpCodes.Brtrue, target);
2732 ig.Emit (OpCodes.Brfalse, target);
2735 } else if (right is BoolConstant) {
2737 if (my_on_true != ((BoolConstant) right).Value)
2738 ig.Emit (OpCodes.Brtrue, target);
2740 ig.Emit (OpCodes.Brfalse, target);
2745 } else if (oper == Operator.LogicalAnd) {
2748 Label tests_end = ig.DefineLabel ();
2750 left.EmitBranchable (ec, tests_end, false);
2751 right.EmitBranchable (ec, target, true);
2752 ig.MarkLabel (tests_end);
2754 left.EmitBranchable (ec, target, false);
2755 right.EmitBranchable (ec, target, false);
2760 } else if (oper == Operator.LogicalOr){
2762 left.EmitBranchable (ec, target, true);
2763 right.EmitBranchable (ec, target, true);
2766 Label tests_end = ig.DefineLabel ();
2767 left.EmitBranchable (ec, tests_end, true);
2768 right.EmitBranchable (ec, target, false);
2769 ig.MarkLabel (tests_end);
2774 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2775 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2776 oper == Operator.Equality || oper == Operator.Inequality)) {
2777 base.EmitBranchable (ec, target, onTrue);
2785 bool isUnsigned = is_unsigned (t) || t == TypeManager.double_type || t == TypeManager.float_type;
2788 case Operator.Equality:
2790 ig.Emit (OpCodes.Beq, target);
2792 ig.Emit (OpCodes.Bne_Un, target);
2795 case Operator.Inequality:
2797 ig.Emit (OpCodes.Bne_Un, target);
2799 ig.Emit (OpCodes.Beq, target);
2802 case Operator.LessThan:
2805 ig.Emit (OpCodes.Blt_Un, target);
2807 ig.Emit (OpCodes.Blt, target);
2810 ig.Emit (OpCodes.Bge_Un, target);
2812 ig.Emit (OpCodes.Bge, target);
2815 case Operator.GreaterThan:
2818 ig.Emit (OpCodes.Bgt_Un, target);
2820 ig.Emit (OpCodes.Bgt, target);
2823 ig.Emit (OpCodes.Ble_Un, target);
2825 ig.Emit (OpCodes.Ble, target);
2828 case Operator.LessThanOrEqual:
2831 ig.Emit (OpCodes.Ble_Un, target);
2833 ig.Emit (OpCodes.Ble, target);
2836 ig.Emit (OpCodes.Bgt_Un, target);
2838 ig.Emit (OpCodes.Bgt, target);
2842 case Operator.GreaterThanOrEqual:
2845 ig.Emit (OpCodes.Bge_Un, target);
2847 ig.Emit (OpCodes.Bge, target);
2850 ig.Emit (OpCodes.Blt_Un, target);
2852 ig.Emit (OpCodes.Blt, target);
2855 Console.WriteLine (oper);
2856 throw new Exception ("what is THAT");
2860 public override void Emit (EmitContext ec)
2862 ILGenerator ig = ec.ig;
2867 // Handle short-circuit operators differently
2870 if (oper == Operator.LogicalAnd) {
2871 Label load_zero = ig.DefineLabel ();
2872 Label end = ig.DefineLabel ();
2874 left.EmitBranchable (ec, load_zero, false);
2876 ig.Emit (OpCodes.Br, end);
2878 ig.MarkLabel (load_zero);
2879 ig.Emit (OpCodes.Ldc_I4_0);
2882 } else if (oper == Operator.LogicalOr) {
2883 Label load_one = ig.DefineLabel ();
2884 Label end = ig.DefineLabel ();
2886 left.EmitBranchable (ec, load_one, true);
2888 ig.Emit (OpCodes.Br, end);
2890 ig.MarkLabel (load_one);
2891 ig.Emit (OpCodes.Ldc_I4_1);
2899 bool isUnsigned = is_unsigned (left.Type);
2902 case Operator.Multiply:
2904 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2905 opcode = OpCodes.Mul_Ovf;
2906 else if (isUnsigned)
2907 opcode = OpCodes.Mul_Ovf_Un;
2909 opcode = OpCodes.Mul;
2911 opcode = OpCodes.Mul;
2915 case Operator.Division:
2917 opcode = OpCodes.Div_Un;
2919 opcode = OpCodes.Div;
2922 case Operator.Modulus:
2924 opcode = OpCodes.Rem_Un;
2926 opcode = OpCodes.Rem;
2929 case Operator.Addition:
2931 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2932 opcode = OpCodes.Add_Ovf;
2933 else if (isUnsigned)
2934 opcode = OpCodes.Add_Ovf_Un;
2936 opcode = OpCodes.Add;
2938 opcode = OpCodes.Add;
2941 case Operator.Subtraction:
2943 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2944 opcode = OpCodes.Sub_Ovf;
2945 else if (isUnsigned)
2946 opcode = OpCodes.Sub_Ovf_Un;
2948 opcode = OpCodes.Sub;
2950 opcode = OpCodes.Sub;
2953 case Operator.RightShift:
2955 opcode = OpCodes.Shr_Un;
2957 opcode = OpCodes.Shr;
2960 case Operator.LeftShift:
2961 opcode = OpCodes.Shl;
2964 case Operator.Equality:
2965 opcode = OpCodes.Ceq;
2968 case Operator.Inequality:
2969 ig.Emit (OpCodes.Ceq);
2970 ig.Emit (OpCodes.Ldc_I4_0);
2972 opcode = OpCodes.Ceq;
2975 case Operator.LessThan:
2977 opcode = OpCodes.Clt_Un;
2979 opcode = OpCodes.Clt;
2982 case Operator.GreaterThan:
2984 opcode = OpCodes.Cgt_Un;
2986 opcode = OpCodes.Cgt;
2989 case Operator.LessThanOrEqual:
2990 Type lt = left.Type;
2992 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
2993 ig.Emit (OpCodes.Cgt_Un);
2995 ig.Emit (OpCodes.Cgt);
2996 ig.Emit (OpCodes.Ldc_I4_0);
2998 opcode = OpCodes.Ceq;
3001 case Operator.GreaterThanOrEqual:
3002 Type le = left.Type;
3004 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3005 ig.Emit (OpCodes.Clt_Un);
3007 ig.Emit (OpCodes.Clt);
3009 ig.Emit (OpCodes.Ldc_I4_0);
3011 opcode = OpCodes.Ceq;
3014 case Operator.BitwiseOr:
3015 opcode = OpCodes.Or;
3018 case Operator.BitwiseAnd:
3019 opcode = OpCodes.And;
3022 case Operator.ExclusiveOr:
3023 opcode = OpCodes.Xor;
3027 throw new Exception ("This should not happen: Operator = "
3028 + oper.ToString ());
3036 // Object created by Binary when the binary operator uses an method instead of being
3037 // a binary operation that maps to a CIL binary operation.
3039 public class BinaryMethod : Expression {
3040 public MethodBase method;
3041 public ArrayList Arguments;
3043 public BinaryMethod (Type t, MethodBase m, ArrayList args)
3048 eclass = ExprClass.Value;
3051 public override Expression DoResolve (EmitContext ec)
3056 public override void Emit (EmitContext ec)
3058 ILGenerator ig = ec.ig;
3060 if (Arguments != null)
3061 Invocation.EmitArguments (ec, method, Arguments, false, null);
3063 if (method is MethodInfo)
3064 ig.Emit (OpCodes.Call, (MethodInfo) method);
3066 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3071 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3072 // b, c, d... may be strings or objects.
3074 public class StringConcat : Expression {
3076 bool invalid = false;
3079 public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
3082 type = TypeManager.string_type;
3083 eclass = ExprClass.Value;
3085 operands = new ArrayList (2);
3090 public override Expression DoResolve (EmitContext ec)
3098 public void Append (EmitContext ec, Expression operand)
3103 if (operand is StringConstant && operands.Count != 0) {
3104 StringConstant last_operand = operands [operands.Count - 1] as StringConstant;
3105 if (last_operand != null) {
3106 operands [operands.Count - 1] = new StringConstant (last_operand.Value + ((StringConstant) operand).Value);
3112 // Conversion to object
3114 if (operand.Type != TypeManager.string_type) {
3115 Expression no = Convert.ImplicitConversion (ec, operand, TypeManager.object_type, loc);
3118 Binary.Error_OperatorCannotBeApplied (loc, "+", TypeManager.string_type, operand.Type);
3124 operands.Add (operand);
3127 public override void Emit (EmitContext ec)
3129 MethodInfo concat_method = null;
3132 // Are we also concating objects?
3134 bool is_strings_only = true;
3137 // Do conversion to arguments; check for strings only
3139 for (int i = 0; i < operands.Count; i ++) {
3140 Expression e = (Expression) operands [i];
3141 is_strings_only &= e.Type == TypeManager.string_type;
3144 for (int i = 0; i < operands.Count; i ++) {
3145 Expression e = (Expression) operands [i];
3147 if (! is_strings_only && e.Type == TypeManager.string_type) {
3148 // need to make sure this is an object, because the EmitParams
3149 // method might look at the type of this expression, see it is a
3150 // string and emit a string [] when we want an object [];
3152 e = Convert.ImplicitConversion (ec, e, TypeManager.object_type, loc);
3154 operands [i] = new Argument (e, Argument.AType.Expression);
3158 // Find the right method
3160 switch (operands.Count) {
3163 // This should not be possible, because simple constant folding
3164 // is taken care of in the Binary code.
3166 throw new Exception ("how did you get here?");
3169 concat_method = is_strings_only ?
3170 TypeManager.string_concat_string_string :
3171 TypeManager.string_concat_object_object ;
3174 concat_method = is_strings_only ?
3175 TypeManager.string_concat_string_string_string :
3176 TypeManager.string_concat_object_object_object ;
3180 // There is not a 4 param overlaod for object (the one that there is
3181 // is actually a varargs methods, and is only in corlib because it was
3182 // introduced there before.).
3184 if (!is_strings_only)
3187 concat_method = TypeManager.string_concat_string_string_string_string;
3190 concat_method = is_strings_only ?
3191 TypeManager.string_concat_string_dot_dot_dot :
3192 TypeManager.string_concat_object_dot_dot_dot ;
3196 Invocation.EmitArguments (ec, concat_method, operands, false, null);
3197 ec.ig.Emit (OpCodes.Call, concat_method);
3202 // Object created with +/= on delegates
3204 public class BinaryDelegate : Expression {
3208 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3213 eclass = ExprClass.Value;
3216 public override Expression DoResolve (EmitContext ec)
3221 public override void Emit (EmitContext ec)
3223 ILGenerator ig = ec.ig;
3225 Invocation.EmitArguments (ec, method, args, false, null);
3227 ig.Emit (OpCodes.Call, (MethodInfo) method);
3228 ig.Emit (OpCodes.Castclass, type);
3231 public Expression Right {
3233 Argument arg = (Argument) args [1];
3238 public bool IsAddition {
3240 return method == TypeManager.delegate_combine_delegate_delegate;
3246 // User-defined conditional logical operator
3247 public class ConditionalLogicalOperator : Expression {
3248 Expression left, right;
3251 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3254 eclass = ExprClass.Value;
3258 this.is_and = is_and;
3261 protected void Error19 ()
3263 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3266 protected void Error218 ()
3268 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3269 "declarations of operator true and operator false");
3272 Expression op_true, op_false, op;
3273 LocalTemporary left_temp;
3275 public override Expression DoResolve (EmitContext ec)
3278 Expression operator_group;
3280 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3281 if (operator_group == null) {
3286 left_temp = new LocalTemporary (ec, type);
3288 ArrayList arguments = new ArrayList ();
3289 arguments.Add (new Argument (left_temp, Argument.AType.Expression));
3290 arguments.Add (new Argument (right, Argument.AType.Expression));
3291 method = Invocation.OverloadResolve (
3292 ec, (MethodGroupExpr) operator_group, arguments, false, loc)
3294 if ((method == null) || (method.ReturnType != type)) {
3299 op = new StaticCallExpr (method, arguments, loc);
3301 op_true = GetOperatorTrue (ec, left_temp, loc);
3302 op_false = GetOperatorFalse (ec, left_temp, loc);
3303 if ((op_true == null) || (op_false == null)) {
3311 public override void Emit (EmitContext ec)
3313 ILGenerator ig = ec.ig;
3314 Label false_target = ig.DefineLabel ();
3315 Label end_target = ig.DefineLabel ();
3318 left_temp.Store (ec);
3320 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
3321 left_temp.Emit (ec);
3322 ig.Emit (OpCodes.Br, end_target);
3323 ig.MarkLabel (false_target);
3325 ig.MarkLabel (end_target);
3329 public class PointerArithmetic : Expression {
3330 Expression left, right;
3334 // We assume that `l' is always a pointer
3336 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3342 is_add = is_addition;
3345 public override Expression DoResolve (EmitContext ec)
3347 eclass = ExprClass.Variable;
3349 if (left.Type == TypeManager.void_ptr_type) {
3350 Error (242, "The operation in question is undefined on void pointers");
3357 public override void Emit (EmitContext ec)
3359 Type op_type = left.Type;
3360 ILGenerator ig = ec.ig;
3361 Type element = TypeManager.GetElementType (op_type);
3362 int size = GetTypeSize (element);
3363 Type rtype = right.Type;
3365 if (rtype.IsPointer){
3367 // handle (pointer - pointer)
3371 ig.Emit (OpCodes.Sub);
3375 ig.Emit (OpCodes.Sizeof, element);
3377 IntLiteral.EmitInt (ig, size);
3378 ig.Emit (OpCodes.Div);
3380 ig.Emit (OpCodes.Conv_I8);
3383 // handle + and - on (pointer op int)
3386 ig.Emit (OpCodes.Conv_I);
3390 ig.Emit (OpCodes.Sizeof, element);
3392 IntLiteral.EmitInt (ig, size);
3393 if (rtype == TypeManager.int64_type)
3394 ig.Emit (OpCodes.Conv_I8);
3395 else if (rtype == TypeManager.uint64_type)
3396 ig.Emit (OpCodes.Conv_U8);
3397 ig.Emit (OpCodes.Mul);
3400 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
3401 ig.Emit (OpCodes.Conv_I);
3404 ig.Emit (OpCodes.Add);
3406 ig.Emit (OpCodes.Sub);
3412 /// Implements the ternary conditional operator (?:)
3414 public class Conditional : Expression {
3415 Expression expr, trueExpr, falseExpr;
3417 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3420 this.trueExpr = trueExpr;
3421 this.falseExpr = falseExpr;
3425 public Expression Expr {
3431 public Expression TrueExpr {
3437 public Expression FalseExpr {
3443 public override Expression DoResolve (EmitContext ec)
3445 expr = expr.Resolve (ec);
3450 if (expr.Type != TypeManager.bool_type){
3451 expr = Expression.ResolveBoolean (
3458 trueExpr = trueExpr.Resolve (ec);
3459 falseExpr = falseExpr.Resolve (ec);
3461 if (trueExpr == null || falseExpr == null)
3464 if ((trueExpr is NullLiteral) && (falseExpr is NullLiteral))
3467 eclass = ExprClass.Value;
3468 if (trueExpr.Type == falseExpr.Type)
3469 type = trueExpr.Type;
3472 Type true_type = trueExpr.Type;
3473 Type false_type = falseExpr.Type;
3476 // First, if an implicit conversion exists from trueExpr
3477 // to falseExpr, then the result type is of type falseExpr.Type
3479 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3482 // Check if both can convert implicitl to each other's type
3484 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3486 "Can not compute type of conditional expression " +
3487 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3488 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3489 "' convert implicitly to each other");
3494 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3498 Error (173, "The type of the conditional expression can " +
3499 "not be computed because there is no implicit conversion" +
3500 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3501 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3506 if (expr is BoolConstant){
3507 BoolConstant bc = (BoolConstant) expr;
3518 public override void Emit (EmitContext ec)
3520 ILGenerator ig = ec.ig;
3521 Label false_target = ig.DefineLabel ();
3522 Label end_target = ig.DefineLabel ();
3524 expr.EmitBranchable (ec, false_target, false);
3526 ig.Emit (OpCodes.Br, end_target);
3527 ig.MarkLabel (false_target);
3528 falseExpr.Emit (ec);
3529 ig.MarkLabel (end_target);
3537 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3538 public readonly string Name;
3539 public readonly Block Block;
3540 public LocalInfo local_info;
3543 LocalTemporary temp;
3545 public LocalVariableReference (Block block, string name, Location l)
3550 eclass = ExprClass.Variable;
3554 // Setting `is_readonly' to false will allow you to create a writable
3555 // reference to a read-only variable. This is used by foreach and using.
3557 public LocalVariableReference (Block block, string name, Location l,
3558 LocalInfo local_info, bool is_readonly)
3559 : this (block, name, l)
3561 this.local_info = local_info;
3562 this.is_readonly = is_readonly;
3565 public VariableInfo VariableInfo {
3567 return local_info.VariableInfo;
3571 public bool IsReadOnly {
3577 protected Expression DoResolveBase (EmitContext ec, Expression lvalue_right_side)
3579 if (local_info == null) {
3580 local_info = Block.GetLocalInfo (Name);
3581 is_readonly = local_info.ReadOnly;
3584 type = local_info.VariableType;
3586 VariableInfo variable_info = local_info.VariableInfo;
3587 if (lvalue_right_side != null){
3589 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3593 if (variable_info != null)
3594 variable_info.SetAssigned (ec);
3597 Expression e = Block.GetConstantExpression (Name);
3599 local_info.Used = true;
3600 eclass = ExprClass.Value;
3601 return e.Resolve (ec);
3604 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3607 if (lvalue_right_side == null)
3608 local_info.Used = true;
3610 if (ec.CurrentAnonymousMethod != null){
3612 // If we are referencing a variable from the external block
3613 // flag it for capturing
3615 if (local_info.Block.Toplevel != ec.CurrentBlock.Toplevel){
3616 ec.CaptureVariable (local_info);
3617 //Console.WriteLine ("Capturing at " + loc);
3624 public override Expression DoResolve (EmitContext ec)
3626 return DoResolveBase (ec, null);
3629 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3631 return DoResolveBase (ec, right_side);
3634 public bool VerifyFixed (bool is_expression)
3636 return !is_expression || local_info.IsFixed;
3639 public override void Emit (EmitContext ec)
3641 ILGenerator ig = ec.ig;
3643 if (local_info.FieldBuilder == null){
3645 // A local variable on the local CLR stack
3647 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3650 // A local variable captured by anonymous methods.
3653 ec.EmitCapturedVariableInstance (local_info);
3655 ig.Emit (OpCodes.Ldfld, local_info.FieldBuilder);
3659 public void Emit (EmitContext ec, bool leave_copy)
3663 ec.ig.Emit (OpCodes.Dup);
3664 if (local_info.FieldBuilder != null){
3665 temp = new LocalTemporary (ec, Type);
3671 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3673 ILGenerator ig = ec.ig;
3674 prepared = prepare_for_load;
3676 if (local_info.FieldBuilder == null){
3678 // A local variable on the local CLR stack
3680 if (local_info.LocalBuilder == null)
3681 throw new Exception ("This should not happen: both Field and Local are null");
3685 ec.ig.Emit (OpCodes.Dup);
3686 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3689 // A local variable captured by anonymous methods or itereators.
3691 ec.EmitCapturedVariableInstance (local_info);
3693 if (prepare_for_load)
3694 ig.Emit (OpCodes.Dup);
3697 ig.Emit (OpCodes.Dup);
3698 temp = new LocalTemporary (ec, Type);
3701 ig.Emit (OpCodes.Stfld, local_info.FieldBuilder);
3707 public void AddressOf (EmitContext ec, AddressOp mode)
3709 ILGenerator ig = ec.ig;
3711 if (local_info.FieldBuilder == null){
3713 // A local variable on the local CLR stack
3715 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3718 // A local variable captured by anonymous methods or iterators
3720 ec.EmitCapturedVariableInstance (local_info);
3721 ig.Emit (OpCodes.Ldflda, local_info.FieldBuilder);
3725 public override string ToString ()
3727 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3732 /// This represents a reference to a parameter in the intermediate
3735 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3741 public Parameter.Modifier mod;
3742 public bool is_ref, is_out, prepared;
3756 LocalTemporary temp;
3758 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3765 eclass = ExprClass.Variable;
3768 public VariableInfo VariableInfo {
3772 public bool VerifyFixed (bool is_expression)
3774 return !is_expression || TypeManager.IsValueType (type);
3777 public bool IsAssigned (EmitContext ec, Location loc)
3779 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsAssigned (vi))
3782 Report.Error (165, loc,
3783 "Use of unassigned parameter `" + name + "'");
3787 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3789 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3792 Report.Error (170, loc,
3793 "Use of possibly unassigned field `" + field_name + "'");
3797 public void SetAssigned (EmitContext ec)
3799 if (is_out && ec.DoFlowAnalysis)
3800 ec.CurrentBranching.SetAssigned (vi);
3803 public void SetFieldAssigned (EmitContext ec, string field_name)
3805 if (is_out && ec.DoFlowAnalysis)
3806 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3809 protected void DoResolveBase (EmitContext ec)
3811 type = pars.GetParameterInfo (ec, idx, out mod);
3812 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3813 is_out = (mod & Parameter.Modifier.OUT) != 0;
3814 eclass = ExprClass.Variable;
3817 vi = block.ParameterMap [idx];
3819 if (ec.CurrentAnonymousMethod != null){
3821 Report.Error (1628, Location,
3822 "Can not reference a ref or out parameter in an anonymous method");
3827 // If we are referencing the parameter from the external block
3828 // flag it for capturing
3830 //Console.WriteLine ("Is parameter `{0}' local? {1}", name, block.IsLocalParameter (name));
3831 if (!block.IsLocalParameter (name)){
3832 ec.CaptureParameter (name, type, idx);
3838 // Notice that for ref/out parameters, the type exposed is not the
3839 // same type exposed externally.
3842 // externally we expose "int&"
3843 // here we expose "int".
3845 // We record this in "is_ref". This means that the type system can treat
3846 // the type as it is expected, but when we generate the code, we generate
3847 // the alternate kind of code.
3849 public override Expression DoResolve (EmitContext ec)
3853 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3856 if (ec.RemapToProxy)
3857 return ec.RemapParameter (idx);
3862 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3868 if (ec.RemapToProxy)
3869 return ec.RemapParameterLValue (idx, right_side);
3874 static public void EmitLdArg (ILGenerator ig, int x)
3878 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3879 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3880 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3881 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3882 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3885 ig.Emit (OpCodes.Ldarg, x);
3889 // This method is used by parameters that are references, that are
3890 // being passed as references: we only want to pass the pointer (that
3891 // is already stored in the parameter, not the address of the pointer,
3892 // and not the value of the variable).
3894 public void EmitLoad (EmitContext ec)
3896 ILGenerator ig = ec.ig;
3902 EmitLdArg (ig, arg_idx);
3905 // FIXME: Review for anonymous methods
3909 public override void Emit (EmitContext ec)
3911 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
3912 ec.EmitParameter (name);
3919 public void Emit (EmitContext ec, bool leave_copy)
3921 ILGenerator ig = ec.ig;
3927 EmitLdArg (ig, arg_idx);
3931 ec.ig.Emit (OpCodes.Dup);
3934 // If we are a reference, we loaded on the stack a pointer
3935 // Now lets load the real value
3937 LoadFromPtr (ig, type);
3941 ec.ig.Emit (OpCodes.Dup);
3944 temp = new LocalTemporary (ec, type);
3950 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3952 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
3953 ec.EmitAssignParameter (name, source, leave_copy, prepare_for_load);
3957 ILGenerator ig = ec.ig;
3960 prepared = prepare_for_load;
3965 if (is_ref && !prepared)
3966 EmitLdArg (ig, arg_idx);
3971 ec.ig.Emit (OpCodes.Dup);
3975 temp = new LocalTemporary (ec, type);
3979 StoreFromPtr (ig, type);
3985 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
3987 ig.Emit (OpCodes.Starg, arg_idx);
3991 public void AddressOf (EmitContext ec, AddressOp mode)
3993 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
3994 ec.EmitAddressOfParameter (name);
4005 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
4007 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
4010 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
4012 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
4019 /// Used for arguments to New(), Invocation()
4021 public class Argument {
4022 public enum AType : byte {
4029 public readonly AType ArgType;
4030 public Expression Expr;
4032 public Argument (Expression expr, AType type)
4035 this.ArgType = type;
4038 public Argument (Expression expr)
4041 this.ArgType = AType.Expression;
4046 if (ArgType == AType.Ref || ArgType == AType.Out)
4047 return TypeManager.GetReferenceType (Expr.Type);
4053 public Parameter.Modifier GetParameterModifier ()
4057 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
4060 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
4063 return Parameter.Modifier.NONE;
4067 public static string FullDesc (Argument a)
4069 if (a.ArgType == AType.ArgList)
4072 return (a.ArgType == AType.Ref ? "ref " :
4073 (a.ArgType == AType.Out ? "out " : "")) +
4074 TypeManager.CSharpName (a.Expr.Type);
4077 public bool ResolveMethodGroup (EmitContext ec, Location loc)
4079 // FIXME: csc doesn't report any error if you try to use `ref' or
4080 // `out' in a delegate creation expression.
4081 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4088 public bool Resolve (EmitContext ec, Location loc)
4090 if (ArgType == AType.Ref) {
4091 Expr = Expr.Resolve (ec);
4095 if (!ec.IsConstructor) {
4096 FieldExpr fe = Expr as FieldExpr;
4097 if (fe != null && fe.FieldInfo.IsInitOnly) {
4098 if (fe.FieldInfo.IsStatic)
4099 Report.Error (199, loc, "A static readonly field cannot be passed ref or out (except in a static constructor)");
4101 Report.Error (192, loc, "A readonly field cannot be passed ref or out (except in a constructor)");
4105 Expr = Expr.ResolveLValue (ec, Expr);
4106 } else if (ArgType == AType.Out)
4107 Expr = Expr.ResolveLValue (ec, EmptyExpression.Null);
4109 Expr = Expr.Resolve (ec);
4114 if (ArgType == AType.Expression)
4118 // Catch errors where fields of a MarshalByRefObject are passed as ref or out
4119 // This is only allowed for `this'
4121 FieldExpr fe = Expr as FieldExpr;
4122 if (fe != null && !fe.IsStatic){
4123 Expression instance = fe.InstanceExpression;
4125 if (instance.GetType () != typeof (This)){
4126 if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
4127 Report.Error (197, loc,
4128 "Can not pass a type that derives from MarshalByRefObject with out or ref");
4135 if (Expr.eclass != ExprClass.Variable){
4137 // We just probe to match the CSC output
4139 if (Expr.eclass == ExprClass.PropertyAccess ||
4140 Expr.eclass == ExprClass.IndexerAccess){
4143 "A property or indexer can not be passed as an out or ref " +
4148 "An lvalue is required as an argument to out or ref");
4156 public void Emit (EmitContext ec)
4159 // Ref and Out parameters need to have their addresses taken.
4161 // ParameterReferences might already be references, so we want
4162 // to pass just the value
4164 if (ArgType == AType.Ref || ArgType == AType.Out){
4165 AddressOp mode = AddressOp.Store;
4167 if (ArgType == AType.Ref)
4168 mode |= AddressOp.Load;
4170 if (Expr is ParameterReference){
4171 ParameterReference pr = (ParameterReference) Expr;
4177 pr.AddressOf (ec, mode);
4180 ((IMemoryLocation)Expr).AddressOf (ec, mode);
4188 /// Invocation of methods or delegates.
4190 public class Invocation : ExpressionStatement {
4191 public readonly ArrayList Arguments;
4194 MethodBase method = null;
4196 static Hashtable method_parameter_cache;
4198 static Invocation ()
4200 method_parameter_cache = new PtrHashtable ();
4204 // arguments is an ArrayList, but we do not want to typecast,
4205 // as it might be null.
4207 // FIXME: only allow expr to be a method invocation or a
4208 // delegate invocation (7.5.5)
4210 public Invocation (Expression expr, ArrayList arguments, Location l)
4213 Arguments = arguments;
4217 public Expression Expr {
4224 /// Returns the Parameters (a ParameterData interface) for the
4227 public static ParameterData GetParameterData (MethodBase mb)
4229 object pd = method_parameter_cache [mb];
4233 return (ParameterData) pd;
4236 ip = TypeManager.LookupParametersByBuilder (mb);
4238 method_parameter_cache [mb] = ip;
4240 return (ParameterData) ip;
4242 ReflectionParameters rp = new ReflectionParameters (mb);
4243 method_parameter_cache [mb] = rp;
4245 return (ParameterData) rp;
4250 /// Determines "better conversion" as specified in 7.4.2.3
4252 /// Returns : p if a->p is better,
4253 /// q if a->q is better,
4254 /// null if neither is better
4256 static Type BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
4258 Type argument_type = a.Type;
4259 Expression argument_expr = a.Expr;
4261 if (argument_type == null)
4262 throw new Exception ("Expression of type " + a.Expr +
4263 " does not resolve its type");
4265 if (p == null || q == null)
4266 throw new InternalErrorException ("BetterConversion Got a null conversion");
4271 if (argument_expr is NullLiteral) {
4273 // If the argument is null and one of the types to compare is 'object' and
4274 // the other is a reference type, we prefer the other.
4276 // This follows from the usual rules:
4277 // * There is an implicit conversion from 'null' to type 'object'
4278 // * There is an implicit conversion from 'null' to any reference type
4279 // * There is an implicit conversion from any reference type to type 'object'
4280 // * There is no implicit conversion from type 'object' to other reference types
4281 // => Conversion of 'null' to a reference type is better than conversion to 'object'
4283 // FIXME: This probably isn't necessary, since the type of a NullLiteral is 'System.Null'.
4284 // I think it used to be 'object' and thus needed a special case to avoid the
4285 // immediately following two checks.
4287 if (!p.IsValueType && q == TypeManager.object_type)
4289 if (!q.IsValueType && p == TypeManager.object_type)
4293 if (argument_type == p)
4296 if (argument_type == q)
4299 Expression p_tmp = new EmptyExpression (p);
4300 Expression q_tmp = new EmptyExpression (q);
4302 bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
4303 bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
4305 if (p_to_q && !q_to_p)
4308 if (q_to_p && !p_to_q)
4311 if (p == TypeManager.sbyte_type)
4312 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4313 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4315 if (q == TypeManager.sbyte_type)
4316 if (p == TypeManager.byte_type || p == TypeManager.ushort_type ||
4317 p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4320 if (p == TypeManager.short_type)
4321 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4322 q == TypeManager.uint64_type)
4324 if (q == TypeManager.short_type)
4325 if (p == TypeManager.ushort_type || p == TypeManager.uint32_type ||
4326 p == TypeManager.uint64_type)
4329 if (p == TypeManager.int32_type)
4330 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4332 if (q == TypeManager.int32_type)
4333 if (p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4336 if (p == TypeManager.int64_type)
4337 if (q == TypeManager.uint64_type)
4339 if (q == TypeManager.int64_type)
4340 if (p == TypeManager.uint64_type)
4347 /// Determines "Better function" between candidate
4348 /// and the current best match
4351 /// Returns an integer indicating :
4352 /// false if candidate ain't better
4353 /// true if candidate is better than the current best match
4355 static bool BetterFunction (EmitContext ec, ArrayList args, int argument_count,
4356 MethodBase candidate, bool candidate_params,
4357 MethodBase best, bool best_params, Location loc)
4359 ParameterData candidate_pd = GetParameterData (candidate);
4360 ParameterData best_pd = GetParameterData (best);
4362 int cand_count = candidate_pd.Count;
4365 // If there is no best method, than this one
4366 // is better, however, if we already found a
4367 // best method, we cant tell. This happens
4378 // interface IFooBar : IFoo, IBar {}
4380 // We cant tell if IFoo.DoIt is better than IBar.DoIt
4382 // However, we have to consider that
4383 // Trim (); is better than Trim (params char[] chars);
4385 if (cand_count == 0 && argument_count == 0)
4386 return !candidate_params && best_params;
4388 if ((candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS) &&
4389 (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.ARGLIST))
4390 if (cand_count != argument_count)
4393 bool better_at_least_one = false;
4394 for (int j = 0; j < argument_count; ++j) {
4395 Argument a = (Argument) args [j];
4397 Type ct = TypeManager.TypeToCoreType (candidate_pd.ParameterType (j));
4398 Type bt = TypeManager.TypeToCoreType (best_pd.ParameterType (j));
4400 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4401 if (candidate_params)
4402 ct = TypeManager.GetElementType (ct);
4404 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4406 bt = TypeManager.GetElementType (bt);
4408 Type better = BetterConversion (ec, a, ct, bt, loc);
4410 // for each argument, the conversion to 'ct' should be no worse than
4411 // the conversion to 'bt'.
4415 // for at least one argument, the conversion to 'ct' should be better than
4416 // the conversion to 'bt'.
4418 better_at_least_one = true;
4422 // If a method (in the normal form) with the
4423 // same signature as the expanded form of the
4424 // current best params method already exists,
4425 // the expanded form is not applicable so we
4426 // force it to select the candidate
4428 if (!candidate_params && best_params && cand_count == argument_count)
4431 return better_at_least_one;
4434 public static string FullMethodDesc (MethodBase mb)
4436 string ret_type = "";
4441 if (mb is MethodInfo)
4442 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
4444 StringBuilder sb = new StringBuilder (ret_type);
4446 sb.Append (mb.ReflectedType.ToString ());
4448 sb.Append (mb.Name);
4450 ParameterData pd = GetParameterData (mb);
4452 int count = pd.Count;
4455 for (int i = count; i > 0; ) {
4458 sb.Append (pd.ParameterDesc (count - i - 1));
4464 return sb.ToString ();
4467 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4469 MemberInfo [] miset;
4470 MethodGroupExpr union;
4475 return (MethodGroupExpr) mg2;
4478 return (MethodGroupExpr) mg1;
4481 MethodGroupExpr left_set = null, right_set = null;
4482 int length1 = 0, length2 = 0;
4484 left_set = (MethodGroupExpr) mg1;
4485 length1 = left_set.Methods.Length;
4487 right_set = (MethodGroupExpr) mg2;
4488 length2 = right_set.Methods.Length;
4490 ArrayList common = new ArrayList ();
4492 foreach (MethodBase r in right_set.Methods){
4493 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
4497 miset = new MemberInfo [length1 + length2 - common.Count];
4498 left_set.Methods.CopyTo (miset, 0);
4502 foreach (MethodBase r in right_set.Methods) {
4503 if (!common.Contains (r))
4507 union = new MethodGroupExpr (miset, loc);
4512 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4513 ArrayList arguments, int arg_count,
4514 ref MethodBase candidate)
4516 return IsParamsMethodApplicable (
4517 ec, me, arguments, arg_count, false, ref candidate) ||
4518 IsParamsMethodApplicable (
4519 ec, me, arguments, arg_count, true, ref candidate);
4524 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4525 ArrayList arguments, int arg_count,
4526 bool do_varargs, ref MethodBase candidate)
4528 return IsParamsMethodApplicable (
4529 ec, arguments, arg_count, candidate, do_varargs);
4533 /// Determines if the candidate method, if a params method, is applicable
4534 /// in its expanded form to the given set of arguments
4536 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
4537 int arg_count, MethodBase candidate,
4540 ParameterData pd = GetParameterData (candidate);
4542 int pd_count = pd.Count;
4546 int count = pd_count - 1;
4548 if (pd.ParameterModifier (count) != Parameter.Modifier.ARGLIST)
4550 if (pd_count != arg_count)
4553 if (pd.ParameterModifier (count) != Parameter.Modifier.PARAMS)
4557 if (count > arg_count)
4560 if (pd_count == 1 && arg_count == 0)
4564 // If we have come this far, the case which
4565 // remains is when the number of parameters is
4566 // less than or equal to the argument count.
4568 for (int i = 0; i < count; ++i) {
4570 Argument a = (Argument) arguments [i];
4572 Parameter.Modifier a_mod = a.GetParameterModifier () &
4573 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4574 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4575 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4577 if (a_mod == p_mod) {
4579 if (a_mod == Parameter.Modifier.NONE)
4580 if (!Convert.ImplicitConversionExists (ec,
4582 pd.ParameterType (i)))
4585 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4586 Type pt = pd.ParameterType (i);
4589 pt = TypeManager.GetReferenceType (pt);
4600 Argument a = (Argument) arguments [count];
4601 if (!(a.Expr is Arglist))
4607 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4609 for (int i = pd_count - 1; i < arg_count; i++) {
4610 Argument a = (Argument) arguments [i];
4612 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4619 static bool IsApplicable (EmitContext ec, MethodGroupExpr me,
4620 ArrayList arguments, int arg_count,
4621 ref MethodBase candidate)
4623 return IsApplicable (ec, arguments, arg_count, candidate);
4627 /// Determines if the candidate method is applicable (section 14.4.2.1)
4628 /// to the given set of arguments
4630 static bool IsApplicable (EmitContext ec, ArrayList arguments, int arg_count,
4631 MethodBase candidate)
4633 ParameterData pd = GetParameterData (candidate);
4635 if (arg_count != pd.Count)
4638 for (int i = arg_count; i > 0; ) {
4641 Argument a = (Argument) arguments [i];
4643 Parameter.Modifier a_mod = a.GetParameterModifier () &
4644 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4645 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4646 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4649 if (a_mod == p_mod ||
4650 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4651 if (a_mod == Parameter.Modifier.NONE) {
4652 if (!Convert.ImplicitConversionExists (ec,
4654 pd.ParameterType (i)))
4658 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4659 Type pt = pd.ParameterType (i);
4662 pt = TypeManager.GetReferenceType (pt);
4674 static private bool IsAncestralType (Type first_type, Type second_type)
4676 return first_type != second_type &&
4677 (second_type.IsSubclassOf (first_type) ||
4678 TypeManager.ImplementsInterface (second_type, first_type));
4682 /// Find the Applicable Function Members (7.4.2.1)
4684 /// me: Method Group expression with the members to select.
4685 /// it might contain constructors or methods (or anything
4686 /// that maps to a method).
4688 /// Arguments: ArrayList containing resolved Argument objects.
4690 /// loc: The location if we want an error to be reported, or a Null
4691 /// location for "probing" purposes.
4693 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4694 /// that is the best match of me on Arguments.
4697 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4698 ArrayList Arguments, bool may_fail,
4701 MethodBase method = null;
4702 bool method_params = false;
4703 Type applicable_type = null;
4705 ArrayList candidates = new ArrayList ();
4708 // Used to keep a map between the candidate
4709 // and whether it is being considered in its
4710 // normal or expanded form
4712 // false is normal form, true is expanded form
4714 Hashtable candidate_to_form = null;
4716 if (Arguments != null)
4717 arg_count = Arguments.Count;
4719 if ((me.Name == "Invoke") &&
4720 TypeManager.IsDelegateType (me.DeclaringType)) {
4721 Error_InvokeOnDelegate (loc);
4725 MethodBase[] methods = me.Methods;
4728 // First we construct the set of applicable methods
4730 bool is_sorted = true;
4731 for (int i = 0; i < methods.Length; i++){
4732 Type decl_type = methods [i].DeclaringType;
4735 // If we have already found an applicable method
4736 // we eliminate all base types (Section 14.5.5.1)
4738 if ((applicable_type != null) &&
4739 IsAncestralType (decl_type, applicable_type))
4743 // Check if candidate is applicable (section 14.4.2.1)
4744 // Is candidate applicable in normal form?
4746 bool is_applicable = IsApplicable (
4747 ec, me, Arguments, arg_count, ref methods [i]);
4749 if (!is_applicable &&
4750 (IsParamsMethodApplicable (
4751 ec, me, Arguments, arg_count, ref methods [i]))) {
4752 MethodBase candidate = methods [i];
4753 if (candidate_to_form == null)
4754 candidate_to_form = new PtrHashtable ();
4755 candidate_to_form [candidate] = candidate;
4756 // Candidate is applicable in expanded form
4757 is_applicable = true;
4763 candidates.Add (methods [i]);
4765 if (applicable_type == null)
4766 applicable_type = decl_type;
4767 else if (applicable_type != decl_type) {
4769 if (IsAncestralType (applicable_type, decl_type))
4770 applicable_type = decl_type;
4774 int candidate_top = candidates.Count;
4776 if (candidate_top == 0) {
4778 // Okay so we have failed to find anything so we
4779 // return by providing info about the closest match
4781 for (int i = 0; i < methods.Length; ++i) {
4782 MethodBase c = (MethodBase) methods [i];
4783 ParameterData pd = GetParameterData (c);
4785 if (pd.Count != arg_count)
4788 VerifyArgumentsCompat (ec, Arguments, arg_count,
4789 c, false, null, may_fail, loc);
4794 string report_name = me.Name;
4795 if (report_name == ".ctor")
4796 report_name = me.DeclaringType.ToString ();
4798 Error_WrongNumArguments (
4799 loc, report_name, arg_count);
4808 // At this point, applicable_type is _one_ of the most derived types
4809 // in the set of types containing the methods in this MethodGroup.
4810 // Filter the candidates so that they only contain methods from the
4811 // most derived types.
4814 int finalized = 0; // Number of finalized candidates
4817 // Invariant: applicable_type is a most derived type
4819 // We'll try to complete Section 14.5.5.1 for 'applicable_type' by
4820 // eliminating all it's base types. At the same time, we'll also move
4821 // every unrelated type to the end of the array, and pick the next
4822 // 'applicable_type'.
4824 Type next_applicable_type = null;
4825 int j = finalized; // where to put the next finalized candidate
4826 int k = finalized; // where to put the next undiscarded candidate
4827 for (int i = finalized; i < candidate_top; ++i) {
4828 Type decl_type = ((MethodBase) candidates[i]).DeclaringType;
4830 if (decl_type == applicable_type) {
4831 candidates[k++] = candidates[j];
4832 candidates[j++] = candidates[i];
4836 if (IsAncestralType (decl_type, applicable_type))
4839 if (next_applicable_type != null &&
4840 IsAncestralType (decl_type, next_applicable_type))
4843 candidates[k++] = candidates[i];
4845 if (next_applicable_type == null ||
4846 IsAncestralType (next_applicable_type, decl_type))
4847 next_applicable_type = decl_type;
4850 applicable_type = next_applicable_type;
4853 } while (applicable_type != null);
4857 // Now we actually find the best method
4860 method = (MethodBase) candidates[0];
4861 method_params = candidate_to_form != null && candidate_to_form.Contains (method);
4862 for (int ix = 1; ix < candidate_top; ix++){
4863 MethodBase candidate = (MethodBase) candidates [ix];
4864 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4866 if (BetterFunction (ec, Arguments, arg_count,
4867 candidate, cand_params,
4868 method, method_params, loc)) {
4870 method_params = cand_params;
4875 // Now check that there are no ambiguities i.e the selected method
4876 // should be better than all the others
4878 bool ambiguous = false;
4879 for (int ix = 0; ix < candidate_top; ix++){
4880 MethodBase candidate = (MethodBase) candidates [ix];
4882 if (candidate == method)
4885 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4886 if (!BetterFunction (ec, Arguments, arg_count,
4887 method, method_params,
4888 candidate, cand_params,
4890 Report.SymbolRelatedToPreviousError (candidate);
4896 Report.SymbolRelatedToPreviousError (method);
4897 Report.Error (121, loc, "Ambiguous call when selecting function due to implicit casts");
4903 // And now check if the arguments are all
4904 // compatible, perform conversions if
4905 // necessary etc. and return if everything is
4908 if (!VerifyArgumentsCompat (ec, Arguments, arg_count, method,
4909 method_params, null, may_fail, loc))
4915 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
4917 Report.Error (1501, loc,
4918 "No overload for method `" + name + "' takes `" +
4919 arg_count + "' arguments");
4922 static void Error_InvokeOnDelegate (Location loc)
4924 Report.Error (1533, loc,
4925 "Invoke cannot be called directly on a delegate");
4928 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
4929 Type delegate_type, string arg_sig, string par_desc)
4931 if (delegate_type == null)
4932 Report.Error (1502, loc,
4933 "The best overloaded match for method '" +
4934 FullMethodDesc (method) +
4935 "' has some invalid arguments");
4937 Report.Error (1594, loc,
4938 "Delegate '" + delegate_type.ToString () +
4939 "' has some invalid arguments.");
4940 Report.Error (1503, loc,
4941 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
4942 idx, arg_sig, par_desc));
4945 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
4946 int arg_count, MethodBase method,
4947 bool chose_params_expanded,
4948 Type delegate_type, bool may_fail,
4951 ParameterData pd = GetParameterData (method);
4952 int pd_count = pd.Count;
4954 for (int j = 0; j < arg_count; j++) {
4955 Argument a = (Argument) Arguments [j];
4956 Expression a_expr = a.Expr;
4957 Type parameter_type = pd.ParameterType (j);
4958 Parameter.Modifier pm = pd.ParameterModifier (j);
4960 if (pm == Parameter.Modifier.PARAMS){
4961 if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
4963 Error_InvalidArguments (
4964 loc, j, method, delegate_type,
4965 Argument.FullDesc (a), pd.ParameterDesc (j));
4969 if (chose_params_expanded)
4970 parameter_type = TypeManager.GetElementType (parameter_type);
4971 } else if (pm == Parameter.Modifier.ARGLIST){
4977 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
4979 Error_InvalidArguments (
4980 loc, j, method, delegate_type,
4981 Argument.FullDesc (a), pd.ParameterDesc (j));
4989 if (!a.Type.Equals (parameter_type)){
4992 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
4996 Error_InvalidArguments (
4997 loc, j, method, delegate_type,
4998 Argument.FullDesc (a), pd.ParameterDesc (j));
5003 // Update the argument with the implicit conversion
5009 Parameter.Modifier a_mod = a.GetParameterModifier () &
5010 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5011 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
5012 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5014 if (a_mod != p_mod &&
5015 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
5017 Report.Error (1502, loc,
5018 "The best overloaded match for method '" + FullMethodDesc (method)+
5019 "' has some invalid arguments");
5020 Report.Error (1503, loc,
5021 "Argument " + (j+1) +
5022 ": Cannot convert from '" + Argument.FullDesc (a)
5023 + "' to '" + pd.ParameterDesc (j) + "'");
5033 public override Expression DoResolve (EmitContext ec)
5036 // First, resolve the expression that is used to
5037 // trigger the invocation
5039 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
5043 if (!(expr is MethodGroupExpr)) {
5044 Type expr_type = expr.Type;
5046 if (expr_type != null){
5047 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
5049 return (new DelegateInvocation (
5050 this.expr, Arguments, loc)).Resolve (ec);
5054 if (!(expr is MethodGroupExpr)){
5055 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup, loc);
5060 // Next, evaluate all the expressions in the argument list
5062 if (Arguments != null){
5063 foreach (Argument a in Arguments){
5064 if (!a.Resolve (ec, loc))
5069 MethodGroupExpr mg = (MethodGroupExpr) expr;
5070 method = OverloadResolve (ec, mg, Arguments, false, loc);
5075 MethodInfo mi = method as MethodInfo;
5077 type = TypeManager.TypeToCoreType (mi.ReturnType);
5078 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null)) {
5079 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
5083 Expression iexpr = mg.InstanceExpression;
5084 if (mi.IsStatic && (iexpr != null) && !(iexpr is This)) {
5085 if (mg.IdenticalTypeName)
5086 mg.InstanceExpression = null;
5088 MemberAccess.error176 (loc, mi.Name);
5094 if (type.IsPointer){
5102 // Only base will allow this invocation to happen.
5104 if (mg.IsBase && method.IsAbstract){
5105 Report.Error (205, loc, "Cannot call an abstract base member: " +
5106 FullMethodDesc (method));
5110 if (method.Name == "Finalize" && Arguments == null) {
5112 Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
5114 Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
5118 if ((method.Attributes & MethodAttributes.SpecialName) != 0) {
5119 if (TypeManager.LookupDeclSpace (method.DeclaringType) != null || TypeManager.IsSpecialMethod (method)) {
5120 Report.Error (571, loc, TypeManager.CSharpSignature (method) + ": can not call operator or accessor");
5125 eclass = ExprClass.Value;
5130 // Emits the list of arguments as an array
5132 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
5134 ILGenerator ig = ec.ig;
5135 int count = arguments.Count - idx;
5136 Argument a = (Argument) arguments [idx];
5137 Type t = a.Expr.Type;
5139 IntConstant.EmitInt (ig, count);
5140 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
5142 int top = arguments.Count;
5143 for (int j = idx; j < top; j++){
5144 a = (Argument) arguments [j];
5146 ig.Emit (OpCodes.Dup);
5147 IntConstant.EmitInt (ig, j - idx);
5150 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj);
5152 ig.Emit (OpCodes.Ldelema, t);
5157 ig.Emit (OpCodes.Stobj, t);
5164 /// Emits a list of resolved Arguments that are in the arguments
5167 /// The MethodBase argument might be null if the
5168 /// emission of the arguments is known not to contain
5169 /// a `params' field (for example in constructors or other routines
5170 /// that keep their arguments in this structure)
5172 /// if `dup_args' is true, a copy of the arguments will be left
5173 /// on the stack. If `dup_args' is true, you can specify `this_arg'
5174 /// which will be duplicated before any other args. Only EmitCall
5175 /// should be using this interface.
5177 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments, bool dup_args, LocalTemporary this_arg)
5181 pd = GetParameterData (mb);
5185 LocalTemporary [] temps = null;
5188 temps = new LocalTemporary [arguments.Count];
5191 // If we are calling a params method with no arguments, special case it
5193 if (arguments == null){
5194 if (pd != null && pd.Count > 0 &&
5195 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
5196 ILGenerator ig = ec.ig;
5198 IntConstant.EmitInt (ig, 0);
5199 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
5205 int top = arguments.Count;
5207 for (int i = 0; i < top; i++){
5208 Argument a = (Argument) arguments [i];
5211 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
5213 // Special case if we are passing the same data as the
5214 // params argument, do not put it in an array.
5216 if (pd.ParameterType (i) == a.Type)
5219 EmitParams (ec, i, arguments);
5226 ec.ig.Emit (OpCodes.Dup);
5227 (temps [i] = new LocalTemporary (ec, a.Type)).Store (ec);
5232 if (this_arg != null)
5235 for (int i = 0; i < top; i ++)
5236 temps [i].Emit (ec);
5239 if (pd != null && pd.Count > top &&
5240 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
5241 ILGenerator ig = ec.ig;
5243 IntConstant.EmitInt (ig, 0);
5244 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
5248 static Type[] GetVarargsTypes (EmitContext ec, MethodBase mb,
5249 ArrayList arguments)
5251 ParameterData pd = GetParameterData (mb);
5253 if (arguments == null)
5254 return new Type [0];
5256 Argument a = (Argument) arguments [pd.Count - 1];
5257 Arglist list = (Arglist) a.Expr;
5259 return list.ArgumentTypes;
5263 /// This checks the ConditionalAttribute on the method
5265 static bool IsMethodExcluded (MethodBase method, EmitContext ec)
5267 if (method.IsConstructor)
5270 IMethodData md = TypeManager.GetMethod (method);
5272 return md.IsExcluded (ec);
5274 // For some methods (generated by delegate class) GetMethod returns null
5275 // because they are not included in builder_to_method table
5276 if (method.DeclaringType is TypeBuilder)
5279 return AttributeTester.IsConditionalMethodExcluded (method);
5283 /// is_base tells whether we want to force the use of the `call'
5284 /// opcode instead of using callvirt. Call is required to call
5285 /// a specific method, while callvirt will always use the most
5286 /// recent method in the vtable.
5288 /// is_static tells whether this is an invocation on a static method
5290 /// instance_expr is an expression that represents the instance
5291 /// it must be non-null if is_static is false.
5293 /// method is the method to invoke.
5295 /// Arguments is the list of arguments to pass to the method or constructor.
5297 public static void EmitCall (EmitContext ec, bool is_base,
5298 bool is_static, Expression instance_expr,
5299 MethodBase method, ArrayList Arguments, Location loc)
5301 EmitCall (ec, is_base, is_static, instance_expr, method, Arguments, loc, false, false);
5304 // `dup_args' leaves an extra copy of the arguments on the stack
5305 // `omit_args' does not leave any arguments at all.
5306 // So, basically, you could make one call with `dup_args' set to true,
5307 // and then another with `omit_args' set to true, and the two calls
5308 // would have the same set of arguments. However, each argument would
5309 // only have been evaluated once.
5310 public static void EmitCall (EmitContext ec, bool is_base,
5311 bool is_static, Expression instance_expr,
5312 MethodBase method, ArrayList Arguments, Location loc,
5313 bool dup_args, bool omit_args)
5315 ILGenerator ig = ec.ig;
5316 bool struct_call = false;
5317 bool this_call = false;
5318 LocalTemporary this_arg = null;
5320 Type decl_type = method.DeclaringType;
5322 if (!RootContext.StdLib) {
5323 // Replace any calls to the system's System.Array type with calls to
5324 // the newly created one.
5325 if (method == TypeManager.system_int_array_get_length)
5326 method = TypeManager.int_array_get_length;
5327 else if (method == TypeManager.system_int_array_get_rank)
5328 method = TypeManager.int_array_get_rank;
5329 else if (method == TypeManager.system_object_array_clone)
5330 method = TypeManager.object_array_clone;
5331 else if (method == TypeManager.system_int_array_get_length_int)
5332 method = TypeManager.int_array_get_length_int;
5333 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5334 method = TypeManager.int_array_get_lower_bound_int;
5335 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5336 method = TypeManager.int_array_get_upper_bound_int;
5337 else if (method == TypeManager.system_void_array_copyto_array_int)
5338 method = TypeManager.void_array_copyto_array_int;
5341 if (ec.TestObsoleteMethodUsage) {
5343 // This checks ObsoleteAttribute on the method and on the declaring type
5345 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
5347 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
5350 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
5352 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
5356 if (IsMethodExcluded (method, ec))
5360 this_call = instance_expr == null;
5361 if (decl_type.IsValueType || (!this_call && instance_expr.Type.IsValueType))
5365 // If this is ourselves, push "this"
5370 ig.Emit (OpCodes.Ldarg_0);
5374 // Push the instance expression
5376 if (instance_expr.Type.IsValueType) {
5378 // Special case: calls to a function declared in a
5379 // reference-type with a value-type argument need
5380 // to have their value boxed.
5381 if (decl_type.IsValueType) {
5383 // If the expression implements IMemoryLocation, then
5384 // we can optimize and use AddressOf on the
5387 // If not we have to use some temporary storage for
5389 if (instance_expr is IMemoryLocation) {
5390 ((IMemoryLocation)instance_expr).
5391 AddressOf (ec, AddressOp.LoadStore);
5393 LocalTemporary temp = new LocalTemporary (ec, instance_expr.Type);
5394 instance_expr.Emit (ec);
5396 temp.AddressOf (ec, AddressOp.Load);
5399 // avoid the overhead of doing this all the time.
5401 t = TypeManager.GetReferenceType (instance_expr.Type);
5403 instance_expr.Emit (ec);
5404 ig.Emit (OpCodes.Box, instance_expr.Type);
5405 t = TypeManager.object_type;
5408 instance_expr.Emit (ec);
5409 t = instance_expr.Type;
5414 this_arg = new LocalTemporary (ec, t);
5415 ig.Emit (OpCodes.Dup);
5416 this_arg.Store (ec);
5422 EmitArguments (ec, method, Arguments, dup_args, this_arg);
5425 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
5426 call_op = OpCodes.Call;
5428 call_op = OpCodes.Callvirt;
5430 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
5431 Type[] varargs_types = GetVarargsTypes (ec, method, Arguments);
5432 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
5439 // and DoFoo is not virtual, you can omit the callvirt,
5440 // because you don't need the null checking behavior.
5442 if (method is MethodInfo)
5443 ig.Emit (call_op, (MethodInfo) method);
5445 ig.Emit (call_op, (ConstructorInfo) method);
5448 public override void Emit (EmitContext ec)
5450 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5452 EmitCall (ec, mg.IsBase, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5455 public override void EmitStatement (EmitContext ec)
5460 // Pop the return value if there is one
5462 if (method is MethodInfo){
5463 Type ret = ((MethodInfo)method).ReturnType;
5464 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5465 ec.ig.Emit (OpCodes.Pop);
5470 public class InvocationOrCast : ExpressionStatement
5473 Expression argument;
5475 public InvocationOrCast (Expression expr, Expression argument, Location loc)
5478 this.argument = argument;
5482 public override Expression DoResolve (EmitContext ec)
5485 // First try to resolve it as a cast.
5487 TypeExpr te = expr.ResolveAsTypeTerminal (ec, true);
5489 Cast cast = new Cast (te, argument, loc);
5490 return cast.Resolve (ec);
5494 // This can either be a type or a delegate invocation.
5495 // Let's just resolve it and see what we'll get.
5497 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5502 // Ok, so it's a Cast.
5504 if (expr.eclass == ExprClass.Type) {
5505 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
5506 return cast.Resolve (ec);
5510 // It's a delegate invocation.
5512 if (!TypeManager.IsDelegateType (expr.Type)) {
5513 Error (149, "Method name expected");
5517 ArrayList args = new ArrayList ();
5518 args.Add (new Argument (argument, Argument.AType.Expression));
5519 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5520 return invocation.Resolve (ec);
5525 Error (201, "Only assignment, call, increment, decrement and new object " +
5526 "expressions can be used as a statement");
5529 public override ExpressionStatement ResolveStatement (EmitContext ec)
5532 // First try to resolve it as a cast.
5534 TypeExpr te = expr.ResolveAsTypeTerminal (ec, true);
5541 // This can either be a type or a delegate invocation.
5542 // Let's just resolve it and see what we'll get.
5544 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5545 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5551 // It's a delegate invocation.
5553 if (!TypeManager.IsDelegateType (expr.Type)) {
5554 Error (149, "Method name expected");
5558 ArrayList args = new ArrayList ();
5559 args.Add (new Argument (argument, Argument.AType.Expression));
5560 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5561 return invocation.ResolveStatement (ec);
5564 public override void Emit (EmitContext ec)
5566 throw new Exception ("Cannot happen");
5569 public override void EmitStatement (EmitContext ec)
5571 throw new Exception ("Cannot happen");
5576 // This class is used to "disable" the code generation for the
5577 // temporary variable when initializing value types.
5579 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5580 public void AddressOf (EmitContext ec, AddressOp Mode)
5587 /// Implements the new expression
5589 public class New : ExpressionStatement, IMemoryLocation {
5590 public readonly ArrayList Arguments;
5593 // During bootstrap, it contains the RequestedType,
5594 // but if `type' is not null, it *might* contain a NewDelegate
5595 // (because of field multi-initialization)
5597 public Expression RequestedType;
5599 MethodBase method = null;
5602 // If set, the new expression is for a value_target, and
5603 // we will not leave anything on the stack.
5605 Expression value_target;
5606 bool value_target_set = false;
5608 public New (Expression requested_type, ArrayList arguments, Location l)
5610 RequestedType = requested_type;
5611 Arguments = arguments;
5615 public bool SetValueTypeVariable (Expression value)
5617 value_target = value;
5618 value_target_set = true;
5619 if (!(value_target is IMemoryLocation)){
5620 Error_UnexpectedKind ("variable", loc);
5627 // This function is used to disable the following code sequence for
5628 // value type initialization:
5630 // AddressOf (temporary)
5634 // Instead the provide will have provided us with the address on the
5635 // stack to store the results.
5637 static Expression MyEmptyExpression;
5639 public void DisableTemporaryValueType ()
5641 if (MyEmptyExpression == null)
5642 MyEmptyExpression = new EmptyAddressOf ();
5645 // To enable this, look into:
5646 // test-34 and test-89 and self bootstrapping.
5648 // For instance, we can avoid a copy by using `newobj'
5649 // instead of Call + Push-temp on value types.
5650 // value_target = MyEmptyExpression;
5653 public override Expression DoResolve (EmitContext ec)
5656 // The New DoResolve might be called twice when initializing field
5657 // expressions (see EmitFieldInitializers, the call to
5658 // GetInitializerExpression will perform a resolve on the expression,
5659 // and later the assign will trigger another resolution
5661 // This leads to bugs (#37014)
5664 if (RequestedType is NewDelegate)
5665 return RequestedType;
5669 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec, false);
5673 type = texpr.ResolveType (ec);
5675 CheckObsoleteAttribute (type);
5677 bool IsDelegate = TypeManager.IsDelegateType (type);
5680 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5681 if (RequestedType != null)
5682 if (!(RequestedType is NewDelegate))
5683 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
5684 return RequestedType;
5687 if (type.IsAbstract && type.IsSealed) {
5688 Report.Error (712, loc, "Cannot create an instance of the static class '{0}'", TypeManager.CSharpName (type));
5692 if (type.IsInterface || type.IsAbstract){
5693 Error (144, "It is not possible to create instances of interfaces or abstract classes");
5697 bool is_struct = type.IsValueType;
5698 eclass = ExprClass.Value;
5701 // SRE returns a match for .ctor () on structs (the object constructor),
5702 // so we have to manually ignore it.
5704 if (is_struct && Arguments == null)
5708 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
5709 ml = MemberLookupFinal (ec, type, type, ".ctor",
5710 MemberTypes.Constructor,
5711 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5716 if (! (ml is MethodGroupExpr)){
5718 ml.Error_UnexpectedKind ("method group", loc);
5724 if (Arguments != null){
5725 foreach (Argument a in Arguments){
5726 if (!a.Resolve (ec, loc))
5731 method = Invocation.OverloadResolve (
5732 ec, (MethodGroupExpr) ml, Arguments, false, loc);
5736 if (method == null) {
5737 if (!is_struct || Arguments.Count > 0) {
5738 Error (1501, String.Format (
5739 "New invocation: Can not find a constructor in `{0}' for this argument list",
5740 TypeManager.CSharpName (type)));
5749 // This DoEmit can be invoked in two contexts:
5750 // * As a mechanism that will leave a value on the stack (new object)
5751 // * As one that wont (init struct)
5753 // You can control whether a value is required on the stack by passing
5754 // need_value_on_stack. The code *might* leave a value on the stack
5755 // so it must be popped manually
5757 // If we are dealing with a ValueType, we have a few
5758 // situations to deal with:
5760 // * The target is a ValueType, and we have been provided
5761 // the instance (this is easy, we are being assigned).
5763 // * The target of New is being passed as an argument,
5764 // to a boxing operation or a function that takes a
5767 // In this case, we need to create a temporary variable
5768 // that is the argument of New.
5770 // Returns whether a value is left on the stack
5772 bool DoEmit (EmitContext ec, bool need_value_on_stack)
5774 bool is_value_type = type.IsValueType;
5775 ILGenerator ig = ec.ig;
5780 // Allow DoEmit() to be called multiple times.
5781 // We need to create a new LocalTemporary each time since
5782 // you can't share LocalBuilders among ILGeneators.
5783 if (!value_target_set)
5784 value_target = new LocalTemporary (ec, type);
5786 ml = (IMemoryLocation) value_target;
5787 ml.AddressOf (ec, AddressOp.Store);
5791 Invocation.EmitArguments (ec, method, Arguments, false, null);
5795 ig.Emit (OpCodes.Initobj, type);
5797 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5798 if (need_value_on_stack){
5799 value_target.Emit (ec);
5804 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
5809 public override void Emit (EmitContext ec)
5814 public override void EmitStatement (EmitContext ec)
5816 if (DoEmit (ec, false))
5817 ec.ig.Emit (OpCodes.Pop);
5820 public void AddressOf (EmitContext ec, AddressOp Mode)
5822 if (!type.IsValueType){
5824 // We throw an exception. So far, I believe we only need to support
5826 // foreach (int j in new StructType ())
5829 throw new Exception ("AddressOf should not be used for classes");
5832 if (!value_target_set)
5833 value_target = new LocalTemporary (ec, type);
5835 IMemoryLocation ml = (IMemoryLocation) value_target;
5836 ml.AddressOf (ec, AddressOp.Store);
5838 Invocation.EmitArguments (ec, method, Arguments, false, null);
5841 ec.ig.Emit (OpCodes.Initobj, type);
5843 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5845 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
5850 /// 14.5.10.2: Represents an array creation expression.
5854 /// There are two possible scenarios here: one is an array creation
5855 /// expression that specifies the dimensions and optionally the
5856 /// initialization data and the other which does not need dimensions
5857 /// specified but where initialization data is mandatory.
5859 public class ArrayCreation : Expression {
5860 Expression requested_base_type;
5861 ArrayList initializers;
5864 // The list of Argument types.
5865 // This is used to construct the `newarray' or constructor signature
5867 ArrayList arguments;
5870 // Method used to create the array object.
5872 MethodBase new_method = null;
5874 Type array_element_type;
5875 Type underlying_type;
5876 bool is_one_dimensional = false;
5877 bool is_builtin_type = false;
5878 bool expect_initializers = false;
5879 int num_arguments = 0;
5883 ArrayList array_data;
5888 // The number of array initializers that we can handle
5889 // via the InitializeArray method - through EmitStaticInitializers
5891 int num_automatic_initializers;
5893 const int max_automatic_initializers = 6;
5895 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
5897 this.requested_base_type = requested_base_type;
5898 this.initializers = initializers;
5902 arguments = new ArrayList ();
5904 foreach (Expression e in exprs) {
5905 arguments.Add (new Argument (e, Argument.AType.Expression));
5910 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
5912 this.requested_base_type = requested_base_type;
5913 this.initializers = initializers;
5917 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
5919 //string tmp = rank.Substring (rank.LastIndexOf ('['));
5921 //dimensions = tmp.Length - 1;
5922 expect_initializers = true;
5925 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
5927 StringBuilder sb = new StringBuilder (rank);
5930 for (int i = 1; i < idx_count; i++)
5935 return new ComposedCast (base_type, sb.ToString (), loc);
5938 void Error_IncorrectArrayInitializer ()
5940 Error (178, "Incorrectly structured array initializer");
5943 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
5945 if (specified_dims) {
5946 Argument a = (Argument) arguments [idx];
5948 if (!a.Resolve (ec, loc))
5951 if (!(a.Expr is Constant)) {
5952 Error (150, "A constant value is expected");
5956 int value = (int) ((Constant) a.Expr).GetValue ();
5958 if (value != probe.Count) {
5959 Error_IncorrectArrayInitializer ();
5963 bounds [idx] = value;
5966 int child_bounds = -1;
5967 foreach (object o in probe) {
5968 if (o is ArrayList) {
5969 int current_bounds = ((ArrayList) o).Count;
5971 if (child_bounds == -1)
5972 child_bounds = current_bounds;
5974 else if (child_bounds != current_bounds){
5975 Error_IncorrectArrayInitializer ();
5978 if (specified_dims && (idx + 1 >= arguments.Count)){
5979 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
5983 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
5987 if (child_bounds != -1){
5988 Error_IncorrectArrayInitializer ();
5992 Expression tmp = (Expression) o;
5993 tmp = tmp.Resolve (ec);
5997 // Console.WriteLine ("I got: " + tmp);
5998 // Handle initialization from vars, fields etc.
6000 Expression conv = Convert.ImplicitConversionRequired (
6001 ec, tmp, underlying_type, loc);
6006 if (conv is StringConstant || conv is DecimalConstant || conv is NullCast) {
6007 // These are subclasses of Constant that can appear as elements of an
6008 // array that cannot be statically initialized (with num_automatic_initializers
6009 // > max_automatic_initializers), so num_automatic_initializers should be left as zero.
6010 array_data.Add (conv);
6011 } else if (conv is Constant) {
6012 // These are the types of Constant that can appear in arrays that can be
6013 // statically allocated.
6014 array_data.Add (conv);
6015 num_automatic_initializers++;
6017 array_data.Add (conv);
6024 public void UpdateIndices (EmitContext ec)
6027 for (ArrayList probe = initializers; probe != null;) {
6028 if (probe.Count > 0 && probe [0] is ArrayList) {
6029 Expression e = new IntConstant (probe.Count);
6030 arguments.Add (new Argument (e, Argument.AType.Expression));
6032 bounds [i++] = probe.Count;
6034 probe = (ArrayList) probe [0];
6037 Expression e = new IntConstant (probe.Count);
6038 arguments.Add (new Argument (e, Argument.AType.Expression));
6040 bounds [i++] = probe.Count;
6047 public bool ValidateInitializers (EmitContext ec, Type array_type)
6049 if (initializers == null) {
6050 if (expect_initializers)
6056 if (underlying_type == null)
6060 // We use this to store all the date values in the order in which we
6061 // will need to store them in the byte blob later
6063 array_data = new ArrayList ();
6064 bounds = new Hashtable ();
6068 if (arguments != null) {
6069 ret = CheckIndices (ec, initializers, 0, true);
6072 arguments = new ArrayList ();
6074 ret = CheckIndices (ec, initializers, 0, false);
6081 if (arguments.Count != dimensions) {
6082 Error_IncorrectArrayInitializer ();
6091 // Converts `source' to an int, uint, long or ulong.
6093 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
6097 bool old_checked = ec.CheckState;
6098 ec.CheckState = true;
6100 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
6101 if (target == null){
6102 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
6103 if (target == null){
6104 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
6105 if (target == null){
6106 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
6108 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
6112 ec.CheckState = old_checked;
6115 // Only positive constants are allowed at compile time
6117 if (target is Constant){
6118 if (target is IntConstant){
6119 if (((IntConstant) target).Value < 0){
6120 Expression.Error_NegativeArrayIndex (loc);
6125 if (target is LongConstant){
6126 if (((LongConstant) target).Value < 0){
6127 Expression.Error_NegativeArrayIndex (loc);
6138 // Creates the type of the array
6140 bool LookupType (EmitContext ec)
6142 StringBuilder array_qualifier = new StringBuilder (rank);
6145 // `In the first form allocates an array instace of the type that results
6146 // from deleting each of the individual expression from the expression list'
6148 if (num_arguments > 0) {
6149 array_qualifier.Append ("[");
6150 for (int i = num_arguments-1; i > 0; i--)
6151 array_qualifier.Append (",");
6152 array_qualifier.Append ("]");
6158 TypeExpr array_type_expr;
6159 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
6160 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec, false);
6161 if (array_type_expr == null)
6164 type = array_type_expr.ResolveType (ec);
6166 if (!type.IsArray) {
6167 Error (622, "Can only use array initializer expressions to assign to array types. Try using a new expression instead.");
6170 underlying_type = TypeManager.GetElementType (type);
6171 dimensions = type.GetArrayRank ();
6176 public override Expression DoResolve (EmitContext ec)
6180 if (!LookupType (ec))
6184 // First step is to validate the initializers and fill
6185 // in any missing bits
6187 if (!ValidateInitializers (ec, type))
6190 if (arguments == null)
6193 arg_count = arguments.Count;
6194 foreach (Argument a in arguments){
6195 if (!a.Resolve (ec, loc))
6198 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
6199 if (real_arg == null)
6206 array_element_type = TypeManager.GetElementType (type);
6208 if (array_element_type.IsAbstract && array_element_type.IsSealed) {
6209 Report.Error (719, loc, "'{0}': array elements cannot be of static type", TypeManager.CSharpName (array_element_type));
6213 if (arg_count == 1) {
6214 is_one_dimensional = true;
6215 eclass = ExprClass.Value;
6219 is_builtin_type = TypeManager.IsBuiltinType (type);
6221 if (is_builtin_type) {
6224 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
6225 AllBindingFlags, loc);
6227 if (!(ml is MethodGroupExpr)) {
6228 ml.Error_UnexpectedKind ("method group", loc);
6233 Error (-6, "New invocation: Can not find a constructor for " +
6234 "this argument list");
6238 new_method = Invocation.OverloadResolve (
6239 ec, (MethodGroupExpr) ml, arguments, false, loc);
6241 if (new_method == null) {
6242 Error (-6, "New invocation: Can not find a constructor for " +
6243 "this argument list");
6247 eclass = ExprClass.Value;
6250 ModuleBuilder mb = CodeGen.Module.Builder;
6251 ArrayList args = new ArrayList ();
6253 if (arguments != null) {
6254 for (int i = 0; i < arg_count; i++)
6255 args.Add (TypeManager.int32_type);
6258 Type [] arg_types = null;
6261 arg_types = new Type [args.Count];
6263 args.CopyTo (arg_types, 0);
6265 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
6268 if (new_method == null) {
6269 Error (-6, "New invocation: Can not find a constructor for " +
6270 "this argument list");
6274 eclass = ExprClass.Value;
6279 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
6284 int count = array_data.Count;
6286 if (underlying_type.IsEnum)
6287 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
6289 factor = GetTypeSize (underlying_type);
6291 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
6293 data = new byte [(count * factor + 4) & ~3];
6296 for (int i = 0; i < count; ++i) {
6297 object v = array_data [i];
6299 if (v is EnumConstant)
6300 v = ((EnumConstant) v).Child;
6302 if (v is Constant && !(v is StringConstant))
6303 v = ((Constant) v).GetValue ();
6309 if (underlying_type == TypeManager.int64_type){
6310 if (!(v is Expression)){
6311 long val = (long) v;
6313 for (int j = 0; j < factor; ++j) {
6314 data [idx + j] = (byte) (val & 0xFF);
6318 } else if (underlying_type == TypeManager.uint64_type){
6319 if (!(v is Expression)){
6320 ulong val = (ulong) v;
6322 for (int j = 0; j < factor; ++j) {
6323 data [idx + j] = (byte) (val & 0xFF);
6327 } else if (underlying_type == TypeManager.float_type) {
6328 if (!(v is Expression)){
6329 element = BitConverter.GetBytes ((float) v);
6331 for (int j = 0; j < factor; ++j)
6332 data [idx + j] = element [j];
6334 } else if (underlying_type == TypeManager.double_type) {
6335 if (!(v is Expression)){
6336 element = BitConverter.GetBytes ((double) v);
6338 for (int j = 0; j < factor; ++j)
6339 data [idx + j] = element [j];
6341 } else if (underlying_type == TypeManager.char_type){
6342 if (!(v is Expression)){
6343 int val = (int) ((char) v);
6345 data [idx] = (byte) (val & 0xff);
6346 data [idx+1] = (byte) (val >> 8);
6348 } else if (underlying_type == TypeManager.short_type){
6349 if (!(v is Expression)){
6350 int val = (int) ((short) v);
6352 data [idx] = (byte) (val & 0xff);
6353 data [idx+1] = (byte) (val >> 8);
6355 } else if (underlying_type == TypeManager.ushort_type){
6356 if (!(v is Expression)){
6357 int val = (int) ((ushort) v);
6359 data [idx] = (byte) (val & 0xff);
6360 data [idx+1] = (byte) (val >> 8);
6362 } else if (underlying_type == TypeManager.int32_type) {
6363 if (!(v is Expression)){
6366 data [idx] = (byte) (val & 0xff);
6367 data [idx+1] = (byte) ((val >> 8) & 0xff);
6368 data [idx+2] = (byte) ((val >> 16) & 0xff);
6369 data [idx+3] = (byte) (val >> 24);
6371 } else if (underlying_type == TypeManager.uint32_type) {
6372 if (!(v is Expression)){
6373 uint val = (uint) v;
6375 data [idx] = (byte) (val & 0xff);
6376 data [idx+1] = (byte) ((val >> 8) & 0xff);
6377 data [idx+2] = (byte) ((val >> 16) & 0xff);
6378 data [idx+3] = (byte) (val >> 24);
6380 } else if (underlying_type == TypeManager.sbyte_type) {
6381 if (!(v is Expression)){
6382 sbyte val = (sbyte) v;
6383 data [idx] = (byte) val;
6385 } else if (underlying_type == TypeManager.byte_type) {
6386 if (!(v is Expression)){
6387 byte val = (byte) v;
6388 data [idx] = (byte) val;
6390 } else if (underlying_type == TypeManager.bool_type) {
6391 if (!(v is Expression)){
6392 bool val = (bool) v;
6393 data [idx] = (byte) (val ? 1 : 0);
6395 } else if (underlying_type == TypeManager.decimal_type){
6396 if (!(v is Expression)){
6397 int [] bits = Decimal.GetBits ((decimal) v);
6400 // FIXME: For some reason, this doesn't work on the MS runtime.
6401 int [] nbits = new int [4];
6402 nbits [0] = bits [3];
6403 nbits [1] = bits [2];
6404 nbits [2] = bits [0];
6405 nbits [3] = bits [1];
6407 for (int j = 0; j < 4; j++){
6408 data [p++] = (byte) (nbits [j] & 0xff);
6409 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6410 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6411 data [p++] = (byte) (nbits [j] >> 24);
6415 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6424 // Emits the initializers for the array
6426 void EmitStaticInitializers (EmitContext ec)
6429 // First, the static data
6432 ILGenerator ig = ec.ig;
6434 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6436 fb = RootContext.MakeStaticData (data);
6438 ig.Emit (OpCodes.Dup);
6439 ig.Emit (OpCodes.Ldtoken, fb);
6440 ig.Emit (OpCodes.Call,
6441 TypeManager.void_initializearray_array_fieldhandle);
6445 // Emits pieces of the array that can not be computed at compile
6446 // time (variables and string locations).
6448 // This always expect the top value on the stack to be the array
6450 void EmitDynamicInitializers (EmitContext ec)
6452 ILGenerator ig = ec.ig;
6453 int dims = bounds.Count;
6454 int [] current_pos = new int [dims];
6455 int top = array_data.Count;
6457 MethodInfo set = null;
6461 ModuleBuilder mb = null;
6462 mb = CodeGen.Module.Builder;
6463 args = new Type [dims + 1];
6466 for (j = 0; j < dims; j++)
6467 args [j] = TypeManager.int32_type;
6469 args [j] = array_element_type;
6471 set = mb.GetArrayMethod (
6473 CallingConventions.HasThis | CallingConventions.Standard,
6474 TypeManager.void_type, args);
6477 for (int i = 0; i < top; i++){
6479 Expression e = null;
6481 if (array_data [i] is Expression)
6482 e = (Expression) array_data [i];
6486 // Basically we do this for string literals and
6487 // other non-literal expressions
6489 if (e is EnumConstant){
6490 e = ((EnumConstant) e).Child;
6493 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6494 num_automatic_initializers <= max_automatic_initializers) {
6495 Type etype = e.Type;
6497 ig.Emit (OpCodes.Dup);
6499 for (int idx = 0; idx < dims; idx++)
6500 IntConstant.EmitInt (ig, current_pos [idx]);
6503 // If we are dealing with a struct, get the
6504 // address of it, so we can store it.
6507 etype.IsSubclassOf (TypeManager.value_type) &&
6508 (!TypeManager.IsBuiltinOrEnum (etype) ||
6509 etype == TypeManager.decimal_type)) {
6514 // Let new know that we are providing
6515 // the address where to store the results
6517 n.DisableTemporaryValueType ();
6520 ig.Emit (OpCodes.Ldelema, etype);
6527 OpCode op = ArrayAccess.GetStoreOpcode (etype, out is_stobj);
6529 ig.Emit (OpCodes.Stobj, etype);
6533 ig.Emit (OpCodes.Call, set);
6541 for (int j = dims - 1; j >= 0; j--){
6543 if (current_pos [j] < (int) bounds [j])
6545 current_pos [j] = 0;
6550 void EmitArrayArguments (EmitContext ec)
6552 ILGenerator ig = ec.ig;
6554 foreach (Argument a in arguments) {
6555 Type atype = a.Type;
6558 if (atype == TypeManager.uint64_type)
6559 ig.Emit (OpCodes.Conv_Ovf_U4);
6560 else if (atype == TypeManager.int64_type)
6561 ig.Emit (OpCodes.Conv_Ovf_I4);
6565 public override void Emit (EmitContext ec)
6567 ILGenerator ig = ec.ig;
6569 EmitArrayArguments (ec);
6570 if (is_one_dimensional)
6571 ig.Emit (OpCodes.Newarr, array_element_type);
6573 if (is_builtin_type)
6574 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6576 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6579 if (initializers != null){
6581 // FIXME: Set this variable correctly.
6583 bool dynamic_initializers = true;
6585 // This will never be true for array types that cannot be statically
6586 // initialized. num_automatic_initializers will always be zero. See
6588 if (num_automatic_initializers > max_automatic_initializers)
6589 EmitStaticInitializers (ec);
6591 if (dynamic_initializers)
6592 EmitDynamicInitializers (ec);
6596 public object EncodeAsAttribute ()
6598 if (!is_one_dimensional){
6599 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6603 if (array_data == null){
6604 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6608 object [] ret = new object [array_data.Count];
6610 foreach (Expression e in array_data){
6613 if (e is NullLiteral)
6616 if (!Attribute.GetAttributeArgumentExpression (e, Location, array_element_type, out v))
6626 /// Represents the `this' construct
6628 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6631 VariableInfo variable_info;
6633 public This (Block block, Location loc)
6639 public This (Location loc)
6644 public VariableInfo VariableInfo {
6645 get { return variable_info; }
6648 public bool VerifyFixed (bool is_expression)
6650 if ((variable_info == null) || (variable_info.LocalInfo == null))
6653 return variable_info.LocalInfo.IsFixed;
6656 public bool ResolveBase (EmitContext ec)
6658 eclass = ExprClass.Variable;
6659 type = ec.ContainerType;
6662 Error (26, "Keyword this not valid in static code");
6666 if ((block != null) && (block.ThisVariable != null))
6667 variable_info = block.ThisVariable.VariableInfo;
6672 public override Expression DoResolve (EmitContext ec)
6674 if (!ResolveBase (ec))
6677 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
6678 Error (188, "The this object cannot be used before all " +
6679 "of its fields are assigned to");
6680 variable_info.SetAssigned (ec);
6684 if (ec.IsFieldInitializer) {
6685 Error (27, "Keyword `this' can't be used outside a constructor, " +
6686 "a method or a property.");
6693 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6695 if (!ResolveBase (ec))
6698 if (variable_info != null)
6699 variable_info.SetAssigned (ec);
6701 if (ec.TypeContainer is Class){
6702 Error (1604, "Cannot assign to `this'");
6709 public void Emit (EmitContext ec, bool leave_copy)
6713 ec.ig.Emit (OpCodes.Dup);
6716 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
6718 ILGenerator ig = ec.ig;
6720 if (ec.TypeContainer is Struct){
6724 ec.ig.Emit (OpCodes.Dup);
6725 ig.Emit (OpCodes.Stobj, type);
6727 throw new Exception ("how did you get here");
6731 public override void Emit (EmitContext ec)
6733 ILGenerator ig = ec.ig;
6736 if (ec.TypeContainer is Struct)
6737 ig.Emit (OpCodes.Ldobj, type);
6740 public void AddressOf (EmitContext ec, AddressOp mode)
6745 // FIGURE OUT WHY LDARG_S does not work
6747 // consider: struct X { int val; int P { set { val = value; }}}
6749 // Yes, this looks very bad. Look at `NOTAS' for
6751 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
6756 /// Represents the `__arglist' construct
6758 public class ArglistAccess : Expression
6760 public ArglistAccess (Location loc)
6765 public bool ResolveBase (EmitContext ec)
6767 eclass = ExprClass.Variable;
6768 type = TypeManager.runtime_argument_handle_type;
6772 public override Expression DoResolve (EmitContext ec)
6774 if (!ResolveBase (ec))
6777 if (ec.IsFieldInitializer || !ec.CurrentBlock.HasVarargs) {
6778 Error (190, "The __arglist construct is valid only within " +
6779 "a variable argument method.");
6786 public override void Emit (EmitContext ec)
6788 ec.ig.Emit (OpCodes.Arglist);
6793 /// Represents the `__arglist (....)' construct
6795 public class Arglist : Expression
6797 public readonly Argument[] Arguments;
6799 public Arglist (Argument[] args, Location l)
6805 public Type[] ArgumentTypes {
6807 Type[] retval = new Type [Arguments.Length];
6808 for (int i = 0; i < Arguments.Length; i++)
6809 retval [i] = Arguments [i].Type;
6814 public override Expression DoResolve (EmitContext ec)
6816 eclass = ExprClass.Variable;
6817 type = TypeManager.runtime_argument_handle_type;
6819 foreach (Argument arg in Arguments) {
6820 if (!arg.Resolve (ec, loc))
6827 public override void Emit (EmitContext ec)
6829 foreach (Argument arg in Arguments)
6835 // This produces the value that renders an instance, used by the iterators code
6837 public class ProxyInstance : Expression, IMemoryLocation {
6838 public override Expression DoResolve (EmitContext ec)
6840 eclass = ExprClass.Variable;
6841 type = ec.ContainerType;
6845 public override void Emit (EmitContext ec)
6847 ec.ig.Emit (OpCodes.Ldarg_0);
6851 public void AddressOf (EmitContext ec, AddressOp mode)
6853 ec.ig.Emit (OpCodes.Ldarg_0);
6858 /// Implements the typeof operator
6860 public class TypeOf : Expression {
6861 public Expression QueriedType;
6862 protected Type typearg;
6864 public TypeOf (Expression queried_type, Location l)
6866 QueriedType = queried_type;
6870 public override Expression DoResolve (EmitContext ec)
6872 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
6876 typearg = texpr.ResolveType (ec);
6878 if (typearg == TypeManager.void_type) {
6879 Error (673, "System.Void cannot be used from C# - " +
6880 "use typeof (void) to get the void type object");
6884 if (typearg.IsPointer && !ec.InUnsafe){
6888 CheckObsoleteAttribute (typearg);
6890 type = TypeManager.type_type;
6891 eclass = ExprClass.Type;
6895 public override void Emit (EmitContext ec)
6897 ec.ig.Emit (OpCodes.Ldtoken, typearg);
6898 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6901 public Type TypeArg {
6902 get { return typearg; }
6907 /// Implements the `typeof (void)' operator
6909 public class TypeOfVoid : TypeOf {
6910 public TypeOfVoid (Location l) : base (null, l)
6915 public override Expression DoResolve (EmitContext ec)
6917 type = TypeManager.type_type;
6918 typearg = TypeManager.void_type;
6919 eclass = ExprClass.Type;
6925 /// Implements the sizeof expression
6927 public class SizeOf : Expression {
6928 public Expression QueriedType;
6931 public SizeOf (Expression queried_type, Location l)
6933 this.QueriedType = queried_type;
6937 public override Expression DoResolve (EmitContext ec)
6941 233, loc, "Sizeof may only be used in an unsafe context " +
6942 "(consider using System.Runtime.InteropServices.Marshal.SizeOf");
6946 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
6950 type_queried = texpr.ResolveType (ec);
6952 CheckObsoleteAttribute (type_queried);
6954 if (!TypeManager.IsUnmanagedType (type_queried)){
6955 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
6959 type = TypeManager.int32_type;
6960 eclass = ExprClass.Value;
6964 public override void Emit (EmitContext ec)
6966 int size = GetTypeSize (type_queried);
6969 ec.ig.Emit (OpCodes.Sizeof, type_queried);
6971 IntConstant.EmitInt (ec.ig, size);
6976 /// Implements the member access expression
6978 public class MemberAccess : Expression {
6979 public readonly string Identifier;
6982 public MemberAccess (Expression expr, string id, Location l)
6989 public Expression Expr {
6995 public static void error176 (Location loc, string name)
6997 Report.Error (176, loc, "Static member `" +
6998 name + "' cannot be accessed " +
6999 "with an instance reference, qualify with a " +
7000 "type name instead");
7003 public static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Expression left, Location loc)
7005 SimpleName sn = left_original as SimpleName;
7006 if (sn == null || left == null || left.Type.Name != sn.Name)
7009 return RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc) != null;
7012 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
7013 Expression left, Location loc,
7014 Expression left_original)
7016 bool left_is_type, left_is_explicit;
7018 // If `left' is null, then we're called from SimpleNameResolve and this is
7019 // a member in the currently defining class.
7021 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
7022 left_is_explicit = false;
7024 // Implicitly default to `this' unless we're static.
7025 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
7026 left = ec.GetThis (loc);
7028 left_is_type = left is TypeExpr;
7029 left_is_explicit = true;
7032 if (member_lookup is FieldExpr){
7033 FieldExpr fe = (FieldExpr) member_lookup;
7034 FieldInfo fi = fe.FieldInfo;
7035 Type decl_type = fi.DeclaringType;
7037 if (fi is FieldBuilder) {
7038 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
7042 if (!c.LookupConstantValue (out o))
7045 object real_value = ((Constant) c.Expr).GetValue ();
7047 return Constantify (real_value, fi.FieldType);
7052 Type t = fi.FieldType;
7056 if (fi is FieldBuilder)
7057 o = TypeManager.GetValue ((FieldBuilder) fi);
7059 o = fi.GetValue (fi);
7061 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
7062 if (left_is_explicit && !left_is_type &&
7063 !IdenticalNameAndTypeName (ec, left_original, member_lookup, loc)) {
7064 error176 (loc, fe.FieldInfo.Name);
7068 Expression enum_member = MemberLookup (
7069 ec, decl_type, "value__", MemberTypes.Field,
7070 AllBindingFlags, loc);
7072 Enum en = TypeManager.LookupEnum (decl_type);
7076 c = Constantify (o, en.UnderlyingType);
7078 c = Constantify (o, enum_member.Type);
7080 return new EnumConstant (c, decl_type);
7083 Expression exp = Constantify (o, t);
7085 if (left_is_explicit && !left_is_type) {
7086 error176 (loc, fe.FieldInfo.Name);
7093 if (fi.FieldType.IsPointer && !ec.InUnsafe){
7099 if (member_lookup is EventExpr) {
7100 EventExpr ee = (EventExpr) member_lookup;
7103 // If the event is local to this class, we transform ourselves into
7107 if (ee.EventInfo.DeclaringType == ec.ContainerType ||
7108 TypeManager.IsNestedChildOf(ec.ContainerType, ee.EventInfo.DeclaringType)) {
7109 MemberInfo mi = GetFieldFromEvent (ee);
7113 // If this happens, then we have an event with its own
7114 // accessors and private field etc so there's no need
7115 // to transform ourselves.
7117 ee.InstanceExpression = left;
7121 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
7124 Report.Error (-200, loc, "Internal error!!");
7128 if (!left_is_explicit)
7131 ee.InstanceExpression = left;
7133 return ResolveMemberAccess (ec, ml, left, loc, left_original);
7137 if (member_lookup is IMemberExpr) {
7138 IMemberExpr me = (IMemberExpr) member_lookup;
7139 MethodGroupExpr mg = me as MethodGroupExpr;
7142 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
7143 mg.IsExplicitImpl = left_is_explicit;
7146 if ((ec.IsFieldInitializer || ec.IsStatic) &&
7147 IdenticalNameAndTypeName (ec, left_original, member_lookup, loc))
7148 return member_lookup;
7150 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
7155 if (!me.IsInstance) {
7156 if (IdenticalNameAndTypeName (ec, left_original, left, loc))
7157 return member_lookup;
7159 if (left_is_explicit) {
7160 error176 (loc, me.Name);
7166 // Since we can not check for instance objects in SimpleName,
7167 // becaue of the rule that allows types and variables to share
7168 // the name (as long as they can be de-ambiguated later, see
7169 // IdenticalNameAndTypeName), we have to check whether left
7170 // is an instance variable in a static context
7172 // However, if the left-hand value is explicitly given, then
7173 // it is already our instance expression, so we aren't in
7177 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
7178 IMemberExpr mexp = (IMemberExpr) left;
7180 if (!mexp.IsStatic){
7181 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
7186 if ((mg != null) && IdenticalNameAndTypeName (ec, left_original, left, loc))
7187 mg.IdenticalTypeName = true;
7189 me.InstanceExpression = left;
7192 return member_lookup;
7195 Console.WriteLine ("Left is: " + left);
7196 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
7197 Environment.Exit (1);
7201 public Expression DoResolve (EmitContext ec, Expression right_side, ResolveFlags flags)
7204 throw new Exception ();
7207 // Resolve the expression with flow analysis turned off, we'll do the definite
7208 // assignment checks later. This is because we don't know yet what the expression
7209 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7210 // definite assignment check on the actual field and not on the whole struct.
7213 Expression original = expr;
7214 expr = expr.Resolve (ec, flags | ResolveFlags.Intermediate | ResolveFlags.DisableFlowAnalysis);
7218 if (expr is SimpleName){
7219 SimpleName child_expr = (SimpleName) expr;
7221 Expression new_expr = new SimpleName (child_expr.Name, Identifier, loc);
7223 return new_expr.Resolve (ec, flags);
7227 // TODO: I mailed Ravi about this, and apparently we can get rid
7228 // of this and put it in the right place.
7230 // Handle enums here when they are in transit.
7231 // Note that we cannot afford to hit MemberLookup in this case because
7232 // it will fail to find any members at all
7235 Type expr_type = expr.Type;
7236 if (expr is TypeExpr){
7237 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
7238 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", expr_type);
7242 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
7243 Enum en = TypeManager.LookupEnum (expr_type);
7246 object value = en.LookupEnumValue (ec, Identifier, loc);
7249 MemberCore mc = en.GetDefinition (Identifier);
7250 ObsoleteAttribute oa = mc.GetObsoleteAttribute (en);
7252 AttributeTester.Report_ObsoleteMessage (oa, mc.GetSignatureForError (), Location);
7254 oa = en.GetObsoleteAttribute (en);
7256 AttributeTester.Report_ObsoleteMessage (oa, en.GetSignatureForError (), Location);
7259 Constant c = Constantify (value, en.UnderlyingType);
7260 return new EnumConstant (c, expr_type);
7263 CheckObsoleteAttribute (expr_type);
7265 FieldInfo fi = expr_type.GetField (Identifier);
7267 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
7269 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), Location);
7275 if (expr_type.IsPointer){
7276 Error (23, "The `.' operator can not be applied to pointer operands (" +
7277 TypeManager.CSharpName (expr_type) + ")");
7281 Expression member_lookup;
7282 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
7283 if (member_lookup == null)
7286 if (member_lookup is TypeExpr) {
7287 if (!(expr is TypeExpr) && !(expr is SimpleName)) {
7288 Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
7289 member_lookup.Type + "' instead");
7293 return member_lookup;
7296 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
7297 if (member_lookup == null)
7300 // The following DoResolve/DoResolveLValue will do the definite assignment
7303 if (right_side != null)
7304 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
7306 member_lookup = member_lookup.DoResolve (ec);
7308 return member_lookup;
7311 public override Expression DoResolve (EmitContext ec)
7313 return DoResolve (ec, null, ResolveFlags.VariableOrValue |
7314 ResolveFlags.SimpleName | ResolveFlags.Type);
7317 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7319 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
7320 ResolveFlags.SimpleName | ResolveFlags.Type);
7323 public override Expression ResolveAsTypeStep (EmitContext ec)
7325 string fname = null;
7326 MemberAccess full_expr = this;
7327 while (full_expr != null) {
7329 fname = String.Concat (full_expr.Identifier, ".", fname);
7331 fname = full_expr.Identifier;
7333 if (full_expr.Expr is SimpleName) {
7334 string full_name = String.Concat (((SimpleName) full_expr.Expr).Name, ".", fname);
7335 Type fully_qualified = ec.DeclSpace.FindType (loc, full_name);
7336 if (fully_qualified != null)
7337 return new TypeExpression (fully_qualified, loc);
7340 full_expr = full_expr.Expr as MemberAccess;
7343 Expression new_expr = expr.ResolveAsTypeStep (ec);
7345 if (new_expr == null)
7348 if (new_expr is SimpleName){
7349 SimpleName child_expr = (SimpleName) new_expr;
7351 new_expr = new SimpleName (child_expr.Name, Identifier, loc);
7353 return new_expr.ResolveAsTypeStep (ec);
7356 Type expr_type = new_expr.Type;
7358 if (expr_type.IsPointer){
7359 Error (23, "The `.' operator can not be applied to pointer operands (" +
7360 TypeManager.CSharpName (expr_type) + ")");
7364 Expression member_lookup;
7365 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
7366 if (member_lookup == null)
7369 if (member_lookup is TypeExpr){
7370 member_lookup.Resolve (ec, ResolveFlags.Type);
7371 return member_lookup;
7377 public override void Emit (EmitContext ec)
7379 throw new Exception ("Should not happen");
7382 public override string ToString ()
7384 return expr + "." + Identifier;
7389 /// Implements checked expressions
7391 public class CheckedExpr : Expression {
7393 public Expression Expr;
7395 public CheckedExpr (Expression e, Location l)
7401 public override Expression DoResolve (EmitContext ec)
7403 bool last_check = ec.CheckState;
7404 bool last_const_check = ec.ConstantCheckState;
7406 ec.CheckState = true;
7407 ec.ConstantCheckState = true;
7408 Expr = Expr.Resolve (ec);
7409 ec.CheckState = last_check;
7410 ec.ConstantCheckState = last_const_check;
7415 if (Expr is Constant)
7418 eclass = Expr.eclass;
7423 public override void Emit (EmitContext ec)
7425 bool last_check = ec.CheckState;
7426 bool last_const_check = ec.ConstantCheckState;
7428 ec.CheckState = true;
7429 ec.ConstantCheckState = true;
7431 ec.CheckState = last_check;
7432 ec.ConstantCheckState = last_const_check;
7438 /// Implements the unchecked expression
7440 public class UnCheckedExpr : Expression {
7442 public Expression Expr;
7444 public UnCheckedExpr (Expression e, Location l)
7450 public override Expression DoResolve (EmitContext ec)
7452 bool last_check = ec.CheckState;
7453 bool last_const_check = ec.ConstantCheckState;
7455 ec.CheckState = false;
7456 ec.ConstantCheckState = false;
7457 Expr = Expr.Resolve (ec);
7458 ec.CheckState = last_check;
7459 ec.ConstantCheckState = last_const_check;
7464 if (Expr is Constant)
7467 eclass = Expr.eclass;
7472 public override void Emit (EmitContext ec)
7474 bool last_check = ec.CheckState;
7475 bool last_const_check = ec.ConstantCheckState;
7477 ec.CheckState = false;
7478 ec.ConstantCheckState = false;
7480 ec.CheckState = last_check;
7481 ec.ConstantCheckState = last_const_check;
7487 /// An Element Access expression.
7489 /// During semantic analysis these are transformed into
7490 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7492 public class ElementAccess : Expression {
7493 public ArrayList Arguments;
7494 public Expression Expr;
7496 public ElementAccess (Expression e, ArrayList e_list, Location l)
7505 Arguments = new ArrayList ();
7506 foreach (Expression tmp in e_list)
7507 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7511 bool CommonResolve (EmitContext ec)
7513 Expr = Expr.Resolve (ec);
7518 if (Arguments == null)
7521 foreach (Argument a in Arguments){
7522 if (!a.Resolve (ec, loc))
7529 Expression MakePointerAccess (EmitContext ec)
7533 if (t == TypeManager.void_ptr_type){
7534 Error (242, "The array index operation is not valid for void pointers");
7537 if (Arguments.Count != 1){
7538 Error (196, "A pointer must be indexed by a single value");
7543 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc).Resolve (ec);
7546 return new Indirection (p, loc).Resolve (ec);
7549 public override Expression DoResolve (EmitContext ec)
7551 if (!CommonResolve (ec))
7555 // We perform some simple tests, and then to "split" the emit and store
7556 // code we create an instance of a different class, and return that.
7558 // I am experimenting with this pattern.
7562 if (t == TypeManager.array_type){
7563 Report.Error (21, loc, "Cannot use indexer on System.Array");
7568 return (new ArrayAccess (this, loc)).Resolve (ec);
7569 else if (t.IsPointer)
7570 return MakePointerAccess (ec);
7572 return (new IndexerAccess (this, loc)).Resolve (ec);
7575 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7577 if (!CommonResolve (ec))
7582 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
7583 else if (t.IsPointer)
7584 return MakePointerAccess (ec);
7586 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
7589 public override void Emit (EmitContext ec)
7591 throw new Exception ("Should never be reached");
7596 /// Implements array access
7598 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7600 // Points to our "data" repository
7604 LocalTemporary temp;
7607 public ArrayAccess (ElementAccess ea_data, Location l)
7610 eclass = ExprClass.Variable;
7614 public override Expression DoResolve (EmitContext ec)
7617 ExprClass eclass = ea.Expr.eclass;
7619 // As long as the type is valid
7620 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7621 eclass == ExprClass.Value)) {
7622 ea.Expr.Error_UnexpectedKind ("variable or value");
7627 Type t = ea.Expr.Type;
7628 if (t.GetArrayRank () != ea.Arguments.Count){
7630 "Incorrect number of indexes for array " +
7631 " expected: " + t.GetArrayRank () + " got: " +
7632 ea.Arguments.Count);
7636 type = TypeManager.GetElementType (t);
7637 if (type.IsPointer && !ec.InUnsafe){
7638 UnsafeError (ea.Location);
7642 foreach (Argument a in ea.Arguments){
7643 Type argtype = a.Type;
7645 if (argtype == TypeManager.int32_type ||
7646 argtype == TypeManager.uint32_type ||
7647 argtype == TypeManager.int64_type ||
7648 argtype == TypeManager.uint64_type) {
7649 Constant c = a.Expr as Constant;
7650 if (c != null && c.IsNegative) {
7651 Report.Warning (251, 2, a.Expr.Location, "Indexing an array with a negative index (array indices always start at zero)");
7657 // Mhm. This is strage, because the Argument.Type is not the same as
7658 // Argument.Expr.Type: the value changes depending on the ref/out setting.
7660 // Wonder if I will run into trouble for this.
7662 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
7667 eclass = ExprClass.Variable;
7673 /// Emits the right opcode to load an object of Type `t'
7674 /// from an array of T
7676 static public void EmitLoadOpcode (ILGenerator ig, Type type)
7678 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7679 ig.Emit (OpCodes.Ldelem_U1);
7680 else if (type == TypeManager.sbyte_type)
7681 ig.Emit (OpCodes.Ldelem_I1);
7682 else if (type == TypeManager.short_type)
7683 ig.Emit (OpCodes.Ldelem_I2);
7684 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7685 ig.Emit (OpCodes.Ldelem_U2);
7686 else if (type == TypeManager.int32_type)
7687 ig.Emit (OpCodes.Ldelem_I4);
7688 else if (type == TypeManager.uint32_type)
7689 ig.Emit (OpCodes.Ldelem_U4);
7690 else if (type == TypeManager.uint64_type)
7691 ig.Emit (OpCodes.Ldelem_I8);
7692 else if (type == TypeManager.int64_type)
7693 ig.Emit (OpCodes.Ldelem_I8);
7694 else if (type == TypeManager.float_type)
7695 ig.Emit (OpCodes.Ldelem_R4);
7696 else if (type == TypeManager.double_type)
7697 ig.Emit (OpCodes.Ldelem_R8);
7698 else if (type == TypeManager.intptr_type)
7699 ig.Emit (OpCodes.Ldelem_I);
7700 else if (TypeManager.IsEnumType (type)){
7701 EmitLoadOpcode (ig, TypeManager.EnumToUnderlying (type));
7702 } else if (type.IsValueType){
7703 ig.Emit (OpCodes.Ldelema, type);
7704 ig.Emit (OpCodes.Ldobj, type);
7706 ig.Emit (OpCodes.Ldelem_Ref);
7710 /// Returns the right opcode to store an object of Type `t'
7711 /// from an array of T.
7713 static public OpCode GetStoreOpcode (Type t, out bool is_stobj)
7715 //Console.WriteLine (new System.Diagnostics.StackTrace ());
7717 t = TypeManager.TypeToCoreType (t);
7718 if (TypeManager.IsEnumType (t))
7719 t = TypeManager.EnumToUnderlying (t);
7720 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
7721 t == TypeManager.bool_type)
7722 return OpCodes.Stelem_I1;
7723 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
7724 t == TypeManager.char_type)
7725 return OpCodes.Stelem_I2;
7726 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
7727 return OpCodes.Stelem_I4;
7728 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
7729 return OpCodes.Stelem_I8;
7730 else if (t == TypeManager.float_type)
7731 return OpCodes.Stelem_R4;
7732 else if (t == TypeManager.double_type)
7733 return OpCodes.Stelem_R8;
7734 else if (t == TypeManager.intptr_type) {
7736 return OpCodes.Stobj;
7737 } else if (t.IsValueType) {
7739 return OpCodes.Stobj;
7741 return OpCodes.Stelem_Ref;
7744 MethodInfo FetchGetMethod ()
7746 ModuleBuilder mb = CodeGen.Module.Builder;
7747 int arg_count = ea.Arguments.Count;
7748 Type [] args = new Type [arg_count];
7751 for (int i = 0; i < arg_count; i++){
7752 //args [i++] = a.Type;
7753 args [i] = TypeManager.int32_type;
7756 get = mb.GetArrayMethod (
7757 ea.Expr.Type, "Get",
7758 CallingConventions.HasThis |
7759 CallingConventions.Standard,
7765 MethodInfo FetchAddressMethod ()
7767 ModuleBuilder mb = CodeGen.Module.Builder;
7768 int arg_count = ea.Arguments.Count;
7769 Type [] args = new Type [arg_count];
7773 ret_type = TypeManager.GetReferenceType (type);
7775 for (int i = 0; i < arg_count; i++){
7776 //args [i++] = a.Type;
7777 args [i] = TypeManager.int32_type;
7780 address = mb.GetArrayMethod (
7781 ea.Expr.Type, "Address",
7782 CallingConventions.HasThis |
7783 CallingConventions.Standard,
7790 // Load the array arguments into the stack.
7792 // If we have been requested to cache the values (cached_locations array
7793 // initialized), then load the arguments the first time and store them
7794 // in locals. otherwise load from local variables.
7796 void LoadArrayAndArguments (EmitContext ec)
7798 ILGenerator ig = ec.ig;
7801 foreach (Argument a in ea.Arguments){
7802 Type argtype = a.Expr.Type;
7806 if (argtype == TypeManager.int64_type)
7807 ig.Emit (OpCodes.Conv_Ovf_I);
7808 else if (argtype == TypeManager.uint64_type)
7809 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7813 public void Emit (EmitContext ec, bool leave_copy)
7815 int rank = ea.Expr.Type.GetArrayRank ();
7816 ILGenerator ig = ec.ig;
7819 LoadArrayAndArguments (ec);
7822 EmitLoadOpcode (ig, type);
7826 method = FetchGetMethod ();
7827 ig.Emit (OpCodes.Call, method);
7830 LoadFromPtr (ec.ig, this.type);
7833 ec.ig.Emit (OpCodes.Dup);
7834 temp = new LocalTemporary (ec, this.type);
7839 public override void Emit (EmitContext ec)
7844 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
7846 int rank = ea.Expr.Type.GetArrayRank ();
7847 ILGenerator ig = ec.ig;
7848 Type t = source.Type;
7849 prepared = prepare_for_load;
7851 if (prepare_for_load) {
7852 AddressOf (ec, AddressOp.LoadStore);
7853 ec.ig.Emit (OpCodes.Dup);
7856 ec.ig.Emit (OpCodes.Dup);
7857 temp = new LocalTemporary (ec, this.type);
7860 StoreFromPtr (ec.ig, t);
7868 LoadArrayAndArguments (ec);
7872 OpCode op = GetStoreOpcode (t, out is_stobj);
7874 // The stobj opcode used by value types will need
7875 // an address on the stack, not really an array/array
7879 ig.Emit (OpCodes.Ldelema, t);
7883 ec.ig.Emit (OpCodes.Dup);
7884 temp = new LocalTemporary (ec, this.type);
7889 ig.Emit (OpCodes.Stobj, t);
7893 ModuleBuilder mb = CodeGen.Module.Builder;
7894 int arg_count = ea.Arguments.Count;
7895 Type [] args = new Type [arg_count + 1];
7900 ec.ig.Emit (OpCodes.Dup);
7901 temp = new LocalTemporary (ec, this.type);
7905 for (int i = 0; i < arg_count; i++){
7906 //args [i++] = a.Type;
7907 args [i] = TypeManager.int32_type;
7910 args [arg_count] = type;
7912 set = mb.GetArrayMethod (
7913 ea.Expr.Type, "Set",
7914 CallingConventions.HasThis |
7915 CallingConventions.Standard,
7916 TypeManager.void_type, args);
7918 ig.Emit (OpCodes.Call, set);
7925 public void AddressOf (EmitContext ec, AddressOp mode)
7927 int rank = ea.Expr.Type.GetArrayRank ();
7928 ILGenerator ig = ec.ig;
7930 LoadArrayAndArguments (ec);
7933 ig.Emit (OpCodes.Ldelema, type);
7935 MethodInfo address = FetchAddressMethod ();
7936 ig.Emit (OpCodes.Call, address);
7943 public ArrayList Properties;
7944 static Hashtable map;
7946 public struct Indexer {
7947 public readonly Type Type;
7948 public readonly MethodInfo Getter, Setter;
7950 public Indexer (Type type, MethodInfo get, MethodInfo set)
7960 map = new Hashtable ();
7965 Properties = new ArrayList ();
7968 void Append (MemberInfo [] mi)
7970 foreach (PropertyInfo property in mi){
7971 MethodInfo get, set;
7973 get = property.GetGetMethod (true);
7974 set = property.GetSetMethod (true);
7975 Properties.Add (new Indexer (property.PropertyType, get, set));
7979 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
7981 string p_name = TypeManager.IndexerPropertyName (lookup_type);
7983 MemberInfo [] mi = TypeManager.MemberLookup (
7984 caller_type, caller_type, lookup_type, MemberTypes.Property,
7985 BindingFlags.Public | BindingFlags.Instance |
7986 BindingFlags.DeclaredOnly, p_name, null);
7988 if (mi == null || mi.Length == 0)
7994 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
7996 Indexers ix = (Indexers) map [lookup_type];
8001 Type copy = lookup_type;
8002 while (copy != TypeManager.object_type && copy != null){
8003 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
8007 ix = new Indexers ();
8012 copy = copy.BaseType;
8015 if (!lookup_type.IsInterface)
8018 TypeExpr [] ifaces = TypeManager.GetInterfaces (lookup_type);
8019 if (ifaces != null) {
8020 foreach (TypeExpr iface in ifaces) {
8021 Type itype = iface.Type;
8022 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
8025 ix = new Indexers ();
8037 /// Expressions that represent an indexer call.
8039 public class IndexerAccess : Expression, IAssignMethod {
8041 // Points to our "data" repository
8043 MethodInfo get, set;
8044 ArrayList set_arguments;
8045 bool is_base_indexer;
8047 protected Type indexer_type;
8048 protected Type current_type;
8049 protected Expression instance_expr;
8050 protected ArrayList arguments;
8052 public IndexerAccess (ElementAccess ea, Location loc)
8053 : this (ea.Expr, false, loc)
8055 this.arguments = ea.Arguments;
8058 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
8061 this.instance_expr = instance_expr;
8062 this.is_base_indexer = is_base_indexer;
8063 this.eclass = ExprClass.Value;
8067 protected virtual bool CommonResolve (EmitContext ec)
8069 indexer_type = instance_expr.Type;
8070 current_type = ec.ContainerType;
8075 public override Expression DoResolve (EmitContext ec)
8077 ArrayList AllGetters = new ArrayList();
8078 if (!CommonResolve (ec))
8082 // Step 1: Query for all `Item' *properties*. Notice
8083 // that the actual methods are pointed from here.
8085 // This is a group of properties, piles of them.
8087 bool found_any = false, found_any_getters = false;
8088 Type lookup_type = indexer_type;
8091 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
8092 if (ilist != null) {
8094 if (ilist.Properties != null) {
8095 foreach (Indexers.Indexer ix in ilist.Properties) {
8096 if (ix.Getter != null)
8097 AllGetters.Add(ix.Getter);
8102 if (AllGetters.Count > 0) {
8103 found_any_getters = true;
8104 get = (MethodInfo) Invocation.OverloadResolve (
8105 ec, new MethodGroupExpr (AllGetters, loc),
8106 arguments, false, loc);
8110 Report.Error (21, loc,
8111 "Type `" + TypeManager.CSharpName (indexer_type) +
8112 "' does not have any indexers defined");
8116 if (!found_any_getters) {
8117 Error (154, "indexer can not be used in this context, because " +
8118 "it lacks a `get' accessor");
8123 Error (1501, "No Overload for method `this' takes `" +
8124 arguments.Count + "' arguments");
8129 // Only base will allow this invocation to happen.
8131 if (get.IsAbstract && this is BaseIndexerAccess){
8132 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
8136 type = get.ReturnType;
8137 if (type.IsPointer && !ec.InUnsafe){
8142 eclass = ExprClass.IndexerAccess;
8146 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8148 ArrayList AllSetters = new ArrayList();
8149 if (!CommonResolve (ec))
8152 bool found_any = false, found_any_setters = false;
8154 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
8155 if (ilist != null) {
8157 if (ilist.Properties != null) {
8158 foreach (Indexers.Indexer ix in ilist.Properties) {
8159 if (ix.Setter != null)
8160 AllSetters.Add(ix.Setter);
8164 if (AllSetters.Count > 0) {
8165 found_any_setters = true;
8166 set_arguments = (ArrayList) arguments.Clone ();
8167 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
8168 set = (MethodInfo) Invocation.OverloadResolve (
8169 ec, new MethodGroupExpr (AllSetters, loc),
8170 set_arguments, false, loc);
8174 Report.Error (21, loc,
8175 "Type `" + TypeManager.CSharpName (indexer_type) +
8176 "' does not have any indexers defined");
8180 if (!found_any_setters) {
8181 Error (154, "indexer can not be used in this context, because " +
8182 "it lacks a `set' accessor");
8187 Error (1501, "No Overload for method `this' takes `" +
8188 arguments.Count + "' arguments");
8193 // Only base will allow this invocation to happen.
8195 if (set.IsAbstract && this is BaseIndexerAccess){
8196 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
8201 // Now look for the actual match in the list of indexers to set our "return" type
8203 type = TypeManager.void_type; // default value
8204 foreach (Indexers.Indexer ix in ilist.Properties){
8205 if (ix.Setter == set){
8211 eclass = ExprClass.IndexerAccess;
8215 bool prepared = false;
8216 LocalTemporary temp;
8218 public void Emit (EmitContext ec, bool leave_copy)
8220 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc, prepared, false);
8222 ec.ig.Emit (OpCodes.Dup);
8223 temp = new LocalTemporary (ec, Type);
8229 // source is ignored, because we already have a copy of it from the
8230 // LValue resolution and we have already constructed a pre-cached
8231 // version of the arguments (ea.set_arguments);
8233 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8235 prepared = prepare_for_load;
8236 Argument a = (Argument) set_arguments [set_arguments.Count - 1];
8241 ec.ig.Emit (OpCodes.Dup);
8242 temp = new LocalTemporary (ec, Type);
8245 } else if (leave_copy) {
8246 temp = new LocalTemporary (ec, Type);
8252 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc, false, prepared);
8259 public override void Emit (EmitContext ec)
8266 /// The base operator for method names
8268 public class BaseAccess : Expression {
8271 public BaseAccess (string member, Location l)
8273 this.member = member;
8277 public override Expression DoResolve (EmitContext ec)
8279 Expression c = CommonResolve (ec);
8285 // MethodGroups use this opportunity to flag an error on lacking ()
8287 if (!(c is MethodGroupExpr))
8288 return c.Resolve (ec);
8292 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8294 Expression c = CommonResolve (ec);
8300 // MethodGroups use this opportunity to flag an error on lacking ()
8302 if (! (c is MethodGroupExpr))
8303 return c.DoResolveLValue (ec, right_side);
8308 Expression CommonResolve (EmitContext ec)
8310 Expression member_lookup;
8311 Type current_type = ec.ContainerType;
8312 Type base_type = current_type.BaseType;
8316 Error (1511, "Keyword base is not allowed in static method");
8320 if (ec.IsFieldInitializer){
8321 Error (1512, "Keyword base is not available in the current context");
8325 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type, member,
8326 AllMemberTypes, AllBindingFlags, loc);
8327 if (member_lookup == null) {
8328 MemberLookupFailed (ec, base_type, base_type, member, null, loc);
8335 left = new TypeExpression (base_type, loc);
8337 left = ec.GetThis (loc);
8339 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
8341 if (e is PropertyExpr){
8342 PropertyExpr pe = (PropertyExpr) e;
8347 if (e is MethodGroupExpr)
8348 ((MethodGroupExpr) e).IsBase = true;
8353 public override void Emit (EmitContext ec)
8355 throw new Exception ("Should never be called");
8360 /// The base indexer operator
8362 public class BaseIndexerAccess : IndexerAccess {
8363 public BaseIndexerAccess (ArrayList args, Location loc)
8364 : base (null, true, loc)
8366 arguments = new ArrayList ();
8367 foreach (Expression tmp in args)
8368 arguments.Add (new Argument (tmp, Argument.AType.Expression));
8371 protected override bool CommonResolve (EmitContext ec)
8373 instance_expr = ec.GetThis (loc);
8375 current_type = ec.ContainerType.BaseType;
8376 indexer_type = current_type;
8378 foreach (Argument a in arguments){
8379 if (!a.Resolve (ec, loc))
8388 /// This class exists solely to pass the Type around and to be a dummy
8389 /// that can be passed to the conversion functions (this is used by
8390 /// foreach implementation to typecast the object return value from
8391 /// get_Current into the proper type. All code has been generated and
8392 /// we only care about the side effect conversions to be performed
8394 /// This is also now used as a placeholder where a no-action expression
8395 /// is needed (the `New' class).
8397 public class EmptyExpression : Expression {
8398 public static readonly EmptyExpression Null = new EmptyExpression ();
8400 // TODO: should be protected
8401 public EmptyExpression ()
8403 type = TypeManager.object_type;
8404 eclass = ExprClass.Value;
8405 loc = Location.Null;
8408 public EmptyExpression (Type t)
8411 eclass = ExprClass.Value;
8412 loc = Location.Null;
8415 public override Expression DoResolve (EmitContext ec)
8420 public override void Emit (EmitContext ec)
8422 // nothing, as we only exist to not do anything.
8426 // This is just because we might want to reuse this bad boy
8427 // instead of creating gazillions of EmptyExpressions.
8428 // (CanImplicitConversion uses it)
8430 public void SetType (Type t)
8436 public class UserCast : Expression {
8440 public UserCast (MethodInfo method, Expression source, Location l)
8442 this.method = method;
8443 this.source = source;
8444 type = method.ReturnType;
8445 eclass = ExprClass.Value;
8449 public override Expression DoResolve (EmitContext ec)
8452 // We are born fully resolved
8457 public override void Emit (EmitContext ec)
8459 ILGenerator ig = ec.ig;
8463 if (method is MethodInfo)
8464 ig.Emit (OpCodes.Call, (MethodInfo) method);
8466 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
8472 // This class is used to "construct" the type during a typecast
8473 // operation. Since the Type.GetType class in .NET can parse
8474 // the type specification, we just use this to construct the type
8475 // one bit at a time.
8477 public class ComposedCast : TypeExpr {
8481 public ComposedCast (Expression left, string dim, Location l)
8488 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
8490 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec, false);
8494 Type ltype = lexpr.ResolveType (ec);
8496 if ((ltype == TypeManager.void_type) && (dim != "*")) {
8497 Report.Error (1547, Location,
8498 "Keyword 'void' cannot be used in this context");
8503 // ltype.Fullname is already fully qualified, so we can skip
8504 // a lot of probes, and go directly to TypeManager.LookupType
8506 string cname = ltype.FullName + dim;
8507 type = TypeManager.LookupTypeDirect (cname);
8510 // For arrays of enumerations we are having a problem
8511 // with the direct lookup. Need to investigate.
8513 // For now, fall back to the full lookup in that case.
8515 type = RootContext.LookupType (
8516 ec.DeclSpace, cname, false, loc);
8522 if (!ec.InUnsafe && type.IsPointer){
8527 eclass = ExprClass.Type;
8531 public override string Name {
8539 // This class is used to represent the address of an array, used
8540 // only by the Fixed statement, this is like the C "&a [0]" construct.
8542 public class ArrayPtr : Expression {
8545 public ArrayPtr (Expression array, Location l)
8547 Type array_type = TypeManager.GetElementType (array.Type);
8551 type = TypeManager.GetPointerType (array_type);
8552 eclass = ExprClass.Value;
8556 public override void Emit (EmitContext ec)
8558 ILGenerator ig = ec.ig;
8561 IntLiteral.EmitInt (ig, 0);
8562 ig.Emit (OpCodes.Ldelema, TypeManager.GetElementType (array.Type));
8565 public override Expression DoResolve (EmitContext ec)
8568 // We are born fully resolved
8575 // Used by the fixed statement
8577 public class StringPtr : Expression {
8580 public StringPtr (LocalBuilder b, Location l)
8583 eclass = ExprClass.Value;
8584 type = TypeManager.char_ptr_type;
8588 public override Expression DoResolve (EmitContext ec)
8590 // This should never be invoked, we are born in fully
8591 // initialized state.
8596 public override void Emit (EmitContext ec)
8598 ILGenerator ig = ec.ig;
8600 ig.Emit (OpCodes.Ldloc, b);
8601 ig.Emit (OpCodes.Conv_I);
8602 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
8603 ig.Emit (OpCodes.Add);
8608 // Implements the `stackalloc' keyword
8610 public class StackAlloc : Expression {
8615 public StackAlloc (Expression type, Expression count, Location l)
8622 public override Expression DoResolve (EmitContext ec)
8624 count = count.Resolve (ec);
8628 if (count.Type != TypeManager.int32_type){
8629 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8634 Constant c = count as Constant;
8635 if (c != null && c.IsNegative) {
8636 Report.Error (247, loc, "Cannot use a negative size with stackalloc");
8640 if (ec.CurrentBranching.InCatch () ||
8641 ec.CurrentBranching.InFinally (true)) {
8643 "stackalloc can not be used in a catch or finally block");
8647 TypeExpr texpr = t.ResolveAsTypeTerminal (ec, false);
8651 otype = texpr.ResolveType (ec);
8653 if (!TypeManager.VerifyUnManaged (otype, loc))
8656 type = TypeManager.GetPointerType (otype);
8657 eclass = ExprClass.Value;
8662 public override void Emit (EmitContext ec)
8664 int size = GetTypeSize (otype);
8665 ILGenerator ig = ec.ig;
8668 ig.Emit (OpCodes.Sizeof, otype);
8670 IntConstant.EmitInt (ig, size);
8672 ig.Emit (OpCodes.Mul);
8673 ig.Emit (OpCodes.Localloc);