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");
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 readonly 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 probe_type = ec.DeclSpace.ResolveType (ProbeType, false, loc);
1036 if (probe_type == null)
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 type = ec.DeclSpace.ResolveType (target_type, false, Location);
1776 CheckObsoleteAttribute (type);
1778 if (type.IsAbstract && type.IsSealed) {
1779 Report.Error (716, loc, "Cannot convert to static type '{0}'", TypeManager.CSharpName (type));
1783 eclass = ExprClass.Value;
1785 if (expr is Constant){
1786 Expression e = TryReduce (ec, type);
1792 if (type.IsPointer && !ec.InUnsafe) {
1796 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1800 public override void Emit (EmitContext ec)
1803 // This one will never happen
1805 throw new Exception ("Should not happen");
1810 /// Binary operators
1812 public class Binary : Expression {
1813 public enum Operator : byte {
1814 Multiply, Division, Modulus,
1815 Addition, Subtraction,
1816 LeftShift, RightShift,
1817 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1818 Equality, Inequality,
1828 Expression left, right;
1830 // This must be kept in sync with Operator!!!
1831 public static readonly string [] oper_names;
1835 oper_names = new string [(int) Operator.TOP];
1837 oper_names [(int) Operator.Multiply] = "op_Multiply";
1838 oper_names [(int) Operator.Division] = "op_Division";
1839 oper_names [(int) Operator.Modulus] = "op_Modulus";
1840 oper_names [(int) Operator.Addition] = "op_Addition";
1841 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1842 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1843 oper_names [(int) Operator.RightShift] = "op_RightShift";
1844 oper_names [(int) Operator.LessThan] = "op_LessThan";
1845 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1846 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1847 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1848 oper_names [(int) Operator.Equality] = "op_Equality";
1849 oper_names [(int) Operator.Inequality] = "op_Inequality";
1850 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1851 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1852 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1853 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1854 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1857 public Binary (Operator oper, Expression left, Expression right, Location loc)
1865 public Operator Oper {
1874 public Expression Left {
1883 public Expression Right {
1894 /// Returns a stringified representation of the Operator
1896 static string OperName (Operator oper)
1899 case Operator.Multiply:
1901 case Operator.Division:
1903 case Operator.Modulus:
1905 case Operator.Addition:
1907 case Operator.Subtraction:
1909 case Operator.LeftShift:
1911 case Operator.RightShift:
1913 case Operator.LessThan:
1915 case Operator.GreaterThan:
1917 case Operator.LessThanOrEqual:
1919 case Operator.GreaterThanOrEqual:
1921 case Operator.Equality:
1923 case Operator.Inequality:
1925 case Operator.BitwiseAnd:
1927 case Operator.BitwiseOr:
1929 case Operator.ExclusiveOr:
1931 case Operator.LogicalOr:
1933 case Operator.LogicalAnd:
1937 return oper.ToString ();
1940 public override string ToString ()
1942 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1943 right.ToString () + ")";
1946 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1948 if (expr.Type == target_type)
1951 return Convert.ImplicitConversion (ec, expr, target_type, loc);
1954 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1957 34, loc, "Operator `" + OperName (oper)
1958 + "' is ambiguous on operands of type `"
1959 + TypeManager.CSharpName (l) + "' "
1960 + "and `" + TypeManager.CSharpName (r)
1964 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
1966 if ((l == t) || (r == t))
1969 if (!check_user_conversions)
1972 if (Convert.ImplicitUserConversionExists (ec, l, t))
1974 else if (Convert.ImplicitUserConversionExists (ec, r, t))
1981 // Note that handling the case l == Decimal || r == Decimal
1982 // is taken care of by the Step 1 Operator Overload resolution.
1984 // If `check_user_conv' is true, we also check whether a user-defined conversion
1985 // exists. Note that we only need to do this if both arguments are of a user-defined
1986 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
1987 // so we don't explicitly check for performance reasons.
1989 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
1991 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
1993 // If either operand is of type double, the other operand is
1994 // conveted to type double.
1996 if (r != TypeManager.double_type)
1997 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
1998 if (l != TypeManager.double_type)
1999 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
2001 type = TypeManager.double_type;
2002 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
2004 // if either operand is of type float, the other operand is
2005 // converted to type float.
2007 if (r != TypeManager.double_type)
2008 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
2009 if (l != TypeManager.double_type)
2010 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
2011 type = TypeManager.float_type;
2012 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2016 // If either operand is of type ulong, the other operand is
2017 // converted to type ulong. or an error ocurrs if the other
2018 // operand is of type sbyte, short, int or long
2020 if (l == TypeManager.uint64_type){
2021 if (r != TypeManager.uint64_type){
2022 if (right is IntConstant){
2023 IntConstant ic = (IntConstant) right;
2025 e = Convert.TryImplicitIntConversion (l, ic);
2028 } else if (right is LongConstant){
2029 long ll = ((LongConstant) right).Value;
2032 right = new ULongConstant ((ulong) ll);
2034 e = Convert.ImplicitNumericConversion (ec, right, l, loc);
2041 if (left is IntConstant){
2042 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
2045 } else if (left is LongConstant){
2046 long ll = ((LongConstant) left).Value;
2049 left = new ULongConstant ((ulong) ll);
2051 e = Convert.ImplicitNumericConversion (ec, left, r, loc);
2058 if ((other == TypeManager.sbyte_type) ||
2059 (other == TypeManager.short_type) ||
2060 (other == TypeManager.int32_type) ||
2061 (other == TypeManager.int64_type))
2062 Error_OperatorAmbiguous (loc, oper, l, r);
2064 left = ForceConversion (ec, left, TypeManager.uint64_type);
2065 right = ForceConversion (ec, right, TypeManager.uint64_type);
2067 type = TypeManager.uint64_type;
2068 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2070 // If either operand is of type long, the other operand is converted
2073 if (l != TypeManager.int64_type)
2074 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
2075 if (r != TypeManager.int64_type)
2076 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
2078 type = TypeManager.int64_type;
2079 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2081 // If either operand is of type uint, and the other
2082 // operand is of type sbyte, short or int, othe operands are
2083 // converted to type long (unless we have an int constant).
2087 if (l == TypeManager.uint32_type){
2088 if (right is IntConstant){
2089 IntConstant ic = (IntConstant) right;
2093 right = new UIntConstant ((uint) val);
2100 } else if (r == TypeManager.uint32_type){
2101 if (left is IntConstant){
2102 IntConstant ic = (IntConstant) left;
2106 left = new UIntConstant ((uint) val);
2115 if ((other == TypeManager.sbyte_type) ||
2116 (other == TypeManager.short_type) ||
2117 (other == TypeManager.int32_type)){
2118 left = ForceConversion (ec, left, TypeManager.int64_type);
2119 right = ForceConversion (ec, right, TypeManager.int64_type);
2120 type = TypeManager.int64_type;
2123 // if either operand is of type uint, the other
2124 // operand is converd to type uint
2126 left = ForceConversion (ec, left, TypeManager.uint32_type);
2127 right = ForceConversion (ec, right, TypeManager.uint32_type);
2128 type = TypeManager.uint32_type;
2130 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2131 if (l != TypeManager.decimal_type)
2132 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
2134 if (r != TypeManager.decimal_type)
2135 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
2136 type = TypeManager.decimal_type;
2138 left = ForceConversion (ec, left, TypeManager.int32_type);
2139 right = ForceConversion (ec, right, TypeManager.int32_type);
2141 type = TypeManager.int32_type;
2144 return (left != null) && (right != null);
2147 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2149 Report.Error (19, loc,
2150 "Operator " + name + " cannot be applied to operands of type `" +
2151 TypeManager.CSharpName (l) + "' and `" +
2152 TypeManager.CSharpName (r) + "'");
2155 void Error_OperatorCannotBeApplied ()
2157 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2160 static bool is_unsigned (Type t)
2162 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2163 t == TypeManager.short_type || t == TypeManager.byte_type);
2166 static bool is_user_defined (Type t)
2168 if (t.IsSubclassOf (TypeManager.value_type) &&
2169 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2175 Expression Make32or64 (EmitContext ec, Expression e)
2179 if (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2180 t == TypeManager.int64_type || t == TypeManager.uint64_type)
2182 Expression ee = Convert.ImplicitConversion (ec, e, TypeManager.int32_type, loc);
2185 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint32_type, loc);
2188 ee = Convert.ImplicitConversion (ec, e, TypeManager.int64_type, loc);
2191 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint64_type, loc);
2197 Expression CheckShiftArguments (EmitContext ec)
2201 e = ForceConversion (ec, right, TypeManager.int32_type);
2203 Error_OperatorCannotBeApplied ();
2208 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
2209 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
2210 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
2211 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
2215 if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
2216 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (31), loc);
2217 right = right.DoResolve (ec);
2219 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (63), loc);
2220 right = right.DoResolve (ec);
2225 Error_OperatorCannotBeApplied ();
2229 Expression ResolveOperator (EmitContext ec)
2232 Type r = right.Type;
2235 // Special cases: string comapred to null
2237 if (oper == Operator.Equality || oper == Operator.Inequality){
2238 if ((l == TypeManager.string_type && (right is NullLiteral)) ||
2239 (r == TypeManager.string_type && (left is NullLiteral))){
2240 Type = TypeManager.bool_type;
2246 if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
2247 Type = TypeManager.bool_type;
2254 // Do not perform operator overload resolution when both sides are
2257 if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
2259 // Step 1: Perform Operator Overload location
2261 Expression left_expr, right_expr;
2263 string op = oper_names [(int) oper];
2265 MethodGroupExpr union;
2266 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2268 right_expr = MemberLookup (
2269 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2270 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2272 union = (MethodGroupExpr) left_expr;
2274 if (union != null) {
2275 ArrayList args = new ArrayList (2);
2276 args.Add (new Argument (left, Argument.AType.Expression));
2277 args.Add (new Argument (right, Argument.AType.Expression));
2279 MethodBase method = Invocation.OverloadResolve (
2280 ec, union, args, true, Location.Null);
2282 if (method != null) {
2283 MethodInfo mi = (MethodInfo) method;
2285 return new BinaryMethod (mi.ReturnType, method, args);
2291 // Step 0: String concatenation (because overloading will get this wrong)
2293 if (oper == Operator.Addition){
2295 // If any of the arguments is a string, cast to string
2298 // Simple constant folding
2299 if (left is StringConstant && right is StringConstant)
2300 return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value);
2302 if (l == TypeManager.string_type || r == TypeManager.string_type) {
2304 if (r == TypeManager.void_type || l == TypeManager.void_type) {
2305 Error_OperatorCannotBeApplied ();
2309 // try to fold it in on the left
2310 if (left is StringConcat) {
2313 // We have to test here for not-null, since we can be doubly-resolved
2314 // take care of not appending twice
2317 type = TypeManager.string_type;
2318 ((StringConcat) left).Append (ec, right);
2319 return left.Resolve (ec);
2325 // Otherwise, start a new concat expression
2326 return new StringConcat (ec, loc, left, right).Resolve (ec);
2330 // Transform a + ( - b) into a - b
2332 if (right is Unary){
2333 Unary right_unary = (Unary) right;
2335 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2336 oper = Operator.Subtraction;
2337 right = right_unary.Expr;
2343 if (oper == Operator.Equality || oper == Operator.Inequality){
2344 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2345 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2346 Error_OperatorCannotBeApplied ();
2350 type = TypeManager.bool_type;
2355 // operator != (object a, object b)
2356 // operator == (object a, object b)
2358 // For this to be used, both arguments have to be reference-types.
2359 // Read the rationale on the spec (14.9.6)
2361 // Also, if at compile time we know that the classes do not inherit
2362 // one from the other, then we catch the error there.
2364 if (!(l.IsValueType || r.IsValueType)){
2365 type = TypeManager.bool_type;
2370 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2374 // Also, a standard conversion must exist from either one
2376 if (!(Convert.ImplicitStandardConversionExists (left, r) ||
2377 Convert.ImplicitStandardConversionExists (right, l))){
2378 Error_OperatorCannotBeApplied ();
2382 // We are going to have to convert to an object to compare
2384 if (l != TypeManager.object_type)
2385 left = new EmptyCast (left, TypeManager.object_type);
2386 if (r != TypeManager.object_type)
2387 right = new EmptyCast (right, TypeManager.object_type);
2390 // FIXME: CSC here catches errors cs254 and cs252
2396 // One of them is a valuetype, but the other one is not.
2398 if (!l.IsValueType || !r.IsValueType) {
2399 Error_OperatorCannotBeApplied ();
2404 // Only perform numeric promotions on:
2405 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2407 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2408 if (l.IsSubclassOf (TypeManager.delegate_type)){
2409 if ((right.eclass == ExprClass.MethodGroup) &&
2410 (RootContext.Version != LanguageVersion.ISO_1)){
2411 Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2418 if (r.IsSubclassOf (TypeManager.delegate_type)){
2420 ArrayList args = new ArrayList (2);
2422 args = new ArrayList (2);
2423 args.Add (new Argument (left, Argument.AType.Expression));
2424 args.Add (new Argument (right, Argument.AType.Expression));
2426 if (oper == Operator.Addition)
2427 method = TypeManager.delegate_combine_delegate_delegate;
2429 method = TypeManager.delegate_remove_delegate_delegate;
2432 Error_OperatorCannotBeApplied ();
2436 return new BinaryDelegate (l, method, args);
2441 // Pointer arithmetic:
2443 // T* operator + (T* x, int y);
2444 // T* operator + (T* x, uint y);
2445 // T* operator + (T* x, long y);
2446 // T* operator + (T* x, ulong y);
2448 // T* operator + (int y, T* x);
2449 // T* operator + (uint y, T *x);
2450 // T* operator + (long y, T *x);
2451 // T* operator + (ulong y, T *x);
2453 // T* operator - (T* x, int y);
2454 // T* operator - (T* x, uint y);
2455 // T* operator - (T* x, long y);
2456 // T* operator - (T* x, ulong y);
2458 // long operator - (T* x, T *y)
2461 if (r.IsPointer && oper == Operator.Subtraction){
2463 return new PointerArithmetic (
2464 false, left, right, TypeManager.int64_type,
2467 Expression t = Make32or64 (ec, right);
2469 return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc).Resolve (ec);
2471 } else if (r.IsPointer && oper == Operator.Addition){
2472 Expression t = Make32or64 (ec, left);
2474 return new PointerArithmetic (true, right, t, r, loc).Resolve (ec);
2479 // Enumeration operators
2481 bool lie = TypeManager.IsEnumType (l);
2482 bool rie = TypeManager.IsEnumType (r);
2486 // U operator - (E e, E f)
2488 if (oper == Operator.Subtraction){
2490 type = TypeManager.EnumToUnderlying (l);
2493 Error_OperatorCannotBeApplied ();
2499 // operator + (E e, U x)
2500 // operator - (E e, U x)
2502 if (oper == Operator.Addition || oper == Operator.Subtraction){
2503 Type enum_type = lie ? l : r;
2504 Type other_type = lie ? r : l;
2505 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2507 if (underlying_type != other_type){
2508 temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
2518 Error_OperatorCannotBeApplied ();
2527 temp = Convert.ImplicitConversion (ec, right, l, loc);
2531 Error_OperatorCannotBeApplied ();
2535 temp = Convert.ImplicitConversion (ec, left, r, loc);
2540 Error_OperatorCannotBeApplied ();
2545 if (oper == Operator.Equality || oper == Operator.Inequality ||
2546 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2547 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2548 if (left.Type != right.Type){
2549 Error_OperatorCannotBeApplied ();
2552 type = TypeManager.bool_type;
2556 if (oper == Operator.BitwiseAnd ||
2557 oper == Operator.BitwiseOr ||
2558 oper == Operator.ExclusiveOr){
2562 Error_OperatorCannotBeApplied ();
2566 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2567 return CheckShiftArguments (ec);
2569 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2570 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2571 type = TypeManager.bool_type;
2576 Error_OperatorCannotBeApplied ();
2580 Expression e = new ConditionalLogicalOperator (
2581 oper == Operator.LogicalAnd, left, right, l, loc);
2582 return e.Resolve (ec);
2586 // operator & (bool x, bool y)
2587 // operator | (bool x, bool y)
2588 // operator ^ (bool x, bool y)
2590 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2591 if (oper == Operator.BitwiseAnd ||
2592 oper == Operator.BitwiseOr ||
2593 oper == Operator.ExclusiveOr){
2600 // Pointer comparison
2602 if (l.IsPointer && r.IsPointer){
2603 if (oper == Operator.Equality || oper == Operator.Inequality ||
2604 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2605 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2606 type = TypeManager.bool_type;
2612 // This will leave left or right set to null if there is an error
2614 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2615 DoNumericPromotions (ec, l, r, check_user_conv);
2616 if (left == null || right == null){
2617 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2622 // reload our cached types if required
2627 if (oper == Operator.BitwiseAnd ||
2628 oper == Operator.BitwiseOr ||
2629 oper == Operator.ExclusiveOr){
2631 if (((l == TypeManager.int32_type) ||
2632 (l == TypeManager.uint32_type) ||
2633 (l == TypeManager.short_type) ||
2634 (l == TypeManager.ushort_type) ||
2635 (l == TypeManager.int64_type) ||
2636 (l == TypeManager.uint64_type))){
2639 Error_OperatorCannotBeApplied ();
2643 Error_OperatorCannotBeApplied ();
2648 if (oper == Operator.Equality ||
2649 oper == Operator.Inequality ||
2650 oper == Operator.LessThanOrEqual ||
2651 oper == Operator.LessThan ||
2652 oper == Operator.GreaterThanOrEqual ||
2653 oper == Operator.GreaterThan){
2654 type = TypeManager.bool_type;
2660 public override Expression DoResolve (EmitContext ec)
2662 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2663 left = ((ParenthesizedExpression) left).Expr;
2664 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2668 if (left.eclass == ExprClass.Type) {
2669 Error (75, "Casting a negative value needs to have the value in parentheses.");
2673 left = left.Resolve (ec);
2674 right = right.Resolve (ec);
2676 if (left == null || right == null)
2679 eclass = ExprClass.Value;
2681 Constant rc = right as Constant;
2682 Constant lc = left as Constant;
2684 if (rc != null & lc != null){
2685 Expression e = ConstantFold.BinaryFold (
2686 ec, oper, lc, rc, loc);
2691 return ResolveOperator (ec);
2695 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2696 /// context of a conditional bool expression. This function will return
2697 /// false if it is was possible to use EmitBranchable, or true if it was.
2699 /// The expression's code is generated, and we will generate a branch to `target'
2700 /// if the resulting expression value is equal to isTrue
2702 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2704 ILGenerator ig = ec.ig;
2707 // This is more complicated than it looks, but its just to avoid
2708 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2709 // but on top of that we want for == and != to use a special path
2710 // if we are comparing against null
2712 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
2713 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2716 // put the constant on the rhs, for simplicity
2718 if (left is Constant) {
2719 Expression swap = right;
2724 if (((Constant) right).IsZeroInteger) {
2727 ig.Emit (OpCodes.Brtrue, target);
2729 ig.Emit (OpCodes.Brfalse, target);
2732 } else if (right is BoolConstant) {
2734 if (my_on_true != ((BoolConstant) right).Value)
2735 ig.Emit (OpCodes.Brtrue, target);
2737 ig.Emit (OpCodes.Brfalse, target);
2742 } else if (oper == Operator.LogicalAnd) {
2745 Label tests_end = ig.DefineLabel ();
2747 left.EmitBranchable (ec, tests_end, false);
2748 right.EmitBranchable (ec, target, true);
2749 ig.MarkLabel (tests_end);
2751 left.EmitBranchable (ec, target, false);
2752 right.EmitBranchable (ec, target, false);
2757 } else if (oper == Operator.LogicalOr){
2759 left.EmitBranchable (ec, target, true);
2760 right.EmitBranchable (ec, target, true);
2763 Label tests_end = ig.DefineLabel ();
2764 left.EmitBranchable (ec, tests_end, true);
2765 right.EmitBranchable (ec, target, false);
2766 ig.MarkLabel (tests_end);
2771 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2772 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2773 oper == Operator.Equality || oper == Operator.Inequality)) {
2774 base.EmitBranchable (ec, target, onTrue);
2782 bool isUnsigned = is_unsigned (t) || t == TypeManager.double_type || t == TypeManager.float_type;
2785 case Operator.Equality:
2787 ig.Emit (OpCodes.Beq, target);
2789 ig.Emit (OpCodes.Bne_Un, target);
2792 case Operator.Inequality:
2794 ig.Emit (OpCodes.Bne_Un, target);
2796 ig.Emit (OpCodes.Beq, target);
2799 case Operator.LessThan:
2802 ig.Emit (OpCodes.Blt_Un, target);
2804 ig.Emit (OpCodes.Blt, target);
2807 ig.Emit (OpCodes.Bge_Un, target);
2809 ig.Emit (OpCodes.Bge, target);
2812 case Operator.GreaterThan:
2815 ig.Emit (OpCodes.Bgt_Un, target);
2817 ig.Emit (OpCodes.Bgt, target);
2820 ig.Emit (OpCodes.Ble_Un, target);
2822 ig.Emit (OpCodes.Ble, target);
2825 case Operator.LessThanOrEqual:
2828 ig.Emit (OpCodes.Ble_Un, target);
2830 ig.Emit (OpCodes.Ble, target);
2833 ig.Emit (OpCodes.Bgt_Un, target);
2835 ig.Emit (OpCodes.Bgt, target);
2839 case Operator.GreaterThanOrEqual:
2842 ig.Emit (OpCodes.Bge_Un, target);
2844 ig.Emit (OpCodes.Bge, target);
2847 ig.Emit (OpCodes.Blt_Un, target);
2849 ig.Emit (OpCodes.Blt, target);
2852 Console.WriteLine (oper);
2853 throw new Exception ("what is THAT");
2857 public override void Emit (EmitContext ec)
2859 ILGenerator ig = ec.ig;
2864 // Handle short-circuit operators differently
2867 if (oper == Operator.LogicalAnd) {
2868 Label load_zero = ig.DefineLabel ();
2869 Label end = ig.DefineLabel ();
2871 left.EmitBranchable (ec, load_zero, false);
2873 ig.Emit (OpCodes.Br, end);
2875 ig.MarkLabel (load_zero);
2876 ig.Emit (OpCodes.Ldc_I4_0);
2879 } else if (oper == Operator.LogicalOr) {
2880 Label load_one = ig.DefineLabel ();
2881 Label end = ig.DefineLabel ();
2883 left.EmitBranchable (ec, load_one, true);
2885 ig.Emit (OpCodes.Br, end);
2887 ig.MarkLabel (load_one);
2888 ig.Emit (OpCodes.Ldc_I4_1);
2896 bool isUnsigned = is_unsigned (left.Type);
2899 case Operator.Multiply:
2901 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2902 opcode = OpCodes.Mul_Ovf;
2903 else if (isUnsigned)
2904 opcode = OpCodes.Mul_Ovf_Un;
2906 opcode = OpCodes.Mul;
2908 opcode = OpCodes.Mul;
2912 case Operator.Division:
2914 opcode = OpCodes.Div_Un;
2916 opcode = OpCodes.Div;
2919 case Operator.Modulus:
2921 opcode = OpCodes.Rem_Un;
2923 opcode = OpCodes.Rem;
2926 case Operator.Addition:
2928 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2929 opcode = OpCodes.Add_Ovf;
2930 else if (isUnsigned)
2931 opcode = OpCodes.Add_Ovf_Un;
2933 opcode = OpCodes.Add;
2935 opcode = OpCodes.Add;
2938 case Operator.Subtraction:
2940 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2941 opcode = OpCodes.Sub_Ovf;
2942 else if (isUnsigned)
2943 opcode = OpCodes.Sub_Ovf_Un;
2945 opcode = OpCodes.Sub;
2947 opcode = OpCodes.Sub;
2950 case Operator.RightShift:
2952 opcode = OpCodes.Shr_Un;
2954 opcode = OpCodes.Shr;
2957 case Operator.LeftShift:
2958 opcode = OpCodes.Shl;
2961 case Operator.Equality:
2962 opcode = OpCodes.Ceq;
2965 case Operator.Inequality:
2966 ig.Emit (OpCodes.Ceq);
2967 ig.Emit (OpCodes.Ldc_I4_0);
2969 opcode = OpCodes.Ceq;
2972 case Operator.LessThan:
2974 opcode = OpCodes.Clt_Un;
2976 opcode = OpCodes.Clt;
2979 case Operator.GreaterThan:
2981 opcode = OpCodes.Cgt_Un;
2983 opcode = OpCodes.Cgt;
2986 case Operator.LessThanOrEqual:
2987 Type lt = left.Type;
2989 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
2990 ig.Emit (OpCodes.Cgt_Un);
2992 ig.Emit (OpCodes.Cgt);
2993 ig.Emit (OpCodes.Ldc_I4_0);
2995 opcode = OpCodes.Ceq;
2998 case Operator.GreaterThanOrEqual:
2999 Type le = left.Type;
3001 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3002 ig.Emit (OpCodes.Clt_Un);
3004 ig.Emit (OpCodes.Clt);
3006 ig.Emit (OpCodes.Ldc_I4_0);
3008 opcode = OpCodes.Ceq;
3011 case Operator.BitwiseOr:
3012 opcode = OpCodes.Or;
3015 case Operator.BitwiseAnd:
3016 opcode = OpCodes.And;
3019 case Operator.ExclusiveOr:
3020 opcode = OpCodes.Xor;
3024 throw new Exception ("This should not happen: Operator = "
3025 + oper.ToString ());
3033 // Object created by Binary when the binary operator uses an method instead of being
3034 // a binary operation that maps to a CIL binary operation.
3036 public class BinaryMethod : Expression {
3037 public MethodBase method;
3038 public ArrayList Arguments;
3040 public BinaryMethod (Type t, MethodBase m, ArrayList args)
3045 eclass = ExprClass.Value;
3048 public override Expression DoResolve (EmitContext ec)
3053 public override void Emit (EmitContext ec)
3055 ILGenerator ig = ec.ig;
3057 if (Arguments != null)
3058 Invocation.EmitArguments (ec, method, Arguments, false, null);
3060 if (method is MethodInfo)
3061 ig.Emit (OpCodes.Call, (MethodInfo) method);
3063 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3068 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3069 // b, c, d... may be strings or objects.
3071 public class StringConcat : Expression {
3073 bool invalid = false;
3076 public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
3079 type = TypeManager.string_type;
3080 eclass = ExprClass.Value;
3082 operands = new ArrayList (2);
3087 public override Expression DoResolve (EmitContext ec)
3095 public void Append (EmitContext ec, Expression operand)
3100 if (operand is StringConstant && operands.Count != 0) {
3101 StringConstant last_operand = operands [operands.Count - 1] as StringConstant;
3102 if (last_operand != null) {
3103 operands [operands.Count - 1] = new StringConstant (last_operand.Value + ((StringConstant) operand).Value);
3109 // Conversion to object
3111 if (operand.Type != TypeManager.string_type) {
3112 Expression no = Convert.ImplicitConversion (ec, operand, TypeManager.object_type, loc);
3115 Binary.Error_OperatorCannotBeApplied (loc, "+", TypeManager.string_type, operand.Type);
3121 operands.Add (operand);
3124 public override void Emit (EmitContext ec)
3126 MethodInfo concat_method = null;
3129 // Are we also concating objects?
3131 bool is_strings_only = true;
3134 // Do conversion to arguments; check for strings only
3136 for (int i = 0; i < operands.Count; i ++) {
3137 Expression e = (Expression) operands [i];
3138 is_strings_only &= e.Type == TypeManager.string_type;
3141 for (int i = 0; i < operands.Count; i ++) {
3142 Expression e = (Expression) operands [i];
3144 if (! is_strings_only && e.Type == TypeManager.string_type) {
3145 // need to make sure this is an object, because the EmitParams
3146 // method might look at the type of this expression, see it is a
3147 // string and emit a string [] when we want an object [];
3149 e = Convert.ImplicitConversion (ec, e, TypeManager.object_type, loc);
3151 operands [i] = new Argument (e, Argument.AType.Expression);
3155 // Find the right method
3157 switch (operands.Count) {
3160 // This should not be possible, because simple constant folding
3161 // is taken care of in the Binary code.
3163 throw new Exception ("how did you get here?");
3166 concat_method = is_strings_only ?
3167 TypeManager.string_concat_string_string :
3168 TypeManager.string_concat_object_object ;
3171 concat_method = is_strings_only ?
3172 TypeManager.string_concat_string_string_string :
3173 TypeManager.string_concat_object_object_object ;
3177 // There is not a 4 param overlaod for object (the one that there is
3178 // is actually a varargs methods, and is only in corlib because it was
3179 // introduced there before.).
3181 if (!is_strings_only)
3184 concat_method = TypeManager.string_concat_string_string_string_string;
3187 concat_method = is_strings_only ?
3188 TypeManager.string_concat_string_dot_dot_dot :
3189 TypeManager.string_concat_object_dot_dot_dot ;
3193 Invocation.EmitArguments (ec, concat_method, operands, false, null);
3194 ec.ig.Emit (OpCodes.Call, concat_method);
3199 // Object created with +/= on delegates
3201 public class BinaryDelegate : Expression {
3205 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3210 eclass = ExprClass.Value;
3213 public override Expression DoResolve (EmitContext ec)
3218 public override void Emit (EmitContext ec)
3220 ILGenerator ig = ec.ig;
3222 Invocation.EmitArguments (ec, method, args, false, null);
3224 ig.Emit (OpCodes.Call, (MethodInfo) method);
3225 ig.Emit (OpCodes.Castclass, type);
3228 public Expression Right {
3230 Argument arg = (Argument) args [1];
3235 public bool IsAddition {
3237 return method == TypeManager.delegate_combine_delegate_delegate;
3243 // User-defined conditional logical operator
3244 public class ConditionalLogicalOperator : Expression {
3245 Expression left, right;
3248 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3251 eclass = ExprClass.Value;
3255 this.is_and = is_and;
3258 protected void Error19 ()
3260 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3263 protected void Error218 ()
3265 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3266 "declarations of operator true and operator false");
3269 Expression op_true, op_false, op;
3270 LocalTemporary left_temp;
3272 public override Expression DoResolve (EmitContext ec)
3275 Expression operator_group;
3277 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3278 if (operator_group == null) {
3283 left_temp = new LocalTemporary (ec, type);
3285 ArrayList arguments = new ArrayList ();
3286 arguments.Add (new Argument (left_temp, Argument.AType.Expression));
3287 arguments.Add (new Argument (right, Argument.AType.Expression));
3288 method = Invocation.OverloadResolve (
3289 ec, (MethodGroupExpr) operator_group, arguments, false, loc)
3291 if ((method == null) || (method.ReturnType != type)) {
3296 op = new StaticCallExpr (method, arguments, loc);
3298 op_true = GetOperatorTrue (ec, left_temp, loc);
3299 op_false = GetOperatorFalse (ec, left_temp, loc);
3300 if ((op_true == null) || (op_false == null)) {
3308 public override void Emit (EmitContext ec)
3310 ILGenerator ig = ec.ig;
3311 Label false_target = ig.DefineLabel ();
3312 Label end_target = ig.DefineLabel ();
3314 ig.Emit (OpCodes.Nop);
3317 left_temp.Store (ec);
3319 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
3320 left_temp.Emit (ec);
3321 ig.Emit (OpCodes.Br, end_target);
3322 ig.MarkLabel (false_target);
3324 ig.MarkLabel (end_target);
3326 ig.Emit (OpCodes.Nop);
3330 public class PointerArithmetic : Expression {
3331 Expression left, right;
3335 // We assume that `l' is always a pointer
3337 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3343 is_add = is_addition;
3346 public override Expression DoResolve (EmitContext ec)
3348 eclass = ExprClass.Variable;
3350 if (left.Type == TypeManager.void_ptr_type) {
3351 Error (242, "The operation in question is undefined on void pointers");
3358 public override void Emit (EmitContext ec)
3360 Type op_type = left.Type;
3361 ILGenerator ig = ec.ig;
3362 Type element = TypeManager.GetElementType (op_type);
3363 int size = GetTypeSize (element);
3364 Type rtype = right.Type;
3366 if (rtype.IsPointer){
3368 // handle (pointer - pointer)
3372 ig.Emit (OpCodes.Sub);
3376 ig.Emit (OpCodes.Sizeof, element);
3378 IntLiteral.EmitInt (ig, size);
3379 ig.Emit (OpCodes.Div);
3381 ig.Emit (OpCodes.Conv_I8);
3384 // handle + and - on (pointer op int)
3387 ig.Emit (OpCodes.Conv_I);
3391 ig.Emit (OpCodes.Sizeof, element);
3393 IntLiteral.EmitInt (ig, size);
3394 if (rtype == TypeManager.int64_type)
3395 ig.Emit (OpCodes.Conv_I8);
3396 else if (rtype == TypeManager.uint64_type)
3397 ig.Emit (OpCodes.Conv_U8);
3398 ig.Emit (OpCodes.Mul);
3401 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
3402 ig.Emit (OpCodes.Conv_I);
3405 ig.Emit (OpCodes.Add);
3407 ig.Emit (OpCodes.Sub);
3413 /// Implements the ternary conditional operator (?:)
3415 public class Conditional : Expression {
3416 Expression expr, trueExpr, falseExpr;
3418 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3421 this.trueExpr = trueExpr;
3422 this.falseExpr = falseExpr;
3426 public Expression Expr {
3432 public Expression TrueExpr {
3438 public Expression FalseExpr {
3444 public override Expression DoResolve (EmitContext ec)
3446 expr = expr.Resolve (ec);
3451 if (expr.Type != TypeManager.bool_type){
3452 expr = Expression.ResolveBoolean (
3459 trueExpr = trueExpr.Resolve (ec);
3460 falseExpr = falseExpr.Resolve (ec);
3462 if (trueExpr == null || falseExpr == null)
3465 eclass = ExprClass.Value;
3466 if (trueExpr.Type == falseExpr.Type)
3467 type = trueExpr.Type;
3470 Type true_type = trueExpr.Type;
3471 Type false_type = falseExpr.Type;
3474 // First, if an implicit conversion exists from trueExpr
3475 // to falseExpr, then the result type is of type falseExpr.Type
3477 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3480 // Check if both can convert implicitl to each other's type
3482 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3484 "Can not compute type of conditional expression " +
3485 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3486 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3487 "' convert implicitly to each other");
3492 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3496 Error (173, "The type of the conditional expression can " +
3497 "not be computed because there is no implicit conversion" +
3498 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3499 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3504 if (expr is BoolConstant){
3505 BoolConstant bc = (BoolConstant) expr;
3516 public override void Emit (EmitContext ec)
3518 ILGenerator ig = ec.ig;
3519 Label false_target = ig.DefineLabel ();
3520 Label end_target = ig.DefineLabel ();
3522 expr.EmitBranchable (ec, false_target, false);
3524 ig.Emit (OpCodes.Br, end_target);
3525 ig.MarkLabel (false_target);
3526 falseExpr.Emit (ec);
3527 ig.MarkLabel (end_target);
3535 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3536 public readonly string Name;
3537 public readonly Block Block;
3538 LocalInfo local_info;
3541 public LocalVariableReference (Block block, string name, Location l)
3546 eclass = ExprClass.Variable;
3549 // Setting `is_readonly' to false will allow you to create a writable
3550 // reference to a read-only variable. This is used by foreach and using.
3551 public LocalVariableReference (Block block, string name, Location l,
3552 LocalInfo local_info, bool is_readonly)
3553 : this (block, name, l)
3555 this.local_info = local_info;
3556 this.is_readonly = is_readonly;
3559 public VariableInfo VariableInfo {
3560 get { return local_info.VariableInfo; }
3563 public bool IsReadOnly {
3569 protected void DoResolveBase (EmitContext ec)
3571 if (local_info == null) {
3572 local_info = Block.GetLocalInfo (Name);
3573 is_readonly = local_info.ReadOnly;
3576 type = local_info.VariableType;
3578 if (ec.InAnonymousMethod)
3579 Block.LiftVariable (local_info);
3583 protected Expression DoResolve (EmitContext ec, bool is_lvalue)
3585 Expression e = Block.GetConstantExpression (Name);
3587 local_info.Used = true;
3588 eclass = ExprClass.Value;
3589 return e.Resolve (ec);
3592 VariableInfo variable_info = local_info.VariableInfo;
3593 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3597 local_info.Used = true;
3599 if (local_info.LocalBuilder == null)
3600 return ec.RemapLocal (local_info);
3605 public override Expression DoResolve (EmitContext ec)
3609 return DoResolve (ec, false);
3612 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3616 VariableInfo variable_info = local_info.VariableInfo;
3617 if (variable_info != null)
3618 variable_info.SetAssigned (ec);
3620 Expression e = DoResolve (ec, true);
3626 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3630 CheckObsoleteAttribute (e.Type);
3632 if (local_info.LocalBuilder == null)
3633 return ec.RemapLocalLValue (local_info, right_side);
3638 public bool VerifyFixed (bool is_expression)
3640 return !is_expression || local_info.IsFixed;
3643 public override void Emit (EmitContext ec)
3645 ILGenerator ig = ec.ig;
3647 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3650 public void Emit (EmitContext ec, bool leave_copy)
3654 ec.ig.Emit (OpCodes.Dup);
3657 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3661 ec.ig.Emit (OpCodes.Dup);
3662 ec.ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3665 public void AddressOf (EmitContext ec, AddressOp mode)
3667 ILGenerator ig = ec.ig;
3669 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3672 public override string ToString ()
3674 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3679 /// This represents a reference to a parameter in the intermediate
3682 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3688 public Parameter.Modifier mod;
3689 public bool is_ref, is_out, prepared;
3690 LocalTemporary temp;
3692 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3699 eclass = ExprClass.Variable;
3702 public VariableInfo VariableInfo {
3706 public bool VerifyFixed (bool is_expression)
3708 return !is_expression || TypeManager.IsValueType (type);
3711 public bool IsAssigned (EmitContext ec, Location loc)
3713 if (!ec.DoFlowAnalysis || !is_out ||
3714 ec.CurrentBranching.IsAssigned (vi))
3717 Report.Error (165, loc,
3718 "Use of unassigned parameter `" + name + "'");
3722 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3724 if (!ec.DoFlowAnalysis || !is_out ||
3725 ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3728 Report.Error (170, loc,
3729 "Use of possibly unassigned field `" + field_name + "'");
3733 public void SetAssigned (EmitContext ec)
3735 if (is_out && ec.DoFlowAnalysis)
3736 ec.CurrentBranching.SetAssigned (vi);
3739 public void SetFieldAssigned (EmitContext ec, string field_name)
3741 if (is_out && ec.DoFlowAnalysis)
3742 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3745 protected void DoResolveBase (EmitContext ec)
3747 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
3748 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3749 is_out = (mod & Parameter.Modifier.OUT) != 0;
3750 eclass = ExprClass.Variable;
3753 vi = block.ParameterMap [idx];
3757 // Notice that for ref/out parameters, the type exposed is not the
3758 // same type exposed externally.
3761 // externally we expose "int&"
3762 // here we expose "int".
3764 // We record this in "is_ref". This means that the type system can treat
3765 // the type as it is expected, but when we generate the code, we generate
3766 // the alternate kind of code.
3768 public override Expression DoResolve (EmitContext ec)
3772 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3775 if (ec.RemapToProxy)
3776 return ec.RemapParameter (idx);
3781 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3787 if (ec.RemapToProxy)
3788 return ec.RemapParameterLValue (idx, right_side);
3793 static public void EmitLdArg (ILGenerator ig, int x)
3797 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3798 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3799 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3800 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3801 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3804 ig.Emit (OpCodes.Ldarg, x);
3808 // This method is used by parameters that are references, that are
3809 // being passed as references: we only want to pass the pointer (that
3810 // is already stored in the parameter, not the address of the pointer,
3811 // and not the value of the variable).
3813 public void EmitLoad (EmitContext ec)
3815 ILGenerator ig = ec.ig;
3821 EmitLdArg (ig, arg_idx);
3824 public override void Emit (EmitContext ec)
3829 public void Emit (EmitContext ec, bool leave_copy)
3831 ILGenerator ig = ec.ig;
3838 EmitLdArg (ig, arg_idx);
3842 ec.ig.Emit (OpCodes.Dup);
3845 // If we are a reference, we loaded on the stack a pointer
3846 // Now lets load the real value
3848 LoadFromPtr (ig, type);
3852 ec.ig.Emit (OpCodes.Dup);
3855 temp = new LocalTemporary (ec, type);
3861 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3863 ILGenerator ig = ec.ig;
3866 prepared = prepare_for_load;
3871 if (is_ref && !prepared)
3872 EmitLdArg (ig, arg_idx);
3877 ec.ig.Emit (OpCodes.Dup);
3881 temp = new LocalTemporary (ec, type);
3885 StoreFromPtr (ig, type);
3891 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
3893 ig.Emit (OpCodes.Starg, arg_idx);
3897 public void AddressOf (EmitContext ec, AddressOp mode)
3906 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
3908 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
3911 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
3913 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
3920 /// Used for arguments to New(), Invocation()
3922 public class Argument {
3923 public enum AType : byte {
3930 public readonly AType ArgType;
3931 public Expression Expr;
3933 public Argument (Expression expr, AType type)
3936 this.ArgType = type;
3939 public Argument (Expression expr)
3942 this.ArgType = AType.Expression;
3947 if (ArgType == AType.Ref || ArgType == AType.Out)
3948 return TypeManager.GetReferenceType (Expr.Type);
3954 public Parameter.Modifier GetParameterModifier ()
3958 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
3961 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
3964 return Parameter.Modifier.NONE;
3968 public static string FullDesc (Argument a)
3970 if (a.ArgType == AType.ArgList)
3973 return (a.ArgType == AType.Ref ? "ref " :
3974 (a.ArgType == AType.Out ? "out " : "")) +
3975 TypeManager.CSharpName (a.Expr.Type);
3978 public bool ResolveMethodGroup (EmitContext ec, Location loc)
3980 // FIXME: csc doesn't report any error if you try to use `ref' or
3981 // `out' in a delegate creation expression.
3982 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
3989 public bool Resolve (EmitContext ec, Location loc)
3991 if (ArgType == AType.Ref) {
3992 Expr = Expr.Resolve (ec);
3996 if (!ec.IsConstructor) {
3997 FieldExpr fe = Expr as FieldExpr;
3998 if (fe != null && fe.FieldInfo.IsInitOnly) {
3999 if (fe.FieldInfo.IsStatic)
4000 Report.Error (199, loc, "A static readonly field cannot be passed ref or out (except in a static constructor)");
4002 Report.Error (192, loc, "A readonly field cannot be passed ref or out (except in a constructor)");
4006 Expr = Expr.ResolveLValue (ec, Expr);
4007 } else if (ArgType == AType.Out)
4008 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
4010 Expr = Expr.Resolve (ec);
4015 if (ArgType == AType.Expression)
4019 // Catch errors where fields of a MarshalByRefObject are passed as ref or out
4020 // This is only allowed for `this'
4022 FieldExpr fe = Expr as FieldExpr;
4023 if (fe != null && !fe.IsStatic){
4024 Expression instance = fe.InstanceExpression;
4026 if (instance.GetType () != typeof (This)){
4027 if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
4028 Report.Error (197, loc,
4029 "Can not pass a type that derives from MarshalByRefObject with out or ref");
4036 if (Expr.eclass != ExprClass.Variable){
4038 // We just probe to match the CSC output
4040 if (Expr.eclass == ExprClass.PropertyAccess ||
4041 Expr.eclass == ExprClass.IndexerAccess){
4044 "A property or indexer can not be passed as an out or ref " +
4049 "An lvalue is required as an argument to out or ref");
4057 public void Emit (EmitContext ec)
4060 // Ref and Out parameters need to have their addresses taken.
4062 // ParameterReferences might already be references, so we want
4063 // to pass just the value
4065 if (ArgType == AType.Ref || ArgType == AType.Out){
4066 AddressOp mode = AddressOp.Store;
4068 if (ArgType == AType.Ref)
4069 mode |= AddressOp.Load;
4071 if (Expr is ParameterReference){
4072 ParameterReference pr = (ParameterReference) Expr;
4078 pr.AddressOf (ec, mode);
4081 ((IMemoryLocation)Expr).AddressOf (ec, mode);
4089 /// Invocation of methods or delegates.
4091 public class Invocation : ExpressionStatement {
4092 public readonly ArrayList Arguments;
4095 MethodBase method = null;
4098 static Hashtable method_parameter_cache;
4100 static Invocation ()
4102 method_parameter_cache = new PtrHashtable ();
4106 // arguments is an ArrayList, but we do not want to typecast,
4107 // as it might be null.
4109 // FIXME: only allow expr to be a method invocation or a
4110 // delegate invocation (7.5.5)
4112 public Invocation (Expression expr, ArrayList arguments, Location l)
4115 Arguments = arguments;
4119 public Expression Expr {
4126 /// Returns the Parameters (a ParameterData interface) for the
4129 public static ParameterData GetParameterData (MethodBase mb)
4131 object pd = method_parameter_cache [mb];
4135 return (ParameterData) pd;
4138 ip = TypeManager.LookupParametersByBuilder (mb);
4140 method_parameter_cache [mb] = ip;
4142 return (ParameterData) ip;
4144 ReflectionParameters rp = new ReflectionParameters (mb);
4145 method_parameter_cache [mb] = rp;
4147 return (ParameterData) rp;
4152 /// Determines "better conversion" as specified in 7.4.2.3
4154 /// Returns : 1 if a->p is better
4155 /// 0 if a->q or neither is better
4157 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
4159 Type argument_type = a.Type;
4160 Expression argument_expr = a.Expr;
4162 if (argument_type == null)
4163 throw new Exception ("Expression of type " + a.Expr +
4164 " does not resolve its type");
4166 if (p == null || q == null)
4167 throw new InternalErrorException ("BetterConversion Got a null conversion");
4170 // This is a special case since csc behaves this way.
4172 if (argument_expr is NullLiteral &&
4173 p == TypeManager.string_type &&
4174 q == TypeManager.object_type)
4176 else if (argument_expr is NullLiteral &&
4177 p == TypeManager.object_type &&
4178 q == TypeManager.string_type)
4182 // csc behaves this way so we emulate it. Basically, if the argument
4183 // is null and one of the types to compare is 'object' and the other
4184 // is a reference type, we prefer the other.
4186 // I can't find this anywhere in the spec but we can interpret this
4187 // to mean that null can be of any type you wish in such a context
4189 if (argument_expr is NullLiteral &&
4191 q == TypeManager.object_type)
4193 else if (argument_expr is NullLiteral &&
4195 p == TypeManager.object_type)
4202 if (argument_type == p)
4205 if (argument_type == q)
4208 Expression p_tmp = new EmptyExpression (p);
4209 Expression q_tmp = new EmptyExpression (q);
4211 if (Convert.ImplicitConversionExists (ec, p_tmp, q) == true &&
4212 Convert.ImplicitConversionExists (ec, q_tmp, p) == false)
4215 if (p == TypeManager.sbyte_type)
4216 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4217 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4220 if (p == TypeManager.short_type)
4221 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4222 q == TypeManager.uint64_type)
4225 if (p == TypeManager.int32_type)
4226 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4229 if (p == TypeManager.int64_type)
4230 if (q == TypeManager.uint64_type)
4237 /// Determines "Better function" between candidate
4238 /// and the current best match
4241 /// Returns an integer indicating :
4242 /// 0 if candidate ain't better
4243 /// 1 if candidate is better than the current best match
4245 static int BetterFunction (EmitContext ec, ArrayList args, int argument_count,
4246 MethodBase candidate, bool candidate_params,
4247 MethodBase best, bool best_params, Location loc)
4249 ParameterData candidate_pd = GetParameterData (candidate);
4250 ParameterData best_pd = GetParameterData (best);
4252 int cand_count = candidate_pd.Count;
4255 // If there is no best method, than this one
4256 // is better, however, if we already found a
4257 // best method, we cant tell. This happens
4268 // interface IFooBar : IFoo, IBar {}
4270 // We cant tell if IFoo.DoIt is better than IBar.DoIt
4272 // However, we have to consider that
4273 // Trim (); is better than Trim (params char[] chars);
4275 if (cand_count == 0 && argument_count == 0)
4276 return best_params ? 1 : 0;
4278 if ((candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS) &&
4279 (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.ARGLIST))
4280 if (cand_count != argument_count)
4284 int rating1 = 0, rating2 = 0;
4286 for (int j = 0; j < argument_count; ++j) {
4289 Argument a = (Argument) args [j];
4291 Type ct = candidate_pd.ParameterType (j);
4292 Type bt = best_pd.ParameterType (j);
4294 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4295 if (candidate_params)
4296 ct = TypeManager.GetElementType (ct);
4298 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4300 bt = TypeManager.GetElementType (bt);
4302 x = BetterConversion (ec, a, ct, bt, loc);
4303 y = BetterConversion (ec, a, bt, ct, loc);
4313 // If a method (in the normal form) with the
4314 // same signature as the expanded form of the
4315 // current best params method already exists,
4316 // the expanded form is not applicable so we
4317 // force it to select the candidate
4319 if (!candidate_params && best_params && cand_count == argument_count)
4322 if (rating1 > rating2)
4328 public static string FullMethodDesc (MethodBase mb)
4330 string ret_type = "";
4335 if (mb is MethodInfo)
4336 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
4338 StringBuilder sb = new StringBuilder (ret_type);
4340 sb.Append (mb.ReflectedType.ToString ());
4342 sb.Append (mb.Name);
4344 ParameterData pd = GetParameterData (mb);
4346 int count = pd.Count;
4349 for (int i = count; i > 0; ) {
4352 sb.Append (pd.ParameterDesc (count - i - 1));
4358 return sb.ToString ();
4361 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4363 MemberInfo [] miset;
4364 MethodGroupExpr union;
4369 return (MethodGroupExpr) mg2;
4372 return (MethodGroupExpr) mg1;
4375 MethodGroupExpr left_set = null, right_set = null;
4376 int length1 = 0, length2 = 0;
4378 left_set = (MethodGroupExpr) mg1;
4379 length1 = left_set.Methods.Length;
4381 right_set = (MethodGroupExpr) mg2;
4382 length2 = right_set.Methods.Length;
4384 ArrayList common = new ArrayList ();
4386 foreach (MethodBase r in right_set.Methods){
4387 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
4391 miset = new MemberInfo [length1 + length2 - common.Count];
4392 left_set.Methods.CopyTo (miset, 0);
4396 foreach (MethodBase r in right_set.Methods) {
4397 if (!common.Contains (r))
4401 union = new MethodGroupExpr (miset, loc);
4406 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4407 ArrayList arguments, int arg_count,
4408 ref MethodBase candidate)
4410 return IsParamsMethodApplicable (
4411 ec, me, arguments, arg_count, false, ref candidate) ||
4412 IsParamsMethodApplicable (
4413 ec, me, arguments, arg_count, true, ref candidate);
4418 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4419 ArrayList arguments, int arg_count,
4420 bool do_varargs, ref MethodBase candidate)
4422 return IsParamsMethodApplicable (
4423 ec, arguments, arg_count, candidate, do_varargs);
4427 /// Determines if the candidate method, if a params method, is applicable
4428 /// in its expanded form to the given set of arguments
4430 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
4431 int arg_count, MethodBase candidate,
4434 ParameterData pd = GetParameterData (candidate);
4436 int pd_count = pd.Count;
4440 int count = pd_count - 1;
4442 if (pd.ParameterModifier (count) != Parameter.Modifier.ARGLIST)
4444 if (pd_count != arg_count)
4447 if (pd.ParameterModifier (count) != Parameter.Modifier.PARAMS)
4451 if (count > arg_count)
4454 if (pd_count == 1 && arg_count == 0)
4458 // If we have come this far, the case which
4459 // remains is when the number of parameters is
4460 // less than or equal to the argument count.
4462 for (int i = 0; i < count; ++i) {
4464 Argument a = (Argument) arguments [i];
4466 Parameter.Modifier a_mod = a.GetParameterModifier () &
4467 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4468 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4469 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4471 if (a_mod == p_mod) {
4473 if (a_mod == Parameter.Modifier.NONE)
4474 if (!Convert.ImplicitConversionExists (ec,
4476 pd.ParameterType (i)))
4479 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4480 Type pt = pd.ParameterType (i);
4483 pt = TypeManager.GetReferenceType (pt);
4494 Argument a = (Argument) arguments [count];
4495 if (!(a.Expr is Arglist))
4501 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4503 for (int i = pd_count - 1; i < arg_count; i++) {
4504 Argument a = (Argument) arguments [i];
4506 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4513 static bool IsApplicable (EmitContext ec, MethodGroupExpr me,
4514 ArrayList arguments, int arg_count,
4515 ref MethodBase candidate)
4517 return IsApplicable (ec, arguments, arg_count, candidate);
4521 /// Determines if the candidate method is applicable (section 14.4.2.1)
4522 /// to the given set of arguments
4524 static bool IsApplicable (EmitContext ec, ArrayList arguments, int arg_count,
4525 MethodBase candidate)
4527 ParameterData pd = GetParameterData (candidate);
4529 if (arg_count != pd.Count)
4532 for (int i = arg_count; i > 0; ) {
4535 Argument a = (Argument) arguments [i];
4537 Parameter.Modifier a_mod = a.GetParameterModifier () &
4538 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4539 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4540 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4543 if (a_mod == p_mod ||
4544 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4545 if (a_mod == Parameter.Modifier.NONE) {
4546 if (!Convert.ImplicitConversionExists (ec,
4548 pd.ParameterType (i)))
4552 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4553 Type pt = pd.ParameterType (i);
4556 pt = TypeManager.GetReferenceType (pt);
4568 static private bool IsAncestralType (Type first_type, Type second_type)
4570 return first_type != second_type &&
4571 (second_type.IsSubclassOf (first_type) ||
4572 TypeManager.ImplementsInterface (second_type, first_type));
4576 /// Find the Applicable Function Members (7.4.2.1)
4578 /// me: Method Group expression with the members to select.
4579 /// it might contain constructors or methods (or anything
4580 /// that maps to a method).
4582 /// Arguments: ArrayList containing resolved Argument objects.
4584 /// loc: The location if we want an error to be reported, or a Null
4585 /// location for "probing" purposes.
4587 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4588 /// that is the best match of me on Arguments.
4591 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4592 ArrayList Arguments, bool may_fail,
4595 MethodBase method = null;
4596 bool method_params = false;
4597 Type applicable_type = null;
4599 ArrayList candidates = new ArrayList ();
4602 // Used to keep a map between the candidate
4603 // and whether it is being considered in its
4604 // normal or expanded form
4606 // false is normal form, true is expanded form
4608 Hashtable candidate_to_form = null;
4610 if (Arguments != null)
4611 arg_count = Arguments.Count;
4613 if ((me.Name == "Invoke") &&
4614 TypeManager.IsDelegateType (me.DeclaringType)) {
4615 Error_InvokeOnDelegate (loc);
4619 MethodBase[] methods = me.Methods;
4622 // First we construct the set of applicable methods
4624 bool is_sorted = true;
4625 for (int i = 0; i < methods.Length; i++){
4626 Type decl_type = methods [i].DeclaringType;
4629 // If we have already found an applicable method
4630 // we eliminate all base types (Section 14.5.5.1)
4632 if ((applicable_type != null) &&
4633 IsAncestralType (decl_type, applicable_type))
4637 // Check if candidate is applicable (section 14.4.2.1)
4638 // Is candidate applicable in normal form?
4640 bool is_applicable = IsApplicable (
4641 ec, me, Arguments, arg_count, ref methods [i]);
4643 if (!is_applicable &&
4644 (IsParamsMethodApplicable (
4645 ec, me, Arguments, arg_count, ref methods [i]))) {
4646 MethodBase candidate = methods [i];
4647 if (candidate_to_form == null)
4648 candidate_to_form = new PtrHashtable ();
4649 candidate_to_form [candidate] = candidate;
4650 // Candidate is applicable in expanded form
4651 is_applicable = true;
4657 candidates.Add (methods [i]);
4659 if (applicable_type == null)
4660 applicable_type = decl_type;
4661 else if (applicable_type != decl_type) {
4663 if (IsAncestralType (applicable_type, decl_type))
4664 applicable_type = decl_type;
4668 int candidate_top = candidates.Count;
4670 if (candidate_top == 0) {
4672 // Okay so we have failed to find anything so we
4673 // return by providing info about the closest match
4675 for (int i = 0; i < methods.Length; ++i) {
4676 MethodBase c = (MethodBase) methods [i];
4677 ParameterData pd = GetParameterData (c);
4679 if (pd.Count != arg_count)
4682 VerifyArgumentsCompat (ec, Arguments, arg_count,
4683 c, false, null, may_fail, loc);
4688 string report_name = me.Name;
4689 if (report_name == ".ctor")
4690 report_name = me.DeclaringType.ToString ();
4692 Error_WrongNumArguments (
4693 loc, report_name, arg_count);
4702 // At this point, applicable_type is _one_ of the most derived types
4703 // in the set of types containing the methods in this MethodGroup.
4704 // Filter the candidates so that they only contain methods from the
4705 // most derived types.
4708 int finalized = 0; // Number of finalized candidates
4711 // Invariant: applicable_type is a most derived type
4713 // We'll try to complete Section 14.5.5.1 for 'applicable_type' by
4714 // eliminating all it's base types. At the same time, we'll also move
4715 // every unrelated type to the end of the array, and pick the next
4716 // 'applicable_type'.
4718 Type next_applicable_type = null;
4719 int j = finalized; // where to put the next finalized candidate
4720 int k = finalized; // where to put the next undiscarded candidate
4721 for (int i = finalized; i < candidate_top; ++i) {
4722 Type decl_type = ((MethodBase) candidates[i]).DeclaringType;
4724 if (decl_type == applicable_type) {
4725 candidates[k++] = candidates[j];
4726 candidates[j++] = candidates[i];
4730 if (IsAncestralType (decl_type, applicable_type))
4733 if (next_applicable_type != null &&
4734 IsAncestralType (decl_type, next_applicable_type))
4737 candidates[k++] = candidates[i];
4739 if (next_applicable_type == null ||
4740 IsAncestralType (next_applicable_type, decl_type))
4741 next_applicable_type = decl_type;
4744 applicable_type = next_applicable_type;
4747 } while (applicable_type != null);
4751 // Now we actually find the best method
4754 method = (MethodBase) candidates[0];
4755 method_params = candidate_to_form != null && candidate_to_form.Contains (method);
4756 for (int ix = 1; ix < candidate_top; ix++){
4757 MethodBase candidate = (MethodBase) candidates [ix];
4758 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4760 if (BetterFunction (ec, Arguments, arg_count,
4761 candidate, cand_params,
4762 method, method_params, loc) != 0) {
4764 method_params = cand_params;
4769 // Now check that there are no ambiguities i.e the selected method
4770 // should be better than all the others
4772 bool ambiguous = false;
4773 for (int ix = 0; ix < candidate_top; ix++){
4774 MethodBase candidate = (MethodBase) candidates [ix];
4776 if (candidate == method)
4779 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4780 if (BetterFunction (ec, Arguments, arg_count,
4781 method, method_params,
4782 candidate, cand_params,
4784 Report.SymbolRelatedToPreviousError (candidate);
4790 Report.SymbolRelatedToPreviousError (method);
4791 Report.Error (121, loc, "Ambiguous call when selecting function due to implicit casts");
4797 // And now check if the arguments are all
4798 // compatible, perform conversions if
4799 // necessary etc. and return if everything is
4802 if (!VerifyArgumentsCompat (ec, Arguments, arg_count, method,
4803 method_params, null, may_fail, loc))
4809 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
4811 Report.Error (1501, loc,
4812 "No overload for method `" + name + "' takes `" +
4813 arg_count + "' arguments");
4816 static void Error_InvokeOnDelegate (Location loc)
4818 Report.Error (1533, loc,
4819 "Invoke cannot be called directly on a delegate");
4822 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
4823 Type delegate_type, string arg_sig, string par_desc)
4825 if (delegate_type == null)
4826 Report.Error (1502, loc,
4827 "The best overloaded match for method '" +
4828 FullMethodDesc (method) +
4829 "' has some invalid arguments");
4831 Report.Error (1594, loc,
4832 "Delegate '" + delegate_type.ToString () +
4833 "' has some invalid arguments.");
4834 Report.Error (1503, loc,
4835 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
4836 idx, arg_sig, par_desc));
4839 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
4840 int arg_count, MethodBase method,
4841 bool chose_params_expanded,
4842 Type delegate_type, bool may_fail,
4845 ParameterData pd = GetParameterData (method);
4846 int pd_count = pd.Count;
4848 for (int j = 0; j < arg_count; j++) {
4849 Argument a = (Argument) Arguments [j];
4850 Expression a_expr = a.Expr;
4851 Type parameter_type = pd.ParameterType (j);
4852 Parameter.Modifier pm = pd.ParameterModifier (j);
4854 if (pm == Parameter.Modifier.PARAMS){
4855 if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
4857 Error_InvalidArguments (
4858 loc, j, method, delegate_type,
4859 Argument.FullDesc (a), pd.ParameterDesc (j));
4863 if (chose_params_expanded)
4864 parameter_type = TypeManager.GetElementType (parameter_type);
4865 } else if (pm == Parameter.Modifier.ARGLIST){
4871 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
4873 Error_InvalidArguments (
4874 loc, j, method, delegate_type,
4875 Argument.FullDesc (a), pd.ParameterDesc (j));
4883 if (!a.Type.Equals (parameter_type)){
4886 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
4890 Error_InvalidArguments (
4891 loc, j, method, delegate_type,
4892 Argument.FullDesc (a), pd.ParameterDesc (j));
4897 // Update the argument with the implicit conversion
4903 Parameter.Modifier a_mod = a.GetParameterModifier () &
4904 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4905 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
4906 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4908 if (a_mod != p_mod &&
4909 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
4911 Report.Error (1502, loc,
4912 "The best overloaded match for method '" + FullMethodDesc (method)+
4913 "' has some invalid arguments");
4914 Report.Error (1503, loc,
4915 "Argument " + (j+1) +
4916 ": Cannot convert from '" + Argument.FullDesc (a)
4917 + "' to '" + pd.ParameterDesc (j) + "'");
4927 public override Expression DoResolve (EmitContext ec)
4930 // First, resolve the expression that is used to
4931 // trigger the invocation
4933 if (expr is BaseAccess)
4936 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4940 if (!(expr is MethodGroupExpr)) {
4941 Type expr_type = expr.Type;
4943 if (expr_type != null){
4944 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
4946 return (new DelegateInvocation (
4947 this.expr, Arguments, loc)).Resolve (ec);
4951 if (!(expr is MethodGroupExpr)){
4952 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup);
4957 // Next, evaluate all the expressions in the argument list
4959 if (Arguments != null){
4960 foreach (Argument a in Arguments){
4961 if (!a.Resolve (ec, loc))
4966 MethodGroupExpr mg = (MethodGroupExpr) expr;
4967 method = OverloadResolve (ec, mg, Arguments, false, loc);
4972 MethodInfo mi = method as MethodInfo;
4974 type = TypeManager.TypeToCoreType (mi.ReturnType);
4975 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null)) {
4976 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
4980 Expression iexpr = mg.InstanceExpression;
4981 if (mi.IsStatic && (iexpr != null) && !(iexpr is This)) {
4982 if (mg.IdenticalTypeName)
4983 mg.InstanceExpression = null;
4985 MemberAccess.error176 (loc, mi.Name);
4991 if (type.IsPointer){
4999 // Only base will allow this invocation to happen.
5001 if (is_base && method.IsAbstract){
5002 Report.Error (205, loc, "Cannot call an abstract base member: " +
5003 FullMethodDesc (method));
5007 if ((method.Attributes & MethodAttributes.SpecialName) != 0){
5008 if (TypeManager.IsSpecialMethod (method))
5009 Report.Error (571, loc, method.Name + ": can not call operator or accessor");
5012 eclass = ExprClass.Value;
5017 // Emits the list of arguments as an array
5019 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
5021 ILGenerator ig = ec.ig;
5022 int count = arguments.Count - idx;
5023 Argument a = (Argument) arguments [idx];
5024 Type t = a.Expr.Type;
5026 IntConstant.EmitInt (ig, count);
5027 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
5029 int top = arguments.Count;
5030 for (int j = idx; j < top; j++){
5031 a = (Argument) arguments [j];
5033 ig.Emit (OpCodes.Dup);
5034 IntConstant.EmitInt (ig, j - idx);
5037 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj);
5039 ig.Emit (OpCodes.Ldelema, t);
5044 ig.Emit (OpCodes.Stobj, t);
5051 /// Emits a list of resolved Arguments that are in the arguments
5054 /// The MethodBase argument might be null if the
5055 /// emission of the arguments is known not to contain
5056 /// a `params' field (for example in constructors or other routines
5057 /// that keep their arguments in this structure)
5059 /// if `dup_args' is true, a copy of the arguments will be left
5060 /// on the stack. If `dup_args' is true, you can specify `this_arg'
5061 /// which will be duplicated before any other args. Only EmitCall
5062 /// should be using this interface.
5064 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments, bool dup_args, LocalTemporary this_arg)
5068 pd = GetParameterData (mb);
5072 LocalTemporary [] temps = null;
5075 temps = new LocalTemporary [arguments.Count];
5078 // If we are calling a params method with no arguments, special case it
5080 if (arguments == null){
5081 if (pd != null && pd.Count > 0 &&
5082 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
5083 ILGenerator ig = ec.ig;
5085 IntConstant.EmitInt (ig, 0);
5086 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
5092 int top = arguments.Count;
5094 for (int i = 0; i < top; i++){
5095 Argument a = (Argument) arguments [i];
5098 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
5100 // Special case if we are passing the same data as the
5101 // params argument, do not put it in an array.
5103 if (pd.ParameterType (i) == a.Type)
5106 EmitParams (ec, i, arguments);
5113 ec.ig.Emit (OpCodes.Dup);
5114 (temps [i] = new LocalTemporary (ec, a.Type)).Store (ec);
5119 if (this_arg != null)
5122 for (int i = 0; i < top; i ++)
5123 temps [i].Emit (ec);
5126 if (pd != null && pd.Count > top &&
5127 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
5128 ILGenerator ig = ec.ig;
5130 IntConstant.EmitInt (ig, 0);
5131 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
5135 static Type[] GetVarargsTypes (EmitContext ec, MethodBase mb,
5136 ArrayList arguments)
5138 ParameterData pd = GetParameterData (mb);
5140 if (arguments == null)
5141 return new Type [0];
5143 Argument a = (Argument) arguments [pd.Count - 1];
5144 Arglist list = (Arglist) a.Expr;
5146 return list.ArgumentTypes;
5150 /// This checks the ConditionalAttribute on the method
5152 static bool IsMethodExcluded (MethodBase method, EmitContext ec)
5154 if (method.IsConstructor)
5157 IMethodData md = TypeManager.GetMethod (method);
5159 return md.IsExcluded (ec);
5161 // For some methods (generated by delegate class) GetMethod returns null
5162 // because they are not included in builder_to_method table
5163 if (method.DeclaringType is TypeBuilder)
5166 return AttributeTester.IsConditionalMethodExcluded (method);
5170 /// is_base tells whether we want to force the use of the `call'
5171 /// opcode instead of using callvirt. Call is required to call
5172 /// a specific method, while callvirt will always use the most
5173 /// recent method in the vtable.
5175 /// is_static tells whether this is an invocation on a static method
5177 /// instance_expr is an expression that represents the instance
5178 /// it must be non-null if is_static is false.
5180 /// method is the method to invoke.
5182 /// Arguments is the list of arguments to pass to the method or constructor.
5184 public static void EmitCall (EmitContext ec, bool is_base,
5185 bool is_static, Expression instance_expr,
5186 MethodBase method, ArrayList Arguments, Location loc)
5188 EmitCall (ec, is_base, is_static, instance_expr, method, Arguments, loc, false, false);
5191 // `dup_args' leaves an extra copy of the arguments on the stack
5192 // `omit_args' does not leave any arguments at all.
5193 // So, basically, you could make one call with `dup_args' set to true,
5194 // and then another with `omit_args' set to true, and the two calls
5195 // would have the same set of arguments. However, each argument would
5196 // only have been evaluated once.
5197 public static void EmitCall (EmitContext ec, bool is_base,
5198 bool is_static, Expression instance_expr,
5199 MethodBase method, ArrayList Arguments, Location loc,
5200 bool dup_args, bool omit_args)
5202 ILGenerator ig = ec.ig;
5203 bool struct_call = false;
5204 bool this_call = false;
5205 LocalTemporary this_arg = null;
5207 Type decl_type = method.DeclaringType;
5209 if (!RootContext.StdLib) {
5210 // Replace any calls to the system's System.Array type with calls to
5211 // the newly created one.
5212 if (method == TypeManager.system_int_array_get_length)
5213 method = TypeManager.int_array_get_length;
5214 else if (method == TypeManager.system_int_array_get_rank)
5215 method = TypeManager.int_array_get_rank;
5216 else if (method == TypeManager.system_object_array_clone)
5217 method = TypeManager.object_array_clone;
5218 else if (method == TypeManager.system_int_array_get_length_int)
5219 method = TypeManager.int_array_get_length_int;
5220 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5221 method = TypeManager.int_array_get_lower_bound_int;
5222 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5223 method = TypeManager.int_array_get_upper_bound_int;
5224 else if (method == TypeManager.system_void_array_copyto_array_int)
5225 method = TypeManager.void_array_copyto_array_int;
5229 // This checks ObsoleteAttribute on the method and on the declaring type
5231 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
5233 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
5236 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
5238 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
5241 if (IsMethodExcluded (method, ec))
5245 this_call = instance_expr == null;
5246 if (decl_type.IsValueType || (!this_call && instance_expr.Type.IsValueType))
5250 // If this is ourselves, push "this"
5255 ig.Emit (OpCodes.Ldarg_0);
5259 // Push the instance expression
5261 if (instance_expr.Type.IsValueType) {
5263 // Special case: calls to a function declared in a
5264 // reference-type with a value-type argument need
5265 // to have their value boxed.
5266 if (decl_type.IsValueType) {
5268 // If the expression implements IMemoryLocation, then
5269 // we can optimize and use AddressOf on the
5272 // If not we have to use some temporary storage for
5274 if (instance_expr is IMemoryLocation) {
5275 ((IMemoryLocation)instance_expr).
5276 AddressOf (ec, AddressOp.LoadStore);
5278 LocalTemporary temp = new LocalTemporary (ec, instance_expr.Type);
5279 instance_expr.Emit (ec);
5281 temp.AddressOf (ec, AddressOp.Load);
5284 // avoid the overhead of doing this all the time.
5286 t = TypeManager.GetReferenceType (instance_expr.Type);
5288 instance_expr.Emit (ec);
5289 ig.Emit (OpCodes.Box, instance_expr.Type);
5290 t = TypeManager.object_type;
5293 instance_expr.Emit (ec);
5294 t = instance_expr.Type;
5299 this_arg = new LocalTemporary (ec, t);
5300 ig.Emit (OpCodes.Dup);
5301 this_arg.Store (ec);
5307 EmitArguments (ec, method, Arguments, dup_args, this_arg);
5310 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
5311 call_op = OpCodes.Call;
5313 call_op = OpCodes.Callvirt;
5315 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
5316 Type[] varargs_types = GetVarargsTypes (ec, method, Arguments);
5317 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
5324 // and DoFoo is not virtual, you can omit the callvirt,
5325 // because you don't need the null checking behavior.
5327 if (method is MethodInfo)
5328 ig.Emit (call_op, (MethodInfo) method);
5330 ig.Emit (call_op, (ConstructorInfo) method);
5333 public override void Emit (EmitContext ec)
5335 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5337 EmitCall (ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5340 public override void EmitStatement (EmitContext ec)
5345 // Pop the return value if there is one
5347 if (method is MethodInfo){
5348 Type ret = ((MethodInfo)method).ReturnType;
5349 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5350 ec.ig.Emit (OpCodes.Pop);
5355 public class InvocationOrCast : ExpressionStatement
5358 Expression argument;
5360 public InvocationOrCast (Expression expr, Expression argument, Location loc)
5363 this.argument = argument;
5367 public override Expression DoResolve (EmitContext ec)
5370 // First try to resolve it as a cast.
5372 type = ec.DeclSpace.ResolveType (expr, true, loc);
5374 Cast cast = new Cast (new TypeExpression (type, loc), argument, loc);
5375 return cast.Resolve (ec);
5379 // This can either be a type or a delegate invocation.
5380 // Let's just resolve it and see what we'll get.
5382 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5387 // Ok, so it's a Cast.
5389 if (expr.eclass == ExprClass.Type) {
5390 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
5391 return cast.Resolve (ec);
5395 // It's a delegate invocation.
5397 if (!TypeManager.IsDelegateType (expr.Type)) {
5398 Error (149, "Method name expected");
5402 ArrayList args = new ArrayList ();
5403 args.Add (new Argument (argument, Argument.AType.Expression));
5404 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5405 return invocation.Resolve (ec);
5410 Error (201, "Only assignment, call, increment, decrement and new object " +
5411 "expressions can be used as a statement");
5414 public override ExpressionStatement ResolveStatement (EmitContext ec)
5417 // First try to resolve it as a cast.
5419 type = ec.DeclSpace.ResolveType (expr, true, loc);
5426 // This can either be a type or a delegate invocation.
5427 // Let's just resolve it and see what we'll get.
5429 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5430 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5436 // It's a delegate invocation.
5438 if (!TypeManager.IsDelegateType (expr.Type)) {
5439 Error (149, "Method name expected");
5443 ArrayList args = new ArrayList ();
5444 args.Add (new Argument (argument, Argument.AType.Expression));
5445 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5446 return invocation.ResolveStatement (ec);
5449 public override void Emit (EmitContext ec)
5451 throw new Exception ("Cannot happen");
5454 public override void EmitStatement (EmitContext ec)
5456 throw new Exception ("Cannot happen");
5461 // This class is used to "disable" the code generation for the
5462 // temporary variable when initializing value types.
5464 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5465 public void AddressOf (EmitContext ec, AddressOp Mode)
5472 /// Implements the new expression
5474 public class New : ExpressionStatement, IMemoryLocation {
5475 public readonly ArrayList Arguments;
5478 // During bootstrap, it contains the RequestedType,
5479 // but if `type' is not null, it *might* contain a NewDelegate
5480 // (because of field multi-initialization)
5482 public Expression RequestedType;
5484 MethodBase method = null;
5487 // If set, the new expression is for a value_target, and
5488 // we will not leave anything on the stack.
5490 Expression value_target;
5491 bool value_target_set = false;
5493 public New (Expression requested_type, ArrayList arguments, Location l)
5495 RequestedType = requested_type;
5496 Arguments = arguments;
5500 public bool SetValueTypeVariable (Expression value)
5502 value_target = value;
5503 value_target_set = true;
5504 if (!(value_target is IMemoryLocation)){
5505 Error_UnexpectedKind ("variable");
5512 // This function is used to disable the following code sequence for
5513 // value type initialization:
5515 // AddressOf (temporary)
5519 // Instead the provide will have provided us with the address on the
5520 // stack to store the results.
5522 static Expression MyEmptyExpression;
5524 public void DisableTemporaryValueType ()
5526 if (MyEmptyExpression == null)
5527 MyEmptyExpression = new EmptyAddressOf ();
5530 // To enable this, look into:
5531 // test-34 and test-89 and self bootstrapping.
5533 // For instance, we can avoid a copy by using `newobj'
5534 // instead of Call + Push-temp on value types.
5535 // value_target = MyEmptyExpression;
5538 public override Expression DoResolve (EmitContext ec)
5541 // The New DoResolve might be called twice when initializing field
5542 // expressions (see EmitFieldInitializers, the call to
5543 // GetInitializerExpression will perform a resolve on the expression,
5544 // and later the assign will trigger another resolution
5546 // This leads to bugs (#37014)
5549 if (RequestedType is NewDelegate)
5550 return RequestedType;
5554 type = ec.DeclSpace.ResolveType (RequestedType, false, loc);
5559 CheckObsoleteAttribute (type);
5561 bool IsDelegate = TypeManager.IsDelegateType (type);
5564 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5565 if (RequestedType != null)
5566 if (!(RequestedType is NewDelegate))
5567 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
5568 return RequestedType;
5571 if (type.IsAbstract && type.IsSealed) {
5572 Report.Error (712, loc, "Cannot create an instance of the static class '{0}'", TypeManager.CSharpName (type));
5576 if (type.IsInterface || type.IsAbstract){
5577 Error (144, "It is not possible to create instances of interfaces or abstract classes");
5581 bool is_struct = type.IsValueType;
5582 eclass = ExprClass.Value;
5585 // SRE returns a match for .ctor () on structs (the object constructor),
5586 // so we have to manually ignore it.
5588 if (is_struct && Arguments == null)
5592 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
5593 ml = MemberLookupFinal (ec, type, type, ".ctor",
5594 MemberTypes.Constructor,
5595 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5600 if (! (ml is MethodGroupExpr)){
5602 ml.Error_UnexpectedKind ("method group");
5608 if (Arguments != null){
5609 foreach (Argument a in Arguments){
5610 if (!a.Resolve (ec, loc))
5615 method = Invocation.OverloadResolve (
5616 ec, (MethodGroupExpr) ml, Arguments, false, loc);
5620 if (method == null) {
5621 if (!is_struct || Arguments.Count > 0) {
5622 Error (1501, String.Format (
5623 "New invocation: Can not find a constructor in `{0}' for this argument list",
5624 TypeManager.CSharpName (type)));
5633 // This DoEmit can be invoked in two contexts:
5634 // * As a mechanism that will leave a value on the stack (new object)
5635 // * As one that wont (init struct)
5637 // You can control whether a value is required on the stack by passing
5638 // need_value_on_stack. The code *might* leave a value on the stack
5639 // so it must be popped manually
5641 // If we are dealing with a ValueType, we have a few
5642 // situations to deal with:
5644 // * The target is a ValueType, and we have been provided
5645 // the instance (this is easy, we are being assigned).
5647 // * The target of New is being passed as an argument,
5648 // to a boxing operation or a function that takes a
5651 // In this case, we need to create a temporary variable
5652 // that is the argument of New.
5654 // Returns whether a value is left on the stack
5656 bool DoEmit (EmitContext ec, bool need_value_on_stack)
5658 bool is_value_type = type.IsValueType;
5659 ILGenerator ig = ec.ig;
5664 // Allow DoEmit() to be called multiple times.
5665 // We need to create a new LocalTemporary each time since
5666 // you can't share LocalBuilders among ILGeneators.
5667 if (!value_target_set)
5668 value_target = new LocalTemporary (ec, type);
5670 ml = (IMemoryLocation) value_target;
5671 ml.AddressOf (ec, AddressOp.Store);
5675 Invocation.EmitArguments (ec, method, Arguments, false, null);
5679 ig.Emit (OpCodes.Initobj, type);
5681 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5682 if (need_value_on_stack){
5683 value_target.Emit (ec);
5688 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
5693 public override void Emit (EmitContext ec)
5698 public override void EmitStatement (EmitContext ec)
5700 if (DoEmit (ec, false))
5701 ec.ig.Emit (OpCodes.Pop);
5704 public void AddressOf (EmitContext ec, AddressOp Mode)
5706 if (!type.IsValueType){
5708 // We throw an exception. So far, I believe we only need to support
5710 // foreach (int j in new StructType ())
5713 throw new Exception ("AddressOf should not be used for classes");
5716 if (!value_target_set)
5717 value_target = new LocalTemporary (ec, type);
5719 IMemoryLocation ml = (IMemoryLocation) value_target;
5720 ml.AddressOf (ec, AddressOp.Store);
5722 Invocation.EmitArguments (ec, method, Arguments, false, null);
5725 ec.ig.Emit (OpCodes.Initobj, type);
5727 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5729 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
5734 /// 14.5.10.2: Represents an array creation expression.
5738 /// There are two possible scenarios here: one is an array creation
5739 /// expression that specifies the dimensions and optionally the
5740 /// initialization data and the other which does not need dimensions
5741 /// specified but where initialization data is mandatory.
5743 public class ArrayCreation : Expression {
5744 Expression requested_base_type;
5745 ArrayList initializers;
5748 // The list of Argument types.
5749 // This is used to construct the `newarray' or constructor signature
5751 ArrayList arguments;
5754 // Method used to create the array object.
5756 MethodBase new_method = null;
5758 Type array_element_type;
5759 Type underlying_type;
5760 bool is_one_dimensional = false;
5761 bool is_builtin_type = false;
5762 bool expect_initializers = false;
5763 int num_arguments = 0;
5767 ArrayList array_data;
5772 // The number of array initializers that we can handle
5773 // via the InitializeArray method - through EmitStaticInitializers
5775 int num_automatic_initializers;
5777 const int max_automatic_initializers = 6;
5779 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
5781 this.requested_base_type = requested_base_type;
5782 this.initializers = initializers;
5786 arguments = new ArrayList ();
5788 foreach (Expression e in exprs) {
5789 arguments.Add (new Argument (e, Argument.AType.Expression));
5794 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
5796 this.requested_base_type = requested_base_type;
5797 this.initializers = initializers;
5801 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
5803 //string tmp = rank.Substring (rank.LastIndexOf ('['));
5805 //dimensions = tmp.Length - 1;
5806 expect_initializers = true;
5809 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
5811 StringBuilder sb = new StringBuilder (rank);
5814 for (int i = 1; i < idx_count; i++)
5819 return new ComposedCast (base_type, sb.ToString (), loc);
5822 void Error_IncorrectArrayInitializer ()
5824 Error (178, "Incorrectly structured array initializer");
5827 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
5829 if (specified_dims) {
5830 Argument a = (Argument) arguments [idx];
5832 if (!a.Resolve (ec, loc))
5835 if (!(a.Expr is Constant)) {
5836 Error (150, "A constant value is expected");
5840 int value = (int) ((Constant) a.Expr).GetValue ();
5842 if (value != probe.Count) {
5843 Error_IncorrectArrayInitializer ();
5847 bounds [idx] = value;
5850 int child_bounds = -1;
5851 foreach (object o in probe) {
5852 if (o is ArrayList) {
5853 int current_bounds = ((ArrayList) o).Count;
5855 if (child_bounds == -1)
5856 child_bounds = current_bounds;
5858 else if (child_bounds != current_bounds){
5859 Error_IncorrectArrayInitializer ();
5862 if (specified_dims && (idx + 1 >= arguments.Count)){
5863 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
5867 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
5871 if (child_bounds != -1){
5872 Error_IncorrectArrayInitializer ();
5876 Expression tmp = (Expression) o;
5877 tmp = tmp.Resolve (ec);
5881 // Console.WriteLine ("I got: " + tmp);
5882 // Handle initialization from vars, fields etc.
5884 Expression conv = Convert.ImplicitConversionRequired (
5885 ec, tmp, underlying_type, loc);
5890 if (conv is StringConstant || conv is DecimalConstant || conv is NullCast) {
5891 // These are subclasses of Constant that can appear as elements of an
5892 // array that cannot be statically initialized (with num_automatic_initializers
5893 // > max_automatic_initializers), so num_automatic_initializers should be left as zero.
5894 array_data.Add (conv);
5895 } else if (conv is Constant) {
5896 // These are the types of Constant that can appear in arrays that can be
5897 // statically allocated.
5898 array_data.Add (conv);
5899 num_automatic_initializers++;
5901 array_data.Add (conv);
5908 public void UpdateIndices (EmitContext ec)
5911 for (ArrayList probe = initializers; probe != null;) {
5912 if (probe.Count > 0 && probe [0] is ArrayList) {
5913 Expression e = new IntConstant (probe.Count);
5914 arguments.Add (new Argument (e, Argument.AType.Expression));
5916 bounds [i++] = probe.Count;
5918 probe = (ArrayList) probe [0];
5921 Expression e = new IntConstant (probe.Count);
5922 arguments.Add (new Argument (e, Argument.AType.Expression));
5924 bounds [i++] = probe.Count;
5931 public bool ValidateInitializers (EmitContext ec, Type array_type)
5933 if (initializers == null) {
5934 if (expect_initializers)
5940 if (underlying_type == null)
5944 // We use this to store all the date values in the order in which we
5945 // will need to store them in the byte blob later
5947 array_data = new ArrayList ();
5948 bounds = new Hashtable ();
5952 if (arguments != null) {
5953 ret = CheckIndices (ec, initializers, 0, true);
5956 arguments = new ArrayList ();
5958 ret = CheckIndices (ec, initializers, 0, false);
5965 if (arguments.Count != dimensions) {
5966 Error_IncorrectArrayInitializer ();
5974 void Error_NegativeArrayIndex ()
5976 Error (284, "Can not create array with a negative size");
5980 // Converts `source' to an int, uint, long or ulong.
5982 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
5986 bool old_checked = ec.CheckState;
5987 ec.CheckState = true;
5989 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
5990 if (target == null){
5991 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
5992 if (target == null){
5993 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
5994 if (target == null){
5995 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
5997 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
6001 ec.CheckState = old_checked;
6004 // Only positive constants are allowed at compile time
6006 if (target is Constant){
6007 if (target is IntConstant){
6008 if (((IntConstant) target).Value < 0){
6009 Error_NegativeArrayIndex ();
6014 if (target is LongConstant){
6015 if (((LongConstant) target).Value < 0){
6016 Error_NegativeArrayIndex ();
6027 // Creates the type of the array
6029 bool LookupType (EmitContext ec)
6031 StringBuilder array_qualifier = new StringBuilder (rank);
6034 // `In the first form allocates an array instace of the type that results
6035 // from deleting each of the individual expression from the expression list'
6037 if (num_arguments > 0) {
6038 array_qualifier.Append ("[");
6039 for (int i = num_arguments-1; i > 0; i--)
6040 array_qualifier.Append (",");
6041 array_qualifier.Append ("]");
6047 Expression array_type_expr;
6048 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
6049 type = ec.DeclSpace.ResolveType (array_type_expr, false, loc);
6054 if (!type.IsArray) {
6055 Error (622, "Can only use array initializer expressions to assign to array types. Try using a new expression instead.");
6058 underlying_type = TypeManager.GetElementType (type);
6059 dimensions = type.GetArrayRank ();
6064 public override Expression DoResolve (EmitContext ec)
6068 if (!LookupType (ec))
6072 // First step is to validate the initializers and fill
6073 // in any missing bits
6075 if (!ValidateInitializers (ec, type))
6078 if (arguments == null)
6081 arg_count = arguments.Count;
6082 foreach (Argument a in arguments){
6083 if (!a.Resolve (ec, loc))
6086 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
6087 if (real_arg == null)
6094 array_element_type = TypeManager.GetElementType (type);
6096 if (array_element_type.IsAbstract && array_element_type.IsSealed) {
6097 Report.Error (719, loc, "'{0}': array elements cannot be of static type", TypeManager.CSharpName (array_element_type));
6101 if (arg_count == 1) {
6102 is_one_dimensional = true;
6103 eclass = ExprClass.Value;
6107 is_builtin_type = TypeManager.IsBuiltinType (type);
6109 if (is_builtin_type) {
6112 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
6113 AllBindingFlags, loc);
6115 if (!(ml is MethodGroupExpr)) {
6116 ml.Error_UnexpectedKind ("method group");
6121 Error (-6, "New invocation: Can not find a constructor for " +
6122 "this argument list");
6126 new_method = Invocation.OverloadResolve (
6127 ec, (MethodGroupExpr) ml, arguments, false, loc);
6129 if (new_method == null) {
6130 Error (-6, "New invocation: Can not find a constructor for " +
6131 "this argument list");
6135 eclass = ExprClass.Value;
6138 ModuleBuilder mb = CodeGen.Module.Builder;
6139 ArrayList args = new ArrayList ();
6141 if (arguments != null) {
6142 for (int i = 0; i < arg_count; i++)
6143 args.Add (TypeManager.int32_type);
6146 Type [] arg_types = null;
6149 arg_types = new Type [args.Count];
6151 args.CopyTo (arg_types, 0);
6153 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
6156 if (new_method == null) {
6157 Error (-6, "New invocation: Can not find a constructor for " +
6158 "this argument list");
6162 eclass = ExprClass.Value;
6167 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
6172 int count = array_data.Count;
6174 if (underlying_type.IsEnum)
6175 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
6177 factor = GetTypeSize (underlying_type);
6179 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
6181 data = new byte [(count * factor + 4) & ~3];
6184 for (int i = 0; i < count; ++i) {
6185 object v = array_data [i];
6187 if (v is EnumConstant)
6188 v = ((EnumConstant) v).Child;
6190 if (v is Constant && !(v is StringConstant))
6191 v = ((Constant) v).GetValue ();
6197 if (underlying_type == TypeManager.int64_type){
6198 if (!(v is Expression)){
6199 long val = (long) v;
6201 for (int j = 0; j < factor; ++j) {
6202 data [idx + j] = (byte) (val & 0xFF);
6206 } else if (underlying_type == TypeManager.uint64_type){
6207 if (!(v is Expression)){
6208 ulong val = (ulong) v;
6210 for (int j = 0; j < factor; ++j) {
6211 data [idx + j] = (byte) (val & 0xFF);
6215 } else if (underlying_type == TypeManager.float_type) {
6216 if (!(v is Expression)){
6217 element = BitConverter.GetBytes ((float) v);
6219 for (int j = 0; j < factor; ++j)
6220 data [idx + j] = element [j];
6222 } else if (underlying_type == TypeManager.double_type) {
6223 if (!(v is Expression)){
6224 element = BitConverter.GetBytes ((double) v);
6226 for (int j = 0; j < factor; ++j)
6227 data [idx + j] = element [j];
6229 } else if (underlying_type == TypeManager.char_type){
6230 if (!(v is Expression)){
6231 int val = (int) ((char) v);
6233 data [idx] = (byte) (val & 0xff);
6234 data [idx+1] = (byte) (val >> 8);
6236 } else if (underlying_type == TypeManager.short_type){
6237 if (!(v is Expression)){
6238 int val = (int) ((short) v);
6240 data [idx] = (byte) (val & 0xff);
6241 data [idx+1] = (byte) (val >> 8);
6243 } else if (underlying_type == TypeManager.ushort_type){
6244 if (!(v is Expression)){
6245 int val = (int) ((ushort) v);
6247 data [idx] = (byte) (val & 0xff);
6248 data [idx+1] = (byte) (val >> 8);
6250 } else if (underlying_type == TypeManager.int32_type) {
6251 if (!(v is Expression)){
6254 data [idx] = (byte) (val & 0xff);
6255 data [idx+1] = (byte) ((val >> 8) & 0xff);
6256 data [idx+2] = (byte) ((val >> 16) & 0xff);
6257 data [idx+3] = (byte) (val >> 24);
6259 } else if (underlying_type == TypeManager.uint32_type) {
6260 if (!(v is Expression)){
6261 uint val = (uint) v;
6263 data [idx] = (byte) (val & 0xff);
6264 data [idx+1] = (byte) ((val >> 8) & 0xff);
6265 data [idx+2] = (byte) ((val >> 16) & 0xff);
6266 data [idx+3] = (byte) (val >> 24);
6268 } else if (underlying_type == TypeManager.sbyte_type) {
6269 if (!(v is Expression)){
6270 sbyte val = (sbyte) v;
6271 data [idx] = (byte) val;
6273 } else if (underlying_type == TypeManager.byte_type) {
6274 if (!(v is Expression)){
6275 byte val = (byte) v;
6276 data [idx] = (byte) val;
6278 } else if (underlying_type == TypeManager.bool_type) {
6279 if (!(v is Expression)){
6280 bool val = (bool) v;
6281 data [idx] = (byte) (val ? 1 : 0);
6283 } else if (underlying_type == TypeManager.decimal_type){
6284 if (!(v is Expression)){
6285 int [] bits = Decimal.GetBits ((decimal) v);
6288 // FIXME: For some reason, this doesn't work on the MS runtime.
6289 int [] nbits = new int [4];
6290 nbits [0] = bits [3];
6291 nbits [1] = bits [2];
6292 nbits [2] = bits [0];
6293 nbits [3] = bits [1];
6295 for (int j = 0; j < 4; j++){
6296 data [p++] = (byte) (nbits [j] & 0xff);
6297 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6298 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6299 data [p++] = (byte) (nbits [j] >> 24);
6303 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6312 // Emits the initializers for the array
6314 void EmitStaticInitializers (EmitContext ec)
6317 // First, the static data
6320 ILGenerator ig = ec.ig;
6322 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6324 fb = RootContext.MakeStaticData (data);
6326 ig.Emit (OpCodes.Dup);
6327 ig.Emit (OpCodes.Ldtoken, fb);
6328 ig.Emit (OpCodes.Call,
6329 TypeManager.void_initializearray_array_fieldhandle);
6333 // Emits pieces of the array that can not be computed at compile
6334 // time (variables and string locations).
6336 // This always expect the top value on the stack to be the array
6338 void EmitDynamicInitializers (EmitContext ec)
6340 ILGenerator ig = ec.ig;
6341 int dims = bounds.Count;
6342 int [] current_pos = new int [dims];
6343 int top = array_data.Count;
6345 MethodInfo set = null;
6349 ModuleBuilder mb = null;
6350 mb = CodeGen.Module.Builder;
6351 args = new Type [dims + 1];
6354 for (j = 0; j < dims; j++)
6355 args [j] = TypeManager.int32_type;
6357 args [j] = array_element_type;
6359 set = mb.GetArrayMethod (
6361 CallingConventions.HasThis | CallingConventions.Standard,
6362 TypeManager.void_type, args);
6365 for (int i = 0; i < top; i++){
6367 Expression e = null;
6369 if (array_data [i] is Expression)
6370 e = (Expression) array_data [i];
6374 // Basically we do this for string literals and
6375 // other non-literal expressions
6377 if (e is EnumConstant){
6378 e = ((EnumConstant) e).Child;
6381 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6382 num_automatic_initializers <= max_automatic_initializers) {
6383 Type etype = e.Type;
6385 ig.Emit (OpCodes.Dup);
6387 for (int idx = 0; idx < dims; idx++)
6388 IntConstant.EmitInt (ig, current_pos [idx]);
6391 // If we are dealing with a struct, get the
6392 // address of it, so we can store it.
6395 etype.IsSubclassOf (TypeManager.value_type) &&
6396 (!TypeManager.IsBuiltinOrEnum (etype) ||
6397 etype == TypeManager.decimal_type)) {
6402 // Let new know that we are providing
6403 // the address where to store the results
6405 n.DisableTemporaryValueType ();
6408 ig.Emit (OpCodes.Ldelema, etype);
6415 OpCode op = ArrayAccess.GetStoreOpcode (etype, out is_stobj);
6417 ig.Emit (OpCodes.Stobj, etype);
6421 ig.Emit (OpCodes.Call, set);
6429 for (int j = dims - 1; j >= 0; j--){
6431 if (current_pos [j] < (int) bounds [j])
6433 current_pos [j] = 0;
6438 void EmitArrayArguments (EmitContext ec)
6440 ILGenerator ig = ec.ig;
6442 foreach (Argument a in arguments) {
6443 Type atype = a.Type;
6446 if (atype == TypeManager.uint64_type)
6447 ig.Emit (OpCodes.Conv_Ovf_U4);
6448 else if (atype == TypeManager.int64_type)
6449 ig.Emit (OpCodes.Conv_Ovf_I4);
6453 public override void Emit (EmitContext ec)
6455 ILGenerator ig = ec.ig;
6457 EmitArrayArguments (ec);
6458 if (is_one_dimensional)
6459 ig.Emit (OpCodes.Newarr, array_element_type);
6461 if (is_builtin_type)
6462 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6464 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6467 if (initializers != null){
6469 // FIXME: Set this variable correctly.
6471 bool dynamic_initializers = true;
6473 // This will never be true for array types that cannot be statically
6474 // initialized. num_automatic_initializers will always be zero. See
6476 if (num_automatic_initializers > max_automatic_initializers)
6477 EmitStaticInitializers (ec);
6479 if (dynamic_initializers)
6480 EmitDynamicInitializers (ec);
6484 public object EncodeAsAttribute ()
6486 if (!is_one_dimensional){
6487 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6491 if (array_data == null){
6492 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6496 object [] ret = new object [array_data.Count];
6498 foreach (Expression e in array_data){
6501 if (e is NullLiteral)
6504 if (!Attribute.GetAttributeArgumentExpression (e, Location, array_element_type, out v))
6514 /// Represents the `this' construct
6516 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6519 VariableInfo variable_info;
6521 public This (Block block, Location loc)
6527 public This (Location loc)
6532 public VariableInfo VariableInfo {
6533 get { return variable_info; }
6536 public bool VerifyFixed (bool is_expression)
6538 if ((variable_info == null) || (variable_info.LocalInfo == null))
6541 return variable_info.LocalInfo.IsFixed;
6544 public bool ResolveBase (EmitContext ec)
6546 eclass = ExprClass.Variable;
6547 type = ec.ContainerType;
6550 Error (26, "Keyword this not valid in static code");
6554 if ((block != null) && (block.ThisVariable != null))
6555 variable_info = block.ThisVariable.VariableInfo;
6560 public override Expression DoResolve (EmitContext ec)
6562 if (!ResolveBase (ec))
6565 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
6566 Error (188, "The this object cannot be used before all " +
6567 "of its fields are assigned to");
6568 variable_info.SetAssigned (ec);
6572 if (ec.IsFieldInitializer) {
6573 Error (27, "Keyword `this' can't be used outside a constructor, " +
6574 "a method or a property.");
6581 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6583 if (!ResolveBase (ec))
6586 if (variable_info != null)
6587 variable_info.SetAssigned (ec);
6589 if (ec.TypeContainer is Class){
6590 Error (1604, "Cannot assign to `this'");
6597 public void Emit (EmitContext ec, bool leave_copy)
6601 ec.ig.Emit (OpCodes.Dup);
6604 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
6606 ILGenerator ig = ec.ig;
6608 if (ec.TypeContainer is Struct){
6612 ec.ig.Emit (OpCodes.Dup);
6613 ig.Emit (OpCodes.Stobj, type);
6615 throw new Exception ("how did you get here");
6619 public override void Emit (EmitContext ec)
6621 ILGenerator ig = ec.ig;
6624 if (ec.TypeContainer is Struct)
6625 ig.Emit (OpCodes.Ldobj, type);
6628 public void AddressOf (EmitContext ec, AddressOp mode)
6633 // FIGURE OUT WHY LDARG_S does not work
6635 // consider: struct X { int val; int P { set { val = value; }}}
6637 // Yes, this looks very bad. Look at `NOTAS' for
6639 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
6644 /// Represents the `__arglist' construct
6646 public class ArglistAccess : Expression
6648 public ArglistAccess (Location loc)
6653 public bool ResolveBase (EmitContext ec)
6655 eclass = ExprClass.Variable;
6656 type = TypeManager.runtime_argument_handle_type;
6660 public override Expression DoResolve (EmitContext ec)
6662 if (!ResolveBase (ec))
6665 if (ec.IsFieldInitializer || !ec.CurrentBlock.HasVarargs) {
6666 Error (190, "The __arglist construct is valid only within " +
6667 "a variable argument method.");
6674 public override void Emit (EmitContext ec)
6676 ec.ig.Emit (OpCodes.Arglist);
6681 /// Represents the `__arglist (....)' construct
6683 public class Arglist : Expression
6685 public readonly Argument[] Arguments;
6687 public Arglist (Argument[] args, Location l)
6693 public Type[] ArgumentTypes {
6695 Type[] retval = new Type [Arguments.Length];
6696 for (int i = 0; i < Arguments.Length; i++)
6697 retval [i] = Arguments [i].Type;
6702 public override Expression DoResolve (EmitContext ec)
6704 eclass = ExprClass.Variable;
6705 type = TypeManager.runtime_argument_handle_type;
6707 foreach (Argument arg in Arguments) {
6708 if (!arg.Resolve (ec, loc))
6715 public override void Emit (EmitContext ec)
6717 foreach (Argument arg in Arguments)
6723 // This produces the value that renders an instance, used by the iterators code
6725 public class ProxyInstance : Expression, IMemoryLocation {
6726 public override Expression DoResolve (EmitContext ec)
6728 eclass = ExprClass.Variable;
6729 type = ec.ContainerType;
6733 public override void Emit (EmitContext ec)
6735 ec.ig.Emit (OpCodes.Ldarg_0);
6739 public void AddressOf (EmitContext ec, AddressOp mode)
6741 ec.ig.Emit (OpCodes.Ldarg_0);
6746 /// Implements the typeof operator
6748 public class TypeOf : Expression {
6749 public readonly Expression QueriedType;
6750 protected Type typearg;
6752 public TypeOf (Expression queried_type, Location l)
6754 QueriedType = queried_type;
6758 public override Expression DoResolve (EmitContext ec)
6760 typearg = ec.DeclSpace.ResolveType (QueriedType, false, loc);
6762 if (typearg == null)
6765 if (typearg == TypeManager.void_type) {
6766 Error (673, "System.Void cannot be used from C# - " +
6767 "use typeof (void) to get the void type object");
6771 if (typearg.IsPointer && !ec.InUnsafe){
6775 CheckObsoleteAttribute (typearg);
6777 type = TypeManager.type_type;
6778 eclass = ExprClass.Type;
6782 public override void Emit (EmitContext ec)
6784 ec.ig.Emit (OpCodes.Ldtoken, typearg);
6785 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6788 public Type TypeArg {
6789 get { return typearg; }
6794 /// Implements the `typeof (void)' operator
6796 public class TypeOfVoid : TypeOf {
6797 public TypeOfVoid (Location l) : base (null, l)
6802 public override Expression DoResolve (EmitContext ec)
6804 type = TypeManager.type_type;
6805 typearg = TypeManager.void_type;
6806 eclass = ExprClass.Type;
6812 /// Implements the sizeof expression
6814 public class SizeOf : Expression {
6815 public readonly Expression QueriedType;
6818 public SizeOf (Expression queried_type, Location l)
6820 this.QueriedType = queried_type;
6824 public override Expression DoResolve (EmitContext ec)
6828 233, loc, "Sizeof may only be used in an unsafe context " +
6829 "(consider using System.Runtime.InteropServices.Marshal.Sizeof");
6833 type_queried = ec.DeclSpace.ResolveType (QueriedType, false, loc);
6834 if (type_queried == null)
6837 CheckObsoleteAttribute (type_queried);
6839 if (!TypeManager.IsUnmanagedType (type_queried)){
6840 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
6844 type = TypeManager.int32_type;
6845 eclass = ExprClass.Value;
6849 public override void Emit (EmitContext ec)
6851 int size = GetTypeSize (type_queried);
6854 ec.ig.Emit (OpCodes.Sizeof, type_queried);
6856 IntConstant.EmitInt (ec.ig, size);
6861 /// Implements the member access expression
6863 public class MemberAccess : Expression {
6864 public readonly string Identifier;
6867 public MemberAccess (Expression expr, string id, Location l)
6874 public Expression Expr {
6880 public static void error176 (Location loc, string name)
6882 Report.Error (176, loc, "Static member `" +
6883 name + "' cannot be accessed " +
6884 "with an instance reference, qualify with a " +
6885 "type name instead");
6888 public static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Expression left, Location loc)
6890 SimpleName sn = left_original as SimpleName;
6891 if (sn == null || left == null || left.Type.Name != sn.Name)
6894 return RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc) != null;
6897 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
6898 Expression left, Location loc,
6899 Expression left_original)
6901 bool left_is_type, left_is_explicit;
6903 // If `left' is null, then we're called from SimpleNameResolve and this is
6904 // a member in the currently defining class.
6906 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
6907 left_is_explicit = false;
6909 // Implicitly default to `this' unless we're static.
6910 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
6911 left = ec.GetThis (loc);
6913 left_is_type = left is TypeExpr;
6914 left_is_explicit = true;
6917 if (member_lookup is FieldExpr){
6918 FieldExpr fe = (FieldExpr) member_lookup;
6919 FieldInfo fi = fe.FieldInfo;
6920 Type decl_type = fi.DeclaringType;
6922 if (fi is FieldBuilder) {
6923 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
6927 if (!c.LookupConstantValue (out o))
6930 object real_value = ((Constant) c.Expr).GetValue ();
6932 return Constantify (real_value, fi.FieldType);
6937 Type t = fi.FieldType;
6941 if (fi is FieldBuilder)
6942 o = TypeManager.GetValue ((FieldBuilder) fi);
6944 o = fi.GetValue (fi);
6946 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
6947 if (left_is_explicit && !left_is_type &&
6948 !IdenticalNameAndTypeName (ec, left_original, member_lookup, loc)) {
6949 error176 (loc, fe.FieldInfo.Name);
6953 Expression enum_member = MemberLookup (
6954 ec, decl_type, "value__", MemberTypes.Field,
6955 AllBindingFlags, loc);
6957 Enum en = TypeManager.LookupEnum (decl_type);
6961 c = Constantify (o, en.UnderlyingType);
6963 c = Constantify (o, enum_member.Type);
6965 return new EnumConstant (c, decl_type);
6968 Expression exp = Constantify (o, t);
6970 if (left_is_explicit && !left_is_type) {
6971 error176 (loc, fe.FieldInfo.Name);
6978 if (fi.FieldType.IsPointer && !ec.InUnsafe){
6984 if (member_lookup is EventExpr) {
6985 EventExpr ee = (EventExpr) member_lookup;
6988 // If the event is local to this class, we transform ourselves into
6992 if (ee.EventInfo.DeclaringType == ec.ContainerType ||
6993 TypeManager.IsNestedChildOf(ec.ContainerType, ee.EventInfo.DeclaringType)) {
6994 MemberInfo mi = GetFieldFromEvent (ee);
6998 // If this happens, then we have an event with its own
6999 // accessors and private field etc so there's no need
7000 // to transform ourselves.
7002 ee.InstanceExpression = left;
7006 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
7009 Report.Error (-200, loc, "Internal error!!");
7013 if (!left_is_explicit)
7016 ee.InstanceExpression = left;
7018 return ResolveMemberAccess (ec, ml, left, loc, left_original);
7022 if (member_lookup is IMemberExpr) {
7023 IMemberExpr me = (IMemberExpr) member_lookup;
7024 MethodGroupExpr mg = me as MethodGroupExpr;
7027 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
7028 mg.IsExplicitImpl = left_is_explicit;
7031 if ((ec.IsFieldInitializer || ec.IsStatic) &&
7032 IdenticalNameAndTypeName (ec, left_original, member_lookup, loc))
7033 return member_lookup;
7035 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
7040 if (!me.IsInstance) {
7041 if (IdenticalNameAndTypeName (ec, left_original, left, loc))
7042 return member_lookup;
7044 if (left_is_explicit) {
7045 error176 (loc, me.Name);
7051 // Since we can not check for instance objects in SimpleName,
7052 // becaue of the rule that allows types and variables to share
7053 // the name (as long as they can be de-ambiguated later, see
7054 // IdenticalNameAndTypeName), we have to check whether left
7055 // is an instance variable in a static context
7057 // However, if the left-hand value is explicitly given, then
7058 // it is already our instance expression, so we aren't in
7062 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
7063 IMemberExpr mexp = (IMemberExpr) left;
7065 if (!mexp.IsStatic){
7066 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
7071 if ((mg != null) && IdenticalNameAndTypeName (ec, left_original, left, loc))
7072 mg.IdenticalTypeName = true;
7074 me.InstanceExpression = left;
7077 return member_lookup;
7080 Console.WriteLine ("Left is: " + left);
7081 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
7082 Environment.Exit (1);
7086 public Expression DoResolve (EmitContext ec, Expression right_side, ResolveFlags flags)
7089 throw new Exception ();
7092 // Resolve the expression with flow analysis turned off, we'll do the definite
7093 // assignment checks later. This is because we don't know yet what the expression
7094 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7095 // definite assignment check on the actual field and not on the whole struct.
7098 Expression original = expr;
7099 expr = expr.Resolve (ec, flags | ResolveFlags.Intermediate | ResolveFlags.DisableFlowAnalysis);
7103 if (expr is SimpleName){
7104 SimpleName child_expr = (SimpleName) expr;
7106 Expression new_expr = new SimpleName (child_expr.Name, Identifier, loc);
7108 return new_expr.Resolve (ec, flags);
7112 // TODO: I mailed Ravi about this, and apparently we can get rid
7113 // of this and put it in the right place.
7115 // Handle enums here when they are in transit.
7116 // Note that we cannot afford to hit MemberLookup in this case because
7117 // it will fail to find any members at all
7120 Type expr_type = expr.Type;
7121 if (expr is TypeExpr){
7122 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
7123 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", expr_type);
7127 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
7128 Enum en = TypeManager.LookupEnum (expr_type);
7131 object value = en.LookupEnumValue (ec, Identifier, loc);
7134 MemberCore mc = en.GetDefinition (Identifier);
7135 ObsoleteAttribute oa = mc.GetObsoleteAttribute (en);
7137 AttributeTester.Report_ObsoleteMessage (oa, mc.GetSignatureForError (), Location);
7139 oa = en.GetObsoleteAttribute (en);
7141 AttributeTester.Report_ObsoleteMessage (oa, en.GetSignatureForError (), Location);
7144 Constant c = Constantify (value, en.UnderlyingType);
7145 return new EnumConstant (c, expr_type);
7148 CheckObsoleteAttribute (expr_type);
7150 FieldInfo fi = expr_type.GetField (Identifier);
7152 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
7154 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), Location);
7160 if (expr_type.IsPointer){
7161 Error (23, "The `.' operator can not be applied to pointer operands (" +
7162 TypeManager.CSharpName (expr_type) + ")");
7166 Expression member_lookup;
7167 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
7168 if (member_lookup == null)
7171 if (member_lookup is TypeExpr) {
7172 if (!(expr is TypeExpr) && !(expr is SimpleName)) {
7173 Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
7174 member_lookup.Type + "' instead");
7178 return member_lookup;
7181 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
7182 if (member_lookup == null)
7185 // The following DoResolve/DoResolveLValue will do the definite assignment
7188 if (right_side != null)
7189 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
7191 member_lookup = member_lookup.DoResolve (ec);
7193 return member_lookup;
7196 public override Expression DoResolve (EmitContext ec)
7198 return DoResolve (ec, null, ResolveFlags.VariableOrValue |
7199 ResolveFlags.SimpleName | ResolveFlags.Type);
7202 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7204 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
7205 ResolveFlags.SimpleName | ResolveFlags.Type);
7208 public override Expression ResolveAsTypeStep (EmitContext ec)
7210 string fname = null;
7211 MemberAccess full_expr = this;
7212 while (full_expr != null) {
7214 fname = String.Concat (full_expr.Identifier, ".", fname);
7216 fname = full_expr.Identifier;
7218 if (full_expr.Expr is SimpleName) {
7219 string full_name = String.Concat (((SimpleName) full_expr.Expr).Name, ".", fname);
7220 Type fully_qualified = ec.DeclSpace.FindType (loc, full_name);
7221 if (fully_qualified != null)
7222 return new TypeExpression (fully_qualified, loc);
7225 full_expr = full_expr.Expr as MemberAccess;
7228 Expression new_expr = expr.ResolveAsTypeStep (ec);
7230 if (new_expr == null)
7233 if (new_expr is SimpleName){
7234 SimpleName child_expr = (SimpleName) new_expr;
7236 new_expr = new SimpleName (child_expr.Name, Identifier, loc);
7238 return new_expr.ResolveAsTypeStep (ec);
7241 Type expr_type = new_expr.Type;
7243 if (expr_type.IsPointer){
7244 Error (23, "The `.' operator can not be applied to pointer operands (" +
7245 TypeManager.CSharpName (expr_type) + ")");
7249 Expression member_lookup;
7250 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
7251 if (member_lookup == null)
7254 if (member_lookup is TypeExpr){
7255 member_lookup.Resolve (ec, ResolveFlags.Type);
7256 return member_lookup;
7262 public override void Emit (EmitContext ec)
7264 throw new Exception ("Should not happen");
7267 public override string ToString ()
7269 return expr + "." + Identifier;
7274 /// Implements checked expressions
7276 public class CheckedExpr : Expression {
7278 public Expression Expr;
7280 public CheckedExpr (Expression e, Location l)
7286 public override Expression DoResolve (EmitContext ec)
7288 bool last_check = ec.CheckState;
7289 bool last_const_check = ec.ConstantCheckState;
7291 ec.CheckState = true;
7292 ec.ConstantCheckState = true;
7293 Expr = Expr.Resolve (ec);
7294 ec.CheckState = last_check;
7295 ec.ConstantCheckState = last_const_check;
7300 if (Expr is Constant)
7303 eclass = Expr.eclass;
7308 public override void Emit (EmitContext ec)
7310 bool last_check = ec.CheckState;
7311 bool last_const_check = ec.ConstantCheckState;
7313 ec.CheckState = true;
7314 ec.ConstantCheckState = true;
7316 ec.CheckState = last_check;
7317 ec.ConstantCheckState = last_const_check;
7323 /// Implements the unchecked expression
7325 public class UnCheckedExpr : Expression {
7327 public Expression Expr;
7329 public UnCheckedExpr (Expression e, Location l)
7335 public override Expression DoResolve (EmitContext ec)
7337 bool last_check = ec.CheckState;
7338 bool last_const_check = ec.ConstantCheckState;
7340 ec.CheckState = false;
7341 ec.ConstantCheckState = false;
7342 Expr = Expr.Resolve (ec);
7343 ec.CheckState = last_check;
7344 ec.ConstantCheckState = last_const_check;
7349 if (Expr is Constant)
7352 eclass = Expr.eclass;
7357 public override void Emit (EmitContext ec)
7359 bool last_check = ec.CheckState;
7360 bool last_const_check = ec.ConstantCheckState;
7362 ec.CheckState = false;
7363 ec.ConstantCheckState = false;
7365 ec.CheckState = last_check;
7366 ec.ConstantCheckState = last_const_check;
7372 /// An Element Access expression.
7374 /// During semantic analysis these are transformed into
7375 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7377 public class ElementAccess : Expression {
7378 public ArrayList Arguments;
7379 public Expression Expr;
7381 public ElementAccess (Expression e, ArrayList e_list, Location l)
7390 Arguments = new ArrayList ();
7391 foreach (Expression tmp in e_list)
7392 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7396 bool CommonResolve (EmitContext ec)
7398 Expr = Expr.Resolve (ec);
7403 if (Arguments == null)
7406 foreach (Argument a in Arguments){
7407 if (!a.Resolve (ec, loc))
7414 Expression MakePointerAccess (EmitContext ec)
7418 if (t == TypeManager.void_ptr_type){
7419 Error (242, "The array index operation is not valid for void pointers");
7422 if (Arguments.Count != 1){
7423 Error (196, "A pointer must be indexed by a single value");
7428 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc).Resolve (ec);
7431 return new Indirection (p, loc).Resolve (ec);
7434 public override Expression DoResolve (EmitContext ec)
7436 if (!CommonResolve (ec))
7440 // We perform some simple tests, and then to "split" the emit and store
7441 // code we create an instance of a different class, and return that.
7443 // I am experimenting with this pattern.
7447 if (t == TypeManager.array_type){
7448 Report.Error (21, loc, "Cannot use indexer on System.Array");
7453 return (new ArrayAccess (this, loc)).Resolve (ec);
7454 else if (t.IsPointer)
7455 return MakePointerAccess (ec);
7457 return (new IndexerAccess (this, loc)).Resolve (ec);
7460 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7462 if (!CommonResolve (ec))
7467 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
7468 else if (t.IsPointer)
7469 return MakePointerAccess (ec);
7471 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
7474 public override void Emit (EmitContext ec)
7476 throw new Exception ("Should never be reached");
7481 /// Implements array access
7483 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7485 // Points to our "data" repository
7489 LocalTemporary temp;
7492 public ArrayAccess (ElementAccess ea_data, Location l)
7495 eclass = ExprClass.Variable;
7499 public override Expression DoResolve (EmitContext ec)
7502 ExprClass eclass = ea.Expr.eclass;
7504 // As long as the type is valid
7505 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7506 eclass == ExprClass.Value)) {
7507 ea.Expr.Error_UnexpectedKind ("variable or value");
7512 Type t = ea.Expr.Type;
7513 if (t.GetArrayRank () != ea.Arguments.Count){
7515 "Incorrect number of indexes for array " +
7516 " expected: " + t.GetArrayRank () + " got: " +
7517 ea.Arguments.Count);
7521 type = TypeManager.GetElementType (t);
7522 if (type.IsPointer && !ec.InUnsafe){
7523 UnsafeError (ea.Location);
7527 foreach (Argument a in ea.Arguments){
7528 Type argtype = a.Type;
7530 if (argtype == TypeManager.int32_type ||
7531 argtype == TypeManager.uint32_type ||
7532 argtype == TypeManager.int64_type ||
7533 argtype == TypeManager.uint64_type)
7537 // Mhm. This is strage, because the Argument.Type is not the same as
7538 // Argument.Expr.Type: the value changes depending on the ref/out setting.
7540 // Wonder if I will run into trouble for this.
7542 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
7547 eclass = ExprClass.Variable;
7553 /// Emits the right opcode to load an object of Type `t'
7554 /// from an array of T
7556 static public void EmitLoadOpcode (ILGenerator ig, Type type)
7558 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7559 ig.Emit (OpCodes.Ldelem_U1);
7560 else if (type == TypeManager.sbyte_type)
7561 ig.Emit (OpCodes.Ldelem_I1);
7562 else if (type == TypeManager.short_type)
7563 ig.Emit (OpCodes.Ldelem_I2);
7564 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7565 ig.Emit (OpCodes.Ldelem_U2);
7566 else if (type == TypeManager.int32_type)
7567 ig.Emit (OpCodes.Ldelem_I4);
7568 else if (type == TypeManager.uint32_type)
7569 ig.Emit (OpCodes.Ldelem_U4);
7570 else if (type == TypeManager.uint64_type)
7571 ig.Emit (OpCodes.Ldelem_I8);
7572 else if (type == TypeManager.int64_type)
7573 ig.Emit (OpCodes.Ldelem_I8);
7574 else if (type == TypeManager.float_type)
7575 ig.Emit (OpCodes.Ldelem_R4);
7576 else if (type == TypeManager.double_type)
7577 ig.Emit (OpCodes.Ldelem_R8);
7578 else if (type == TypeManager.intptr_type)
7579 ig.Emit (OpCodes.Ldelem_I);
7580 else if (TypeManager.IsEnumType (type)){
7581 EmitLoadOpcode (ig, TypeManager.EnumToUnderlying (type));
7582 } else if (type.IsValueType){
7583 ig.Emit (OpCodes.Ldelema, type);
7584 ig.Emit (OpCodes.Ldobj, type);
7586 ig.Emit (OpCodes.Ldelem_Ref);
7590 /// Returns the right opcode to store an object of Type `t'
7591 /// from an array of T.
7593 static public OpCode GetStoreOpcode (Type t, out bool is_stobj)
7595 //Console.WriteLine (new System.Diagnostics.StackTrace ());
7597 t = TypeManager.TypeToCoreType (t);
7598 if (TypeManager.IsEnumType (t))
7599 t = TypeManager.EnumToUnderlying (t);
7600 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
7601 t == TypeManager.bool_type)
7602 return OpCodes.Stelem_I1;
7603 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
7604 t == TypeManager.char_type)
7605 return OpCodes.Stelem_I2;
7606 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
7607 return OpCodes.Stelem_I4;
7608 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
7609 return OpCodes.Stelem_I8;
7610 else if (t == TypeManager.float_type)
7611 return OpCodes.Stelem_R4;
7612 else if (t == TypeManager.double_type)
7613 return OpCodes.Stelem_R8;
7614 else if (t == TypeManager.intptr_type) {
7616 return OpCodes.Stobj;
7617 } else if (t.IsValueType) {
7619 return OpCodes.Stobj;
7621 return OpCodes.Stelem_Ref;
7624 MethodInfo FetchGetMethod ()
7626 ModuleBuilder mb = CodeGen.Module.Builder;
7627 int arg_count = ea.Arguments.Count;
7628 Type [] args = new Type [arg_count];
7631 for (int i = 0; i < arg_count; i++){
7632 //args [i++] = a.Type;
7633 args [i] = TypeManager.int32_type;
7636 get = mb.GetArrayMethod (
7637 ea.Expr.Type, "Get",
7638 CallingConventions.HasThis |
7639 CallingConventions.Standard,
7645 MethodInfo FetchAddressMethod ()
7647 ModuleBuilder mb = CodeGen.Module.Builder;
7648 int arg_count = ea.Arguments.Count;
7649 Type [] args = new Type [arg_count];
7653 ret_type = TypeManager.GetReferenceType (type);
7655 for (int i = 0; i < arg_count; i++){
7656 //args [i++] = a.Type;
7657 args [i] = TypeManager.int32_type;
7660 address = mb.GetArrayMethod (
7661 ea.Expr.Type, "Address",
7662 CallingConventions.HasThis |
7663 CallingConventions.Standard,
7670 // Load the array arguments into the stack.
7672 // If we have been requested to cache the values (cached_locations array
7673 // initialized), then load the arguments the first time and store them
7674 // in locals. otherwise load from local variables.
7676 void LoadArrayAndArguments (EmitContext ec)
7678 ILGenerator ig = ec.ig;
7681 foreach (Argument a in ea.Arguments){
7682 Type argtype = a.Expr.Type;
7686 if (argtype == TypeManager.int64_type)
7687 ig.Emit (OpCodes.Conv_Ovf_I);
7688 else if (argtype == TypeManager.uint64_type)
7689 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7693 public void Emit (EmitContext ec, bool leave_copy)
7695 int rank = ea.Expr.Type.GetArrayRank ();
7696 ILGenerator ig = ec.ig;
7699 LoadArrayAndArguments (ec);
7702 EmitLoadOpcode (ig, type);
7706 method = FetchGetMethod ();
7707 ig.Emit (OpCodes.Call, method);
7710 LoadFromPtr (ec.ig, this.type);
7713 ec.ig.Emit (OpCodes.Dup);
7714 temp = new LocalTemporary (ec, this.type);
7719 public override void Emit (EmitContext ec)
7724 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
7726 int rank = ea.Expr.Type.GetArrayRank ();
7727 ILGenerator ig = ec.ig;
7728 Type t = source.Type;
7729 prepared = prepare_for_load;
7731 if (prepare_for_load) {
7732 AddressOf (ec, AddressOp.LoadStore);
7733 ec.ig.Emit (OpCodes.Dup);
7736 ec.ig.Emit (OpCodes.Dup);
7737 temp = new LocalTemporary (ec, this.type);
7740 StoreFromPtr (ec.ig, t);
7748 LoadArrayAndArguments (ec);
7752 OpCode op = GetStoreOpcode (t, out is_stobj);
7754 // The stobj opcode used by value types will need
7755 // an address on the stack, not really an array/array
7759 ig.Emit (OpCodes.Ldelema, t);
7763 ec.ig.Emit (OpCodes.Dup);
7764 temp = new LocalTemporary (ec, this.type);
7769 ig.Emit (OpCodes.Stobj, t);
7773 ModuleBuilder mb = CodeGen.Module.Builder;
7774 int arg_count = ea.Arguments.Count;
7775 Type [] args = new Type [arg_count + 1];
7780 ec.ig.Emit (OpCodes.Dup);
7781 temp = new LocalTemporary (ec, this.type);
7785 for (int i = 0; i < arg_count; i++){
7786 //args [i++] = a.Type;
7787 args [i] = TypeManager.int32_type;
7790 args [arg_count] = type;
7792 set = mb.GetArrayMethod (
7793 ea.Expr.Type, "Set",
7794 CallingConventions.HasThis |
7795 CallingConventions.Standard,
7796 TypeManager.void_type, args);
7798 ig.Emit (OpCodes.Call, set);
7805 public void AddressOf (EmitContext ec, AddressOp mode)
7807 int rank = ea.Expr.Type.GetArrayRank ();
7808 ILGenerator ig = ec.ig;
7810 LoadArrayAndArguments (ec);
7813 ig.Emit (OpCodes.Ldelema, type);
7815 MethodInfo address = FetchAddressMethod ();
7816 ig.Emit (OpCodes.Call, address);
7823 public ArrayList Properties;
7824 static Hashtable map;
7826 public struct Indexer {
7827 public readonly Type Type;
7828 public readonly MethodInfo Getter, Setter;
7830 public Indexer (Type type, MethodInfo get, MethodInfo set)
7840 map = new Hashtable ();
7845 Properties = new ArrayList ();
7848 void Append (MemberInfo [] mi)
7850 foreach (PropertyInfo property in mi){
7851 MethodInfo get, set;
7853 get = property.GetGetMethod (true);
7854 set = property.GetSetMethod (true);
7855 Properties.Add (new Indexer (property.PropertyType, get, set));
7859 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
7861 string p_name = TypeManager.IndexerPropertyName (lookup_type);
7863 MemberInfo [] mi = TypeManager.MemberLookup (
7864 caller_type, caller_type, lookup_type, MemberTypes.Property,
7865 BindingFlags.Public | BindingFlags.Instance |
7866 BindingFlags.DeclaredOnly, p_name, null);
7868 if (mi == null || mi.Length == 0)
7874 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
7876 Indexers ix = (Indexers) map [lookup_type];
7881 Type copy = lookup_type;
7882 while (copy != TypeManager.object_type && copy != null){
7883 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
7887 ix = new Indexers ();
7892 copy = copy.BaseType;
7895 if (!lookup_type.IsInterface)
7898 TypeExpr [] ifaces = TypeManager.GetInterfaces (lookup_type);
7899 if (ifaces != null) {
7900 foreach (TypeExpr iface in ifaces) {
7901 Type itype = iface.Type;
7902 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
7905 ix = new Indexers ();
7917 /// Expressions that represent an indexer call.
7919 public class IndexerAccess : Expression, IAssignMethod {
7921 // Points to our "data" repository
7923 MethodInfo get, set;
7924 ArrayList set_arguments;
7925 bool is_base_indexer;
7927 protected Type indexer_type;
7928 protected Type current_type;
7929 protected Expression instance_expr;
7930 protected ArrayList arguments;
7932 public IndexerAccess (ElementAccess ea, Location loc)
7933 : this (ea.Expr, false, loc)
7935 this.arguments = ea.Arguments;
7938 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
7941 this.instance_expr = instance_expr;
7942 this.is_base_indexer = is_base_indexer;
7943 this.eclass = ExprClass.Value;
7947 protected virtual bool CommonResolve (EmitContext ec)
7949 indexer_type = instance_expr.Type;
7950 current_type = ec.ContainerType;
7955 public override Expression DoResolve (EmitContext ec)
7957 ArrayList AllGetters = new ArrayList();
7958 if (!CommonResolve (ec))
7962 // Step 1: Query for all `Item' *properties*. Notice
7963 // that the actual methods are pointed from here.
7965 // This is a group of properties, piles of them.
7967 bool found_any = false, found_any_getters = false;
7968 Type lookup_type = indexer_type;
7971 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
7972 if (ilist != null) {
7974 if (ilist.Properties != null) {
7975 foreach (Indexers.Indexer ix in ilist.Properties) {
7976 if (ix.Getter != null)
7977 AllGetters.Add(ix.Getter);
7982 if (AllGetters.Count > 0) {
7983 found_any_getters = true;
7984 get = (MethodInfo) Invocation.OverloadResolve (
7985 ec, new MethodGroupExpr (AllGetters, loc),
7986 arguments, false, loc);
7990 Report.Error (21, loc,
7991 "Type `" + TypeManager.CSharpName (indexer_type) +
7992 "' does not have any indexers defined");
7996 if (!found_any_getters) {
7997 Error (154, "indexer can not be used in this context, because " +
7998 "it lacks a `get' accessor");
8003 Error (1501, "No Overload for method `this' takes `" +
8004 arguments.Count + "' arguments");
8009 // Only base will allow this invocation to happen.
8011 if (get.IsAbstract && this is BaseIndexerAccess){
8012 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
8016 type = get.ReturnType;
8017 if (type.IsPointer && !ec.InUnsafe){
8022 eclass = ExprClass.IndexerAccess;
8026 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8028 ArrayList AllSetters = new ArrayList();
8029 if (!CommonResolve (ec))
8032 bool found_any = false, found_any_setters = false;
8034 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
8035 if (ilist != null) {
8037 if (ilist.Properties != null) {
8038 foreach (Indexers.Indexer ix in ilist.Properties) {
8039 if (ix.Setter != null)
8040 AllSetters.Add(ix.Setter);
8044 if (AllSetters.Count > 0) {
8045 found_any_setters = true;
8046 set_arguments = (ArrayList) arguments.Clone ();
8047 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
8048 set = (MethodInfo) Invocation.OverloadResolve (
8049 ec, new MethodGroupExpr (AllSetters, loc),
8050 set_arguments, false, loc);
8054 Report.Error (21, loc,
8055 "Type `" + TypeManager.CSharpName (indexer_type) +
8056 "' does not have any indexers defined");
8060 if (!found_any_setters) {
8061 Error (154, "indexer can not be used in this context, because " +
8062 "it lacks a `set' accessor");
8067 Error (1501, "No Overload for method `this' takes `" +
8068 arguments.Count + "' arguments");
8073 // Only base will allow this invocation to happen.
8075 if (set.IsAbstract && this is BaseIndexerAccess){
8076 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
8081 // Now look for the actual match in the list of indexers to set our "return" type
8083 type = TypeManager.void_type; // default value
8084 foreach (Indexers.Indexer ix in ilist.Properties){
8085 if (ix.Setter == set){
8091 eclass = ExprClass.IndexerAccess;
8095 bool prepared = false;
8096 LocalTemporary temp;
8098 public void Emit (EmitContext ec, bool leave_copy)
8100 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc, prepared, false);
8102 ec.ig.Emit (OpCodes.Dup);
8103 temp = new LocalTemporary (ec, Type);
8109 // source is ignored, because we already have a copy of it from the
8110 // LValue resolution and we have already constructed a pre-cached
8111 // version of the arguments (ea.set_arguments);
8113 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8115 prepared = prepare_for_load;
8116 Argument a = (Argument) set_arguments [set_arguments.Count - 1];
8121 ec.ig.Emit (OpCodes.Dup);
8122 temp = new LocalTemporary (ec, Type);
8125 } else if (leave_copy) {
8126 temp = new LocalTemporary (ec, Type);
8132 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc, false, prepared);
8139 public override void Emit (EmitContext ec)
8146 /// The base operator for method names
8148 public class BaseAccess : Expression {
8151 public BaseAccess (string member, Location l)
8153 this.member = member;
8157 public override Expression DoResolve (EmitContext ec)
8159 Expression c = CommonResolve (ec);
8165 // MethodGroups use this opportunity to flag an error on lacking ()
8167 if (!(c is MethodGroupExpr))
8168 return c.Resolve (ec);
8172 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8174 Expression c = CommonResolve (ec);
8180 // MethodGroups use this opportunity to flag an error on lacking ()
8182 if (! (c is MethodGroupExpr))
8183 return c.DoResolveLValue (ec, right_side);
8188 Expression CommonResolve (EmitContext ec)
8190 Expression member_lookup;
8191 Type current_type = ec.ContainerType;
8192 Type base_type = current_type.BaseType;
8196 Error (1511, "Keyword base is not allowed in static method");
8200 if (ec.IsFieldInitializer){
8201 Error (1512, "Keyword base is not available in the current context");
8205 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type, member,
8206 AllMemberTypes, AllBindingFlags, loc);
8207 if (member_lookup == null) {
8208 MemberLookupFailed (ec, base_type, base_type, member, null, loc);
8215 left = new TypeExpression (base_type, loc);
8217 left = ec.GetThis (loc);
8219 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
8221 if (e is PropertyExpr){
8222 PropertyExpr pe = (PropertyExpr) e;
8227 if (e is MethodGroupExpr)
8228 ((MethodGroupExpr) e).IsBase = true;
8233 public override void Emit (EmitContext ec)
8235 throw new Exception ("Should never be called");
8240 /// The base indexer operator
8242 public class BaseIndexerAccess : IndexerAccess {
8243 public BaseIndexerAccess (ArrayList args, Location loc)
8244 : base (null, true, loc)
8246 arguments = new ArrayList ();
8247 foreach (Expression tmp in args)
8248 arguments.Add (new Argument (tmp, Argument.AType.Expression));
8251 protected override bool CommonResolve (EmitContext ec)
8253 instance_expr = ec.GetThis (loc);
8255 current_type = ec.ContainerType.BaseType;
8256 indexer_type = current_type;
8258 foreach (Argument a in arguments){
8259 if (!a.Resolve (ec, loc))
8268 /// This class exists solely to pass the Type around and to be a dummy
8269 /// that can be passed to the conversion functions (this is used by
8270 /// foreach implementation to typecast the object return value from
8271 /// get_Current into the proper type. All code has been generated and
8272 /// we only care about the side effect conversions to be performed
8274 /// This is also now used as a placeholder where a no-action expression
8275 /// is needed (the `New' class).
8277 public class EmptyExpression : Expression {
8278 public EmptyExpression ()
8280 type = TypeManager.object_type;
8281 eclass = ExprClass.Value;
8282 loc = Location.Null;
8285 public EmptyExpression (Type t)
8288 eclass = ExprClass.Value;
8289 loc = Location.Null;
8292 public override Expression DoResolve (EmitContext ec)
8297 public override void Emit (EmitContext ec)
8299 // nothing, as we only exist to not do anything.
8303 // This is just because we might want to reuse this bad boy
8304 // instead of creating gazillions of EmptyExpressions.
8305 // (CanImplicitConversion uses it)
8307 public void SetType (Type t)
8313 public class UserCast : Expression {
8317 public UserCast (MethodInfo method, Expression source, Location l)
8319 this.method = method;
8320 this.source = source;
8321 type = method.ReturnType;
8322 eclass = ExprClass.Value;
8326 public override Expression DoResolve (EmitContext ec)
8329 // We are born fully resolved
8334 public override void Emit (EmitContext ec)
8336 ILGenerator ig = ec.ig;
8340 if (method is MethodInfo)
8341 ig.Emit (OpCodes.Call, (MethodInfo) method);
8343 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
8349 // This class is used to "construct" the type during a typecast
8350 // operation. Since the Type.GetType class in .NET can parse
8351 // the type specification, we just use this to construct the type
8352 // one bit at a time.
8354 public class ComposedCast : TypeExpr {
8358 public ComposedCast (Expression left, string dim, Location l)
8365 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
8367 Type ltype = ec.DeclSpace.ResolveType (left, false, loc);
8371 if ((ltype == TypeManager.void_type) && (dim != "*")) {
8372 Report.Error (1547, Location,
8373 "Keyword 'void' cannot be used in this context");
8378 // ltype.Fullname is already fully qualified, so we can skip
8379 // a lot of probes, and go directly to TypeManager.LookupType
8381 string cname = ltype.FullName + dim;
8382 type = TypeManager.LookupTypeDirect (cname);
8385 // For arrays of enumerations we are having a problem
8386 // with the direct lookup. Need to investigate.
8388 // For now, fall back to the full lookup in that case.
8390 type = RootContext.LookupType (
8391 ec.DeclSpace, cname, false, loc);
8397 if (!ec.ResolvingTypeTree){
8399 // If the above flag is set, this is being invoked from the ResolveType function.
8400 // Upper layers take care of the type validity in this context.
8402 if (!ec.InUnsafe && type.IsPointer){
8408 eclass = ExprClass.Type;
8412 public override string Name {
8420 // This class is used to represent the address of an array, used
8421 // only by the Fixed statement, this is like the C "&a [0]" construct.
8423 public class ArrayPtr : Expression {
8426 public ArrayPtr (Expression array, Location l)
8428 Type array_type = TypeManager.GetElementType (array.Type);
8432 type = TypeManager.GetPointerType (array_type);
8433 eclass = ExprClass.Value;
8437 public override void Emit (EmitContext ec)
8439 ILGenerator ig = ec.ig;
8442 IntLiteral.EmitInt (ig, 0);
8443 ig.Emit (OpCodes.Ldelema, TypeManager.GetElementType (array.Type));
8446 public override Expression DoResolve (EmitContext ec)
8449 // We are born fully resolved
8456 // Used by the fixed statement
8458 public class StringPtr : Expression {
8461 public StringPtr (LocalBuilder b, Location l)
8464 eclass = ExprClass.Value;
8465 type = TypeManager.char_ptr_type;
8469 public override Expression DoResolve (EmitContext ec)
8471 // This should never be invoked, we are born in fully
8472 // initialized state.
8477 public override void Emit (EmitContext ec)
8479 ILGenerator ig = ec.ig;
8481 ig.Emit (OpCodes.Ldloc, b);
8482 ig.Emit (OpCodes.Conv_I);
8483 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
8484 ig.Emit (OpCodes.Add);
8489 // Implements the `stackalloc' keyword
8491 public class StackAlloc : Expression {
8496 public StackAlloc (Expression type, Expression count, Location l)
8503 public override Expression DoResolve (EmitContext ec)
8505 count = count.Resolve (ec);
8509 if (count.Type != TypeManager.int32_type){
8510 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8515 Constant c = count as Constant;
8516 // TODO: because we don't have property IsNegative
8517 if (c != null && c.ConvertToUInt () == null) {
8518 Report.Error (247, loc, "Cannot use a negative size with stackalloc");
8522 if (ec.CurrentBranching.InCatch () ||
8523 ec.CurrentBranching.InFinally (true)) {
8525 "stackalloc can not be used in a catch or finally block");
8529 otype = ec.DeclSpace.ResolveType (t, false, loc);
8534 if (!TypeManager.VerifyUnManaged (otype, loc))
8537 type = TypeManager.GetPointerType (otype);
8538 eclass = ExprClass.Value;
8543 public override void Emit (EmitContext ec)
8545 int size = GetTypeSize (otype);
8546 ILGenerator ig = ec.ig;
8549 ig.Emit (OpCodes.Sizeof, otype);
8551 IntConstant.EmitInt (ig, size);
8553 ig.Emit (OpCodes.Mul);
8554 ig.Emit (OpCodes.Localloc);