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 (ec, (MethodGroupExpr) mg, args, loc);
74 return new StaticCallExpr ((MethodInfo) method, args, loc);
77 public override void EmitStatement (EmitContext ec)
80 if (TypeManager.TypeToCoreType (type) != TypeManager.void_type)
81 ec.ig.Emit (OpCodes.Pop);
84 public MethodInfo Method {
89 public class ParenthesizedExpression : Expression
91 public Expression Expr;
93 public ParenthesizedExpression (Expression expr, Location loc)
99 public override Expression DoResolve (EmitContext ec)
101 Expr = Expr.Resolve (ec);
105 public override void Emit (EmitContext ec)
107 throw new Exception ("Should not happen");
112 /// Unary expressions.
116 /// Unary implements unary expressions. It derives from
117 /// ExpressionStatement becuase the pre/post increment/decrement
118 /// operators can be used in a statement context.
120 public class Unary : Expression {
121 public enum Operator : byte {
122 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
123 Indirection, AddressOf, TOP
126 public Operator Oper;
127 public Expression Expr;
129 public Unary (Operator op, Expression expr, Location loc)
137 /// Returns a stringified representation of the Operator
139 static public string OperName (Operator oper)
142 case Operator.UnaryPlus:
144 case Operator.UnaryNegation:
146 case Operator.LogicalNot:
148 case Operator.OnesComplement:
150 case Operator.AddressOf:
152 case Operator.Indirection:
156 return oper.ToString ();
159 public static readonly string [] oper_names;
163 oper_names = new string [(int)Operator.TOP];
165 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
166 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
167 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
168 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
169 oper_names [(int) Operator.Indirection] = "op_Indirection";
170 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
173 void Error23 (Type t)
176 23, "Operator " + OperName (Oper) +
177 " cannot be applied to operand of type `" +
178 TypeManager.CSharpName (t) + "'");
182 /// The result has been already resolved:
184 /// FIXME: a minus constant -128 sbyte cant be turned into a
187 static Expression TryReduceNegative (Constant expr)
191 if (expr is IntConstant)
192 e = new IntConstant (-((IntConstant) expr).Value);
193 else if (expr is UIntConstant){
194 uint value = ((UIntConstant) expr).Value;
196 if (value < 2147483649)
197 return new IntConstant (-(int)value);
199 e = new LongConstant (-value);
201 else if (expr is LongConstant)
202 e = new LongConstant (-((LongConstant) expr).Value);
203 else if (expr is ULongConstant){
204 ulong value = ((ULongConstant) expr).Value;
206 if (value < 9223372036854775809)
207 return new LongConstant(-(long)value);
209 else if (expr is FloatConstant)
210 e = new FloatConstant (-((FloatConstant) expr).Value);
211 else if (expr is DoubleConstant)
212 e = new DoubleConstant (-((DoubleConstant) expr).Value);
213 else if (expr is DecimalConstant)
214 e = new DecimalConstant (-((DecimalConstant) expr).Value);
215 else if (expr is ShortConstant)
216 e = new IntConstant (-((ShortConstant) expr).Value);
217 else if (expr is UShortConstant)
218 e = new IntConstant (-((UShortConstant) expr).Value);
223 // This routine will attempt to simplify the unary expression when the
224 // argument is a constant. The result is returned in `result' and the
225 // function returns true or false depending on whether a reduction
226 // was performed or not
228 bool Reduce (EmitContext ec, Constant e, out Expression result)
230 Type expr_type = e.Type;
233 case Operator.UnaryPlus:
237 case Operator.UnaryNegation:
238 result = TryReduceNegative (e);
241 case Operator.LogicalNot:
242 if (expr_type != TypeManager.bool_type) {
248 BoolConstant b = (BoolConstant) e;
249 result = new BoolConstant (!(b.Value));
252 case Operator.OnesComplement:
253 if (!((expr_type == TypeManager.int32_type) ||
254 (expr_type == TypeManager.uint32_type) ||
255 (expr_type == TypeManager.int64_type) ||
256 (expr_type == TypeManager.uint64_type) ||
257 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
260 if (Convert.ImplicitConversionExists (ec, e, TypeManager.int32_type)){
261 result = new Cast (new TypeExpression (TypeManager.int32_type, loc), e, loc);
262 result = result.Resolve (ec);
263 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint32_type)){
264 result = new Cast (new TypeExpression (TypeManager.uint32_type, loc), e, loc);
265 result = result.Resolve (ec);
266 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.int64_type)){
267 result = new Cast (new TypeExpression (TypeManager.int64_type, loc), e, loc);
268 result = result.Resolve (ec);
269 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint64_type)){
270 result = new Cast (new TypeExpression (TypeManager.uint64_type, loc), e, loc);
271 result = result.Resolve (ec);
274 if (result == null || !(result is Constant)){
280 expr_type = result.Type;
281 e = (Constant) result;
284 if (e is EnumConstant){
285 EnumConstant enum_constant = (EnumConstant) e;
288 if (Reduce (ec, enum_constant.Child, out reduced)){
289 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
297 if (expr_type == TypeManager.int32_type){
298 result = new IntConstant (~ ((IntConstant) e).Value);
299 } else if (expr_type == TypeManager.uint32_type){
300 result = new UIntConstant (~ ((UIntConstant) e).Value);
301 } else if (expr_type == TypeManager.int64_type){
302 result = new LongConstant (~ ((LongConstant) e).Value);
303 } else if (expr_type == TypeManager.uint64_type){
304 result = new ULongConstant (~ ((ULongConstant) e).Value);
312 case Operator.AddressOf:
316 case Operator.Indirection:
320 throw new Exception ("Can not constant fold: " + Oper.ToString());
323 Expression ResolveOperator (EmitContext ec)
325 Type expr_type = Expr.Type;
328 // Step 1: Perform Operator Overload location
333 op_name = oper_names [(int) Oper];
335 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
338 Expression e = StaticCallExpr.MakeSimpleCall (
339 ec, (MethodGroupExpr) mg, Expr, loc);
349 // Only perform numeric promotions on:
352 if (expr_type == null)
356 // Step 2: Default operations on CLI native types.
359 // Attempt to use a constant folding operation.
360 if (Expr is Constant){
363 if (Reduce (ec, (Constant) Expr, out result))
368 case Operator.LogicalNot:
369 if (expr_type != TypeManager.bool_type) {
370 Expr = ResolveBoolean (ec, Expr, loc);
377 type = TypeManager.bool_type;
380 case Operator.OnesComplement:
381 if (!((expr_type == TypeManager.int32_type) ||
382 (expr_type == TypeManager.uint32_type) ||
383 (expr_type == TypeManager.int64_type) ||
384 (expr_type == TypeManager.uint64_type) ||
385 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
388 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
390 type = TypeManager.int32_type;
393 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint32_type, loc);
395 type = TypeManager.uint32_type;
398 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
400 type = TypeManager.int64_type;
403 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint64_type, loc);
405 type = TypeManager.uint64_type;
414 case Operator.AddressOf:
415 if (Expr.eclass != ExprClass.Variable){
416 Error (211, "Cannot take the address of non-variables");
425 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
429 IVariable variable = Expr as IVariable;
430 if (!ec.InFixedInitializer && ((variable == null) || !variable.VerifyFixed (false))) {
431 Error (212, "You can only take the address of an unfixed expression inside " +
432 "of a fixed statement initializer");
436 if (ec.InFixedInitializer && ((variable != null) && variable.VerifyFixed (false))) {
437 Error (213, "You can not fix an already fixed expression");
441 // According to the specs, a variable is considered definitely assigned if you take
443 if ((variable != null) && (variable.VariableInfo != null))
444 variable.VariableInfo.SetAssigned (ec);
446 type = TypeManager.GetPointerType (Expr.Type);
449 case Operator.Indirection:
455 if (!expr_type.IsPointer){
456 Error (193, "The * or -> operator can only be applied to pointers");
461 // We create an Indirection expression, because
462 // it can implement the IMemoryLocation.
464 return new Indirection (Expr, loc);
466 case Operator.UnaryPlus:
468 // A plus in front of something is just a no-op, so return the child.
472 case Operator.UnaryNegation:
474 // Deals with -literals
475 // int operator- (int x)
476 // long operator- (long x)
477 // float operator- (float f)
478 // double operator- (double d)
479 // decimal operator- (decimal d)
481 Expression expr = null;
484 // transform - - expr into expr
487 Unary unary = (Unary) Expr;
489 if (unary.Oper == Operator.UnaryNegation)
494 // perform numeric promotions to int,
498 // The following is inneficient, because we call
499 // ImplicitConversion too many times.
501 // It is also not clear if we should convert to Float
502 // or Double initially.
504 if (expr_type == TypeManager.uint32_type){
506 // FIXME: handle exception to this rule that
507 // permits the int value -2147483648 (-2^31) to
508 // bt wrote as a decimal interger literal
510 type = TypeManager.int64_type;
511 Expr = Convert.ImplicitConversion (ec, Expr, type, loc);
515 if (expr_type == TypeManager.uint64_type){
517 // FIXME: Handle exception of `long value'
518 // -92233720368547758087 (-2^63) to be wrote as
519 // decimal integer literal.
525 if (expr_type == TypeManager.float_type){
530 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
537 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
544 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.double_type, loc);
555 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
556 TypeManager.CSharpName (expr_type) + "'");
560 public override Expression DoResolve (EmitContext ec)
562 if (Oper == Operator.AddressOf)
563 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
565 Expr = Expr.Resolve (ec);
570 eclass = ExprClass.Value;
571 return ResolveOperator (ec);
574 public override Expression DoResolveLValue (EmitContext ec, Expression right)
576 if (Oper == Operator.Indirection)
577 return base.DoResolveLValue (ec, right);
579 Error (131, "The left-hand side of an assignment must be a " +
580 "variable, property or indexer");
584 public override void Emit (EmitContext ec)
586 ILGenerator ig = ec.ig;
589 case Operator.UnaryPlus:
590 throw new Exception ("This should be caught by Resolve");
592 case Operator.UnaryNegation:
594 ig.Emit (OpCodes.Ldc_I4_0);
595 if (type == TypeManager.int64_type)
596 ig.Emit (OpCodes.Conv_U8);
598 ig.Emit (OpCodes.Sub_Ovf);
601 ig.Emit (OpCodes.Neg);
606 case Operator.LogicalNot:
608 ig.Emit (OpCodes.Ldc_I4_0);
609 ig.Emit (OpCodes.Ceq);
612 case Operator.OnesComplement:
614 ig.Emit (OpCodes.Not);
617 case Operator.AddressOf:
618 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
622 throw new Exception ("This should not happen: Operator = "
627 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
629 if (Oper == Operator.LogicalNot)
630 Expr.EmitBranchable (ec, target, !onTrue);
632 base.EmitBranchable (ec, target, onTrue);
635 public override string ToString ()
637 return "Unary (" + Oper + ", " + Expr + ")";
643 // Unary operators are turned into Indirection expressions
644 // after semantic analysis (this is so we can take the address
645 // of an indirection).
647 public class Indirection : Expression, IMemoryLocation, IAssignMethod {
649 LocalTemporary temporary;
652 public Indirection (Expression expr, Location l)
655 this.type = TypeManager.GetElementType (expr.Type);
656 eclass = ExprClass.Variable;
660 void LoadExprValue (EmitContext ec)
664 public override void Emit (EmitContext ec)
669 LoadFromPtr (ec.ig, Type);
672 public void Emit (EmitContext ec, bool leave_copy)
676 ec.ig.Emit (OpCodes.Dup);
677 temporary = new LocalTemporary (ec, expr.Type);
678 temporary.Store (ec);
682 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
684 prepared = prepare_for_load;
688 if (prepare_for_load)
689 ec.ig.Emit (OpCodes.Dup);
693 ec.ig.Emit (OpCodes.Dup);
694 temporary = new LocalTemporary (ec, expr.Type);
695 temporary.Store (ec);
698 StoreFromPtr (ec.ig, type);
700 if (temporary != null)
704 public void AddressOf (EmitContext ec, AddressOp Mode)
709 public override Expression DoResolve (EmitContext ec)
712 // Born fully resolved
717 public override string ToString ()
719 return "*(" + expr + ")";
724 /// Unary Mutator expressions (pre and post ++ and --)
728 /// UnaryMutator implements ++ and -- expressions. It derives from
729 /// ExpressionStatement becuase the pre/post increment/decrement
730 /// operators can be used in a statement context.
732 /// FIXME: Idea, we could split this up in two classes, one simpler
733 /// for the common case, and one with the extra fields for more complex
734 /// classes (indexers require temporary access; overloaded require method)
737 public class UnaryMutator : ExpressionStatement {
739 public enum Mode : byte {
746 PreDecrement = IsDecrement,
747 PostIncrement = IsPost,
748 PostDecrement = IsPost | IsDecrement
752 bool is_expr = false;
753 bool recurse = false;
758 // This is expensive for the simplest case.
760 StaticCallExpr method;
762 public UnaryMutator (Mode m, Expression e, Location l)
769 static string OperName (Mode mode)
771 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
775 void Error23 (Type t)
778 23, "Operator " + OperName (mode) +
779 " cannot be applied to operand of type `" +
780 TypeManager.CSharpName (t) + "'");
784 /// Returns whether an object of type `t' can be incremented
785 /// or decremented with add/sub (ie, basically whether we can
786 /// use pre-post incr-decr operations on it, but it is not a
787 /// System.Decimal, which we require operator overloading to catch)
789 static bool IsIncrementableNumber (Type t)
791 return (t == TypeManager.sbyte_type) ||
792 (t == TypeManager.byte_type) ||
793 (t == TypeManager.short_type) ||
794 (t == TypeManager.ushort_type) ||
795 (t == TypeManager.int32_type) ||
796 (t == TypeManager.uint32_type) ||
797 (t == TypeManager.int64_type) ||
798 (t == TypeManager.uint64_type) ||
799 (t == TypeManager.char_type) ||
800 (t.IsSubclassOf (TypeManager.enum_type)) ||
801 (t == TypeManager.float_type) ||
802 (t == TypeManager.double_type) ||
803 (t.IsPointer && t != TypeManager.void_ptr_type);
806 Expression ResolveOperator (EmitContext ec)
808 Type expr_type = expr.Type;
811 // Step 1: Perform Operator Overload location
816 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
817 op_name = "op_Increment";
819 op_name = "op_Decrement";
821 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
823 if (mg == null && expr_type.BaseType != null)
824 mg = MemberLookup (ec, expr_type.BaseType, op_name,
825 MemberTypes.Method, AllBindingFlags, loc);
828 method = StaticCallExpr.MakeSimpleCall (
829 ec, (MethodGroupExpr) mg, expr, loc);
836 // The operand of the prefix/postfix increment decrement operators
837 // should be an expression that is classified as a variable,
838 // a property access or an indexer access
841 if (expr.eclass == ExprClass.Variable){
842 LocalVariableReference var = expr as LocalVariableReference;
843 if ((var != null) && var.IsReadOnly)
844 Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
845 if (IsIncrementableNumber (expr_type) ||
846 expr_type == TypeManager.decimal_type){
849 } else if (expr.eclass == ExprClass.IndexerAccess){
850 IndexerAccess ia = (IndexerAccess) expr;
852 expr = ia.ResolveLValue (ec, this);
857 } else if (expr.eclass == ExprClass.PropertyAccess){
858 PropertyExpr pe = (PropertyExpr) expr;
860 if (pe.VerifyAssignable ())
865 expr.Error_UnexpectedKind ("variable, indexer or property access");
869 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
870 TypeManager.CSharpName (expr_type) + "'");
874 public override Expression DoResolve (EmitContext ec)
876 expr = expr.Resolve (ec);
881 eclass = ExprClass.Value;
882 return ResolveOperator (ec);
885 static int PtrTypeSize (Type t)
887 return GetTypeSize (TypeManager.GetElementType (t));
891 // Loads the proper "1" into the stack based on the type, then it emits the
892 // opcode for the operation requested
894 void LoadOneAndEmitOp (EmitContext ec, Type t)
897 // Measure if getting the typecode and using that is more/less efficient
898 // that comparing types. t.GetTypeCode() is an internal call.
900 ILGenerator ig = ec.ig;
902 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
903 LongConstant.EmitLong (ig, 1);
904 else if (t == TypeManager.double_type)
905 ig.Emit (OpCodes.Ldc_R8, 1.0);
906 else if (t == TypeManager.float_type)
907 ig.Emit (OpCodes.Ldc_R4, 1.0F);
908 else if (t.IsPointer){
909 int n = PtrTypeSize (t);
912 ig.Emit (OpCodes.Sizeof, t);
914 IntConstant.EmitInt (ig, n);
916 ig.Emit (OpCodes.Ldc_I4_1);
919 // Now emit the operation
922 if (t == TypeManager.int32_type ||
923 t == TypeManager.int64_type){
924 if ((mode & Mode.IsDecrement) != 0)
925 ig.Emit (OpCodes.Sub_Ovf);
927 ig.Emit (OpCodes.Add_Ovf);
928 } else if (t == TypeManager.uint32_type ||
929 t == TypeManager.uint64_type){
930 if ((mode & Mode.IsDecrement) != 0)
931 ig.Emit (OpCodes.Sub_Ovf_Un);
933 ig.Emit (OpCodes.Add_Ovf_Un);
935 if ((mode & Mode.IsDecrement) != 0)
936 ig.Emit (OpCodes.Sub_Ovf);
938 ig.Emit (OpCodes.Add_Ovf);
941 if ((mode & Mode.IsDecrement) != 0)
942 ig.Emit (OpCodes.Sub);
944 ig.Emit (OpCodes.Add);
947 if (t == TypeManager.sbyte_type){
949 ig.Emit (OpCodes.Conv_Ovf_I1);
951 ig.Emit (OpCodes.Conv_I1);
952 } else if (t == TypeManager.byte_type){
954 ig.Emit (OpCodes.Conv_Ovf_U1);
956 ig.Emit (OpCodes.Conv_U1);
957 } else if (t == TypeManager.short_type){
959 ig.Emit (OpCodes.Conv_Ovf_I2);
961 ig.Emit (OpCodes.Conv_I2);
962 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
964 ig.Emit (OpCodes.Conv_Ovf_U2);
966 ig.Emit (OpCodes.Conv_U2);
971 void EmitCode (EmitContext ec, bool is_expr)
974 this.is_expr = is_expr;
975 ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
979 public override void Emit (EmitContext ec)
982 // We use recurse to allow ourselfs to be the source
983 // of an assignment. This little hack prevents us from
984 // having to allocate another expression
987 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
989 LoadOneAndEmitOp (ec, expr.Type);
991 ec.ig.Emit (OpCodes.Call, method.Method);
999 public override void EmitStatement (EmitContext ec)
1001 EmitCode (ec, false);
1006 /// Base class for the `Is' and `As' classes.
1010 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1013 public abstract class Probe : Expression {
1014 public readonly Expression ProbeType;
1015 protected Expression expr;
1016 protected Type probe_type;
1018 public Probe (Expression expr, Expression probe_type, Location l)
1020 ProbeType = probe_type;
1025 public Expression Expr {
1031 public override Expression DoResolve (EmitContext ec)
1033 probe_type = ec.DeclSpace.ResolveType (ProbeType, false, loc);
1035 if (probe_type == null)
1038 CheckObsoleteAttribute (probe_type);
1040 expr = expr.Resolve (ec);
1049 /// Implementation of the `is' operator.
1051 public class Is : Probe {
1052 public Is (Expression expr, Expression probe_type, Location l)
1053 : base (expr, probe_type, l)
1058 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1063 public override void Emit (EmitContext ec)
1065 ILGenerator ig = ec.ig;
1070 case Action.AlwaysFalse:
1071 ig.Emit (OpCodes.Pop);
1072 IntConstant.EmitInt (ig, 0);
1074 case Action.AlwaysTrue:
1075 ig.Emit (OpCodes.Pop);
1076 IntConstant.EmitInt (ig, 1);
1078 case Action.LeaveOnStack:
1079 // the `e != null' rule.
1080 ig.Emit (OpCodes.Ldnull);
1081 ig.Emit (OpCodes.Ceq);
1082 ig.Emit (OpCodes.Ldc_I4_0);
1083 ig.Emit (OpCodes.Ceq);
1086 ig.Emit (OpCodes.Isinst, probe_type);
1087 ig.Emit (OpCodes.Ldnull);
1088 ig.Emit (OpCodes.Cgt_Un);
1091 throw new Exception ("never reached");
1094 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
1096 ILGenerator ig = ec.ig;
1099 case Action.AlwaysFalse:
1101 ig.Emit (OpCodes.Br, target);
1104 case Action.AlwaysTrue:
1106 ig.Emit (OpCodes.Br, target);
1109 case Action.LeaveOnStack:
1110 // the `e != null' rule.
1112 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1116 ig.Emit (OpCodes.Isinst, probe_type);
1117 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1120 throw new Exception ("never reached");
1123 public override Expression DoResolve (EmitContext ec)
1125 Expression e = base.DoResolve (ec);
1127 if ((e == null) || (expr == null))
1130 Type etype = expr.Type;
1131 bool warning_always_matches = false;
1132 bool warning_never_matches = false;
1134 type = TypeManager.bool_type;
1135 eclass = ExprClass.Value;
1138 // First case, if at compile time, there is an implicit conversion
1139 // then e != null (objects) or true (value types)
1141 e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1144 if (etype.IsValueType)
1145 action = Action.AlwaysTrue;
1147 action = Action.LeaveOnStack;
1149 warning_always_matches = true;
1150 } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1152 // Second case: explicit reference convresion
1154 if (expr is NullLiteral)
1155 action = Action.AlwaysFalse;
1157 action = Action.Probe;
1159 action = Action.AlwaysFalse;
1160 warning_never_matches = true;
1163 if (warning_always_matches)
1164 Warning (183, "The given expression is always of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1165 else if (warning_never_matches){
1166 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1167 Warning (184, "The given expression is never of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1175 /// Implementation of the `as' operator.
1177 public class As : Probe {
1178 public As (Expression expr, Expression probe_type, Location l)
1179 : base (expr, probe_type, l)
1183 bool do_isinst = false;
1185 public override void Emit (EmitContext ec)
1187 ILGenerator ig = ec.ig;
1192 ig.Emit (OpCodes.Isinst, probe_type);
1195 static void Error_CannotConvertType (Type source, Type target, Location loc)
1198 39, loc, "as operator can not convert from `" +
1199 TypeManager.CSharpName (source) + "' to `" +
1200 TypeManager.CSharpName (target) + "'");
1203 public override Expression DoResolve (EmitContext ec)
1205 Expression e = base.DoResolve (ec);
1211 eclass = ExprClass.Value;
1212 Type etype = expr.Type;
1214 if (TypeManager.IsValueType (probe_type)){
1215 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1216 TypeManager.CSharpName (probe_type) + " is a value type)");
1221 e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1228 if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1233 Error_CannotConvertType (etype, probe_type, loc);
1239 /// This represents a typecast in the source language.
1241 /// FIXME: Cast expressions have an unusual set of parsing
1242 /// rules, we need to figure those out.
1244 public class Cast : Expression {
1245 Expression target_type;
1248 public Cast (Expression cast_type, Expression expr, Location loc)
1250 this.target_type = cast_type;
1255 public Expression TargetType {
1261 public Expression Expr {
1270 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1272 if (!ec.ConstantCheckState)
1275 if ((value < min) || (value > max)) {
1276 Error (221, "Constant value `" + value + "' cannot be converted " +
1277 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1278 "syntax to override)");
1285 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1287 if (!ec.ConstantCheckState)
1291 Error (221, "Constant value `" + value + "' cannot be converted " +
1292 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1293 "syntax to override)");
1300 bool CheckUnsigned (EmitContext ec, long value, Type type)
1302 if (!ec.ConstantCheckState)
1306 Error (221, "Constant value `" + value + "' cannot be converted " +
1307 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1308 "syntax to override)");
1316 /// Attempts to do a compile-time folding of a constant cast.
1318 Expression TryReduce (EmitContext ec, Type target_type)
1320 Expression real_expr = expr;
1321 if (real_expr is EnumConstant)
1322 real_expr = ((EnumConstant) real_expr).Child;
1324 if (real_expr is ByteConstant){
1325 byte v = ((ByteConstant) real_expr).Value;
1327 if (target_type == TypeManager.sbyte_type) {
1328 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1330 return new SByteConstant ((sbyte) v);
1332 if (target_type == TypeManager.short_type)
1333 return new ShortConstant ((short) v);
1334 if (target_type == TypeManager.ushort_type)
1335 return new UShortConstant ((ushort) v);
1336 if (target_type == TypeManager.int32_type)
1337 return new IntConstant ((int) v);
1338 if (target_type == TypeManager.uint32_type)
1339 return new UIntConstant ((uint) v);
1340 if (target_type == TypeManager.int64_type)
1341 return new LongConstant ((long) v);
1342 if (target_type == TypeManager.uint64_type)
1343 return new ULongConstant ((ulong) v);
1344 if (target_type == TypeManager.float_type)
1345 return new FloatConstant ((float) v);
1346 if (target_type == TypeManager.double_type)
1347 return new DoubleConstant ((double) v);
1348 if (target_type == TypeManager.char_type)
1349 return new CharConstant ((char) v);
1350 if (target_type == TypeManager.decimal_type)
1351 return new DecimalConstant ((decimal) v);
1353 if (real_expr is SByteConstant){
1354 sbyte v = ((SByteConstant) real_expr).Value;
1356 if (target_type == TypeManager.byte_type) {
1357 if (!CheckUnsigned (ec, v, target_type))
1359 return new ByteConstant ((byte) v);
1361 if (target_type == TypeManager.short_type)
1362 return new ShortConstant ((short) v);
1363 if (target_type == TypeManager.ushort_type) {
1364 if (!CheckUnsigned (ec, v, target_type))
1366 return new UShortConstant ((ushort) v);
1367 } if (target_type == TypeManager.int32_type)
1368 return new IntConstant ((int) v);
1369 if (target_type == TypeManager.uint32_type) {
1370 if (!CheckUnsigned (ec, v, target_type))
1372 return new UIntConstant ((uint) v);
1373 } if (target_type == TypeManager.int64_type)
1374 return new LongConstant ((long) v);
1375 if (target_type == TypeManager.uint64_type) {
1376 if (!CheckUnsigned (ec, v, target_type))
1378 return new ULongConstant ((ulong) v);
1380 if (target_type == TypeManager.float_type)
1381 return new FloatConstant ((float) v);
1382 if (target_type == TypeManager.double_type)
1383 return new DoubleConstant ((double) v);
1384 if (target_type == TypeManager.char_type) {
1385 if (!CheckUnsigned (ec, v, target_type))
1387 return new CharConstant ((char) v);
1389 if (target_type == TypeManager.decimal_type)
1390 return new DecimalConstant ((decimal) v);
1392 if (real_expr is ShortConstant){
1393 short v = ((ShortConstant) real_expr).Value;
1395 if (target_type == TypeManager.byte_type) {
1396 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1398 return new ByteConstant ((byte) v);
1400 if (target_type == TypeManager.sbyte_type) {
1401 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1403 return new SByteConstant ((sbyte) v);
1405 if (target_type == TypeManager.ushort_type) {
1406 if (!CheckUnsigned (ec, v, target_type))
1408 return new UShortConstant ((ushort) v);
1410 if (target_type == TypeManager.int32_type)
1411 return new IntConstant ((int) v);
1412 if (target_type == TypeManager.uint32_type) {
1413 if (!CheckUnsigned (ec, v, target_type))
1415 return new UIntConstant ((uint) v);
1417 if (target_type == TypeManager.int64_type)
1418 return new LongConstant ((long) v);
1419 if (target_type == TypeManager.uint64_type) {
1420 if (!CheckUnsigned (ec, v, target_type))
1422 return new ULongConstant ((ulong) v);
1424 if (target_type == TypeManager.float_type)
1425 return new FloatConstant ((float) v);
1426 if (target_type == TypeManager.double_type)
1427 return new DoubleConstant ((double) v);
1428 if (target_type == TypeManager.char_type) {
1429 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1431 return new CharConstant ((char) v);
1433 if (target_type == TypeManager.decimal_type)
1434 return new DecimalConstant ((decimal) v);
1436 if (real_expr is UShortConstant){
1437 ushort v = ((UShortConstant) real_expr).Value;
1439 if (target_type == TypeManager.byte_type) {
1440 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1442 return new ByteConstant ((byte) v);
1444 if (target_type == TypeManager.sbyte_type) {
1445 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1447 return new SByteConstant ((sbyte) v);
1449 if (target_type == TypeManager.short_type) {
1450 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1452 return new ShortConstant ((short) v);
1454 if (target_type == TypeManager.int32_type)
1455 return new IntConstant ((int) v);
1456 if (target_type == TypeManager.uint32_type)
1457 return new UIntConstant ((uint) v);
1458 if (target_type == TypeManager.int64_type)
1459 return new LongConstant ((long) v);
1460 if (target_type == TypeManager.uint64_type)
1461 return new ULongConstant ((ulong) v);
1462 if (target_type == TypeManager.float_type)
1463 return new FloatConstant ((float) v);
1464 if (target_type == TypeManager.double_type)
1465 return new DoubleConstant ((double) v);
1466 if (target_type == TypeManager.char_type) {
1467 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1469 return new CharConstant ((char) v);
1471 if (target_type == TypeManager.decimal_type)
1472 return new DecimalConstant ((decimal) v);
1474 if (real_expr is IntConstant){
1475 int v = ((IntConstant) real_expr).Value;
1477 if (target_type == TypeManager.byte_type) {
1478 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1480 return new ByteConstant ((byte) v);
1482 if (target_type == TypeManager.sbyte_type) {
1483 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1485 return new SByteConstant ((sbyte) v);
1487 if (target_type == TypeManager.short_type) {
1488 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1490 return new ShortConstant ((short) v);
1492 if (target_type == TypeManager.ushort_type) {
1493 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1495 return new UShortConstant ((ushort) v);
1497 if (target_type == TypeManager.uint32_type) {
1498 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1500 return new UIntConstant ((uint) v);
1502 if (target_type == TypeManager.int64_type)
1503 return new LongConstant ((long) v);
1504 if (target_type == TypeManager.uint64_type) {
1505 if (!CheckUnsigned (ec, v, target_type))
1507 return new ULongConstant ((ulong) v);
1509 if (target_type == TypeManager.float_type)
1510 return new FloatConstant ((float) v);
1511 if (target_type == TypeManager.double_type)
1512 return new DoubleConstant ((double) v);
1513 if (target_type == TypeManager.char_type) {
1514 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1516 return new CharConstant ((char) v);
1518 if (target_type == TypeManager.decimal_type)
1519 return new DecimalConstant ((decimal) v);
1521 if (real_expr is UIntConstant){
1522 uint v = ((UIntConstant) real_expr).Value;
1524 if (target_type == TypeManager.byte_type) {
1525 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1527 return new ByteConstant ((byte) v);
1529 if (target_type == TypeManager.sbyte_type) {
1530 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1532 return new SByteConstant ((sbyte) v);
1534 if (target_type == TypeManager.short_type) {
1535 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1537 return new ShortConstant ((short) v);
1539 if (target_type == TypeManager.ushort_type) {
1540 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1542 return new UShortConstant ((ushort) v);
1544 if (target_type == TypeManager.int32_type) {
1545 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1547 return new IntConstant ((int) v);
1549 if (target_type == TypeManager.int64_type)
1550 return new LongConstant ((long) v);
1551 if (target_type == TypeManager.uint64_type)
1552 return new ULongConstant ((ulong) v);
1553 if (target_type == TypeManager.float_type)
1554 return new FloatConstant ((float) v);
1555 if (target_type == TypeManager.double_type)
1556 return new DoubleConstant ((double) v);
1557 if (target_type == TypeManager.char_type) {
1558 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1560 return new CharConstant ((char) v);
1562 if (target_type == TypeManager.decimal_type)
1563 return new DecimalConstant ((decimal) v);
1565 if (real_expr is LongConstant){
1566 long v = ((LongConstant) real_expr).Value;
1568 if (target_type == TypeManager.byte_type) {
1569 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1571 return new ByteConstant ((byte) v);
1573 if (target_type == TypeManager.sbyte_type) {
1574 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1576 return new SByteConstant ((sbyte) v);
1578 if (target_type == TypeManager.short_type) {
1579 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1581 return new ShortConstant ((short) v);
1583 if (target_type == TypeManager.ushort_type) {
1584 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1586 return new UShortConstant ((ushort) v);
1588 if (target_type == TypeManager.int32_type) {
1589 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1591 return new IntConstant ((int) v);
1593 if (target_type == TypeManager.uint32_type) {
1594 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1596 return new UIntConstant ((uint) v);
1598 if (target_type == TypeManager.uint64_type) {
1599 if (!CheckUnsigned (ec, v, target_type))
1601 return new ULongConstant ((ulong) v);
1603 if (target_type == TypeManager.float_type)
1604 return new FloatConstant ((float) v);
1605 if (target_type == TypeManager.double_type)
1606 return new DoubleConstant ((double) v);
1607 if (target_type == TypeManager.char_type) {
1608 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1610 return new CharConstant ((char) v);
1612 if (target_type == TypeManager.decimal_type)
1613 return new DecimalConstant ((decimal) v);
1615 if (real_expr is ULongConstant){
1616 ulong v = ((ULongConstant) real_expr).Value;
1618 if (target_type == TypeManager.byte_type) {
1619 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1621 return new ByteConstant ((byte) v);
1623 if (target_type == TypeManager.sbyte_type) {
1624 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1626 return new SByteConstant ((sbyte) v);
1628 if (target_type == TypeManager.short_type) {
1629 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1631 return new ShortConstant ((short) v);
1633 if (target_type == TypeManager.ushort_type) {
1634 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1636 return new UShortConstant ((ushort) v);
1638 if (target_type == TypeManager.int32_type) {
1639 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1641 return new IntConstant ((int) v);
1643 if (target_type == TypeManager.uint32_type) {
1644 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1646 return new UIntConstant ((uint) v);
1648 if (target_type == TypeManager.int64_type) {
1649 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1651 return new LongConstant ((long) v);
1653 if (target_type == TypeManager.float_type)
1654 return new FloatConstant ((float) v);
1655 if (target_type == TypeManager.double_type)
1656 return new DoubleConstant ((double) v);
1657 if (target_type == TypeManager.char_type) {
1658 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1660 return new CharConstant ((char) v);
1662 if (target_type == TypeManager.decimal_type)
1663 return new DecimalConstant ((decimal) v);
1665 if (real_expr is FloatConstant){
1666 float v = ((FloatConstant) real_expr).Value;
1668 if (target_type == TypeManager.byte_type)
1669 return new ByteConstant ((byte) v);
1670 if (target_type == TypeManager.sbyte_type)
1671 return new SByteConstant ((sbyte) v);
1672 if (target_type == TypeManager.short_type)
1673 return new ShortConstant ((short) v);
1674 if (target_type == TypeManager.ushort_type)
1675 return new UShortConstant ((ushort) v);
1676 if (target_type == TypeManager.int32_type)
1677 return new IntConstant ((int) v);
1678 if (target_type == TypeManager.uint32_type)
1679 return new UIntConstant ((uint) v);
1680 if (target_type == TypeManager.int64_type)
1681 return new LongConstant ((long) v);
1682 if (target_type == TypeManager.uint64_type)
1683 return new ULongConstant ((ulong) v);
1684 if (target_type == TypeManager.double_type)
1685 return new DoubleConstant ((double) v);
1686 if (target_type == TypeManager.char_type)
1687 return new CharConstant ((char) v);
1688 if (target_type == TypeManager.decimal_type)
1689 return new DecimalConstant ((decimal) v);
1691 if (real_expr is DoubleConstant){
1692 double v = ((DoubleConstant) real_expr).Value;
1694 if (target_type == TypeManager.byte_type){
1695 return new ByteConstant ((byte) v);
1696 } if (target_type == TypeManager.sbyte_type)
1697 return new SByteConstant ((sbyte) v);
1698 if (target_type == TypeManager.short_type)
1699 return new ShortConstant ((short) v);
1700 if (target_type == TypeManager.ushort_type)
1701 return new UShortConstant ((ushort) v);
1702 if (target_type == TypeManager.int32_type)
1703 return new IntConstant ((int) v);
1704 if (target_type == TypeManager.uint32_type)
1705 return new UIntConstant ((uint) v);
1706 if (target_type == TypeManager.int64_type)
1707 return new LongConstant ((long) v);
1708 if (target_type == TypeManager.uint64_type)
1709 return new ULongConstant ((ulong) v);
1710 if (target_type == TypeManager.float_type)
1711 return new FloatConstant ((float) v);
1712 if (target_type == TypeManager.char_type)
1713 return new CharConstant ((char) v);
1714 if (target_type == TypeManager.decimal_type)
1715 return new DecimalConstant ((decimal) v);
1718 if (real_expr is CharConstant){
1719 char v = ((CharConstant) real_expr).Value;
1721 if (target_type == TypeManager.byte_type) {
1722 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1724 return new ByteConstant ((byte) v);
1726 if (target_type == TypeManager.sbyte_type) {
1727 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1729 return new SByteConstant ((sbyte) v);
1731 if (target_type == TypeManager.short_type) {
1732 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1734 return new ShortConstant ((short) v);
1736 if (target_type == TypeManager.int32_type)
1737 return new IntConstant ((int) v);
1738 if (target_type == TypeManager.uint32_type)
1739 return new UIntConstant ((uint) v);
1740 if (target_type == TypeManager.int64_type)
1741 return new LongConstant ((long) v);
1742 if (target_type == TypeManager.uint64_type)
1743 return new ULongConstant ((ulong) v);
1744 if (target_type == TypeManager.float_type)
1745 return new FloatConstant ((float) v);
1746 if (target_type == TypeManager.double_type)
1747 return new DoubleConstant ((double) v);
1748 if (target_type == TypeManager.char_type) {
1749 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1751 return new CharConstant ((char) v);
1753 if (target_type == TypeManager.decimal_type)
1754 return new DecimalConstant ((decimal) v);
1760 public override Expression DoResolve (EmitContext ec)
1762 expr = expr.Resolve (ec);
1766 type = ec.DeclSpace.ResolveType (target_type, false, Location);
1771 CheckObsoleteAttribute (type);
1773 eclass = ExprClass.Value;
1775 if (expr is Constant){
1776 Expression e = TryReduce (ec, type);
1782 if (type.IsPointer && !ec.InUnsafe) {
1786 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1790 public override void Emit (EmitContext ec)
1793 // This one will never happen
1795 throw new Exception ("Should not happen");
1800 /// Binary operators
1802 public class Binary : Expression {
1803 public enum Operator : byte {
1804 Multiply, Division, Modulus,
1805 Addition, Subtraction,
1806 LeftShift, RightShift,
1807 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1808 Equality, Inequality,
1818 Expression left, right;
1820 // This must be kept in sync with Operator!!!
1821 public static readonly string [] oper_names;
1825 oper_names = new string [(int) Operator.TOP];
1827 oper_names [(int) Operator.Multiply] = "op_Multiply";
1828 oper_names [(int) Operator.Division] = "op_Division";
1829 oper_names [(int) Operator.Modulus] = "op_Modulus";
1830 oper_names [(int) Operator.Addition] = "op_Addition";
1831 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1832 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1833 oper_names [(int) Operator.RightShift] = "op_RightShift";
1834 oper_names [(int) Operator.LessThan] = "op_LessThan";
1835 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1836 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1837 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1838 oper_names [(int) Operator.Equality] = "op_Equality";
1839 oper_names [(int) Operator.Inequality] = "op_Inequality";
1840 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1841 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1842 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1843 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1844 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1847 public Binary (Operator oper, Expression left, Expression right, Location loc)
1855 public Operator Oper {
1864 public Expression Left {
1873 public Expression Right {
1884 /// Returns a stringified representation of the Operator
1886 static string OperName (Operator oper)
1889 case Operator.Multiply:
1891 case Operator.Division:
1893 case Operator.Modulus:
1895 case Operator.Addition:
1897 case Operator.Subtraction:
1899 case Operator.LeftShift:
1901 case Operator.RightShift:
1903 case Operator.LessThan:
1905 case Operator.GreaterThan:
1907 case Operator.LessThanOrEqual:
1909 case Operator.GreaterThanOrEqual:
1911 case Operator.Equality:
1913 case Operator.Inequality:
1915 case Operator.BitwiseAnd:
1917 case Operator.BitwiseOr:
1919 case Operator.ExclusiveOr:
1921 case Operator.LogicalOr:
1923 case Operator.LogicalAnd:
1927 return oper.ToString ();
1930 public override string ToString ()
1932 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1933 right.ToString () + ")";
1936 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1938 if (expr.Type == target_type)
1941 return Convert.ImplicitConversion (ec, expr, target_type, loc);
1944 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1947 34, loc, "Operator `" + OperName (oper)
1948 + "' is ambiguous on operands of type `"
1949 + TypeManager.CSharpName (l) + "' "
1950 + "and `" + TypeManager.CSharpName (r)
1954 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
1956 if ((l == t) || (r == t))
1959 if (!check_user_conversions)
1962 if (Convert.ImplicitUserConversionExists (ec, l, t))
1964 else if (Convert.ImplicitUserConversionExists (ec, r, t))
1971 // Note that handling the case l == Decimal || r == Decimal
1972 // is taken care of by the Step 1 Operator Overload resolution.
1974 // If `check_user_conv' is true, we also check whether a user-defined conversion
1975 // exists. Note that we only need to do this if both arguments are of a user-defined
1976 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
1977 // so we don't explicitly check for performance reasons.
1979 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
1981 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
1983 // If either operand is of type double, the other operand is
1984 // conveted to type double.
1986 if (r != TypeManager.double_type)
1987 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
1988 if (l != TypeManager.double_type)
1989 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
1991 type = TypeManager.double_type;
1992 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
1994 // if either operand is of type float, the other operand is
1995 // converted to type float.
1997 if (r != TypeManager.double_type)
1998 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
1999 if (l != TypeManager.double_type)
2000 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
2001 type = TypeManager.float_type;
2002 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2006 // If either operand is of type ulong, the other operand is
2007 // converted to type ulong. or an error ocurrs if the other
2008 // operand is of type sbyte, short, int or long
2010 if (l == TypeManager.uint64_type){
2011 if (r != TypeManager.uint64_type){
2012 if (right is IntConstant){
2013 IntConstant ic = (IntConstant) right;
2015 e = Convert.TryImplicitIntConversion (l, ic);
2018 } else if (right is LongConstant){
2019 long ll = ((LongConstant) right).Value;
2022 right = new ULongConstant ((ulong) ll);
2024 e = Convert.ImplicitNumericConversion (ec, right, l, loc);
2031 if (left is IntConstant){
2032 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
2035 } else if (left is LongConstant){
2036 long ll = ((LongConstant) left).Value;
2039 left = new ULongConstant ((ulong) ll);
2041 e = Convert.ImplicitNumericConversion (ec, left, r, loc);
2048 if ((other == TypeManager.sbyte_type) ||
2049 (other == TypeManager.short_type) ||
2050 (other == TypeManager.int32_type) ||
2051 (other == TypeManager.int64_type))
2052 Error_OperatorAmbiguous (loc, oper, l, r);
2054 left = ForceConversion (ec, left, TypeManager.uint64_type);
2055 right = ForceConversion (ec, right, TypeManager.uint64_type);
2057 type = TypeManager.uint64_type;
2058 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2060 // If either operand is of type long, the other operand is converted
2063 if (l != TypeManager.int64_type)
2064 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
2065 if (r != TypeManager.int64_type)
2066 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
2068 type = TypeManager.int64_type;
2069 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2071 // If either operand is of type uint, and the other
2072 // operand is of type sbyte, short or int, othe operands are
2073 // converted to type long (unless we have an int constant).
2077 if (l == TypeManager.uint32_type){
2078 if (right is IntConstant){
2079 IntConstant ic = (IntConstant) right;
2083 right = new UIntConstant ((uint) val);
2090 } else if (r == TypeManager.uint32_type){
2091 if (left is IntConstant){
2092 IntConstant ic = (IntConstant) left;
2096 left = new UIntConstant ((uint) val);
2105 if ((other == TypeManager.sbyte_type) ||
2106 (other == TypeManager.short_type) ||
2107 (other == TypeManager.int32_type)){
2108 left = ForceConversion (ec, left, TypeManager.int64_type);
2109 right = ForceConversion (ec, right, TypeManager.int64_type);
2110 type = TypeManager.int64_type;
2113 // if either operand is of type uint, the other
2114 // operand is converd to type uint
2116 left = ForceConversion (ec, left, TypeManager.uint32_type);
2117 right = ForceConversion (ec, right, TypeManager.uint32_type);
2118 type = TypeManager.uint32_type;
2120 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2121 if (l != TypeManager.decimal_type)
2122 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
2124 if (r != TypeManager.decimal_type)
2125 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
2126 type = TypeManager.decimal_type;
2128 left = ForceConversion (ec, left, TypeManager.int32_type);
2129 right = ForceConversion (ec, right, TypeManager.int32_type);
2131 type = TypeManager.int32_type;
2134 return (left != null) && (right != null);
2137 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2139 Report.Error (19, loc,
2140 "Operator " + name + " cannot be applied to operands of type `" +
2141 TypeManager.CSharpName (l) + "' and `" +
2142 TypeManager.CSharpName (r) + "'");
2145 void Error_OperatorCannotBeApplied ()
2147 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2150 static bool is_unsigned (Type t)
2152 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2153 t == TypeManager.short_type || t == TypeManager.byte_type);
2156 static bool is_user_defined (Type t)
2158 if (t.IsSubclassOf (TypeManager.value_type) &&
2159 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2165 Expression Make32or64 (EmitContext ec, Expression e)
2169 if (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2170 t == TypeManager.int64_type || t == TypeManager.uint64_type)
2172 Expression ee = Convert.ImplicitConversion (ec, e, TypeManager.int32_type, loc);
2175 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint32_type, loc);
2178 ee = Convert.ImplicitConversion (ec, e, TypeManager.int64_type, loc);
2181 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint64_type, loc);
2187 Expression CheckShiftArguments (EmitContext ec)
2191 e = ForceConversion (ec, right, TypeManager.int32_type);
2193 Error_OperatorCannotBeApplied ();
2198 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
2199 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
2200 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
2201 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
2205 if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
2206 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (31), loc);
2207 right = right.DoResolve (ec);
2209 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (63), loc);
2210 right = right.DoResolve (ec);
2215 Error_OperatorCannotBeApplied ();
2219 Expression ResolveOperator (EmitContext ec)
2222 Type r = right.Type;
2225 // Special cases: string comapred to null
2227 if (oper == Operator.Equality || oper == Operator.Inequality){
2228 if ((l == TypeManager.string_type && (right is NullLiteral)) ||
2229 (r == TypeManager.string_type && (left is NullLiteral))){
2230 Type = TypeManager.bool_type;
2236 if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
2237 Type = TypeManager.bool_type;
2244 // Do not perform operator overload resolution when both sides are
2247 if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
2249 // Step 1: Perform Operator Overload location
2251 Expression left_expr, right_expr;
2253 string op = oper_names [(int) oper];
2255 MethodGroupExpr union;
2256 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2258 right_expr = MemberLookup (
2259 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2260 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2262 union = (MethodGroupExpr) left_expr;
2264 if (union != null) {
2265 ArrayList args = new ArrayList (2);
2266 args.Add (new Argument (left, Argument.AType.Expression));
2267 args.Add (new Argument (right, Argument.AType.Expression));
2269 MethodBase method = Invocation.OverloadResolve (ec, union, args, Location.Null);
2270 if (method != null) {
2271 MethodInfo mi = (MethodInfo) method;
2273 return new BinaryMethod (mi.ReturnType, method, args);
2279 // Step 0: String concatenation (because overloading will get this wrong)
2281 if (oper == Operator.Addition){
2283 // If any of the arguments is a string, cast to string
2286 // Simple constant folding
2287 if (left is StringConstant && right is StringConstant)
2288 return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value);
2290 if (l == TypeManager.string_type || r == TypeManager.string_type) {
2292 if (r == TypeManager.void_type || l == TypeManager.void_type) {
2293 Error_OperatorCannotBeApplied ();
2297 // try to fold it in on the left
2298 if (left is StringConcat) {
2301 // We have to test here for not-null, since we can be doubly-resolved
2302 // take care of not appending twice
2305 type = TypeManager.string_type;
2306 ((StringConcat) left).Append (ec, right);
2307 return left.Resolve (ec);
2313 // Otherwise, start a new concat expression
2314 return new StringConcat (ec, loc, left, right).Resolve (ec);
2318 // Transform a + ( - b) into a - b
2320 if (right is Unary){
2321 Unary right_unary = (Unary) right;
2323 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2324 oper = Operator.Subtraction;
2325 right = right_unary.Expr;
2331 if (oper == Operator.Equality || oper == Operator.Inequality){
2332 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2333 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2334 Error_OperatorCannotBeApplied ();
2338 type = TypeManager.bool_type;
2343 // operator != (object a, object b)
2344 // operator == (object a, object b)
2346 // For this to be used, both arguments have to be reference-types.
2347 // Read the rationale on the spec (14.9.6)
2349 // Also, if at compile time we know that the classes do not inherit
2350 // one from the other, then we catch the error there.
2352 if (!(l.IsValueType || r.IsValueType)){
2353 type = TypeManager.bool_type;
2358 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2362 // Also, a standard conversion must exist from either one
2364 if (!(Convert.ImplicitStandardConversionExists (left, r) ||
2365 Convert.ImplicitStandardConversionExists (right, l))){
2366 Error_OperatorCannotBeApplied ();
2370 // We are going to have to convert to an object to compare
2372 if (l != TypeManager.object_type)
2373 left = new EmptyCast (left, TypeManager.object_type);
2374 if (r != TypeManager.object_type)
2375 right = new EmptyCast (right, TypeManager.object_type);
2378 // FIXME: CSC here catches errors cs254 and cs252
2384 // One of them is a valuetype, but the other one is not.
2386 if (!l.IsValueType || !r.IsValueType) {
2387 Error_OperatorCannotBeApplied ();
2392 // Only perform numeric promotions on:
2393 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2395 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2396 if (l.IsSubclassOf (TypeManager.delegate_type)){
2397 if (right.eclass == ExprClass.MethodGroup && RootContext.V2){
2398 Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2405 if (r.IsSubclassOf (TypeManager.delegate_type)){
2407 ArrayList args = new ArrayList (2);
2409 args = new ArrayList (2);
2410 args.Add (new Argument (left, Argument.AType.Expression));
2411 args.Add (new Argument (right, Argument.AType.Expression));
2413 if (oper == Operator.Addition)
2414 method = TypeManager.delegate_combine_delegate_delegate;
2416 method = TypeManager.delegate_remove_delegate_delegate;
2419 Error_OperatorCannotBeApplied ();
2423 return new BinaryDelegate (l, method, args);
2428 // Pointer arithmetic:
2430 // T* operator + (T* x, int y);
2431 // T* operator + (T* x, uint y);
2432 // T* operator + (T* x, long y);
2433 // T* operator + (T* x, ulong y);
2435 // T* operator + (int y, T* x);
2436 // T* operator + (uint y, T *x);
2437 // T* operator + (long y, T *x);
2438 // T* operator + (ulong y, T *x);
2440 // T* operator - (T* x, int y);
2441 // T* operator - (T* x, uint y);
2442 // T* operator - (T* x, long y);
2443 // T* operator - (T* x, ulong y);
2445 // long operator - (T* x, T *y)
2448 if (r.IsPointer && oper == Operator.Subtraction){
2450 return new PointerArithmetic (
2451 false, left, right, TypeManager.int64_type,
2454 Expression t = Make32or64 (ec, right);
2456 return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc).Resolve (ec);
2458 } else if (r.IsPointer && oper == Operator.Addition){
2459 Expression t = Make32or64 (ec, left);
2461 return new PointerArithmetic (true, right, t, r, loc).Resolve (ec);
2466 // Enumeration operators
2468 bool lie = TypeManager.IsEnumType (l);
2469 bool rie = TypeManager.IsEnumType (r);
2473 // U operator - (E e, E f)
2475 if (oper == Operator.Subtraction){
2477 type = TypeManager.EnumToUnderlying (l);
2480 Error_OperatorCannotBeApplied ();
2486 // operator + (E e, U x)
2487 // operator - (E e, U x)
2489 if (oper == Operator.Addition || oper == Operator.Subtraction){
2490 Type enum_type = lie ? l : r;
2491 Type other_type = lie ? r : l;
2492 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2494 if (underlying_type != other_type){
2495 temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
2505 Error_OperatorCannotBeApplied ();
2514 temp = Convert.ImplicitConversion (ec, right, l, loc);
2518 Error_OperatorCannotBeApplied ();
2522 temp = Convert.ImplicitConversion (ec, left, r, loc);
2527 Error_OperatorCannotBeApplied ();
2532 if (oper == Operator.Equality || oper == Operator.Inequality ||
2533 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2534 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2535 if (left.Type != right.Type){
2536 Error_OperatorCannotBeApplied ();
2539 type = TypeManager.bool_type;
2543 if (oper == Operator.BitwiseAnd ||
2544 oper == Operator.BitwiseOr ||
2545 oper == Operator.ExclusiveOr){
2549 Error_OperatorCannotBeApplied ();
2553 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2554 return CheckShiftArguments (ec);
2556 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2557 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2558 type = TypeManager.bool_type;
2563 Error_OperatorCannotBeApplied ();
2567 Expression e = new ConditionalLogicalOperator (
2568 oper == Operator.LogicalAnd, left, right, l, loc);
2569 return e.Resolve (ec);
2573 // operator & (bool x, bool y)
2574 // operator | (bool x, bool y)
2575 // operator ^ (bool x, bool y)
2577 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2578 if (oper == Operator.BitwiseAnd ||
2579 oper == Operator.BitwiseOr ||
2580 oper == Operator.ExclusiveOr){
2587 // Pointer comparison
2589 if (l.IsPointer && r.IsPointer){
2590 if (oper == Operator.Equality || oper == Operator.Inequality ||
2591 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2592 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2593 type = TypeManager.bool_type;
2599 // This will leave left or right set to null if there is an error
2601 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2602 DoNumericPromotions (ec, l, r, check_user_conv);
2603 if (left == null || right == null){
2604 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2609 // reload our cached types if required
2614 if (oper == Operator.BitwiseAnd ||
2615 oper == Operator.BitwiseOr ||
2616 oper == Operator.ExclusiveOr){
2618 if (((l == TypeManager.int32_type) ||
2619 (l == TypeManager.uint32_type) ||
2620 (l == TypeManager.short_type) ||
2621 (l == TypeManager.ushort_type) ||
2622 (l == TypeManager.int64_type) ||
2623 (l == TypeManager.uint64_type))){
2626 Error_OperatorCannotBeApplied ();
2630 Error_OperatorCannotBeApplied ();
2635 if (oper == Operator.Equality ||
2636 oper == Operator.Inequality ||
2637 oper == Operator.LessThanOrEqual ||
2638 oper == Operator.LessThan ||
2639 oper == Operator.GreaterThanOrEqual ||
2640 oper == Operator.GreaterThan){
2641 type = TypeManager.bool_type;
2647 public override Expression DoResolve (EmitContext ec)
2649 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2650 left = ((ParenthesizedExpression) left).Expr;
2651 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2655 if (left.eclass == ExprClass.Type) {
2656 Error (75, "Casting a negative value needs to have the value in parentheses.");
2660 left = left.Resolve (ec);
2661 right = right.Resolve (ec);
2663 if (left == null || right == null)
2666 eclass = ExprClass.Value;
2668 Constant rc = right as Constant;
2669 Constant lc = left as Constant;
2671 if (rc != null & lc != null){
2672 Expression e = ConstantFold.BinaryFold (
2673 ec, oper, lc, rc, loc);
2678 return ResolveOperator (ec);
2682 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2683 /// context of a conditional bool expression. This function will return
2684 /// false if it is was possible to use EmitBranchable, or true if it was.
2686 /// The expression's code is generated, and we will generate a branch to `target'
2687 /// if the resulting expression value is equal to isTrue
2689 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2691 ILGenerator ig = ec.ig;
2694 // This is more complicated than it looks, but its just to avoid
2695 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2696 // but on top of that we want for == and != to use a special path
2697 // if we are comparing against null
2699 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
2700 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2703 // put the constant on the rhs, for simplicity
2705 if (left is Constant) {
2706 Expression swap = right;
2711 if (((Constant) right).IsZeroInteger) {
2714 ig.Emit (OpCodes.Brtrue, target);
2716 ig.Emit (OpCodes.Brfalse, target);
2719 } else if (right is BoolConstant) {
2721 if (my_on_true != ((BoolConstant) right).Value)
2722 ig.Emit (OpCodes.Brtrue, target);
2724 ig.Emit (OpCodes.Brfalse, target);
2729 } else if (oper == Operator.LogicalAnd) {
2732 Label tests_end = ig.DefineLabel ();
2734 left.EmitBranchable (ec, tests_end, false);
2735 right.EmitBranchable (ec, target, true);
2736 ig.MarkLabel (tests_end);
2738 left.EmitBranchable (ec, target, false);
2739 right.EmitBranchable (ec, target, false);
2744 } else if (oper == Operator.LogicalOr){
2746 left.EmitBranchable (ec, target, true);
2747 right.EmitBranchable (ec, target, true);
2750 Label tests_end = ig.DefineLabel ();
2751 left.EmitBranchable (ec, tests_end, true);
2752 right.EmitBranchable (ec, target, false);
2753 ig.MarkLabel (tests_end);
2758 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2759 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2760 oper == Operator.Equality || oper == Operator.Inequality)) {
2761 base.EmitBranchable (ec, target, onTrue);
2769 bool isUnsigned = is_unsigned (t) || t == TypeManager.double_type || t == TypeManager.float_type;
2772 case Operator.Equality:
2774 ig.Emit (OpCodes.Beq, target);
2776 ig.Emit (OpCodes.Bne_Un, target);
2779 case Operator.Inequality:
2781 ig.Emit (OpCodes.Bne_Un, target);
2783 ig.Emit (OpCodes.Beq, target);
2786 case Operator.LessThan:
2789 ig.Emit (OpCodes.Blt_Un, target);
2791 ig.Emit (OpCodes.Blt, target);
2794 ig.Emit (OpCodes.Bge_Un, target);
2796 ig.Emit (OpCodes.Bge, target);
2799 case Operator.GreaterThan:
2802 ig.Emit (OpCodes.Bgt_Un, target);
2804 ig.Emit (OpCodes.Bgt, target);
2807 ig.Emit (OpCodes.Ble_Un, target);
2809 ig.Emit (OpCodes.Ble, target);
2812 case Operator.LessThanOrEqual:
2815 ig.Emit (OpCodes.Ble_Un, target);
2817 ig.Emit (OpCodes.Ble, target);
2820 ig.Emit (OpCodes.Bgt_Un, target);
2822 ig.Emit (OpCodes.Bgt, target);
2826 case Operator.GreaterThanOrEqual:
2829 ig.Emit (OpCodes.Bge_Un, target);
2831 ig.Emit (OpCodes.Bge, target);
2834 ig.Emit (OpCodes.Blt_Un, target);
2836 ig.Emit (OpCodes.Blt, target);
2839 Console.WriteLine (oper);
2840 throw new Exception ("what is THAT");
2844 public override void Emit (EmitContext ec)
2846 ILGenerator ig = ec.ig;
2851 // Handle short-circuit operators differently
2854 if (oper == Operator.LogicalAnd) {
2855 Label load_zero = ig.DefineLabel ();
2856 Label end = ig.DefineLabel ();
2858 left.EmitBranchable (ec, load_zero, false);
2860 ig.Emit (OpCodes.Br, end);
2862 ig.MarkLabel (load_zero);
2863 ig.Emit (OpCodes.Ldc_I4_0);
2866 } else if (oper == Operator.LogicalOr) {
2867 Label load_one = ig.DefineLabel ();
2868 Label end = ig.DefineLabel ();
2870 left.EmitBranchable (ec, load_one, true);
2872 ig.Emit (OpCodes.Br, end);
2874 ig.MarkLabel (load_one);
2875 ig.Emit (OpCodes.Ldc_I4_1);
2883 bool isUnsigned = is_unsigned (left.Type);
2886 case Operator.Multiply:
2888 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2889 opcode = OpCodes.Mul_Ovf;
2890 else if (isUnsigned)
2891 opcode = OpCodes.Mul_Ovf_Un;
2893 opcode = OpCodes.Mul;
2895 opcode = OpCodes.Mul;
2899 case Operator.Division:
2901 opcode = OpCodes.Div_Un;
2903 opcode = OpCodes.Div;
2906 case Operator.Modulus:
2908 opcode = OpCodes.Rem_Un;
2910 opcode = OpCodes.Rem;
2913 case Operator.Addition:
2915 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2916 opcode = OpCodes.Add_Ovf;
2917 else if (isUnsigned)
2918 opcode = OpCodes.Add_Ovf_Un;
2920 opcode = OpCodes.Add;
2922 opcode = OpCodes.Add;
2925 case Operator.Subtraction:
2927 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2928 opcode = OpCodes.Sub_Ovf;
2929 else if (isUnsigned)
2930 opcode = OpCodes.Sub_Ovf_Un;
2932 opcode = OpCodes.Sub;
2934 opcode = OpCodes.Sub;
2937 case Operator.RightShift:
2939 opcode = OpCodes.Shr_Un;
2941 opcode = OpCodes.Shr;
2944 case Operator.LeftShift:
2945 opcode = OpCodes.Shl;
2948 case Operator.Equality:
2949 opcode = OpCodes.Ceq;
2952 case Operator.Inequality:
2953 ig.Emit (OpCodes.Ceq);
2954 ig.Emit (OpCodes.Ldc_I4_0);
2956 opcode = OpCodes.Ceq;
2959 case Operator.LessThan:
2961 opcode = OpCodes.Clt_Un;
2963 opcode = OpCodes.Clt;
2966 case Operator.GreaterThan:
2968 opcode = OpCodes.Cgt_Un;
2970 opcode = OpCodes.Cgt;
2973 case Operator.LessThanOrEqual:
2974 Type lt = left.Type;
2976 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
2977 ig.Emit (OpCodes.Cgt_Un);
2979 ig.Emit (OpCodes.Cgt);
2980 ig.Emit (OpCodes.Ldc_I4_0);
2982 opcode = OpCodes.Ceq;
2985 case Operator.GreaterThanOrEqual:
2986 Type le = left.Type;
2988 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
2989 ig.Emit (OpCodes.Clt_Un);
2991 ig.Emit (OpCodes.Clt);
2993 ig.Emit (OpCodes.Ldc_I4_0);
2995 opcode = OpCodes.Ceq;
2998 case Operator.BitwiseOr:
2999 opcode = OpCodes.Or;
3002 case Operator.BitwiseAnd:
3003 opcode = OpCodes.And;
3006 case Operator.ExclusiveOr:
3007 opcode = OpCodes.Xor;
3011 throw new Exception ("This should not happen: Operator = "
3012 + oper.ToString ());
3020 // Object created by Binary when the binary operator uses an method instead of being
3021 // a binary operation that maps to a CIL binary operation.
3023 public class BinaryMethod : Expression {
3024 public MethodBase method;
3025 public ArrayList Arguments;
3027 public BinaryMethod (Type t, MethodBase m, ArrayList args)
3032 eclass = ExprClass.Value;
3035 public override Expression DoResolve (EmitContext ec)
3040 public override void Emit (EmitContext ec)
3042 ILGenerator ig = ec.ig;
3044 if (Arguments != null)
3045 Invocation.EmitArguments (ec, method, Arguments, false, null);
3047 if (method is MethodInfo)
3048 ig.Emit (OpCodes.Call, (MethodInfo) method);
3050 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3055 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3056 // b, c, d... may be strings or objects.
3058 public class StringConcat : Expression {
3060 bool invalid = false;
3063 public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
3066 type = TypeManager.string_type;
3067 eclass = ExprClass.Value;
3069 operands = new ArrayList (2);
3074 public override Expression DoResolve (EmitContext ec)
3082 public void Append (EmitContext ec, Expression operand)
3087 if (operand is StringConstant && operands.Count != 0) {
3088 StringConstant last_operand = operands [operands.Count - 1] as StringConstant;
3089 if (last_operand != null) {
3090 operands [operands.Count - 1] = new StringConstant (last_operand.Value + ((StringConstant) operand).Value);
3096 // Conversion to object
3098 if (operand.Type != TypeManager.string_type) {
3099 Expression no = Convert.ImplicitConversion (ec, operand, TypeManager.object_type, loc);
3102 Binary.Error_OperatorCannotBeApplied (loc, "+", TypeManager.string_type, operand.Type);
3108 operands.Add (operand);
3111 public override void Emit (EmitContext ec)
3113 MethodInfo concat_method = null;
3116 // Are we also concating objects?
3118 bool is_strings_only = true;
3121 // Do conversion to arguments; check for strings only
3123 for (int i = 0; i < operands.Count; i ++) {
3124 Expression e = (Expression) operands [i];
3125 is_strings_only &= e.Type == TypeManager.string_type;
3128 for (int i = 0; i < operands.Count; i ++) {
3129 Expression e = (Expression) operands [i];
3131 if (! is_strings_only && e.Type == TypeManager.string_type) {
3132 // need to make sure this is an object, because the EmitParams
3133 // method might look at the type of this expression, see it is a
3134 // string and emit a string [] when we want an object [];
3136 e = Convert.ImplicitConversion (ec, e, TypeManager.object_type, loc);
3138 operands [i] = new Argument (e, Argument.AType.Expression);
3142 // Find the right method
3144 switch (operands.Count) {
3147 // This should not be possible, because simple constant folding
3148 // is taken care of in the Binary code.
3150 throw new Exception ("how did you get here?");
3153 concat_method = is_strings_only ?
3154 TypeManager.string_concat_string_string :
3155 TypeManager.string_concat_object_object ;
3158 concat_method = is_strings_only ?
3159 TypeManager.string_concat_string_string_string :
3160 TypeManager.string_concat_object_object_object ;
3164 // There is not a 4 param overlaod for object (the one that there is
3165 // is actually a varargs methods, and is only in corlib because it was
3166 // introduced there before.).
3168 if (!is_strings_only)
3171 concat_method = TypeManager.string_concat_string_string_string_string;
3174 concat_method = is_strings_only ?
3175 TypeManager.string_concat_string_dot_dot_dot :
3176 TypeManager.string_concat_object_dot_dot_dot ;
3180 Invocation.EmitArguments (ec, concat_method, operands, false, null);
3181 ec.ig.Emit (OpCodes.Call, concat_method);
3186 // Object created with +/= on delegates
3188 public class BinaryDelegate : Expression {
3192 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3197 eclass = ExprClass.Value;
3200 public override Expression DoResolve (EmitContext ec)
3205 public override void Emit (EmitContext ec)
3207 ILGenerator ig = ec.ig;
3209 Invocation.EmitArguments (ec, method, args, false, null);
3211 ig.Emit (OpCodes.Call, (MethodInfo) method);
3212 ig.Emit (OpCodes.Castclass, type);
3215 public Expression Right {
3217 Argument arg = (Argument) args [1];
3222 public bool IsAddition {
3224 return method == TypeManager.delegate_combine_delegate_delegate;
3230 // User-defined conditional logical operator
3231 public class ConditionalLogicalOperator : Expression {
3232 Expression left, right;
3235 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3238 eclass = ExprClass.Value;
3242 this.is_and = is_and;
3245 protected void Error19 ()
3247 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3250 protected void Error218 ()
3252 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3253 "declarations of operator true and operator false");
3256 Expression op_true, op_false, op;
3257 LocalTemporary left_temp;
3259 public override Expression DoResolve (EmitContext ec)
3262 Expression operator_group;
3264 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3265 if (operator_group == null) {
3270 left_temp = new LocalTemporary (ec, type);
3272 ArrayList arguments = new ArrayList ();
3273 arguments.Add (new Argument (left_temp, Argument.AType.Expression));
3274 arguments.Add (new Argument (right, Argument.AType.Expression));
3275 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) operator_group, arguments, loc) as MethodInfo;
3276 if ((method == null) || (method.ReturnType != type)) {
3281 op = new StaticCallExpr (method, arguments, loc);
3283 op_true = GetOperatorTrue (ec, left_temp, loc);
3284 op_false = GetOperatorFalse (ec, left_temp, loc);
3285 if ((op_true == null) || (op_false == null)) {
3293 public override void Emit (EmitContext ec)
3295 ILGenerator ig = ec.ig;
3296 Label false_target = ig.DefineLabel ();
3297 Label end_target = ig.DefineLabel ();
3299 ig.Emit (OpCodes.Nop);
3302 left_temp.Store (ec);
3304 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
3305 left_temp.Emit (ec);
3306 ig.Emit (OpCodes.Br, end_target);
3307 ig.MarkLabel (false_target);
3309 ig.MarkLabel (end_target);
3311 ig.Emit (OpCodes.Nop);
3315 public class PointerArithmetic : Expression {
3316 Expression left, right;
3320 // We assume that `l' is always a pointer
3322 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3328 is_add = is_addition;
3331 public override Expression DoResolve (EmitContext ec)
3333 eclass = ExprClass.Variable;
3335 if (left.Type == TypeManager.void_ptr_type) {
3336 Error (242, "The operation in question is undefined on void pointers");
3343 public override void Emit (EmitContext ec)
3345 Type op_type = left.Type;
3346 ILGenerator ig = ec.ig;
3347 Type element = TypeManager.GetElementType (op_type);
3348 int size = GetTypeSize (element);
3349 Type rtype = right.Type;
3351 if (rtype.IsPointer){
3353 // handle (pointer - pointer)
3357 ig.Emit (OpCodes.Sub);
3361 ig.Emit (OpCodes.Sizeof, element);
3363 IntLiteral.EmitInt (ig, size);
3364 ig.Emit (OpCodes.Div);
3366 ig.Emit (OpCodes.Conv_I8);
3369 // handle + and - on (pointer op int)
3372 ig.Emit (OpCodes.Conv_I);
3376 ig.Emit (OpCodes.Sizeof, element);
3378 IntLiteral.EmitInt (ig, size);
3379 if (rtype == TypeManager.int64_type)
3380 ig.Emit (OpCodes.Conv_I8);
3381 else if (rtype == TypeManager.uint64_type)
3382 ig.Emit (OpCodes.Conv_U8);
3383 ig.Emit (OpCodes.Mul);
3384 ig.Emit (OpCodes.Conv_I);
3387 ig.Emit (OpCodes.Add);
3389 ig.Emit (OpCodes.Sub);
3395 /// Implements the ternary conditional operator (?:)
3397 public class Conditional : Expression {
3398 Expression expr, trueExpr, falseExpr;
3400 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3403 this.trueExpr = trueExpr;
3404 this.falseExpr = falseExpr;
3408 public Expression Expr {
3414 public Expression TrueExpr {
3420 public Expression FalseExpr {
3426 public override Expression DoResolve (EmitContext ec)
3428 expr = expr.Resolve (ec);
3433 if (expr.Type != TypeManager.bool_type){
3434 expr = Expression.ResolveBoolean (
3441 trueExpr = trueExpr.Resolve (ec);
3442 falseExpr = falseExpr.Resolve (ec);
3444 if (trueExpr == null || falseExpr == null)
3447 eclass = ExprClass.Value;
3448 if (trueExpr.Type == falseExpr.Type)
3449 type = trueExpr.Type;
3452 Type true_type = trueExpr.Type;
3453 Type false_type = falseExpr.Type;
3455 if (trueExpr is NullLiteral){
3458 } else if (falseExpr is NullLiteral){
3464 // First, if an implicit conversion exists from trueExpr
3465 // to falseExpr, then the result type is of type falseExpr.Type
3467 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3470 // Check if both can convert implicitl to each other's type
3472 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3474 "Can not compute type of conditional expression " +
3475 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3476 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3477 "' convert implicitly to each other");
3482 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3486 Error (173, "The type of the conditional expression can " +
3487 "not be computed because there is no implicit conversion" +
3488 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3489 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3494 if (expr is BoolConstant){
3495 BoolConstant bc = (BoolConstant) expr;
3506 public override void Emit (EmitContext ec)
3508 ILGenerator ig = ec.ig;
3509 Label false_target = ig.DefineLabel ();
3510 Label end_target = ig.DefineLabel ();
3512 expr.EmitBranchable (ec, false_target, false);
3514 ig.Emit (OpCodes.Br, end_target);
3515 ig.MarkLabel (false_target);
3516 falseExpr.Emit (ec);
3517 ig.MarkLabel (end_target);
3525 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3526 public readonly string Name;
3527 public readonly Block Block;
3528 LocalInfo local_info;
3531 public LocalVariableReference (Block block, string name, Location l)
3536 eclass = ExprClass.Variable;
3539 // Setting `is_readonly' to false will allow you to create a writable
3540 // reference to a read-only variable. This is used by foreach and using.
3541 public LocalVariableReference (Block block, string name, Location l,
3542 LocalInfo local_info, bool is_readonly)
3543 : this (block, name, l)
3545 this.local_info = local_info;
3546 this.is_readonly = is_readonly;
3549 public VariableInfo VariableInfo {
3550 get { return local_info.VariableInfo; }
3553 public bool IsReadOnly {
3559 protected void DoResolveBase (EmitContext ec)
3561 if (local_info == null) {
3562 local_info = Block.GetLocalInfo (Name);
3563 is_readonly = local_info.ReadOnly;
3566 type = local_info.VariableType;
3568 if (ec.InAnonymousMethod)
3569 Block.LiftVariable (local_info);
3573 protected Expression DoResolve (EmitContext ec, bool is_lvalue)
3575 Expression e = Block.GetConstantExpression (Name);
3577 local_info.Used = true;
3578 eclass = ExprClass.Value;
3579 return e.Resolve (ec);
3582 VariableInfo variable_info = local_info.VariableInfo;
3583 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3587 local_info.Used = true;
3589 if (local_info.LocalBuilder == null)
3590 return ec.RemapLocal (local_info);
3595 public override Expression DoResolve (EmitContext ec)
3599 return DoResolve (ec, false);
3602 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3606 VariableInfo variable_info = local_info.VariableInfo;
3607 if (variable_info != null)
3608 variable_info.SetAssigned (ec);
3610 Expression e = DoResolve (ec, true);
3616 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3620 CheckObsoleteAttribute (e.Type);
3622 if (local_info.LocalBuilder == null)
3623 return ec.RemapLocalLValue (local_info, right_side);
3628 public bool VerifyFixed (bool is_expression)
3630 return !is_expression || local_info.IsFixed;
3633 public override void Emit (EmitContext ec)
3635 ILGenerator ig = ec.ig;
3637 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3640 public void Emit (EmitContext ec, bool leave_copy)
3644 ec.ig.Emit (OpCodes.Dup);
3647 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3651 ec.ig.Emit (OpCodes.Dup);
3652 ec.ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3655 public void AddressOf (EmitContext ec, AddressOp mode)
3657 ILGenerator ig = ec.ig;
3659 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3662 public override string ToString ()
3664 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3669 /// This represents a reference to a parameter in the intermediate
3672 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3678 public Parameter.Modifier mod;
3679 public bool is_ref, is_out, prepared;
3680 LocalTemporary temp;
3682 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3689 eclass = ExprClass.Variable;
3692 public VariableInfo VariableInfo {
3696 public bool VerifyFixed (bool is_expression)
3698 return !is_expression || TypeManager.IsValueType (type);
3701 public bool IsAssigned (EmitContext ec, Location loc)
3703 if (!ec.DoFlowAnalysis || !is_out ||
3704 ec.CurrentBranching.IsAssigned (vi))
3707 Report.Error (165, loc,
3708 "Use of unassigned parameter `" + name + "'");
3712 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3714 if (!ec.DoFlowAnalysis || !is_out ||
3715 ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3718 Report.Error (170, loc,
3719 "Use of possibly unassigned field `" + field_name + "'");
3723 public void SetAssigned (EmitContext ec)
3725 if (is_out && ec.DoFlowAnalysis)
3726 ec.CurrentBranching.SetAssigned (vi);
3729 public void SetFieldAssigned (EmitContext ec, string field_name)
3731 if (is_out && ec.DoFlowAnalysis)
3732 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3735 protected void DoResolveBase (EmitContext ec)
3737 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
3738 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3739 is_out = (mod & Parameter.Modifier.OUT) != 0;
3740 eclass = ExprClass.Variable;
3743 vi = block.ParameterMap [idx];
3747 // Notice that for ref/out parameters, the type exposed is not the
3748 // same type exposed externally.
3751 // externally we expose "int&"
3752 // here we expose "int".
3754 // We record this in "is_ref". This means that the type system can treat
3755 // the type as it is expected, but when we generate the code, we generate
3756 // the alternate kind of code.
3758 public override Expression DoResolve (EmitContext ec)
3762 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3765 if (ec.RemapToProxy)
3766 return ec.RemapParameter (idx);
3771 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3777 if (ec.RemapToProxy)
3778 return ec.RemapParameterLValue (idx, right_side);
3783 static public void EmitLdArg (ILGenerator ig, int x)
3787 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3788 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3789 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3790 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3791 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3794 ig.Emit (OpCodes.Ldarg, x);
3798 // This method is used by parameters that are references, that are
3799 // being passed as references: we only want to pass the pointer (that
3800 // is already stored in the parameter, not the address of the pointer,
3801 // and not the value of the variable).
3803 public void EmitLoad (EmitContext ec)
3805 ILGenerator ig = ec.ig;
3811 EmitLdArg (ig, arg_idx);
3814 public override void Emit (EmitContext ec)
3819 public void Emit (EmitContext ec, bool leave_copy)
3821 ILGenerator ig = ec.ig;
3828 EmitLdArg (ig, arg_idx);
3832 ec.ig.Emit (OpCodes.Dup);
3835 // If we are a reference, we loaded on the stack a pointer
3836 // Now lets load the real value
3838 LoadFromPtr (ig, type);
3842 ec.ig.Emit (OpCodes.Dup);
3845 temp = new LocalTemporary (ec, type);
3851 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3853 ILGenerator ig = ec.ig;
3856 prepared = prepare_for_load;
3861 if (is_ref && !prepared)
3862 EmitLdArg (ig, arg_idx);
3867 ec.ig.Emit (OpCodes.Dup);
3871 temp = new LocalTemporary (ec, type);
3875 StoreFromPtr (ig, type);
3881 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
3883 ig.Emit (OpCodes.Starg, arg_idx);
3887 public void AddressOf (EmitContext ec, AddressOp mode)
3896 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
3898 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
3901 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
3903 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
3910 /// Used for arguments to New(), Invocation()
3912 public class Argument {
3913 public enum AType : byte {
3920 public readonly AType ArgType;
3921 public Expression Expr;
3923 public Argument (Expression expr, AType type)
3926 this.ArgType = type;
3929 public Argument (Expression expr)
3932 this.ArgType = AType.Expression;
3937 if (ArgType == AType.Ref || ArgType == AType.Out)
3938 return TypeManager.GetReferenceType (Expr.Type);
3944 public Parameter.Modifier GetParameterModifier ()
3948 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
3951 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
3954 return Parameter.Modifier.NONE;
3958 public static string FullDesc (Argument a)
3960 if (a.ArgType == AType.ArgList)
3963 return (a.ArgType == AType.Ref ? "ref " :
3964 (a.ArgType == AType.Out ? "out " : "")) +
3965 TypeManager.CSharpName (a.Expr.Type);
3968 public bool ResolveMethodGroup (EmitContext ec, Location loc)
3970 // FIXME: csc doesn't report any error if you try to use `ref' or
3971 // `out' in a delegate creation expression.
3972 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
3979 public bool Resolve (EmitContext ec, Location loc)
3981 if (ArgType == AType.Ref) {
3982 Expr = Expr.Resolve (ec);
3986 Expr = Expr.ResolveLValue (ec, Expr);
3987 } else if (ArgType == AType.Out)
3988 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
3990 Expr = Expr.Resolve (ec);
3995 if (ArgType == AType.Expression)
3999 // Catch errors where fields of a MarshalByRefObject are passed as ref or out
4000 // This is only allowed for `this'
4002 FieldExpr fe = Expr as FieldExpr;
4003 if (fe != null && !fe.IsStatic){
4004 Expression instance = fe.InstanceExpression;
4006 if (instance.GetType () != typeof (This)){
4007 if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
4008 Report.Error (197, loc,
4009 "Can not pass a type that derives from MarshalByRefObject with out or ref");
4016 if (Expr.eclass != ExprClass.Variable){
4018 // We just probe to match the CSC output
4020 if (Expr.eclass == ExprClass.PropertyAccess ||
4021 Expr.eclass == ExprClass.IndexerAccess){
4024 "A property or indexer can not be passed as an out or ref " +
4029 "An lvalue is required as an argument to out or ref");
4037 public void Emit (EmitContext ec)
4040 // Ref and Out parameters need to have their addresses taken.
4042 // ParameterReferences might already be references, so we want
4043 // to pass just the value
4045 if (ArgType == AType.Ref || ArgType == AType.Out){
4046 AddressOp mode = AddressOp.Store;
4048 if (ArgType == AType.Ref)
4049 mode |= AddressOp.Load;
4051 if (Expr is ParameterReference){
4052 ParameterReference pr = (ParameterReference) Expr;
4058 pr.AddressOf (ec, mode);
4061 ((IMemoryLocation)Expr).AddressOf (ec, mode);
4069 /// Invocation of methods or delegates.
4071 public class Invocation : ExpressionStatement {
4072 public readonly ArrayList Arguments;
4075 MethodBase method = null;
4078 static Hashtable method_parameter_cache;
4080 static Invocation ()
4082 method_parameter_cache = new PtrHashtable ();
4086 // arguments is an ArrayList, but we do not want to typecast,
4087 // as it might be null.
4089 // FIXME: only allow expr to be a method invocation or a
4090 // delegate invocation (7.5.5)
4092 public Invocation (Expression expr, ArrayList arguments, Location l)
4095 Arguments = arguments;
4099 public Expression Expr {
4106 /// Returns the Parameters (a ParameterData interface) for the
4109 public static ParameterData GetParameterData (MethodBase mb)
4111 object pd = method_parameter_cache [mb];
4115 return (ParameterData) pd;
4118 ip = TypeManager.LookupParametersByBuilder (mb);
4120 method_parameter_cache [mb] = ip;
4122 return (ParameterData) ip;
4124 ReflectionParameters rp = new ReflectionParameters (mb);
4125 method_parameter_cache [mb] = rp;
4127 return (ParameterData) rp;
4132 /// Determines "better conversion" as specified in 7.4.2.3
4134 /// Returns : 1 if a->p is better
4135 /// 0 if a->q or neither is better
4137 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
4139 Type argument_type = a.Type;
4140 Expression argument_expr = a.Expr;
4142 if (argument_type == null)
4143 throw new Exception ("Expression of type " + a.Expr +
4144 " does not resolve its type");
4147 // This is a special case since csc behaves this way.
4149 if (argument_expr is NullLiteral &&
4150 p == TypeManager.string_type &&
4151 q == TypeManager.object_type)
4153 else if (argument_expr is NullLiteral &&
4154 p == TypeManager.object_type &&
4155 q == TypeManager.string_type)
4159 // csc behaves this way so we emulate it. Basically, if the argument
4160 // is null and one of the types to compare is 'object' and the other
4161 // is a reference type, we prefer the other.
4163 // I can't find this anywhere in the spec but we can interpret this
4164 // to mean that null can be of any type you wish in such a context
4166 if (p != null && q != null) {
4167 if (argument_expr is NullLiteral &&
4169 q == TypeManager.object_type)
4171 else if (argument_expr is NullLiteral &&
4173 p == TypeManager.object_type)
4180 if (argument_type == p)
4183 if (argument_type == q)
4187 Expression tmp = Convert.ImplicitConversion (ec, argument_expr, p, loc);
4195 Expression p_tmp = new EmptyExpression (p);
4196 Expression q_tmp = new EmptyExpression (q);
4198 if (Convert.ImplicitConversionExists (ec, p_tmp, q) == true &&
4199 Convert.ImplicitConversionExists (ec, q_tmp, p) == false)
4202 if (p == TypeManager.sbyte_type)
4203 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4204 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4207 if (p == TypeManager.short_type)
4208 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4209 q == TypeManager.uint64_type)
4212 if (p == TypeManager.int32_type)
4213 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4216 if (p == TypeManager.int64_type)
4217 if (q == TypeManager.uint64_type)
4224 /// Determines "Better function" between candidate
4225 /// and the current best match
4228 /// Returns an integer indicating :
4229 /// 0 if candidate ain't better
4230 /// 1 if candidate is better than the current best match
4232 static int BetterFunction (EmitContext ec, ArrayList args,
4233 MethodBase candidate, bool candidate_params,
4234 MethodBase best, bool best_params,
4237 ParameterData candidate_pd = GetParameterData (candidate);
4238 ParameterData best_pd;
4244 argument_count = args.Count;
4246 int cand_count = candidate_pd.Count;
4249 // If there is no best method, than this one
4250 // is better, however, if we already found a
4251 // best method, we cant tell. This happens
4262 // interface IFooBar : IFoo, IBar {}
4264 // We cant tell if IFoo.DoIt is better than IBar.DoIt
4266 // However, we have to consider that
4267 // Trim (); is better than Trim (params char[] chars);
4269 if (cand_count == 0 && argument_count == 0)
4270 return best == null || best_params ? 1 : 0;
4272 if ((candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS) &&
4273 (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.ARGLIST))
4274 if (cand_count != argument_count)
4280 if (argument_count == 0 && cand_count == 1 &&
4281 candidate_pd.ParameterModifier (cand_count - 1) == Parameter.Modifier.PARAMS)
4284 for (int j = 0; j < argument_count; ++j) {
4286 Argument a = (Argument) args [j];
4287 Type t = candidate_pd.ParameterType (j);
4289 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4290 if (candidate_params)
4291 t = TypeManager.GetElementType (t);
4293 x = BetterConversion (ec, a, t, null, loc);
4305 best_pd = GetParameterData (best);
4307 int rating1 = 0, rating2 = 0;
4309 for (int j = 0; j < argument_count; ++j) {
4312 Argument a = (Argument) args [j];
4314 Type ct = candidate_pd.ParameterType (j);
4315 Type bt = best_pd.ParameterType (j);
4317 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4318 if (candidate_params)
4319 ct = TypeManager.GetElementType (ct);
4321 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4323 bt = TypeManager.GetElementType (bt);
4325 x = BetterConversion (ec, a, ct, bt, loc);
4326 y = BetterConversion (ec, a, bt, ct, loc);
4336 // If a method (in the normal form) with the
4337 // same signature as the expanded form of the
4338 // current best params method already exists,
4339 // the expanded form is not applicable so we
4340 // force it to select the candidate
4342 if (!candidate_params && best_params && cand_count == argument_count)
4345 if (rating1 > rating2)
4351 public static string FullMethodDesc (MethodBase mb)
4353 string ret_type = "";
4358 if (mb is MethodInfo)
4359 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
4361 StringBuilder sb = new StringBuilder (ret_type);
4363 sb.Append (mb.ReflectedType.ToString ());
4365 sb.Append (mb.Name);
4367 ParameterData pd = GetParameterData (mb);
4369 int count = pd.Count;
4372 for (int i = count; i > 0; ) {
4375 sb.Append (pd.ParameterDesc (count - i - 1));
4381 return sb.ToString ();
4384 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4386 MemberInfo [] miset;
4387 MethodGroupExpr union;
4392 return (MethodGroupExpr) mg2;
4395 return (MethodGroupExpr) mg1;
4398 MethodGroupExpr left_set = null, right_set = null;
4399 int length1 = 0, length2 = 0;
4401 left_set = (MethodGroupExpr) mg1;
4402 length1 = left_set.Methods.Length;
4404 right_set = (MethodGroupExpr) mg2;
4405 length2 = right_set.Methods.Length;
4407 ArrayList common = new ArrayList ();
4409 foreach (MethodBase r in right_set.Methods){
4410 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
4414 miset = new MemberInfo [length1 + length2 - common.Count];
4415 left_set.Methods.CopyTo (miset, 0);
4419 foreach (MethodBase r in right_set.Methods) {
4420 if (!common.Contains (r))
4424 union = new MethodGroupExpr (miset, loc);
4430 /// Determines if the candidate method, if a params method, is applicable
4431 /// in its expanded form to the given set of arguments
4433 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
4434 MethodBase candidate, bool do_varargs)
4438 if (arguments == null)
4441 arg_count = arguments.Count;
4443 ParameterData pd = GetParameterData (candidate);
4445 int pd_count = pd.Count;
4449 int count = pd_count - 1;
4451 if (pd.ParameterModifier (count) != Parameter.Modifier.ARGLIST)
4453 if (pd_count != arg_count)
4456 if (pd.ParameterModifier (count) != Parameter.Modifier.PARAMS)
4460 if (count > arg_count)
4463 if (pd_count == 1 && arg_count == 0)
4467 // If we have come this far, the case which
4468 // remains is when the number of parameters is
4469 // less than or equal to the argument count.
4471 for (int i = 0; i < count; ++i) {
4473 Argument a = (Argument) arguments [i];
4475 Parameter.Modifier a_mod = a.GetParameterModifier () &
4476 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4477 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4478 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4480 if (a_mod == p_mod) {
4482 if (a_mod == Parameter.Modifier.NONE)
4483 if (!Convert.ImplicitConversionExists (ec,
4485 pd.ParameterType (i)))
4488 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4489 Type pt = pd.ParameterType (i);
4492 pt = TypeManager.GetReferenceType (pt);
4503 Argument a = (Argument) arguments [count];
4504 if (!(a.Expr is Arglist))
4510 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4512 for (int i = pd_count - 1; i < arg_count; i++) {
4513 Argument a = (Argument) arguments [i];
4515 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4523 /// Determines if the candidate method is applicable (section 14.4.2.1)
4524 /// to the given set of arguments
4526 static bool IsApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
4530 if (arguments == null)
4533 arg_count = arguments.Count;
4536 ParameterData pd = GetParameterData (candidate);
4538 if (arg_count != pd.Count)
4541 for (int i = arg_count; i > 0; ) {
4544 Argument a = (Argument) arguments [i];
4546 Parameter.Modifier a_mod = a.GetParameterModifier () &
4547 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4548 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4549 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4552 if (a_mod == p_mod ||
4553 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4554 if (a_mod == Parameter.Modifier.NONE) {
4555 if (!Convert.ImplicitConversionExists (ec,
4557 pd.ParameterType (i)))
4561 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4562 Type pt = pd.ParameterType (i);
4565 pt = TypeManager.GetReferenceType (pt);
4578 /// Find the Applicable Function Members (7.4.2.1)
4580 /// me: Method Group expression with the members to select.
4581 /// it might contain constructors or methods (or anything
4582 /// that maps to a method).
4584 /// Arguments: ArrayList containing resolved Argument objects.
4586 /// loc: The location if we want an error to be reported, or a Null
4587 /// location for "probing" purposes.
4589 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4590 /// that is the best match of me on Arguments.
4593 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4594 ArrayList Arguments, Location loc)
4596 MethodBase method = null;
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;
4612 // First we construct the set of applicable methods
4614 // We start at the top of the type hierarchy and
4615 // go down to find applicable methods
4617 applicable_type = me.DeclaringType;
4619 if (me.Name == "Invoke" && TypeManager.IsDelegateType (applicable_type)) {
4620 Error_InvokeOnDelegate (loc);
4624 bool found_applicable = false;
4626 foreach (MethodBase candidate in me.Methods){
4627 Type decl_type = candidate.DeclaringType;
4630 // If we have already found an applicable method
4631 // we eliminate all base types (Section 14.5.5.1)
4633 if (decl_type != applicable_type &&
4634 (applicable_type.IsSubclassOf (decl_type) ||
4635 TypeManager.ImplementsInterface (applicable_type, decl_type)) &&
4640 // Check if candidate is applicable (section 14.4.2.1)
4641 if (IsApplicable (ec, Arguments, candidate)) {
4642 // Candidate is applicable in normal form
4643 candidates.Add (candidate);
4644 applicable_type = candidate.DeclaringType;
4645 found_applicable = true;
4646 } else if (IsParamsMethodApplicable (ec, Arguments, candidate, false)) {
4647 if (candidate_to_form == null)
4648 candidate_to_form = new PtrHashtable ();
4650 // Candidate is applicable in expanded form
4651 candidates.Add (candidate);
4652 applicable_type = candidate.DeclaringType;
4653 found_applicable = true;
4654 candidate_to_form [candidate] = candidate;
4655 } else if (IsParamsMethodApplicable (ec, Arguments, candidate, true)) {
4656 if (candidate_to_form == null)
4657 candidate_to_form = new PtrHashtable ();
4659 // Candidate is applicable in expanded form
4660 candidates.Add (candidate);
4661 applicable_type = candidate.DeclaringType;
4662 found_applicable = true;
4663 candidate_to_form [candidate] = candidate;
4669 // Now we actually find the best method
4671 int candidate_top = candidates.Count;
4672 for (int ix = 0; ix < candidate_top; ix++){
4673 MethodBase candidate = (MethodBase) candidates [ix];
4675 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4676 bool method_params = false;
4679 method_params = candidate_to_form != null && candidate_to_form.Contains (method);
4681 int x = BetterFunction (ec, Arguments,
4682 candidate, cand_params,
4683 method, method_params,
4692 if (Arguments == null)
4695 argument_count = Arguments.Count;
4698 if (method == null) {
4700 // Okay so we have failed to find anything so we
4701 // return by providing info about the closest match
4703 for (int i = 0; i < me.Methods.Length; ++i) {
4705 MethodBase c = (MethodBase) me.Methods [i];
4706 ParameterData pd = GetParameterData (c);
4708 if (pd.Count != argument_count)
4711 VerifyArgumentsCompat (ec, Arguments, argument_count, c, false,
4716 if (!Location.IsNull (loc)) {
4717 string report_name = me.Name;
4718 if (report_name == ".ctor")
4719 report_name = me.DeclaringType.ToString ();
4721 Error_WrongNumArguments (loc, report_name, argument_count);
4728 // Now check that there are no ambiguities i.e the selected method
4729 // should be better than all the others
4731 bool best_params = candidate_to_form != null && candidate_to_form.Contains (method);
4733 for (int ix = 0; ix < candidate_top; ix++){
4734 MethodBase candidate = (MethodBase) candidates [ix];
4736 if (candidate == method)
4740 // If a normal method is applicable in
4741 // the sense that it has the same
4742 // number of arguments, then the
4743 // expanded params method is never
4744 // applicable so we debar the params
4747 // if ((IsParamsMethodApplicable (ec, Arguments, candidate) &&
4748 // IsApplicable (ec, Arguments, method)))
4751 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4752 int x = BetterFunction (ec, Arguments,
4753 method, best_params,
4754 candidate, cand_params,
4760 "Ambiguous call when selecting function due to implicit casts");
4766 // And now check if the arguments are all
4767 // compatible, perform conversions if
4768 // necessary etc. and return if everything is
4771 if (!VerifyArgumentsCompat (ec, Arguments, argument_count, method,
4772 best_params, null, loc))
4778 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
4780 Report.Error (1501, loc,
4781 "No overload for method `" + name + "' takes `" +
4782 arg_count + "' arguments");
4785 static void Error_InvokeOnDelegate (Location loc)
4787 Report.Error (1533, loc,
4788 "Invoke cannot be called directly on a delegate");
4791 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
4792 Type delegate_type, string arg_sig, string par_desc)
4794 if (delegate_type == null)
4795 Report.Error (1502, loc,
4796 "The best overloaded match for method '" +
4797 FullMethodDesc (method) +
4798 "' has some invalid arguments");
4800 Report.Error (1594, loc,
4801 "Delegate '" + delegate_type.ToString () +
4802 "' has some invalid arguments.");
4803 Report.Error (1503, loc,
4804 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
4805 idx, arg_sig, par_desc));
4808 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
4811 bool chose_params_expanded,
4815 ParameterData pd = GetParameterData (method);
4816 int pd_count = pd.Count;
4818 for (int j = 0; j < argument_count; j++) {
4819 Argument a = (Argument) Arguments [j];
4820 Expression a_expr = a.Expr;
4821 Type parameter_type = pd.ParameterType (j);
4822 Parameter.Modifier pm = pd.ParameterModifier (j);
4824 if (pm == Parameter.Modifier.PARAMS){
4825 if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
4826 if (!Location.IsNull (loc))
4827 Error_InvalidArguments (
4828 loc, j, method, delegate_type,
4829 Argument.FullDesc (a), pd.ParameterDesc (j));
4833 if (chose_params_expanded)
4834 parameter_type = TypeManager.GetElementType (parameter_type);
4835 } else if (pm == Parameter.Modifier.ARGLIST){
4841 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
4842 if (!Location.IsNull (loc))
4843 Error_InvalidArguments (
4844 loc, j, method, delegate_type,
4845 Argument.FullDesc (a), pd.ParameterDesc (j));
4853 if (a.Type != parameter_type){
4856 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
4859 if (!Location.IsNull (loc))
4860 Error_InvalidArguments (
4861 loc, j, method, delegate_type,
4862 Argument.FullDesc (a), pd.ParameterDesc (j));
4867 // Update the argument with the implicit conversion
4873 Parameter.Modifier a_mod = a.GetParameterModifier () &
4874 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4875 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
4876 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4878 if (a_mod != p_mod &&
4879 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
4880 if (!Location.IsNull (loc)) {
4881 Report.Error (1502, loc,
4882 "The best overloaded match for method '" + FullMethodDesc (method)+
4883 "' has some invalid arguments");
4884 Report.Error (1503, loc,
4885 "Argument " + (j+1) +
4886 ": Cannot convert from '" + Argument.FullDesc (a)
4887 + "' to '" + pd.ParameterDesc (j) + "'");
4897 public override Expression DoResolve (EmitContext ec)
4900 // First, resolve the expression that is used to
4901 // trigger the invocation
4903 if (expr is BaseAccess)
4906 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4910 if (!(expr is MethodGroupExpr)) {
4911 Type expr_type = expr.Type;
4913 if (expr_type != null){
4914 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
4916 return (new DelegateInvocation (
4917 this.expr, Arguments, loc)).Resolve (ec);
4921 if (!(expr is MethodGroupExpr)){
4922 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup);
4927 // Next, evaluate all the expressions in the argument list
4929 if (Arguments != null){
4930 foreach (Argument a in Arguments){
4931 if (!a.Resolve (ec, loc))
4936 MethodGroupExpr mg = (MethodGroupExpr) expr;
4937 method = OverloadResolve (ec, mg, Arguments, loc);
4939 if (method == null){
4941 "Could not find any applicable function for this argument list");
4945 MethodInfo mi = method as MethodInfo;
4947 type = TypeManager.TypeToCoreType (mi.ReturnType);
4948 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null)) {
4949 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
4953 Expression iexpr = mg.InstanceExpression;
4954 if (mi.IsStatic && (iexpr != null) && !(iexpr is This)) {
4955 if (mg.IdenticalTypeName)
4956 mg.InstanceExpression = null;
4958 MemberAccess.error176 (loc, mi.Name);
4964 if (type.IsPointer){
4972 // Only base will allow this invocation to happen.
4974 if (is_base && method.IsAbstract){
4975 Report.Error (205, loc, "Cannot call an abstract base member: " +
4976 FullMethodDesc (method));
4980 if ((method.Attributes & MethodAttributes.SpecialName) != 0){
4981 if (TypeManager.IsSpecialMethod (method))
4982 Report.Error (571, loc, method.Name + ": can not call operator or accessor");
4985 eclass = ExprClass.Value;
4990 // Emits the list of arguments as an array
4992 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
4994 ILGenerator ig = ec.ig;
4995 int count = arguments.Count - idx;
4996 Argument a = (Argument) arguments [idx];
4997 Type t = a.Expr.Type;
4999 IntConstant.EmitInt (ig, count);
5000 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
5002 int top = arguments.Count;
5003 for (int j = idx; j < top; j++){
5004 a = (Argument) arguments [j];
5006 ig.Emit (OpCodes.Dup);
5007 IntConstant.EmitInt (ig, j - idx);
5010 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj);
5012 ig.Emit (OpCodes.Ldelema, t);
5017 ig.Emit (OpCodes.Stobj, t);
5024 /// Emits a list of resolved Arguments that are in the arguments
5027 /// The MethodBase argument might be null if the
5028 /// emission of the arguments is known not to contain
5029 /// a `params' field (for example in constructors or other routines
5030 /// that keep their arguments in this structure)
5032 /// if `dup_args' is true, a copy of the arguments will be left
5033 /// on the stack. If `dup_args' is true, you can specify `this_arg'
5034 /// which will be duplicated before any other args. Only EmitCall
5035 /// should be using this interface.
5037 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments, bool dup_args, LocalTemporary this_arg)
5041 pd = GetParameterData (mb);
5045 LocalTemporary [] temps = null;
5048 temps = new LocalTemporary [arguments.Count];
5051 // If we are calling a params method with no arguments, special case it
5053 if (arguments == null){
5054 if (pd != null && pd.Count > 0 &&
5055 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
5056 ILGenerator ig = ec.ig;
5058 IntConstant.EmitInt (ig, 0);
5059 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
5065 int top = arguments.Count;
5067 for (int i = 0; i < top; i++){
5068 Argument a = (Argument) arguments [i];
5071 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
5073 // Special case if we are passing the same data as the
5074 // params argument, do not put it in an array.
5076 if (pd.ParameterType (i) == a.Type)
5079 EmitParams (ec, i, arguments);
5086 ec.ig.Emit (OpCodes.Dup);
5087 (temps [i] = new LocalTemporary (ec, a.Type)).Store (ec);
5092 if (this_arg != null)
5095 for (int i = 0; i < top; i ++)
5096 temps [i].Emit (ec);
5099 if (pd != null && pd.Count > top &&
5100 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
5101 ILGenerator ig = ec.ig;
5103 IntConstant.EmitInt (ig, 0);
5104 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
5108 static Type[] GetVarargsTypes (EmitContext ec, MethodBase mb,
5109 ArrayList arguments)
5111 ParameterData pd = GetParameterData (mb);
5113 if (arguments == null)
5114 return new Type [0];
5116 Argument a = (Argument) arguments [pd.Count - 1];
5117 Arglist list = (Arglist) a.Expr;
5119 return list.ArgumentTypes;
5123 /// This checks the ConditionalAttribute on the method
5125 static bool IsMethodExcluded (MethodBase method, EmitContext ec)
5127 if (method.IsConstructor)
5130 IMethodData md = TypeManager.GetMethod (method);
5132 return md.IsExcluded (ec);
5134 // For some methods (generated by delegate class) GetMethod returns null
5135 // because they are not included in builder_to_method table
5136 if (method.DeclaringType is TypeBuilder)
5139 return AttributeTester.IsConditionalMethodExcluded (method);
5143 /// is_base tells whether we want to force the use of the `call'
5144 /// opcode instead of using callvirt. Call is required to call
5145 /// a specific method, while callvirt will always use the most
5146 /// recent method in the vtable.
5148 /// is_static tells whether this is an invocation on a static method
5150 /// instance_expr is an expression that represents the instance
5151 /// it must be non-null if is_static is false.
5153 /// method is the method to invoke.
5155 /// Arguments is the list of arguments to pass to the method or constructor.
5157 public static void EmitCall (EmitContext ec, bool is_base,
5158 bool is_static, Expression instance_expr,
5159 MethodBase method, ArrayList Arguments, Location loc)
5161 EmitCall (ec, is_base, is_static, instance_expr, method, Arguments, loc, false, false);
5164 // `dup_args' leaves an extra copy of the arguments on the stack
5165 // `omit_args' does not leave any arguments at all.
5166 // So, basically, you could make one call with `dup_args' set to true,
5167 // and then another with `omit_args' set to true, and the two calls
5168 // would have the same set of arguments. However, each argument would
5169 // only have been evaluated once.
5170 public static void EmitCall (EmitContext ec, bool is_base,
5171 bool is_static, Expression instance_expr,
5172 MethodBase method, ArrayList Arguments, Location loc,
5173 bool dup_args, bool omit_args)
5175 ILGenerator ig = ec.ig;
5176 bool struct_call = false;
5177 bool this_call = false;
5178 LocalTemporary this_arg = null;
5180 Type decl_type = method.DeclaringType;
5182 if (!RootContext.StdLib) {
5183 // Replace any calls to the system's System.Array type with calls to
5184 // the newly created one.
5185 if (method == TypeManager.system_int_array_get_length)
5186 method = TypeManager.int_array_get_length;
5187 else if (method == TypeManager.system_int_array_get_rank)
5188 method = TypeManager.int_array_get_rank;
5189 else if (method == TypeManager.system_object_array_clone)
5190 method = TypeManager.object_array_clone;
5191 else if (method == TypeManager.system_int_array_get_length_int)
5192 method = TypeManager.int_array_get_length_int;
5193 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5194 method = TypeManager.int_array_get_lower_bound_int;
5195 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5196 method = TypeManager.int_array_get_upper_bound_int;
5197 else if (method == TypeManager.system_void_array_copyto_array_int)
5198 method = TypeManager.void_array_copyto_array_int;
5202 // This checks ObsoleteAttribute on the method and on the declaring type
5204 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
5206 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
5209 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
5211 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
5214 if (IsMethodExcluded (method, ec))
5218 this_call = instance_expr == null;
5219 if (decl_type.IsValueType || (!this_call && instance_expr.Type.IsValueType))
5223 // If this is ourselves, push "this"
5228 ig.Emit (OpCodes.Ldarg_0);
5232 // Push the instance expression
5234 if (instance_expr.Type.IsValueType) {
5236 // Special case: calls to a function declared in a
5237 // reference-type with a value-type argument need
5238 // to have their value boxed.
5239 if (decl_type.IsValueType) {
5241 // If the expression implements IMemoryLocation, then
5242 // we can optimize and use AddressOf on the
5245 // If not we have to use some temporary storage for
5247 if (instance_expr is IMemoryLocation) {
5248 ((IMemoryLocation)instance_expr).
5249 AddressOf (ec, AddressOp.LoadStore);
5251 LocalTemporary temp = new LocalTemporary (ec, instance_expr.Type);
5252 instance_expr.Emit (ec);
5254 temp.AddressOf (ec, AddressOp.Load);
5257 // avoid the overhead of doing this all the time.
5259 t = TypeManager.GetReferenceType (instance_expr.Type);
5261 instance_expr.Emit (ec);
5262 ig.Emit (OpCodes.Box, instance_expr.Type);
5263 t = TypeManager.object_type;
5266 instance_expr.Emit (ec);
5267 t = instance_expr.Type;
5272 this_arg = new LocalTemporary (ec, t);
5273 ig.Emit (OpCodes.Dup);
5274 this_arg.Store (ec);
5280 EmitArguments (ec, method, Arguments, dup_args, this_arg);
5283 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
5284 call_op = OpCodes.Call;
5286 call_op = OpCodes.Callvirt;
5288 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
5289 Type[] varargs_types = GetVarargsTypes (ec, method, Arguments);
5290 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
5297 // and DoFoo is not virtual, you can omit the callvirt,
5298 // because you don't need the null checking behavior.
5300 if (method is MethodInfo)
5301 ig.Emit (call_op, (MethodInfo) method);
5303 ig.Emit (call_op, (ConstructorInfo) method);
5306 public override void Emit (EmitContext ec)
5308 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5310 EmitCall (ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5313 public override void EmitStatement (EmitContext ec)
5318 // Pop the return value if there is one
5320 if (method is MethodInfo){
5321 Type ret = ((MethodInfo)method).ReturnType;
5322 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5323 ec.ig.Emit (OpCodes.Pop);
5328 public class InvocationOrCast : ExpressionStatement
5331 Expression argument;
5333 public InvocationOrCast (Expression expr, Expression argument, Location loc)
5336 this.argument = argument;
5340 public override Expression DoResolve (EmitContext ec)
5343 // First try to resolve it as a cast.
5345 type = ec.DeclSpace.ResolveType (expr, true, loc);
5347 Cast cast = new Cast (new TypeExpression (type, loc), argument, loc);
5348 return cast.Resolve (ec);
5352 // This can either be a type or a delegate invocation.
5353 // Let's just resolve it and see what we'll get.
5355 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5360 // Ok, so it's a Cast.
5362 if (expr.eclass == ExprClass.Type) {
5363 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
5364 return cast.Resolve (ec);
5368 // It's a delegate invocation.
5370 if (!TypeManager.IsDelegateType (expr.Type)) {
5371 Error (149, "Method name expected");
5375 ArrayList args = new ArrayList ();
5376 args.Add (new Argument (argument, Argument.AType.Expression));
5377 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5378 return invocation.Resolve (ec);
5383 Error (201, "Only assignment, call, increment, decrement and new object " +
5384 "expressions can be used as a statement");
5387 public override ExpressionStatement ResolveStatement (EmitContext ec)
5390 // First try to resolve it as a cast.
5392 type = ec.DeclSpace.ResolveType (expr, true, loc);
5399 // This can either be a type or a delegate invocation.
5400 // Let's just resolve it and see what we'll get.
5402 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5403 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5409 // It's a delegate invocation.
5411 if (!TypeManager.IsDelegateType (expr.Type)) {
5412 Error (149, "Method name expected");
5416 ArrayList args = new ArrayList ();
5417 args.Add (new Argument (argument, Argument.AType.Expression));
5418 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5419 return invocation.ResolveStatement (ec);
5422 public override void Emit (EmitContext ec)
5424 throw new Exception ("Cannot happen");
5427 public override void EmitStatement (EmitContext ec)
5429 throw new Exception ("Cannot happen");
5434 // This class is used to "disable" the code generation for the
5435 // temporary variable when initializing value types.
5437 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5438 public void AddressOf (EmitContext ec, AddressOp Mode)
5445 /// Implements the new expression
5447 public class New : ExpressionStatement, IMemoryLocation {
5448 public readonly ArrayList Arguments;
5451 // During bootstrap, it contains the RequestedType,
5452 // but if `type' is not null, it *might* contain a NewDelegate
5453 // (because of field multi-initialization)
5455 public Expression RequestedType;
5457 MethodBase method = null;
5460 // If set, the new expression is for a value_target, and
5461 // we will not leave anything on the stack.
5463 Expression value_target;
5464 bool value_target_set = false;
5466 public New (Expression requested_type, ArrayList arguments, Location l)
5468 RequestedType = requested_type;
5469 Arguments = arguments;
5473 public bool SetValueTypeVariable (Expression value)
5475 value_target = value;
5476 value_target_set = true;
5477 if (!(value_target is IMemoryLocation)){
5478 Error_UnexpectedKind ("variable");
5485 // This function is used to disable the following code sequence for
5486 // value type initialization:
5488 // AddressOf (temporary)
5492 // Instead the provide will have provided us with the address on the
5493 // stack to store the results.
5495 static Expression MyEmptyExpression;
5497 public void DisableTemporaryValueType ()
5499 if (MyEmptyExpression == null)
5500 MyEmptyExpression = new EmptyAddressOf ();
5503 // To enable this, look into:
5504 // test-34 and test-89 and self bootstrapping.
5506 // For instance, we can avoid a copy by using `newobj'
5507 // instead of Call + Push-temp on value types.
5508 // value_target = MyEmptyExpression;
5511 public override Expression DoResolve (EmitContext ec)
5514 // The New DoResolve might be called twice when initializing field
5515 // expressions (see EmitFieldInitializers, the call to
5516 // GetInitializerExpression will perform a resolve on the expression,
5517 // and later the assign will trigger another resolution
5519 // This leads to bugs (#37014)
5522 if (RequestedType is NewDelegate)
5523 return RequestedType;
5527 type = ec.DeclSpace.ResolveType (RequestedType, false, loc);
5532 CheckObsoleteAttribute (type);
5534 bool IsDelegate = TypeManager.IsDelegateType (type);
5537 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5538 if (RequestedType != null)
5539 if (!(RequestedType is NewDelegate))
5540 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
5541 return RequestedType;
5544 if (type.IsInterface || type.IsAbstract){
5545 Error (144, "It is not possible to create instances of interfaces or abstract classes");
5549 bool is_struct = type.IsValueType;
5550 eclass = ExprClass.Value;
5553 // SRE returns a match for .ctor () on structs (the object constructor),
5554 // so we have to manually ignore it.
5556 if (is_struct && Arguments == null)
5560 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
5561 ml = MemberLookupFinal (ec, type, type, ".ctor",
5562 MemberTypes.Constructor,
5563 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5568 if (! (ml is MethodGroupExpr)){
5570 ml.Error_UnexpectedKind ("method group");
5576 if (Arguments != null){
5577 foreach (Argument a in Arguments){
5578 if (!a.Resolve (ec, loc))
5583 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
5587 if (method == null) {
5588 if (!is_struct || Arguments.Count > 0) {
5589 Error (1501, String.Format (
5590 "New invocation: Can not find a constructor in `{0}' for this argument list",
5591 TypeManager.CSharpName (type)));
5600 // This DoEmit can be invoked in two contexts:
5601 // * As a mechanism that will leave a value on the stack (new object)
5602 // * As one that wont (init struct)
5604 // You can control whether a value is required on the stack by passing
5605 // need_value_on_stack. The code *might* leave a value on the stack
5606 // so it must be popped manually
5608 // If we are dealing with a ValueType, we have a few
5609 // situations to deal with:
5611 // * The target is a ValueType, and we have been provided
5612 // the instance (this is easy, we are being assigned).
5614 // * The target of New is being passed as an argument,
5615 // to a boxing operation or a function that takes a
5618 // In this case, we need to create a temporary variable
5619 // that is the argument of New.
5621 // Returns whether a value is left on the stack
5623 bool DoEmit (EmitContext ec, bool need_value_on_stack)
5625 bool is_value_type = type.IsValueType;
5626 ILGenerator ig = ec.ig;
5631 // Allow DoEmit() to be called multiple times.
5632 // We need to create a new LocalTemporary each time since
5633 // you can't share LocalBuilders among ILGeneators.
5634 if (!value_target_set)
5635 value_target = new LocalTemporary (ec, type);
5637 ml = (IMemoryLocation) value_target;
5638 ml.AddressOf (ec, AddressOp.Store);
5642 Invocation.EmitArguments (ec, method, Arguments, false, null);
5646 ig.Emit (OpCodes.Initobj, type);
5648 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5649 if (need_value_on_stack){
5650 value_target.Emit (ec);
5655 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
5660 public override void Emit (EmitContext ec)
5665 public override void EmitStatement (EmitContext ec)
5667 if (DoEmit (ec, false))
5668 ec.ig.Emit (OpCodes.Pop);
5671 public void AddressOf (EmitContext ec, AddressOp Mode)
5673 if (!type.IsValueType){
5675 // We throw an exception. So far, I believe we only need to support
5677 // foreach (int j in new StructType ())
5680 throw new Exception ("AddressOf should not be used for classes");
5683 if (!value_target_set)
5684 value_target = new LocalTemporary (ec, type);
5686 IMemoryLocation ml = (IMemoryLocation) value_target;
5687 ml.AddressOf (ec, AddressOp.Store);
5689 Invocation.EmitArguments (ec, method, Arguments, false, null);
5692 ec.ig.Emit (OpCodes.Initobj, type);
5694 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5696 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
5701 /// 14.5.10.2: Represents an array creation expression.
5705 /// There are two possible scenarios here: one is an array creation
5706 /// expression that specifies the dimensions and optionally the
5707 /// initialization data and the other which does not need dimensions
5708 /// specified but where initialization data is mandatory.
5710 public class ArrayCreation : Expression {
5711 Expression requested_base_type;
5712 ArrayList initializers;
5715 // The list of Argument types.
5716 // This is used to construct the `newarray' or constructor signature
5718 ArrayList arguments;
5721 // Method used to create the array object.
5723 MethodBase new_method = null;
5725 Type array_element_type;
5726 Type underlying_type;
5727 bool is_one_dimensional = false;
5728 bool is_builtin_type = false;
5729 bool expect_initializers = false;
5730 int num_arguments = 0;
5734 ArrayList array_data;
5739 // The number of array initializers that we can handle
5740 // via the InitializeArray method - through EmitStaticInitializers
5742 int num_automatic_initializers;
5744 const int max_automatic_initializers = 6;
5746 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
5748 this.requested_base_type = requested_base_type;
5749 this.initializers = initializers;
5753 arguments = new ArrayList ();
5755 foreach (Expression e in exprs) {
5756 arguments.Add (new Argument (e, Argument.AType.Expression));
5761 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
5763 this.requested_base_type = requested_base_type;
5764 this.initializers = initializers;
5768 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
5770 //string tmp = rank.Substring (rank.LastIndexOf ('['));
5772 //dimensions = tmp.Length - 1;
5773 expect_initializers = true;
5776 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
5778 StringBuilder sb = new StringBuilder (rank);
5781 for (int i = 1; i < idx_count; i++)
5786 return new ComposedCast (base_type, sb.ToString (), loc);
5789 void Error_IncorrectArrayInitializer ()
5791 Error (178, "Incorrectly structured array initializer");
5794 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
5796 if (specified_dims) {
5797 Argument a = (Argument) arguments [idx];
5799 if (!a.Resolve (ec, loc))
5802 if (!(a.Expr is Constant)) {
5803 Error (150, "A constant value is expected");
5807 int value = (int) ((Constant) a.Expr).GetValue ();
5809 if (value != probe.Count) {
5810 Error_IncorrectArrayInitializer ();
5814 bounds [idx] = value;
5817 int child_bounds = -1;
5818 foreach (object o in probe) {
5819 if (o is ArrayList) {
5820 int current_bounds = ((ArrayList) o).Count;
5822 if (child_bounds == -1)
5823 child_bounds = current_bounds;
5825 else if (child_bounds != current_bounds){
5826 Error_IncorrectArrayInitializer ();
5829 if (specified_dims && (idx + 1 >= arguments.Count)){
5830 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
5834 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
5838 if (child_bounds != -1){
5839 Error_IncorrectArrayInitializer ();
5843 Expression tmp = (Expression) o;
5844 tmp = tmp.Resolve (ec);
5848 // Console.WriteLine ("I got: " + tmp);
5849 // Handle initialization from vars, fields etc.
5851 Expression conv = Convert.ImplicitConversionRequired (
5852 ec, tmp, underlying_type, loc);
5857 if (conv is StringConstant || conv is DecimalConstant || conv is NullCast) {
5858 // These are subclasses of Constant that can appear as elements of an
5859 // array that cannot be statically initialized (with num_automatic_initializers
5860 // > max_automatic_initializers), so num_automatic_initializers should be left as zero.
5861 array_data.Add (conv);
5862 } else if (conv is Constant) {
5863 // These are the types of Constant that can appear in arrays that can be
5864 // statically allocated.
5865 array_data.Add (conv);
5866 num_automatic_initializers++;
5868 array_data.Add (conv);
5875 public void UpdateIndices (EmitContext ec)
5878 for (ArrayList probe = initializers; probe != null;) {
5879 if (probe.Count > 0 && probe [0] is ArrayList) {
5880 Expression e = new IntConstant (probe.Count);
5881 arguments.Add (new Argument (e, Argument.AType.Expression));
5883 bounds [i++] = probe.Count;
5885 probe = (ArrayList) probe [0];
5888 Expression e = new IntConstant (probe.Count);
5889 arguments.Add (new Argument (e, Argument.AType.Expression));
5891 bounds [i++] = probe.Count;
5898 public bool ValidateInitializers (EmitContext ec, Type array_type)
5900 if (initializers == null) {
5901 if (expect_initializers)
5907 if (underlying_type == null)
5911 // We use this to store all the date values in the order in which we
5912 // will need to store them in the byte blob later
5914 array_data = new ArrayList ();
5915 bounds = new Hashtable ();
5919 if (arguments != null) {
5920 ret = CheckIndices (ec, initializers, 0, true);
5923 arguments = new ArrayList ();
5925 ret = CheckIndices (ec, initializers, 0, false);
5932 if (arguments.Count != dimensions) {
5933 Error_IncorrectArrayInitializer ();
5941 void Error_NegativeArrayIndex ()
5943 Error (284, "Can not create array with a negative size");
5947 // Converts `source' to an int, uint, long or ulong.
5949 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
5953 bool old_checked = ec.CheckState;
5954 ec.CheckState = true;
5956 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
5957 if (target == null){
5958 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
5959 if (target == null){
5960 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
5961 if (target == null){
5962 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
5964 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
5968 ec.CheckState = old_checked;
5971 // Only positive constants are allowed at compile time
5973 if (target is Constant){
5974 if (target is IntConstant){
5975 if (((IntConstant) target).Value < 0){
5976 Error_NegativeArrayIndex ();
5981 if (target is LongConstant){
5982 if (((LongConstant) target).Value < 0){
5983 Error_NegativeArrayIndex ();
5994 // Creates the type of the array
5996 bool LookupType (EmitContext ec)
5998 StringBuilder array_qualifier = new StringBuilder (rank);
6001 // `In the first form allocates an array instace of the type that results
6002 // from deleting each of the individual expression from the expression list'
6004 if (num_arguments > 0) {
6005 array_qualifier.Append ("[");
6006 for (int i = num_arguments-1; i > 0; i--)
6007 array_qualifier.Append (",");
6008 array_qualifier.Append ("]");
6014 Expression array_type_expr;
6015 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
6016 type = ec.DeclSpace.ResolveType (array_type_expr, false, loc);
6021 if (!type.IsArray) {
6022 Error (622, "Can only use array initializer expressions to assign to array types. Try using a new expression instead.");
6025 underlying_type = TypeManager.GetElementType (type);
6026 dimensions = type.GetArrayRank ();
6031 public override Expression DoResolve (EmitContext ec)
6035 if (!LookupType (ec))
6039 // First step is to validate the initializers and fill
6040 // in any missing bits
6042 if (!ValidateInitializers (ec, type))
6045 if (arguments == null)
6048 arg_count = arguments.Count;
6049 foreach (Argument a in arguments){
6050 if (!a.Resolve (ec, loc))
6053 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
6054 if (real_arg == null)
6061 array_element_type = TypeManager.GetElementType (type);
6063 if (arg_count == 1) {
6064 is_one_dimensional = true;
6065 eclass = ExprClass.Value;
6069 is_builtin_type = TypeManager.IsBuiltinType (type);
6071 if (is_builtin_type) {
6074 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
6075 AllBindingFlags, loc);
6077 if (!(ml is MethodGroupExpr)) {
6078 ml.Error_UnexpectedKind ("method group");
6083 Error (-6, "New invocation: Can not find a constructor for " +
6084 "this argument list");
6088 new_method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, arguments, loc);
6090 if (new_method == null) {
6091 Error (-6, "New invocation: Can not find a constructor for " +
6092 "this argument list");
6096 eclass = ExprClass.Value;
6099 ModuleBuilder mb = CodeGen.Module.Builder;
6100 ArrayList args = new ArrayList ();
6102 if (arguments != null) {
6103 for (int i = 0; i < arg_count; i++)
6104 args.Add (TypeManager.int32_type);
6107 Type [] arg_types = null;
6110 arg_types = new Type [args.Count];
6112 args.CopyTo (arg_types, 0);
6114 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
6117 if (new_method == null) {
6118 Error (-6, "New invocation: Can not find a constructor for " +
6119 "this argument list");
6123 eclass = ExprClass.Value;
6128 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
6133 int count = array_data.Count;
6135 if (underlying_type.IsEnum)
6136 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
6138 factor = GetTypeSize (underlying_type);
6140 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
6142 data = new byte [(count * factor + 4) & ~3];
6145 for (int i = 0; i < count; ++i) {
6146 object v = array_data [i];
6148 if (v is EnumConstant)
6149 v = ((EnumConstant) v).Child;
6151 if (v is Constant && !(v is StringConstant))
6152 v = ((Constant) v).GetValue ();
6158 if (underlying_type == TypeManager.int64_type){
6159 if (!(v is Expression)){
6160 long val = (long) v;
6162 for (int j = 0; j < factor; ++j) {
6163 data [idx + j] = (byte) (val & 0xFF);
6167 } else if (underlying_type == TypeManager.uint64_type){
6168 if (!(v is Expression)){
6169 ulong val = (ulong) v;
6171 for (int j = 0; j < factor; ++j) {
6172 data [idx + j] = (byte) (val & 0xFF);
6176 } else if (underlying_type == TypeManager.float_type) {
6177 if (!(v is Expression)){
6178 element = BitConverter.GetBytes ((float) v);
6180 for (int j = 0; j < factor; ++j)
6181 data [idx + j] = element [j];
6183 } else if (underlying_type == TypeManager.double_type) {
6184 if (!(v is Expression)){
6185 element = BitConverter.GetBytes ((double) v);
6187 for (int j = 0; j < factor; ++j)
6188 data [idx + j] = element [j];
6190 } else if (underlying_type == TypeManager.char_type){
6191 if (!(v is Expression)){
6192 int val = (int) ((char) v);
6194 data [idx] = (byte) (val & 0xff);
6195 data [idx+1] = (byte) (val >> 8);
6197 } else if (underlying_type == TypeManager.short_type){
6198 if (!(v is Expression)){
6199 int val = (int) ((short) v);
6201 data [idx] = (byte) (val & 0xff);
6202 data [idx+1] = (byte) (val >> 8);
6204 } else if (underlying_type == TypeManager.ushort_type){
6205 if (!(v is Expression)){
6206 int val = (int) ((ushort) v);
6208 data [idx] = (byte) (val & 0xff);
6209 data [idx+1] = (byte) (val >> 8);
6211 } else if (underlying_type == TypeManager.int32_type) {
6212 if (!(v is Expression)){
6215 data [idx] = (byte) (val & 0xff);
6216 data [idx+1] = (byte) ((val >> 8) & 0xff);
6217 data [idx+2] = (byte) ((val >> 16) & 0xff);
6218 data [idx+3] = (byte) (val >> 24);
6220 } else if (underlying_type == TypeManager.uint32_type) {
6221 if (!(v is Expression)){
6222 uint val = (uint) v;
6224 data [idx] = (byte) (val & 0xff);
6225 data [idx+1] = (byte) ((val >> 8) & 0xff);
6226 data [idx+2] = (byte) ((val >> 16) & 0xff);
6227 data [idx+3] = (byte) (val >> 24);
6229 } else if (underlying_type == TypeManager.sbyte_type) {
6230 if (!(v is Expression)){
6231 sbyte val = (sbyte) v;
6232 data [idx] = (byte) val;
6234 } else if (underlying_type == TypeManager.byte_type) {
6235 if (!(v is Expression)){
6236 byte val = (byte) v;
6237 data [idx] = (byte) val;
6239 } else if (underlying_type == TypeManager.bool_type) {
6240 if (!(v is Expression)){
6241 bool val = (bool) v;
6242 data [idx] = (byte) (val ? 1 : 0);
6244 } else if (underlying_type == TypeManager.decimal_type){
6245 if (!(v is Expression)){
6246 int [] bits = Decimal.GetBits ((decimal) v);
6249 // FIXME: For some reason, this doesn't work on the MS runtime.
6250 int [] nbits = new int [4];
6251 nbits [0] = bits [3];
6252 nbits [1] = bits [2];
6253 nbits [2] = bits [0];
6254 nbits [3] = bits [1];
6256 for (int j = 0; j < 4; j++){
6257 data [p++] = (byte) (nbits [j] & 0xff);
6258 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6259 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6260 data [p++] = (byte) (nbits [j] >> 24);
6264 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6273 // Emits the initializers for the array
6275 void EmitStaticInitializers (EmitContext ec)
6278 // First, the static data
6281 ILGenerator ig = ec.ig;
6283 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6285 fb = RootContext.MakeStaticData (data);
6287 ig.Emit (OpCodes.Dup);
6288 ig.Emit (OpCodes.Ldtoken, fb);
6289 ig.Emit (OpCodes.Call,
6290 TypeManager.void_initializearray_array_fieldhandle);
6294 // Emits pieces of the array that can not be computed at compile
6295 // time (variables and string locations).
6297 // This always expect the top value on the stack to be the array
6299 void EmitDynamicInitializers (EmitContext ec)
6301 ILGenerator ig = ec.ig;
6302 int dims = bounds.Count;
6303 int [] current_pos = new int [dims];
6304 int top = array_data.Count;
6306 MethodInfo set = null;
6310 ModuleBuilder mb = null;
6311 mb = CodeGen.Module.Builder;
6312 args = new Type [dims + 1];
6315 for (j = 0; j < dims; j++)
6316 args [j] = TypeManager.int32_type;
6318 args [j] = array_element_type;
6320 set = mb.GetArrayMethod (
6322 CallingConventions.HasThis | CallingConventions.Standard,
6323 TypeManager.void_type, args);
6326 for (int i = 0; i < top; i++){
6328 Expression e = null;
6330 if (array_data [i] is Expression)
6331 e = (Expression) array_data [i];
6335 // Basically we do this for string literals and
6336 // other non-literal expressions
6338 if (e is EnumConstant){
6339 e = ((EnumConstant) e).Child;
6342 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6343 num_automatic_initializers <= max_automatic_initializers) {
6344 Type etype = e.Type;
6346 ig.Emit (OpCodes.Dup);
6348 for (int idx = 0; idx < dims; idx++)
6349 IntConstant.EmitInt (ig, current_pos [idx]);
6352 // If we are dealing with a struct, get the
6353 // address of it, so we can store it.
6356 etype.IsSubclassOf (TypeManager.value_type) &&
6357 (!TypeManager.IsBuiltinOrEnum (etype) ||
6358 etype == TypeManager.decimal_type)) {
6363 // Let new know that we are providing
6364 // the address where to store the results
6366 n.DisableTemporaryValueType ();
6369 ig.Emit (OpCodes.Ldelema, etype);
6376 OpCode op = ArrayAccess.GetStoreOpcode (etype, out is_stobj);
6378 ig.Emit (OpCodes.Stobj, etype);
6382 ig.Emit (OpCodes.Call, set);
6390 for (int j = dims - 1; j >= 0; j--){
6392 if (current_pos [j] < (int) bounds [j])
6394 current_pos [j] = 0;
6399 void EmitArrayArguments (EmitContext ec)
6401 ILGenerator ig = ec.ig;
6403 foreach (Argument a in arguments) {
6404 Type atype = a.Type;
6407 if (atype == TypeManager.uint64_type)
6408 ig.Emit (OpCodes.Conv_Ovf_U4);
6409 else if (atype == TypeManager.int64_type)
6410 ig.Emit (OpCodes.Conv_Ovf_I4);
6414 public override void Emit (EmitContext ec)
6416 ILGenerator ig = ec.ig;
6418 EmitArrayArguments (ec);
6419 if (is_one_dimensional)
6420 ig.Emit (OpCodes.Newarr, array_element_type);
6422 if (is_builtin_type)
6423 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6425 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6428 if (initializers != null){
6430 // FIXME: Set this variable correctly.
6432 bool dynamic_initializers = true;
6434 // This will never be true for array types that cannot be statically
6435 // initialized. num_automatic_initializers will always be zero. See
6437 if (num_automatic_initializers > max_automatic_initializers)
6438 EmitStaticInitializers (ec);
6440 if (dynamic_initializers)
6441 EmitDynamicInitializers (ec);
6445 public object EncodeAsAttribute ()
6447 if (!is_one_dimensional){
6448 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6452 if (array_data == null){
6453 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6457 object [] ret = new object [array_data.Count];
6459 foreach (Expression e in array_data){
6462 if (e is NullLiteral)
6465 if (!Attribute.GetAttributeArgumentExpression (e, Location, array_element_type, out v))
6473 public Expression TurnIntoConstant ()
6476 // Should use something like the above attribute thing.
6477 // It should return a subclass of Constant that just returns
6478 // the computed value of the array
6480 throw new Exception ("Does not support yet Turning array into a Constant");
6485 /// Represents the `this' construct
6487 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6490 VariableInfo variable_info;
6492 public This (Block block, Location loc)
6498 public This (Location loc)
6503 public VariableInfo VariableInfo {
6504 get { return variable_info; }
6507 public bool VerifyFixed (bool is_expression)
6509 if ((variable_info == null) || (variable_info.LocalInfo == null))
6512 return variable_info.LocalInfo.IsFixed;
6515 public bool ResolveBase (EmitContext ec)
6517 eclass = ExprClass.Variable;
6518 type = ec.ContainerType;
6521 Error (26, "Keyword this not valid in static code");
6525 if ((block != null) && (block.ThisVariable != null))
6526 variable_info = block.ThisVariable.VariableInfo;
6531 public override Expression DoResolve (EmitContext ec)
6533 if (!ResolveBase (ec))
6536 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
6537 Error (188, "The this object cannot be used before all " +
6538 "of its fields are assigned to");
6539 variable_info.SetAssigned (ec);
6543 if (ec.IsFieldInitializer) {
6544 Error (27, "Keyword `this' can't be used outside a constructor, " +
6545 "a method or a property.");
6552 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6554 if (!ResolveBase (ec))
6557 if (variable_info != null)
6558 variable_info.SetAssigned (ec);
6560 if (ec.TypeContainer is Class){
6561 Error (1604, "Cannot assign to `this'");
6568 public void Emit (EmitContext ec, bool leave_copy)
6572 ec.ig.Emit (OpCodes.Dup);
6575 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
6577 ILGenerator ig = ec.ig;
6579 if (ec.TypeContainer is Struct){
6583 ec.ig.Emit (OpCodes.Dup);
6584 ig.Emit (OpCodes.Stobj, type);
6586 throw new Exception ("how did you get here");
6590 public override void Emit (EmitContext ec)
6592 ILGenerator ig = ec.ig;
6595 if (ec.TypeContainer is Struct)
6596 ig.Emit (OpCodes.Ldobj, type);
6599 public void AddressOf (EmitContext ec, AddressOp mode)
6604 // FIGURE OUT WHY LDARG_S does not work
6606 // consider: struct X { int val; int P { set { val = value; }}}
6608 // Yes, this looks very bad. Look at `NOTAS' for
6610 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
6615 /// Represents the `__arglist' construct
6617 public class ArglistAccess : Expression
6619 public ArglistAccess (Location loc)
6624 public bool ResolveBase (EmitContext ec)
6626 eclass = ExprClass.Variable;
6627 type = TypeManager.runtime_argument_handle_type;
6631 public override Expression DoResolve (EmitContext ec)
6633 if (!ResolveBase (ec))
6636 if (ec.IsFieldInitializer || !ec.CurrentBlock.HasVarargs) {
6637 Error (190, "The __arglist construct is valid only within " +
6638 "a variable argument method.");
6645 public override void Emit (EmitContext ec)
6647 ec.ig.Emit (OpCodes.Arglist);
6652 /// Represents the `__arglist (....)' construct
6654 public class Arglist : Expression
6656 public readonly Argument[] Arguments;
6658 public Arglist (Argument[] args, Location l)
6664 public Type[] ArgumentTypes {
6666 Type[] retval = new Type [Arguments.Length];
6667 for (int i = 0; i < Arguments.Length; i++)
6668 retval [i] = Arguments [i].Type;
6673 public override Expression DoResolve (EmitContext ec)
6675 eclass = ExprClass.Variable;
6676 type = TypeManager.runtime_argument_handle_type;
6678 foreach (Argument arg in Arguments) {
6679 if (!arg.Resolve (ec, loc))
6686 public override void Emit (EmitContext ec)
6688 foreach (Argument arg in Arguments)
6694 // This produces the value that renders an instance, used by the iterators code
6696 public class ProxyInstance : Expression, IMemoryLocation {
6697 public override Expression DoResolve (EmitContext ec)
6699 eclass = ExprClass.Variable;
6700 type = ec.ContainerType;
6704 public override void Emit (EmitContext ec)
6706 ec.ig.Emit (OpCodes.Ldarg_0);
6710 public void AddressOf (EmitContext ec, AddressOp mode)
6712 ec.ig.Emit (OpCodes.Ldarg_0);
6717 /// Implements the typeof operator
6719 public class TypeOf : Expression {
6720 public readonly Expression QueriedType;
6721 protected Type typearg;
6723 public TypeOf (Expression queried_type, Location l)
6725 QueriedType = queried_type;
6729 public override Expression DoResolve (EmitContext ec)
6731 typearg = ec.DeclSpace.ResolveType (QueriedType, false, loc);
6733 if (typearg == null)
6736 if (typearg == TypeManager.void_type) {
6737 Error (673, "System.Void cannot be used from C# - " +
6738 "use typeof (void) to get the void type object");
6742 CheckObsoleteAttribute (typearg);
6744 type = TypeManager.type_type;
6745 eclass = ExprClass.Type;
6749 public override void Emit (EmitContext ec)
6751 ec.ig.Emit (OpCodes.Ldtoken, typearg);
6752 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6755 public Type TypeArg {
6756 get { return typearg; }
6761 /// Implements the `typeof (void)' operator
6763 public class TypeOfVoid : TypeOf {
6764 public TypeOfVoid (Location l) : base (null, l)
6769 public override Expression DoResolve (EmitContext ec)
6771 type = TypeManager.type_type;
6772 typearg = TypeManager.void_type;
6773 eclass = ExprClass.Type;
6779 /// Implements the sizeof expression
6781 public class SizeOf : Expression {
6782 public readonly Expression QueriedType;
6785 public SizeOf (Expression queried_type, Location l)
6787 this.QueriedType = queried_type;
6791 public override Expression DoResolve (EmitContext ec)
6795 233, loc, "Sizeof may only be used in an unsafe context " +
6796 "(consider using System.Runtime.InteropServices.Marshal.Sizeof");
6800 type_queried = ec.DeclSpace.ResolveType (QueriedType, false, loc);
6801 if (type_queried == null)
6804 CheckObsoleteAttribute (type_queried);
6806 if (!TypeManager.IsUnmanagedType (type_queried)){
6807 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
6811 type = TypeManager.int32_type;
6812 eclass = ExprClass.Value;
6816 public override void Emit (EmitContext ec)
6818 int size = GetTypeSize (type_queried);
6821 ec.ig.Emit (OpCodes.Sizeof, type_queried);
6823 IntConstant.EmitInt (ec.ig, size);
6828 /// Implements the member access expression
6830 public class MemberAccess : Expression {
6831 public readonly string Identifier;
6834 public MemberAccess (Expression expr, string id, Location l)
6841 public Expression Expr {
6847 public static void error176 (Location loc, string name)
6849 Report.Error (176, loc, "Static member `" +
6850 name + "' cannot be accessed " +
6851 "with an instance reference, qualify with a " +
6852 "type name instead");
6855 public static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Expression left, Location loc)
6857 SimpleName sn = left_original as SimpleName;
6858 if (sn == null || left == null || left.Type.Name != sn.Name)
6861 return RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc) != null;
6864 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
6865 Expression left, Location loc,
6866 Expression left_original)
6868 bool left_is_type, left_is_explicit;
6870 // If `left' is null, then we're called from SimpleNameResolve and this is
6871 // a member in the currently defining class.
6873 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
6874 left_is_explicit = false;
6876 // Implicitly default to `this' unless we're static.
6877 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
6878 left = ec.GetThis (loc);
6880 left_is_type = left is TypeExpr;
6881 left_is_explicit = true;
6884 if (member_lookup is FieldExpr){
6885 FieldExpr fe = (FieldExpr) member_lookup;
6886 FieldInfo fi = fe.FieldInfo;
6887 Type decl_type = fi.DeclaringType;
6889 if (fi is FieldBuilder) {
6890 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
6894 if (!c.LookupConstantValue (out o))
6897 object real_value = ((Constant) c.Expr).GetValue ();
6899 return Constantify (real_value, fi.FieldType);
6904 Type t = fi.FieldType;
6908 if (fi is FieldBuilder)
6909 o = TypeManager.GetValue ((FieldBuilder) fi);
6911 o = fi.GetValue (fi);
6913 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
6914 if (left_is_explicit && !left_is_type &&
6915 !IdenticalNameAndTypeName (ec, left_original, member_lookup, loc)) {
6916 error176 (loc, fe.FieldInfo.Name);
6920 Expression enum_member = MemberLookup (
6921 ec, decl_type, "value__", MemberTypes.Field,
6922 AllBindingFlags, loc);
6924 Enum en = TypeManager.LookupEnum (decl_type);
6928 c = Constantify (o, en.UnderlyingType);
6930 c = Constantify (o, enum_member.Type);
6932 return new EnumConstant (c, decl_type);
6935 Expression exp = Constantify (o, t);
6937 if (left_is_explicit && !left_is_type) {
6938 error176 (loc, fe.FieldInfo.Name);
6945 if (fi.FieldType.IsPointer && !ec.InUnsafe){
6951 if (member_lookup is EventExpr) {
6952 EventExpr ee = (EventExpr) member_lookup;
6955 // If the event is local to this class, we transform ourselves into
6959 if (ee.EventInfo.DeclaringType == ec.ContainerType ||
6960 TypeManager.IsNestedChildOf(ec.ContainerType, ee.EventInfo.DeclaringType)) {
6961 MemberInfo mi = GetFieldFromEvent (ee);
6965 // If this happens, then we have an event with its own
6966 // accessors and private field etc so there's no need
6967 // to transform ourselves.
6969 ee.InstanceExpression = left;
6973 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
6976 Report.Error (-200, loc, "Internal error!!");
6980 if (!left_is_explicit)
6983 ee.InstanceExpression = left;
6985 return ResolveMemberAccess (ec, ml, left, loc, left_original);
6989 if (member_lookup is IMemberExpr) {
6990 IMemberExpr me = (IMemberExpr) member_lookup;
6991 MethodGroupExpr mg = me as MethodGroupExpr;
6994 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
6995 mg.IsExplicitImpl = left_is_explicit;
6998 if ((ec.IsFieldInitializer || ec.IsStatic) &&
6999 IdenticalNameAndTypeName (ec, left_original, member_lookup, loc))
7000 return member_lookup;
7002 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
7007 if (!me.IsInstance) {
7008 if (IdenticalNameAndTypeName (ec, left_original, left, loc))
7009 return member_lookup;
7011 if (left_is_explicit) {
7012 error176 (loc, me.Name);
7018 // Since we can not check for instance objects in SimpleName,
7019 // becaue of the rule that allows types and variables to share
7020 // the name (as long as they can be de-ambiguated later, see
7021 // IdenticalNameAndTypeName), we have to check whether left
7022 // is an instance variable in a static context
7024 // However, if the left-hand value is explicitly given, then
7025 // it is already our instance expression, so we aren't in
7029 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
7030 IMemberExpr mexp = (IMemberExpr) left;
7032 if (!mexp.IsStatic){
7033 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
7038 if ((mg != null) && IdenticalNameAndTypeName (ec, left_original, left, loc))
7039 mg.IdenticalTypeName = true;
7041 me.InstanceExpression = left;
7044 return member_lookup;
7047 Console.WriteLine ("Left is: " + left);
7048 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
7049 Environment.Exit (1);
7053 public Expression DoResolve (EmitContext ec, Expression right_side, ResolveFlags flags)
7056 throw new Exception ();
7059 // Resolve the expression with flow analysis turned off, we'll do the definite
7060 // assignment checks later. This is because we don't know yet what the expression
7061 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7062 // definite assignment check on the actual field and not on the whole struct.
7065 Expression original = expr;
7066 expr = expr.Resolve (ec, flags | ResolveFlags.Intermediate | ResolveFlags.DisableFlowAnalysis);
7070 if (expr is SimpleName){
7071 SimpleName child_expr = (SimpleName) expr;
7073 Expression new_expr = new SimpleName (child_expr.Name, Identifier, loc);
7075 return new_expr.Resolve (ec, flags);
7079 // TODO: I mailed Ravi about this, and apparently we can get rid
7080 // of this and put it in the right place.
7082 // Handle enums here when they are in transit.
7083 // Note that we cannot afford to hit MemberLookup in this case because
7084 // it will fail to find any members at all
7087 Type expr_type = expr.Type;
7088 if (expr is TypeExpr){
7089 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
7090 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", expr_type);
7094 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
7095 Enum en = TypeManager.LookupEnum (expr_type);
7098 object value = en.LookupEnumValue (ec, Identifier, loc);
7101 ObsoleteAttribute oa = en.GetObsoleteAttribute (ec, Identifier);
7103 AttributeTester.Report_ObsoleteMessage (oa, en.GetSignatureForError (), Location);
7106 Constant c = Constantify (value, en.UnderlyingType);
7107 return new EnumConstant (c, expr_type);
7110 CheckObsoleteAttribute (expr_type);
7112 FieldInfo fi = expr_type.GetField (Identifier);
7114 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
7116 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), Location);
7122 if (expr_type.IsPointer){
7123 Error (23, "The `.' operator can not be applied to pointer operands (" +
7124 TypeManager.CSharpName (expr_type) + ")");
7128 Expression member_lookup;
7129 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
7130 if (member_lookup == null)
7133 if (member_lookup is TypeExpr) {
7134 if (!(expr is TypeExpr) && !(expr is SimpleName)) {
7135 Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
7136 member_lookup.Type + "' instead");
7140 return member_lookup;
7143 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
7144 if (member_lookup == null)
7147 // The following DoResolve/DoResolveLValue will do the definite assignment
7150 if (right_side != null)
7151 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
7153 member_lookup = member_lookup.DoResolve (ec);
7155 return member_lookup;
7158 public override Expression DoResolve (EmitContext ec)
7160 return DoResolve (ec, null, ResolveFlags.VariableOrValue |
7161 ResolveFlags.SimpleName | ResolveFlags.Type);
7164 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7166 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
7167 ResolveFlags.SimpleName | ResolveFlags.Type);
7170 public override Expression ResolveAsTypeStep (EmitContext ec)
7172 string fname = null;
7173 MemberAccess full_expr = this;
7174 while (full_expr != null) {
7176 fname = String.Concat (full_expr.Identifier, ".", fname);
7178 fname = full_expr.Identifier;
7180 if (full_expr.Expr is SimpleName) {
7181 string full_name = String.Concat (((SimpleName) full_expr.Expr).Name, ".", fname);
7182 Type fully_qualified = ec.DeclSpace.FindType (loc, full_name);
7183 if (fully_qualified != null)
7184 return new TypeExpression (fully_qualified, loc);
7187 full_expr = full_expr.Expr as MemberAccess;
7190 Expression new_expr = expr.ResolveAsTypeStep (ec);
7192 if (new_expr == null)
7195 if (new_expr is SimpleName){
7196 SimpleName child_expr = (SimpleName) new_expr;
7198 new_expr = new SimpleName (child_expr.Name, Identifier, loc);
7200 return new_expr.ResolveAsTypeStep (ec);
7203 Type expr_type = new_expr.Type;
7205 if (expr_type.IsPointer){
7206 Error (23, "The `.' operator can not be applied to pointer operands (" +
7207 TypeManager.CSharpName (expr_type) + ")");
7211 Expression member_lookup;
7212 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
7213 if (member_lookup == null)
7216 if (member_lookup is TypeExpr){
7217 member_lookup.Resolve (ec, ResolveFlags.Type);
7218 return member_lookup;
7224 public override void Emit (EmitContext ec)
7226 throw new Exception ("Should not happen");
7229 public override string ToString ()
7231 return expr + "." + Identifier;
7236 /// Implements checked expressions
7238 public class CheckedExpr : Expression {
7240 public Expression Expr;
7242 public CheckedExpr (Expression e, Location l)
7248 public override Expression DoResolve (EmitContext ec)
7250 bool last_check = ec.CheckState;
7251 bool last_const_check = ec.ConstantCheckState;
7253 ec.CheckState = true;
7254 ec.ConstantCheckState = true;
7255 Expr = Expr.Resolve (ec);
7256 ec.CheckState = last_check;
7257 ec.ConstantCheckState = last_const_check;
7262 if (Expr is Constant)
7265 eclass = Expr.eclass;
7270 public override void Emit (EmitContext ec)
7272 bool last_check = ec.CheckState;
7273 bool last_const_check = ec.ConstantCheckState;
7275 ec.CheckState = true;
7276 ec.ConstantCheckState = true;
7278 ec.CheckState = last_check;
7279 ec.ConstantCheckState = last_const_check;
7285 /// Implements the unchecked expression
7287 public class UnCheckedExpr : Expression {
7289 public Expression Expr;
7291 public UnCheckedExpr (Expression e, Location l)
7297 public override Expression DoResolve (EmitContext ec)
7299 bool last_check = ec.CheckState;
7300 bool last_const_check = ec.ConstantCheckState;
7302 ec.CheckState = false;
7303 ec.ConstantCheckState = false;
7304 Expr = Expr.Resolve (ec);
7305 ec.CheckState = last_check;
7306 ec.ConstantCheckState = last_const_check;
7311 if (Expr is Constant)
7314 eclass = Expr.eclass;
7319 public override void Emit (EmitContext ec)
7321 bool last_check = ec.CheckState;
7322 bool last_const_check = ec.ConstantCheckState;
7324 ec.CheckState = false;
7325 ec.ConstantCheckState = false;
7327 ec.CheckState = last_check;
7328 ec.ConstantCheckState = last_const_check;
7334 /// An Element Access expression.
7336 /// During semantic analysis these are transformed into
7337 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7339 public class ElementAccess : Expression {
7340 public ArrayList Arguments;
7341 public Expression Expr;
7343 public ElementAccess (Expression e, ArrayList e_list, Location l)
7352 Arguments = new ArrayList ();
7353 foreach (Expression tmp in e_list)
7354 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7358 bool CommonResolve (EmitContext ec)
7360 Expr = Expr.Resolve (ec);
7365 if (Arguments == null)
7368 foreach (Argument a in Arguments){
7369 if (!a.Resolve (ec, loc))
7376 Expression MakePointerAccess (EmitContext ec)
7380 if (t == TypeManager.void_ptr_type){
7381 Error (242, "The array index operation is not valid for void pointers");
7384 if (Arguments.Count != 1){
7385 Error (196, "A pointer must be indexed by a single value");
7390 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc).Resolve (ec);
7393 return new Indirection (p, loc).Resolve (ec);
7396 public override Expression DoResolve (EmitContext ec)
7398 if (!CommonResolve (ec))
7402 // We perform some simple tests, and then to "split" the emit and store
7403 // code we create an instance of a different class, and return that.
7405 // I am experimenting with this pattern.
7409 if (t == TypeManager.array_type){
7410 Report.Error (21, loc, "Cannot use indexer on System.Array");
7415 return (new ArrayAccess (this, loc)).Resolve (ec);
7416 else if (t.IsPointer)
7417 return MakePointerAccess (ec);
7419 return (new IndexerAccess (this, loc)).Resolve (ec);
7422 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7424 if (!CommonResolve (ec))
7429 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
7430 else if (t.IsPointer)
7431 return MakePointerAccess (ec);
7433 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
7436 public override void Emit (EmitContext ec)
7438 throw new Exception ("Should never be reached");
7443 /// Implements array access
7445 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7447 // Points to our "data" repository
7451 LocalTemporary temp;
7454 public ArrayAccess (ElementAccess ea_data, Location l)
7457 eclass = ExprClass.Variable;
7461 public override Expression DoResolve (EmitContext ec)
7464 ExprClass eclass = ea.Expr.eclass;
7466 // As long as the type is valid
7467 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7468 eclass == ExprClass.Value)) {
7469 ea.Expr.Error_UnexpectedKind ("variable or value");
7474 Type t = ea.Expr.Type;
7475 if (t.GetArrayRank () != ea.Arguments.Count){
7477 "Incorrect number of indexes for array " +
7478 " expected: " + t.GetArrayRank () + " got: " +
7479 ea.Arguments.Count);
7483 type = TypeManager.GetElementType (t);
7484 if (type.IsPointer && !ec.InUnsafe){
7485 UnsafeError (ea.Location);
7489 foreach (Argument a in ea.Arguments){
7490 Type argtype = a.Type;
7492 if (argtype == TypeManager.int32_type ||
7493 argtype == TypeManager.uint32_type ||
7494 argtype == TypeManager.int64_type ||
7495 argtype == TypeManager.uint64_type)
7499 // Mhm. This is strage, because the Argument.Type is not the same as
7500 // Argument.Expr.Type: the value changes depending on the ref/out setting.
7502 // Wonder if I will run into trouble for this.
7504 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
7509 eclass = ExprClass.Variable;
7515 /// Emits the right opcode to load an object of Type `t'
7516 /// from an array of T
7518 static public void EmitLoadOpcode (ILGenerator ig, Type type)
7520 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7521 ig.Emit (OpCodes.Ldelem_U1);
7522 else if (type == TypeManager.sbyte_type)
7523 ig.Emit (OpCodes.Ldelem_I1);
7524 else if (type == TypeManager.short_type)
7525 ig.Emit (OpCodes.Ldelem_I2);
7526 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7527 ig.Emit (OpCodes.Ldelem_U2);
7528 else if (type == TypeManager.int32_type)
7529 ig.Emit (OpCodes.Ldelem_I4);
7530 else if (type == TypeManager.uint32_type)
7531 ig.Emit (OpCodes.Ldelem_U4);
7532 else if (type == TypeManager.uint64_type)
7533 ig.Emit (OpCodes.Ldelem_I8);
7534 else if (type == TypeManager.int64_type)
7535 ig.Emit (OpCodes.Ldelem_I8);
7536 else if (type == TypeManager.float_type)
7537 ig.Emit (OpCodes.Ldelem_R4);
7538 else if (type == TypeManager.double_type)
7539 ig.Emit (OpCodes.Ldelem_R8);
7540 else if (type == TypeManager.intptr_type)
7541 ig.Emit (OpCodes.Ldelem_I);
7542 else if (TypeManager.IsEnumType (type)){
7543 EmitLoadOpcode (ig, TypeManager.EnumToUnderlying (type));
7544 } else if (type.IsValueType){
7545 ig.Emit (OpCodes.Ldelema, type);
7546 ig.Emit (OpCodes.Ldobj, type);
7548 ig.Emit (OpCodes.Ldelem_Ref);
7552 /// Returns the right opcode to store an object of Type `t'
7553 /// from an array of T.
7555 static public OpCode GetStoreOpcode (Type t, out bool is_stobj)
7557 //Console.WriteLine (new System.Diagnostics.StackTrace ());
7559 t = TypeManager.TypeToCoreType (t);
7560 if (TypeManager.IsEnumType (t))
7561 t = TypeManager.EnumToUnderlying (t);
7562 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
7563 t == TypeManager.bool_type)
7564 return OpCodes.Stelem_I1;
7565 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
7566 t == TypeManager.char_type)
7567 return OpCodes.Stelem_I2;
7568 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
7569 return OpCodes.Stelem_I4;
7570 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
7571 return OpCodes.Stelem_I8;
7572 else if (t == TypeManager.float_type)
7573 return OpCodes.Stelem_R4;
7574 else if (t == TypeManager.double_type)
7575 return OpCodes.Stelem_R8;
7576 else if (t == TypeManager.intptr_type) {
7578 return OpCodes.Stobj;
7579 } else if (t.IsValueType) {
7581 return OpCodes.Stobj;
7583 return OpCodes.Stelem_Ref;
7586 MethodInfo FetchGetMethod ()
7588 ModuleBuilder mb = CodeGen.Module.Builder;
7589 int arg_count = ea.Arguments.Count;
7590 Type [] args = new Type [arg_count];
7593 for (int i = 0; i < arg_count; i++){
7594 //args [i++] = a.Type;
7595 args [i] = TypeManager.int32_type;
7598 get = mb.GetArrayMethod (
7599 ea.Expr.Type, "Get",
7600 CallingConventions.HasThis |
7601 CallingConventions.Standard,
7607 MethodInfo FetchAddressMethod ()
7609 ModuleBuilder mb = CodeGen.Module.Builder;
7610 int arg_count = ea.Arguments.Count;
7611 Type [] args = new Type [arg_count];
7615 ret_type = TypeManager.GetReferenceType (type);
7617 for (int i = 0; i < arg_count; i++){
7618 //args [i++] = a.Type;
7619 args [i] = TypeManager.int32_type;
7622 address = mb.GetArrayMethod (
7623 ea.Expr.Type, "Address",
7624 CallingConventions.HasThis |
7625 CallingConventions.Standard,
7632 // Load the array arguments into the stack.
7634 // If we have been requested to cache the values (cached_locations array
7635 // initialized), then load the arguments the first time and store them
7636 // in locals. otherwise load from local variables.
7638 void LoadArrayAndArguments (EmitContext ec)
7640 ILGenerator ig = ec.ig;
7643 foreach (Argument a in ea.Arguments){
7644 Type argtype = a.Expr.Type;
7648 if (argtype == TypeManager.int64_type)
7649 ig.Emit (OpCodes.Conv_Ovf_I);
7650 else if (argtype == TypeManager.uint64_type)
7651 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7655 public void Emit (EmitContext ec, bool leave_copy)
7657 int rank = ea.Expr.Type.GetArrayRank ();
7658 ILGenerator ig = ec.ig;
7661 LoadArrayAndArguments (ec);
7664 EmitLoadOpcode (ig, type);
7668 method = FetchGetMethod ();
7669 ig.Emit (OpCodes.Call, method);
7672 LoadFromPtr (ec.ig, this.type);
7675 ec.ig.Emit (OpCodes.Dup);
7676 temp = new LocalTemporary (ec, this.type);
7681 public override void Emit (EmitContext ec)
7686 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
7688 int rank = ea.Expr.Type.GetArrayRank ();
7689 ILGenerator ig = ec.ig;
7690 Type t = source.Type;
7691 prepared = prepare_for_load;
7693 if (prepare_for_load) {
7694 AddressOf (ec, AddressOp.LoadStore);
7695 ec.ig.Emit (OpCodes.Dup);
7698 ec.ig.Emit (OpCodes.Dup);
7699 temp = new LocalTemporary (ec, this.type);
7702 StoreFromPtr (ec.ig, t);
7710 LoadArrayAndArguments (ec);
7714 OpCode op = GetStoreOpcode (t, out is_stobj);
7716 // The stobj opcode used by value types will need
7717 // an address on the stack, not really an array/array
7721 ig.Emit (OpCodes.Ldelema, t);
7725 ec.ig.Emit (OpCodes.Dup);
7726 temp = new LocalTemporary (ec, this.type);
7731 ig.Emit (OpCodes.Stobj, t);
7735 ModuleBuilder mb = CodeGen.Module.Builder;
7736 int arg_count = ea.Arguments.Count;
7737 Type [] args = new Type [arg_count + 1];
7742 ec.ig.Emit (OpCodes.Dup);
7743 temp = new LocalTemporary (ec, this.type);
7747 for (int i = 0; i < arg_count; i++){
7748 //args [i++] = a.Type;
7749 args [i] = TypeManager.int32_type;
7752 args [arg_count] = type;
7754 set = mb.GetArrayMethod (
7755 ea.Expr.Type, "Set",
7756 CallingConventions.HasThis |
7757 CallingConventions.Standard,
7758 TypeManager.void_type, args);
7760 ig.Emit (OpCodes.Call, set);
7767 public void AddressOf (EmitContext ec, AddressOp mode)
7769 int rank = ea.Expr.Type.GetArrayRank ();
7770 ILGenerator ig = ec.ig;
7772 LoadArrayAndArguments (ec);
7775 ig.Emit (OpCodes.Ldelema, type);
7777 MethodInfo address = FetchAddressMethod ();
7778 ig.Emit (OpCodes.Call, address);
7785 public ArrayList Properties;
7786 static Hashtable map;
7788 public struct Indexer {
7789 public readonly Type Type;
7790 public readonly MethodInfo Getter, Setter;
7792 public Indexer (Type type, MethodInfo get, MethodInfo set)
7802 map = new Hashtable ();
7807 Properties = new ArrayList ();
7810 void Append (MemberInfo [] mi)
7812 foreach (PropertyInfo property in mi){
7813 MethodInfo get, set;
7815 get = property.GetGetMethod (true);
7816 set = property.GetSetMethod (true);
7817 Properties.Add (new Indexer (property.PropertyType, get, set));
7821 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
7823 string p_name = TypeManager.IndexerPropertyName (lookup_type);
7825 MemberInfo [] mi = TypeManager.MemberLookup (
7826 caller_type, caller_type, lookup_type, MemberTypes.Property,
7827 BindingFlags.Public | BindingFlags.Instance |
7828 BindingFlags.DeclaredOnly, p_name, null);
7830 if (mi == null || mi.Length == 0)
7836 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
7838 Indexers ix = (Indexers) map [lookup_type];
7843 Type copy = lookup_type;
7844 while (copy != TypeManager.object_type && copy != null){
7845 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
7849 ix = new Indexers ();
7854 copy = copy.BaseType;
7857 if (!lookup_type.IsInterface)
7860 TypeExpr [] ifaces = TypeManager.GetInterfaces (lookup_type);
7861 if (ifaces != null) {
7862 foreach (TypeExpr iface in ifaces) {
7863 Type itype = iface.Type;
7864 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
7867 ix = new Indexers ();
7879 /// Expressions that represent an indexer call.
7881 public class IndexerAccess : Expression, IAssignMethod {
7883 // Points to our "data" repository
7885 MethodInfo get, set;
7886 ArrayList set_arguments;
7887 bool is_base_indexer;
7889 protected Type indexer_type;
7890 protected Type current_type;
7891 protected Expression instance_expr;
7892 protected ArrayList arguments;
7894 public IndexerAccess (ElementAccess ea, Location loc)
7895 : this (ea.Expr, false, loc)
7897 this.arguments = ea.Arguments;
7900 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
7903 this.instance_expr = instance_expr;
7904 this.is_base_indexer = is_base_indexer;
7905 this.eclass = ExprClass.Value;
7909 protected virtual bool CommonResolve (EmitContext ec)
7911 indexer_type = instance_expr.Type;
7912 current_type = ec.ContainerType;
7917 public override Expression DoResolve (EmitContext ec)
7919 ArrayList AllGetters = new ArrayList();
7920 if (!CommonResolve (ec))
7924 // Step 1: Query for all `Item' *properties*. Notice
7925 // that the actual methods are pointed from here.
7927 // This is a group of properties, piles of them.
7929 bool found_any = false, found_any_getters = false;
7930 Type lookup_type = indexer_type;
7933 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
7934 if (ilist != null) {
7936 if (ilist.Properties != null) {
7937 foreach (Indexers.Indexer ix in ilist.Properties) {
7938 if (ix.Getter != null)
7939 AllGetters.Add(ix.Getter);
7944 if (AllGetters.Count > 0) {
7945 found_any_getters = true;
7946 get = (MethodInfo) Invocation.OverloadResolve (
7947 ec, new MethodGroupExpr (AllGetters, loc), arguments, loc);
7951 Report.Error (21, loc,
7952 "Type `" + TypeManager.CSharpName (indexer_type) +
7953 "' does not have any indexers defined");
7957 if (!found_any_getters) {
7958 Error (154, "indexer can not be used in this context, because " +
7959 "it lacks a `get' accessor");
7964 Error (1501, "No Overload for method `this' takes `" +
7965 arguments.Count + "' arguments");
7970 // Only base will allow this invocation to happen.
7972 if (get.IsAbstract && this is BaseIndexerAccess){
7973 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
7977 type = get.ReturnType;
7978 if (type.IsPointer && !ec.InUnsafe){
7983 eclass = ExprClass.IndexerAccess;
7987 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7989 ArrayList AllSetters = new ArrayList();
7990 if (!CommonResolve (ec))
7993 bool found_any = false, found_any_setters = false;
7995 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
7996 if (ilist != null) {
7998 if (ilist.Properties != null) {
7999 foreach (Indexers.Indexer ix in ilist.Properties) {
8000 if (ix.Setter != null)
8001 AllSetters.Add(ix.Setter);
8005 if (AllSetters.Count > 0) {
8006 found_any_setters = true;
8007 set_arguments = (ArrayList) arguments.Clone ();
8008 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
8009 set = (MethodInfo) Invocation.OverloadResolve (
8010 ec, new MethodGroupExpr (AllSetters, loc),
8011 set_arguments, loc);
8015 Report.Error (21, loc,
8016 "Type `" + TypeManager.CSharpName (indexer_type) +
8017 "' does not have any indexers defined");
8021 if (!found_any_setters) {
8022 Error (154, "indexer can not be used in this context, because " +
8023 "it lacks a `set' accessor");
8028 Error (1501, "No Overload for method `this' takes `" +
8029 arguments.Count + "' arguments");
8034 // Only base will allow this invocation to happen.
8036 if (set.IsAbstract && this is BaseIndexerAccess){
8037 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
8042 // Now look for the actual match in the list of indexers to set our "return" type
8044 type = TypeManager.void_type; // default value
8045 foreach (Indexers.Indexer ix in ilist.Properties){
8046 if (ix.Setter == set){
8052 eclass = ExprClass.IndexerAccess;
8056 bool prepared = false;
8057 LocalTemporary temp;
8059 public void Emit (EmitContext ec, bool leave_copy)
8061 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc, prepared, false);
8063 ec.ig.Emit (OpCodes.Dup);
8064 temp = new LocalTemporary (ec, Type);
8070 // source is ignored, because we already have a copy of it from the
8071 // LValue resolution and we have already constructed a pre-cached
8072 // version of the arguments (ea.set_arguments);
8074 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8076 prepared = prepare_for_load;
8077 Argument a = (Argument) set_arguments [set_arguments.Count - 1];
8082 ec.ig.Emit (OpCodes.Dup);
8083 temp = new LocalTemporary (ec, Type);
8086 } else if (leave_copy) {
8087 temp = new LocalTemporary (ec, Type);
8093 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc, false, prepared);
8100 public override void Emit (EmitContext ec)
8107 /// The base operator for method names
8109 public class BaseAccess : Expression {
8112 public BaseAccess (string member, Location l)
8114 this.member = member;
8118 public override Expression DoResolve (EmitContext ec)
8120 Expression c = CommonResolve (ec);
8126 // MethodGroups use this opportunity to flag an error on lacking ()
8128 if (!(c is MethodGroupExpr))
8129 return c.Resolve (ec);
8133 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8135 Expression c = CommonResolve (ec);
8141 // MethodGroups use this opportunity to flag an error on lacking ()
8143 if (! (c is MethodGroupExpr))
8144 return c.DoResolveLValue (ec, right_side);
8149 Expression CommonResolve (EmitContext ec)
8151 Expression member_lookup;
8152 Type current_type = ec.ContainerType;
8153 Type base_type = current_type.BaseType;
8157 Error (1511, "Keyword base is not allowed in static method");
8161 if (ec.IsFieldInitializer){
8162 Error (1512, "Keyword base is not available in the current context");
8166 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type, member,
8167 AllMemberTypes, AllBindingFlags, loc);
8168 if (member_lookup == null) {
8169 MemberLookupFailed (ec, base_type, base_type, member, null, loc);
8176 left = new TypeExpression (base_type, loc);
8178 left = ec.GetThis (loc);
8180 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
8182 if (e is PropertyExpr){
8183 PropertyExpr pe = (PropertyExpr) e;
8188 if (e is MethodGroupExpr)
8189 ((MethodGroupExpr) e).IsBase = true;
8194 public override void Emit (EmitContext ec)
8196 throw new Exception ("Should never be called");
8201 /// The base indexer operator
8203 public class BaseIndexerAccess : IndexerAccess {
8204 public BaseIndexerAccess (ArrayList args, Location loc)
8205 : base (null, true, loc)
8207 arguments = new ArrayList ();
8208 foreach (Expression tmp in args)
8209 arguments.Add (new Argument (tmp, Argument.AType.Expression));
8212 protected override bool CommonResolve (EmitContext ec)
8214 instance_expr = ec.GetThis (loc);
8216 current_type = ec.ContainerType.BaseType;
8217 indexer_type = current_type;
8219 foreach (Argument a in arguments){
8220 if (!a.Resolve (ec, loc))
8229 /// This class exists solely to pass the Type around and to be a dummy
8230 /// that can be passed to the conversion functions (this is used by
8231 /// foreach implementation to typecast the object return value from
8232 /// get_Current into the proper type. All code has been generated and
8233 /// we only care about the side effect conversions to be performed
8235 /// This is also now used as a placeholder where a no-action expression
8236 /// is needed (the `New' class).
8238 public class EmptyExpression : Expression {
8239 public EmptyExpression ()
8241 type = TypeManager.object_type;
8242 eclass = ExprClass.Value;
8243 loc = Location.Null;
8246 public EmptyExpression (Type t)
8249 eclass = ExprClass.Value;
8250 loc = Location.Null;
8253 public override Expression DoResolve (EmitContext ec)
8258 public override void Emit (EmitContext ec)
8260 // nothing, as we only exist to not do anything.
8264 // This is just because we might want to reuse this bad boy
8265 // instead of creating gazillions of EmptyExpressions.
8266 // (CanImplicitConversion uses it)
8268 public void SetType (Type t)
8274 public class UserCast : Expression {
8278 public UserCast (MethodInfo method, Expression source, Location l)
8280 this.method = method;
8281 this.source = source;
8282 type = method.ReturnType;
8283 eclass = ExprClass.Value;
8287 public override Expression DoResolve (EmitContext ec)
8290 // We are born fully resolved
8295 public override void Emit (EmitContext ec)
8297 ILGenerator ig = ec.ig;
8301 if (method is MethodInfo)
8302 ig.Emit (OpCodes.Call, (MethodInfo) method);
8304 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
8310 // This class is used to "construct" the type during a typecast
8311 // operation. Since the Type.GetType class in .NET can parse
8312 // the type specification, we just use this to construct the type
8313 // one bit at a time.
8315 public class ComposedCast : TypeExpr {
8319 public ComposedCast (Expression left, string dim, Location l)
8326 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
8328 Type ltype = ec.DeclSpace.ResolveType (left, false, loc);
8332 if ((ltype == TypeManager.void_type) && (dim != "*")) {
8333 Report.Error (1547, Location,
8334 "Keyword 'void' cannot be used in this context");
8339 // ltype.Fullname is already fully qualified, so we can skip
8340 // a lot of probes, and go directly to TypeManager.LookupType
8342 string cname = ltype.FullName + dim;
8343 type = TypeManager.LookupTypeDirect (cname);
8346 // For arrays of enumerations we are having a problem
8347 // with the direct lookup. Need to investigate.
8349 // For now, fall back to the full lookup in that case.
8351 type = RootContext.LookupType (
8352 ec.DeclSpace, cname, false, loc);
8358 if (!ec.ResolvingTypeTree){
8360 // If the above flag is set, this is being invoked from the ResolveType function.
8361 // Upper layers take care of the type validity in this context.
8363 if (!ec.InUnsafe && type.IsPointer){
8369 eclass = ExprClass.Type;
8373 public override string Name {
8381 // This class is used to represent the address of an array, used
8382 // only by the Fixed statement, this is like the C "&a [0]" construct.
8384 public class ArrayPtr : Expression {
8387 public ArrayPtr (Expression array, Location l)
8389 Type array_type = TypeManager.GetElementType (array.Type);
8393 type = TypeManager.GetPointerType (array_type);
8394 eclass = ExprClass.Value;
8398 public override void Emit (EmitContext ec)
8400 ILGenerator ig = ec.ig;
8403 IntLiteral.EmitInt (ig, 0);
8404 ig.Emit (OpCodes.Ldelema, TypeManager.GetElementType (array.Type));
8407 public override Expression DoResolve (EmitContext ec)
8410 // We are born fully resolved
8417 // Used by the fixed statement
8419 public class StringPtr : Expression {
8422 public StringPtr (LocalBuilder b, Location l)
8425 eclass = ExprClass.Value;
8426 type = TypeManager.char_ptr_type;
8430 public override Expression DoResolve (EmitContext ec)
8432 // This should never be invoked, we are born in fully
8433 // initialized state.
8438 public override void Emit (EmitContext ec)
8440 ILGenerator ig = ec.ig;
8442 ig.Emit (OpCodes.Ldloc, b);
8443 ig.Emit (OpCodes.Conv_I);
8444 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
8445 ig.Emit (OpCodes.Add);
8450 // Implements the `stackalloc' keyword
8452 public class StackAlloc : Expression {
8457 public StackAlloc (Expression type, Expression count, Location l)
8464 public override Expression DoResolve (EmitContext ec)
8466 count = count.Resolve (ec);
8470 if (count.Type != TypeManager.int32_type){
8471 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8476 Constant c = count as Constant;
8477 // TODO: because we don't have property IsNegative
8478 if (c != null && c.ConvertToUInt () == null) {
8479 Report.Error (247, loc, "Cannot use a negative size with stackalloc");
8483 if (ec.CurrentBranching.InCatch () ||
8484 ec.CurrentBranching.InFinally (true)) {
8486 "stackalloc can not be used in a catch or finally block");
8490 otype = ec.DeclSpace.ResolveType (t, false, loc);
8495 if (!TypeManager.VerifyUnManaged (otype, loc))
8498 type = TypeManager.GetPointerType (otype);
8499 eclass = ExprClass.Value;
8504 public override void Emit (EmitContext ec)
8506 int size = GetTypeSize (otype);
8507 ILGenerator ig = ec.ig;
8510 ig.Emit (OpCodes.Sizeof, otype);
8512 IntConstant.EmitInt (ig, size);
8514 ig.Emit (OpCodes.Mul);
8515 ig.Emit (OpCodes.Localloc);