2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001 Ximian, 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);
51 ec.ig.Emit (OpCodes.Call, mi);
55 static public Expression 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);
86 /// Unary expressions.
90 /// Unary implements unary expressions. It derives from
91 /// ExpressionStatement becuase the pre/post increment/decrement
92 /// operators can be used in a statement context.
94 public class Unary : Expression {
95 public enum Operator : byte {
96 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
97 Indirection, AddressOf, TOP
100 public Operator Oper;
101 public Expression Expr;
103 public Unary (Operator op, Expression expr, Location loc)
111 /// Returns a stringified representation of the Operator
113 static public string OperName (Operator oper)
116 case Operator.UnaryPlus:
118 case Operator.UnaryNegation:
120 case Operator.LogicalNot:
122 case Operator.OnesComplement:
124 case Operator.AddressOf:
126 case Operator.Indirection:
130 return oper.ToString ();
133 public static readonly string [] oper_names;
137 oper_names = new string [(int)Operator.TOP];
139 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
140 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
141 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
142 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
143 oper_names [(int) Operator.Indirection] = "op_Indirection";
144 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
147 void Error23 (Type t)
150 23, "Operator " + OperName (Oper) +
151 " cannot be applied to operand of type `" +
152 TypeManager.CSharpName (t) + "'");
156 /// The result has been already resolved:
158 /// FIXME: a minus constant -128 sbyte cant be turned into a
161 static Expression TryReduceNegative (Constant expr)
165 if (expr is IntConstant)
166 e = new IntConstant (-((IntConstant) expr).Value);
167 else if (expr is UIntConstant){
168 uint value = ((UIntConstant) expr).Value;
170 if (value < 2147483649)
171 return new IntConstant (-(int)value);
173 e = new LongConstant (-value);
175 else if (expr is LongConstant)
176 e = new LongConstant (-((LongConstant) expr).Value);
177 else if (expr is ULongConstant){
178 ulong value = ((ULongConstant) expr).Value;
180 if (value < 9223372036854775809)
181 return new LongConstant(-(long)value);
183 else if (expr is FloatConstant)
184 e = new FloatConstant (-((FloatConstant) expr).Value);
185 else if (expr is DoubleConstant)
186 e = new DoubleConstant (-((DoubleConstant) expr).Value);
187 else if (expr is DecimalConstant)
188 e = new DecimalConstant (-((DecimalConstant) expr).Value);
189 else if (expr is ShortConstant)
190 e = new IntConstant (-((ShortConstant) expr).Value);
191 else if (expr is UShortConstant)
192 e = new IntConstant (-((UShortConstant) expr).Value);
197 // This routine will attempt to simplify the unary expression when the
198 // argument is a constant. The result is returned in `result' and the
199 // function returns true or false depending on whether a reduction
200 // was performed or not
202 bool Reduce (EmitContext ec, Constant e, out Expression result)
204 Type expr_type = e.Type;
207 case Operator.UnaryPlus:
211 case Operator.UnaryNegation:
212 result = TryReduceNegative (e);
215 case Operator.LogicalNot:
216 if (expr_type != TypeManager.bool_type) {
222 BoolConstant b = (BoolConstant) e;
223 result = new BoolConstant (!(b.Value));
226 case Operator.OnesComplement:
227 if (!((expr_type == TypeManager.int32_type) ||
228 (expr_type == TypeManager.uint32_type) ||
229 (expr_type == TypeManager.int64_type) ||
230 (expr_type == TypeManager.uint64_type) ||
231 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
234 if (Convert.ImplicitConversionExists (ec, e, TypeManager.int32_type)){
235 result = new Cast (new TypeExpr (TypeManager.int32_type, loc), e, loc);
236 result = result.Resolve (ec);
237 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint32_type)){
238 result = new Cast (new TypeExpr (TypeManager.uint32_type, loc), e, loc);
239 result = result.Resolve (ec);
240 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.int64_type)){
241 result = new Cast (new TypeExpr (TypeManager.int64_type, loc), e, loc);
242 result = result.Resolve (ec);
243 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint64_type)){
244 result = new Cast (new TypeExpr (TypeManager.uint64_type, loc), e, loc);
245 result = result.Resolve (ec);
248 if (result == null || !(result is Constant)){
254 expr_type = result.Type;
255 e = (Constant) result;
258 if (e is EnumConstant){
259 EnumConstant enum_constant = (EnumConstant) e;
262 if (Reduce (ec, enum_constant.Child, out reduced)){
263 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
271 if (expr_type == TypeManager.int32_type){
272 result = new IntConstant (~ ((IntConstant) e).Value);
273 } else if (expr_type == TypeManager.uint32_type){
274 result = new UIntConstant (~ ((UIntConstant) e).Value);
275 } else if (expr_type == TypeManager.int64_type){
276 result = new LongConstant (~ ((LongConstant) e).Value);
277 } else if (expr_type == TypeManager.uint64_type){
278 result = new ULongConstant (~ ((ULongConstant) e).Value);
286 case Operator.AddressOf:
290 case Operator.Indirection:
294 throw new Exception ("Can not constant fold: " + Oper.ToString());
297 Expression ResolveOperator (EmitContext ec)
299 Type expr_type = Expr.Type;
302 // Step 1: Perform Operator Overload location
307 op_name = oper_names [(int) Oper];
309 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
312 Expression e = StaticCallExpr.MakeSimpleCall (
313 ec, (MethodGroupExpr) mg, Expr, loc);
323 // Only perform numeric promotions on:
326 if (expr_type == null)
330 // Step 2: Default operations on CLI native types.
333 // Attempt to use a constant folding operation.
334 if (Expr is Constant){
337 if (Reduce (ec, (Constant) Expr, out result))
342 case Operator.LogicalNot:
343 if (expr_type != TypeManager.bool_type) {
344 Expr = ResolveBoolean (ec, Expr, loc);
351 type = TypeManager.bool_type;
354 case Operator.OnesComplement:
355 if (!((expr_type == TypeManager.int32_type) ||
356 (expr_type == TypeManager.uint32_type) ||
357 (expr_type == TypeManager.int64_type) ||
358 (expr_type == TypeManager.uint64_type) ||
359 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
362 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
364 type = TypeManager.int32_type;
367 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint32_type, loc);
369 type = TypeManager.uint32_type;
372 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
374 type = TypeManager.int64_type;
377 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint64_type, loc);
379 type = TypeManager.uint64_type;
388 case Operator.AddressOf:
389 if (Expr.eclass != ExprClass.Variable){
390 Error (211, "Cannot take the address of non-variables");
399 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
403 IVariable variable = Expr as IVariable;
404 if (!ec.InFixedInitializer && ((variable == null) || !variable.VerifyFixed (false))) {
405 Error (212, "You can only take the address of an unfixed expression inside " +
406 "of a fixed statement initializer");
410 // According to the specs, a variable is considered definitely assigned if you take
412 if ((variable != null) && (variable.VariableInfo != null))
413 variable.VariableInfo.SetAssigned (ec);
415 type = TypeManager.GetPointerType (Expr.Type);
418 case Operator.Indirection:
424 if (!expr_type.IsPointer){
425 Error (193, "The * or -> operator can only be applied to pointers");
430 // We create an Indirection expression, because
431 // it can implement the IMemoryLocation.
433 return new Indirection (Expr, loc);
435 case Operator.UnaryPlus:
437 // A plus in front of something is just a no-op, so return the child.
441 case Operator.UnaryNegation:
443 // Deals with -literals
444 // int operator- (int x)
445 // long operator- (long x)
446 // float operator- (float f)
447 // double operator- (double d)
448 // decimal operator- (decimal d)
450 Expression expr = null;
453 // transform - - expr into expr
456 Unary unary = (Unary) Expr;
458 if (unary.Oper == Operator.UnaryNegation)
463 // perform numeric promotions to int,
467 // The following is inneficient, because we call
468 // ImplicitConversion too many times.
470 // It is also not clear if we should convert to Float
471 // or Double initially.
473 if (expr_type == TypeManager.uint32_type){
475 // FIXME: handle exception to this rule that
476 // permits the int value -2147483648 (-2^31) to
477 // bt wrote as a decimal interger literal
479 type = TypeManager.int64_type;
480 Expr = Convert.ImplicitConversion (ec, Expr, type, loc);
484 if (expr_type == TypeManager.uint64_type){
486 // FIXME: Handle exception of `long value'
487 // -92233720368547758087 (-2^63) to be wrote as
488 // decimal integer literal.
494 if (expr_type == TypeManager.float_type){
499 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
506 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
513 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.double_type, loc);
524 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
525 TypeManager.CSharpName (expr_type) + "'");
529 public override Expression DoResolve (EmitContext ec)
531 if (Oper == Operator.AddressOf)
532 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
534 Expr = Expr.Resolve (ec);
539 eclass = ExprClass.Value;
540 return ResolveOperator (ec);
543 public override void Emit (EmitContext ec)
545 ILGenerator ig = ec.ig;
546 Type expr_type = Expr.Type;
549 case Operator.UnaryPlus:
550 throw new Exception ("This should be caught by Resolve");
552 case Operator.UnaryNegation:
554 ig.Emit (OpCodes.Neg);
557 case Operator.LogicalNot:
559 ig.Emit (OpCodes.Ldc_I4_0);
560 ig.Emit (OpCodes.Ceq);
563 case Operator.OnesComplement:
565 ig.Emit (OpCodes.Not);
568 case Operator.AddressOf:
569 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
573 throw new Exception ("This should not happen: Operator = "
579 /// This will emit the child expression for `ec' avoiding the logical
580 /// not. The parent will take care of changing brfalse/brtrue
582 public void EmitLogicalNot (EmitContext ec)
584 if (Oper != Operator.LogicalNot)
585 throw new Exception ("EmitLogicalNot can only be called with !expr");
590 public override string ToString ()
592 return "Unary (" + Oper + ", " + Expr + ")";
598 // Unary operators are turned into Indirection expressions
599 // after semantic analysis (this is so we can take the address
600 // of an indirection).
602 public class Indirection : Expression, IMemoryLocation, IAssignMethod {
604 LocalTemporary temporary;
607 public Indirection (Expression expr, Location l)
610 this.type = TypeManager.TypeToCoreType (expr.Type.GetElementType ());
611 eclass = ExprClass.Variable;
615 void LoadExprValue (EmitContext ec)
619 public override void Emit (EmitContext ec)
621 ILGenerator ig = ec.ig;
623 if (temporary != null){
629 ec.ig.Emit (OpCodes.Dup);
630 temporary.Store (ec);
631 have_temporary = true;
635 LoadFromPtr (ig, Type);
638 public void EmitAssign (EmitContext ec, Expression source)
640 if (temporary != null){
645 ec.ig.Emit (OpCodes.Dup);
646 temporary.Store (ec);
647 have_temporary = true;
653 StoreFromPtr (ec.ig, type);
656 public void AddressOf (EmitContext ec, AddressOp Mode)
658 if (temporary != null){
664 ec.ig.Emit (OpCodes.Dup);
665 temporary.Store (ec);
666 have_temporary = true;
671 public override Expression DoResolve (EmitContext ec)
674 // Born fully resolved
679 public new void CacheTemporaries (EmitContext ec)
681 temporary = new LocalTemporary (ec, type);
684 public override string ToString ()
686 return "*(" + expr + ")";
691 /// Unary Mutator expressions (pre and post ++ and --)
695 /// UnaryMutator implements ++ and -- expressions. It derives from
696 /// ExpressionStatement becuase the pre/post increment/decrement
697 /// operators can be used in a statement context.
699 /// FIXME: Idea, we could split this up in two classes, one simpler
700 /// for the common case, and one with the extra fields for more complex
701 /// classes (indexers require temporary access; overloaded require method)
704 public class UnaryMutator : ExpressionStatement {
706 public enum Mode : byte {
713 PreDecrement = IsDecrement,
714 PostIncrement = IsPost,
715 PostDecrement = IsPost | IsDecrement
720 LocalTemporary temp_storage;
723 // This is expensive for the simplest case.
727 public UnaryMutator (Mode m, Expression e, Location l)
734 static string OperName (Mode mode)
736 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
740 void Error23 (Type t)
743 23, "Operator " + OperName (mode) +
744 " cannot be applied to operand of type `" +
745 TypeManager.CSharpName (t) + "'");
749 /// Returns whether an object of type `t' can be incremented
750 /// or decremented with add/sub (ie, basically whether we can
751 /// use pre-post incr-decr operations on it, but it is not a
752 /// System.Decimal, which we require operator overloading to catch)
754 static bool IsIncrementableNumber (Type t)
756 return (t == TypeManager.sbyte_type) ||
757 (t == TypeManager.byte_type) ||
758 (t == TypeManager.short_type) ||
759 (t == TypeManager.ushort_type) ||
760 (t == TypeManager.int32_type) ||
761 (t == TypeManager.uint32_type) ||
762 (t == TypeManager.int64_type) ||
763 (t == TypeManager.uint64_type) ||
764 (t == TypeManager.char_type) ||
765 (t.IsSubclassOf (TypeManager.enum_type)) ||
766 (t == TypeManager.float_type) ||
767 (t == TypeManager.double_type) ||
768 (t.IsPointer && t != TypeManager.void_ptr_type);
771 Expression ResolveOperator (EmitContext ec)
773 Type expr_type = expr.Type;
776 // Step 1: Perform Operator Overload location
781 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
782 op_name = "op_Increment";
784 op_name = "op_Decrement";
786 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
788 if (mg == null && expr_type.BaseType != null)
789 mg = MemberLookup (ec, expr_type.BaseType, op_name,
790 MemberTypes.Method, AllBindingFlags, loc);
793 method = StaticCallExpr.MakeSimpleCall (
794 ec, (MethodGroupExpr) mg, expr, loc);
801 // The operand of the prefix/postfix increment decrement operators
802 // should be an expression that is classified as a variable,
803 // a property access or an indexer access
806 if (expr.eclass == ExprClass.Variable){
807 if (IsIncrementableNumber (expr_type) ||
808 expr_type == TypeManager.decimal_type){
811 } else if (expr.eclass == ExprClass.IndexerAccess){
812 IndexerAccess ia = (IndexerAccess) expr;
814 temp_storage = new LocalTemporary (ec, expr.Type);
816 expr = ia.ResolveLValue (ec, temp_storage);
821 } else if (expr.eclass == ExprClass.PropertyAccess){
822 PropertyExpr pe = (PropertyExpr) expr;
824 if (pe.VerifyAssignable ())
829 expr.Error_UnexpectedKind ("variable, indexer or property access");
833 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
834 TypeManager.CSharpName (expr_type) + "'");
838 public override Expression DoResolve (EmitContext ec)
840 expr = expr.Resolve (ec);
845 eclass = ExprClass.Value;
846 return ResolveOperator (ec);
849 static int PtrTypeSize (Type t)
851 return GetTypeSize (t.GetElementType ());
855 // Loads the proper "1" into the stack based on the type, then it emits the
856 // opcode for the operation requested
858 void LoadOneAndEmitOp (EmitContext ec, Type t)
861 // Measure if getting the typecode and using that is more/less efficient
862 // that comparing types. t.GetTypeCode() is an internal call.
864 ILGenerator ig = ec.ig;
866 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
867 LongConstant.EmitLong (ig, 1);
868 else if (t == TypeManager.double_type)
869 ig.Emit (OpCodes.Ldc_R8, 1.0);
870 else if (t == TypeManager.float_type)
871 ig.Emit (OpCodes.Ldc_R4, 1.0F);
872 else if (t.IsPointer){
873 int n = PtrTypeSize (t);
876 ig.Emit (OpCodes.Sizeof, t);
878 IntConstant.EmitInt (ig, n);
880 ig.Emit (OpCodes.Ldc_I4_1);
883 // Now emit the operation
886 if (t == TypeManager.int32_type ||
887 t == TypeManager.int64_type){
888 if ((mode & Mode.IsDecrement) != 0)
889 ig.Emit (OpCodes.Sub_Ovf);
891 ig.Emit (OpCodes.Add_Ovf);
892 } else if (t == TypeManager.uint32_type ||
893 t == TypeManager.uint64_type){
894 if ((mode & Mode.IsDecrement) != 0)
895 ig.Emit (OpCodes.Sub_Ovf_Un);
897 ig.Emit (OpCodes.Add_Ovf_Un);
899 if ((mode & Mode.IsDecrement) != 0)
900 ig.Emit (OpCodes.Sub_Ovf);
902 ig.Emit (OpCodes.Add_Ovf);
905 if ((mode & Mode.IsDecrement) != 0)
906 ig.Emit (OpCodes.Sub);
908 ig.Emit (OpCodes.Add);
911 if (t == TypeManager.sbyte_type){
913 ig.Emit (OpCodes.Conv_Ovf_I1);
915 ig.Emit (OpCodes.Conv_I1);
916 } else if (t == TypeManager.byte_type){
918 ig.Emit (OpCodes.Conv_Ovf_U1);
920 ig.Emit (OpCodes.Conv_U1);
921 } else if (t == TypeManager.short_type){
923 ig.Emit (OpCodes.Conv_Ovf_I2);
925 ig.Emit (OpCodes.Conv_I2);
926 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
928 ig.Emit (OpCodes.Conv_Ovf_U2);
930 ig.Emit (OpCodes.Conv_U2);
935 static EmptyExpression empty_expr;
937 void EmitCode (EmitContext ec, bool is_expr)
939 ILGenerator ig = ec.ig;
940 IAssignMethod ia = (IAssignMethod) expr;
941 Type expr_type = expr.Type;
943 ia.CacheTemporaries (ec);
945 if (temp_storage == null){
947 // Temporary improvement: if we are dealing with something that does
948 // not require complicated instance setup, avoid using a temporary
950 // For now: only localvariables when not remapped
953 if (method == null &&
954 (expr is LocalVariableReference && ec.RemapToProxy == false) ||
955 (expr is FieldExpr && ((FieldExpr) expr).FieldInfo.IsStatic)){
956 if (empty_expr == null)
957 empty_expr = new EmptyExpression ();
960 case Mode.PreIncrement:
961 case Mode.PreDecrement:
964 LoadOneAndEmitOp (ec, expr_type);
966 ig.Emit (OpCodes.Dup);
967 ia.EmitAssign (ec, empty_expr);
970 case Mode.PostIncrement:
971 case Mode.PostDecrement:
974 ig.Emit (OpCodes.Dup);
976 LoadOneAndEmitOp (ec, expr_type);
977 ia.EmitAssign (ec, empty_expr);
982 temp_storage = new LocalTemporary (ec, expr_type);
986 case Mode.PreIncrement:
987 case Mode.PreDecrement:
991 LoadOneAndEmitOp (ec, expr_type);
995 temp_storage.Store (ec);
996 ia.EmitAssign (ec, temp_storage);
998 temp_storage.Emit (ec);
1001 case Mode.PostIncrement:
1002 case Mode.PostDecrement:
1006 if (method == null){
1010 ig.Emit (OpCodes.Dup);
1012 LoadOneAndEmitOp (ec, expr_type);
1017 temp_storage.Store (ec);
1018 ia.EmitAssign (ec, temp_storage);
1023 public override void Emit (EmitContext ec)
1025 EmitCode (ec, true);
1029 public override void EmitStatement (EmitContext ec)
1031 EmitCode (ec, false);
1037 /// Base class for the `Is' and `As' classes.
1041 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1044 public abstract class Probe : Expression {
1045 public readonly Expression ProbeType;
1046 protected Expression expr;
1047 protected Type probe_type;
1049 public Probe (Expression expr, Expression probe_type, Location l)
1051 ProbeType = probe_type;
1056 public Expression Expr {
1062 public override Expression DoResolve (EmitContext ec)
1064 probe_type = ec.DeclSpace.ResolveType (ProbeType, false, loc);
1066 if (probe_type == null)
1069 expr = expr.Resolve (ec);
1076 /// Implementation of the `is' operator.
1078 public class Is : Probe {
1079 public Is (Expression expr, Expression probe_type, Location l)
1080 : base (expr, probe_type, l)
1085 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1090 public override void Emit (EmitContext ec)
1092 ILGenerator ig = ec.ig;
1097 case Action.AlwaysFalse:
1098 ig.Emit (OpCodes.Pop);
1099 IntConstant.EmitInt (ig, 0);
1101 case Action.AlwaysTrue:
1102 ig.Emit (OpCodes.Pop);
1103 IntConstant.EmitInt (ig, 1);
1105 case Action.LeaveOnStack:
1106 // the `e != null' rule.
1107 ig.Emit (OpCodes.Ldnull);
1108 ig.Emit (OpCodes.Ceq);
1109 ig.Emit (OpCodes.Ldc_I4_0);
1110 ig.Emit (OpCodes.Ceq);
1113 ig.Emit (OpCodes.Isinst, probe_type);
1114 ig.Emit (OpCodes.Ldnull);
1115 ig.Emit (OpCodes.Cgt_Un);
1118 throw new Exception ("never reached");
1121 public override Expression DoResolve (EmitContext ec)
1123 Expression e = base.DoResolve (ec);
1125 if ((e == null) || (expr == null))
1128 Type etype = expr.Type;
1129 bool warning_always_matches = false;
1130 bool warning_never_matches = false;
1132 type = TypeManager.bool_type;
1133 eclass = ExprClass.Value;
1136 // First case, if at compile time, there is an implicit conversion
1137 // then e != null (objects) or true (value types)
1139 e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1142 if (etype.IsValueType)
1143 action = Action.AlwaysTrue;
1145 action = Action.LeaveOnStack;
1147 warning_always_matches = true;
1148 } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1150 // Second case: explicit reference convresion
1152 if (expr is NullLiteral)
1153 action = Action.AlwaysFalse;
1155 action = Action.Probe;
1157 action = Action.AlwaysFalse;
1158 warning_never_matches = true;
1161 if (RootContext.WarningLevel >= 1){
1162 if (warning_always_matches)
1163 Warning (183, "The expression is always of type `" +
1164 TypeManager.CSharpName (probe_type) + "'");
1165 else if (warning_never_matches){
1166 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1168 "The expression is never of type `" +
1169 TypeManager.CSharpName (probe_type) + "'");
1178 /// Implementation of the `as' operator.
1180 public class As : Probe {
1181 public As (Expression expr, Expression probe_type, Location l)
1182 : base (expr, probe_type, l)
1186 bool do_isinst = false;
1188 public override void Emit (EmitContext ec)
1190 ILGenerator ig = ec.ig;
1195 ig.Emit (OpCodes.Isinst, probe_type);
1198 static void Error_CannotConvertType (Type source, Type target, Location loc)
1201 39, loc, "as operator can not convert from `" +
1202 TypeManager.CSharpName (source) + "' to `" +
1203 TypeManager.CSharpName (target) + "'");
1206 public override Expression DoResolve (EmitContext ec)
1208 Expression e = base.DoResolve (ec);
1214 eclass = ExprClass.Value;
1215 Type etype = expr.Type;
1217 if (TypeManager.IsValueType (probe_type)){
1218 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1219 TypeManager.CSharpName (probe_type) + " is a value type");
1224 e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1231 if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1236 Error_CannotConvertType (etype, probe_type, loc);
1242 /// This represents a typecast in the source language.
1244 /// FIXME: Cast expressions have an unusual set of parsing
1245 /// rules, we need to figure those out.
1247 public class Cast : Expression {
1248 Expression target_type;
1251 public Cast (Expression cast_type, Expression expr, Location loc)
1253 this.target_type = cast_type;
1258 public Expression TargetType {
1264 public Expression Expr {
1273 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1275 if (!ec.ConstantCheckState)
1278 if ((value < min) || (value > max)) {
1279 Error (221, "Constant value `" + value + "' cannot be converted " +
1280 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1281 "syntax to override)");
1288 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1290 if (!ec.ConstantCheckState)
1294 Error (221, "Constant value `" + value + "' cannot be converted " +
1295 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1296 "syntax to override)");
1303 bool CheckUnsigned (EmitContext ec, long value, Type type)
1305 if (!ec.ConstantCheckState)
1309 Error (221, "Constant value `" + value + "' cannot be converted " +
1310 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1311 "syntax to override)");
1319 /// Attempts to do a compile-time folding of a constant cast.
1321 Expression TryReduce (EmitContext ec, Type target_type)
1323 Expression real_expr = expr;
1324 if (real_expr is EnumConstant)
1325 real_expr = ((EnumConstant) real_expr).Child;
1327 if (real_expr is ByteConstant){
1328 byte v = ((ByteConstant) real_expr).Value;
1330 if (target_type == TypeManager.sbyte_type) {
1331 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1333 return new SByteConstant ((sbyte) v);
1335 if (target_type == TypeManager.short_type)
1336 return new ShortConstant ((short) v);
1337 if (target_type == TypeManager.ushort_type)
1338 return new UShortConstant ((ushort) v);
1339 if (target_type == TypeManager.int32_type)
1340 return new IntConstant ((int) v);
1341 if (target_type == TypeManager.uint32_type)
1342 return new UIntConstant ((uint) v);
1343 if (target_type == TypeManager.int64_type)
1344 return new LongConstant ((long) v);
1345 if (target_type == TypeManager.uint64_type)
1346 return new ULongConstant ((ulong) v);
1347 if (target_type == TypeManager.float_type)
1348 return new FloatConstant ((float) v);
1349 if (target_type == TypeManager.double_type)
1350 return new DoubleConstant ((double) v);
1351 if (target_type == TypeManager.char_type)
1352 return new CharConstant ((char) v);
1353 if (target_type == TypeManager.decimal_type)
1354 return new DecimalConstant ((decimal) v);
1356 if (real_expr is SByteConstant){
1357 sbyte v = ((SByteConstant) real_expr).Value;
1359 if (target_type == TypeManager.byte_type) {
1360 if (!CheckUnsigned (ec, v, target_type))
1362 return new ByteConstant ((byte) v);
1364 if (target_type == TypeManager.short_type)
1365 return new ShortConstant ((short) v);
1366 if (target_type == TypeManager.ushort_type) {
1367 if (!CheckUnsigned (ec, v, target_type))
1369 return new UShortConstant ((ushort) v);
1370 } if (target_type == TypeManager.int32_type)
1371 return new IntConstant ((int) v);
1372 if (target_type == TypeManager.uint32_type) {
1373 if (!CheckUnsigned (ec, v, target_type))
1375 return new UIntConstant ((uint) v);
1376 } if (target_type == TypeManager.int64_type)
1377 return new LongConstant ((long) v);
1378 if (target_type == TypeManager.uint64_type) {
1379 if (!CheckUnsigned (ec, v, target_type))
1381 return new ULongConstant ((ulong) v);
1383 if (target_type == TypeManager.float_type)
1384 return new FloatConstant ((float) v);
1385 if (target_type == TypeManager.double_type)
1386 return new DoubleConstant ((double) v);
1387 if (target_type == TypeManager.char_type) {
1388 if (!CheckUnsigned (ec, v, target_type))
1390 return new CharConstant ((char) v);
1392 if (target_type == TypeManager.decimal_type)
1393 return new DecimalConstant ((decimal) v);
1395 if (real_expr is ShortConstant){
1396 short v = ((ShortConstant) real_expr).Value;
1398 if (target_type == TypeManager.byte_type) {
1399 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1401 return new ByteConstant ((byte) v);
1403 if (target_type == TypeManager.sbyte_type) {
1404 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1406 return new SByteConstant ((sbyte) v);
1408 if (target_type == TypeManager.ushort_type) {
1409 if (!CheckUnsigned (ec, v, target_type))
1411 return new UShortConstant ((ushort) v);
1413 if (target_type == TypeManager.int32_type)
1414 return new IntConstant ((int) v);
1415 if (target_type == TypeManager.uint32_type) {
1416 if (!CheckUnsigned (ec, v, target_type))
1418 return new UIntConstant ((uint) v);
1420 if (target_type == TypeManager.int64_type)
1421 return new LongConstant ((long) v);
1422 if (target_type == TypeManager.uint64_type) {
1423 if (!CheckUnsigned (ec, v, target_type))
1425 return new ULongConstant ((ulong) v);
1427 if (target_type == TypeManager.float_type)
1428 return new FloatConstant ((float) v);
1429 if (target_type == TypeManager.double_type)
1430 return new DoubleConstant ((double) v);
1431 if (target_type == TypeManager.char_type) {
1432 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1434 return new CharConstant ((char) v);
1436 if (target_type == TypeManager.decimal_type)
1437 return new DecimalConstant ((decimal) v);
1439 if (real_expr is UShortConstant){
1440 ushort v = ((UShortConstant) real_expr).Value;
1442 if (target_type == TypeManager.byte_type) {
1443 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1445 return new ByteConstant ((byte) v);
1447 if (target_type == TypeManager.sbyte_type) {
1448 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1450 return new SByteConstant ((sbyte) v);
1452 if (target_type == TypeManager.short_type) {
1453 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1455 return new ShortConstant ((short) v);
1457 if (target_type == TypeManager.int32_type)
1458 return new IntConstant ((int) v);
1459 if (target_type == TypeManager.uint32_type)
1460 return new UIntConstant ((uint) v);
1461 if (target_type == TypeManager.int64_type)
1462 return new LongConstant ((long) v);
1463 if (target_type == TypeManager.uint64_type)
1464 return new ULongConstant ((ulong) v);
1465 if (target_type == TypeManager.float_type)
1466 return new FloatConstant ((float) v);
1467 if (target_type == TypeManager.double_type)
1468 return new DoubleConstant ((double) v);
1469 if (target_type == TypeManager.char_type) {
1470 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1472 return new CharConstant ((char) v);
1474 if (target_type == TypeManager.decimal_type)
1475 return new DecimalConstant ((decimal) v);
1477 if (real_expr is IntConstant){
1478 int v = ((IntConstant) real_expr).Value;
1480 if (target_type == TypeManager.byte_type) {
1481 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1483 return new ByteConstant ((byte) v);
1485 if (target_type == TypeManager.sbyte_type) {
1486 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1488 return new SByteConstant ((sbyte) v);
1490 if (target_type == TypeManager.short_type) {
1491 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1493 return new ShortConstant ((short) v);
1495 if (target_type == TypeManager.ushort_type) {
1496 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1498 return new UShortConstant ((ushort) v);
1500 if (target_type == TypeManager.uint32_type) {
1501 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1503 return new UIntConstant ((uint) v);
1505 if (target_type == TypeManager.int64_type)
1506 return new LongConstant ((long) v);
1507 if (target_type == TypeManager.uint64_type) {
1508 if (!CheckUnsigned (ec, v, target_type))
1510 return new ULongConstant ((ulong) v);
1512 if (target_type == TypeManager.float_type)
1513 return new FloatConstant ((float) v);
1514 if (target_type == TypeManager.double_type)
1515 return new DoubleConstant ((double) v);
1516 if (target_type == TypeManager.char_type) {
1517 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1519 return new CharConstant ((char) v);
1521 if (target_type == TypeManager.decimal_type)
1522 return new DecimalConstant ((decimal) v);
1524 if (real_expr is UIntConstant){
1525 uint v = ((UIntConstant) real_expr).Value;
1527 if (target_type == TypeManager.byte_type) {
1528 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1530 return new ByteConstant ((byte) v);
1532 if (target_type == TypeManager.sbyte_type) {
1533 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1535 return new SByteConstant ((sbyte) v);
1537 if (target_type == TypeManager.short_type) {
1538 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1540 return new ShortConstant ((short) v);
1542 if (target_type == TypeManager.ushort_type) {
1543 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1545 return new UShortConstant ((ushort) v);
1547 if (target_type == TypeManager.int32_type) {
1548 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1550 return new IntConstant ((int) v);
1552 if (target_type == TypeManager.int64_type)
1553 return new LongConstant ((long) v);
1554 if (target_type == TypeManager.uint64_type)
1555 return new ULongConstant ((ulong) v);
1556 if (target_type == TypeManager.float_type)
1557 return new FloatConstant ((float) v);
1558 if (target_type == TypeManager.double_type)
1559 return new DoubleConstant ((double) v);
1560 if (target_type == TypeManager.char_type) {
1561 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1563 return new CharConstant ((char) v);
1565 if (target_type == TypeManager.decimal_type)
1566 return new DecimalConstant ((decimal) v);
1568 if (real_expr is LongConstant){
1569 long v = ((LongConstant) real_expr).Value;
1571 if (target_type == TypeManager.byte_type) {
1572 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1574 return new ByteConstant ((byte) v);
1576 if (target_type == TypeManager.sbyte_type) {
1577 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1579 return new SByteConstant ((sbyte) v);
1581 if (target_type == TypeManager.short_type) {
1582 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1584 return new ShortConstant ((short) v);
1586 if (target_type == TypeManager.ushort_type) {
1587 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1589 return new UShortConstant ((ushort) v);
1591 if (target_type == TypeManager.int32_type) {
1592 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1594 return new IntConstant ((int) v);
1596 if (target_type == TypeManager.uint32_type) {
1597 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1599 return new UIntConstant ((uint) v);
1601 if (target_type == TypeManager.uint64_type) {
1602 if (!CheckUnsigned (ec, v, target_type))
1604 return new ULongConstant ((ulong) v);
1606 if (target_type == TypeManager.float_type)
1607 return new FloatConstant ((float) v);
1608 if (target_type == TypeManager.double_type)
1609 return new DoubleConstant ((double) v);
1610 if (target_type == TypeManager.char_type) {
1611 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1613 return new CharConstant ((char) v);
1615 if (target_type == TypeManager.decimal_type)
1616 return new DecimalConstant ((decimal) v);
1618 if (real_expr is ULongConstant){
1619 ulong v = ((ULongConstant) real_expr).Value;
1621 if (target_type == TypeManager.byte_type) {
1622 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1624 return new ByteConstant ((byte) v);
1626 if (target_type == TypeManager.sbyte_type) {
1627 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1629 return new SByteConstant ((sbyte) v);
1631 if (target_type == TypeManager.short_type) {
1632 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1634 return new ShortConstant ((short) v);
1636 if (target_type == TypeManager.ushort_type) {
1637 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1639 return new UShortConstant ((ushort) v);
1641 if (target_type == TypeManager.int32_type) {
1642 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1644 return new IntConstant ((int) v);
1646 if (target_type == TypeManager.uint32_type) {
1647 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1649 return new UIntConstant ((uint) v);
1651 if (target_type == TypeManager.int64_type) {
1652 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1654 return new LongConstant ((long) v);
1656 if (target_type == TypeManager.float_type)
1657 return new FloatConstant ((float) v);
1658 if (target_type == TypeManager.double_type)
1659 return new DoubleConstant ((double) v);
1660 if (target_type == TypeManager.char_type) {
1661 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1663 return new CharConstant ((char) v);
1665 if (target_type == TypeManager.decimal_type)
1666 return new DecimalConstant ((decimal) v);
1668 if (real_expr is FloatConstant){
1669 float v = ((FloatConstant) real_expr).Value;
1671 if (target_type == TypeManager.byte_type)
1672 return new ByteConstant ((byte) v);
1673 if (target_type == TypeManager.sbyte_type)
1674 return new SByteConstant ((sbyte) v);
1675 if (target_type == TypeManager.short_type)
1676 return new ShortConstant ((short) v);
1677 if (target_type == TypeManager.ushort_type)
1678 return new UShortConstant ((ushort) v);
1679 if (target_type == TypeManager.int32_type)
1680 return new IntConstant ((int) v);
1681 if (target_type == TypeManager.uint32_type)
1682 return new UIntConstant ((uint) v);
1683 if (target_type == TypeManager.int64_type)
1684 return new LongConstant ((long) v);
1685 if (target_type == TypeManager.uint64_type)
1686 return new ULongConstant ((ulong) v);
1687 if (target_type == TypeManager.double_type)
1688 return new DoubleConstant ((double) v);
1689 if (target_type == TypeManager.char_type)
1690 return new CharConstant ((char) v);
1691 if (target_type == TypeManager.decimal_type)
1692 return new DecimalConstant ((decimal) v);
1694 if (real_expr is DoubleConstant){
1695 double v = ((DoubleConstant) real_expr).Value;
1697 if (target_type == TypeManager.byte_type)
1698 return new ByteConstant ((byte) v);
1699 if (target_type == TypeManager.sbyte_type)
1700 return new SByteConstant ((sbyte) v);
1701 if (target_type == TypeManager.short_type)
1702 return new ShortConstant ((short) v);
1703 if (target_type == TypeManager.ushort_type)
1704 return new UShortConstant ((ushort) v);
1705 if (target_type == TypeManager.int32_type)
1706 return new IntConstant ((int) v);
1707 if (target_type == TypeManager.uint32_type)
1708 return new UIntConstant ((uint) v);
1709 if (target_type == TypeManager.int64_type)
1710 return new LongConstant ((long) v);
1711 if (target_type == TypeManager.uint64_type)
1712 return new ULongConstant ((ulong) v);
1713 if (target_type == TypeManager.float_type)
1714 return new FloatConstant ((float) v);
1715 if (target_type == TypeManager.char_type)
1716 return new CharConstant ((char) v);
1717 if (target_type == TypeManager.decimal_type)
1718 return new DecimalConstant ((decimal) v);
1721 if (real_expr is CharConstant){
1722 char v = ((CharConstant) real_expr).Value;
1724 if (target_type == TypeManager.byte_type) {
1725 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1727 return new ByteConstant ((byte) v);
1729 if (target_type == TypeManager.sbyte_type) {
1730 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1732 return new SByteConstant ((sbyte) v);
1734 if (target_type == TypeManager.short_type) {
1735 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1737 return new ShortConstant ((short) v);
1739 if (target_type == TypeManager.int32_type)
1740 return new IntConstant ((int) v);
1741 if (target_type == TypeManager.uint32_type)
1742 return new UIntConstant ((uint) v);
1743 if (target_type == TypeManager.int64_type)
1744 return new LongConstant ((long) v);
1745 if (target_type == TypeManager.uint64_type)
1746 return new ULongConstant ((ulong) v);
1747 if (target_type == TypeManager.float_type)
1748 return new FloatConstant ((float) v);
1749 if (target_type == TypeManager.double_type)
1750 return new DoubleConstant ((double) v);
1751 if (target_type == TypeManager.char_type) {
1752 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1754 return new CharConstant ((char) v);
1756 if (target_type == TypeManager.decimal_type)
1757 return new DecimalConstant ((decimal) v);
1763 public override Expression DoResolve (EmitContext ec)
1765 expr = expr.Resolve (ec);
1769 int errors = Report.Errors;
1771 type = ec.DeclSpace.ResolveType (target_type, false, Location);
1776 eclass = ExprClass.Value;
1778 if (expr is Constant){
1779 Expression e = TryReduce (ec, type);
1785 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1789 public override void Emit (EmitContext ec)
1792 // This one will never happen
1794 throw new Exception ("Should not happen");
1799 /// Binary operators
1801 public class Binary : Expression {
1802 public enum Operator : byte {
1803 Multiply, Division, Modulus,
1804 Addition, Subtraction,
1805 LeftShift, RightShift,
1806 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1807 Equality, Inequality,
1817 Expression left, right;
1820 // After resolution, method might contain the operator overload
1823 protected MethodBase method;
1824 ArrayList Arguments;
1826 bool DelegateOperation;
1828 // This must be kept in sync with Operator!!!
1829 public static readonly string [] oper_names;
1833 oper_names = new string [(int) Operator.TOP];
1835 oper_names [(int) Operator.Multiply] = "op_Multiply";
1836 oper_names [(int) Operator.Division] = "op_Division";
1837 oper_names [(int) Operator.Modulus] = "op_Modulus";
1838 oper_names [(int) Operator.Addition] = "op_Addition";
1839 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1840 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1841 oper_names [(int) Operator.RightShift] = "op_RightShift";
1842 oper_names [(int) Operator.LessThan] = "op_LessThan";
1843 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1844 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1845 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1846 oper_names [(int) Operator.Equality] = "op_Equality";
1847 oper_names [(int) Operator.Inequality] = "op_Inequality";
1848 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1849 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1850 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1851 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1852 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1855 public Binary (Operator oper, Expression left, Expression right, Location loc)
1863 public Operator Oper {
1872 public Expression Left {
1881 public Expression Right {
1892 /// Returns a stringified representation of the Operator
1894 static string OperName (Operator oper)
1897 case Operator.Multiply:
1899 case Operator.Division:
1901 case Operator.Modulus:
1903 case Operator.Addition:
1905 case Operator.Subtraction:
1907 case Operator.LeftShift:
1909 case Operator.RightShift:
1911 case Operator.LessThan:
1913 case Operator.GreaterThan:
1915 case Operator.LessThanOrEqual:
1917 case Operator.GreaterThanOrEqual:
1919 case Operator.Equality:
1921 case Operator.Inequality:
1923 case Operator.BitwiseAnd:
1925 case Operator.BitwiseOr:
1927 case Operator.ExclusiveOr:
1929 case Operator.LogicalOr:
1931 case Operator.LogicalAnd:
1935 return oper.ToString ();
1938 public override string ToString ()
1940 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1941 right.ToString () + ")";
1944 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1946 if (expr.Type == target_type)
1949 return Convert.ImplicitConversion (ec, expr, target_type, loc);
1952 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1955 34, loc, "Operator `" + OperName (oper)
1956 + "' is ambiguous on operands of type `"
1957 + TypeManager.CSharpName (l) + "' "
1958 + "and `" + TypeManager.CSharpName (r)
1962 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
1964 if ((l == t) || (r == t))
1967 if (!check_user_conversions)
1970 if (Convert.ImplicitUserConversionExists (ec, l, t))
1972 else if (Convert.ImplicitUserConversionExists (ec, r, t))
1979 // Note that handling the case l == Decimal || r == Decimal
1980 // is taken care of by the Step 1 Operator Overload resolution.
1982 // If `check_user_conv' is true, we also check whether a user-defined conversion
1983 // exists. Note that we only need to do this if both arguments are of a user-defined
1984 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
1985 // so we don't explicitly check for performance reasons.
1987 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
1989 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
1991 // If either operand is of type double, the other operand is
1992 // conveted to type double.
1994 if (r != TypeManager.double_type)
1995 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
1996 if (l != TypeManager.double_type)
1997 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
1999 type = TypeManager.double_type;
2000 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
2002 // if either operand is of type float, the other operand is
2003 // converted to type float.
2005 if (r != TypeManager.double_type)
2006 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
2007 if (l != TypeManager.double_type)
2008 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
2009 type = TypeManager.float_type;
2010 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2014 // If either operand is of type ulong, the other operand is
2015 // converted to type ulong. or an error ocurrs if the other
2016 // operand is of type sbyte, short, int or long
2018 if (l == TypeManager.uint64_type){
2019 if (r != TypeManager.uint64_type){
2020 if (right is IntConstant){
2021 IntConstant ic = (IntConstant) right;
2023 e = Convert.TryImplicitIntConversion (l, ic);
2026 } else if (right is LongConstant){
2027 long ll = ((LongConstant) right).Value;
2030 right = new ULongConstant ((ulong) ll);
2032 e = Convert.ImplicitNumericConversion (ec, right, l, loc);
2039 if (left is IntConstant){
2040 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
2043 } else if (left is LongConstant){
2044 long ll = ((LongConstant) left).Value;
2047 left = new ULongConstant ((ulong) ll);
2049 e = Convert.ImplicitNumericConversion (ec, left, r, loc);
2056 if ((other == TypeManager.sbyte_type) ||
2057 (other == TypeManager.short_type) ||
2058 (other == TypeManager.int32_type) ||
2059 (other == TypeManager.int64_type))
2060 Error_OperatorAmbiguous (loc, oper, l, r);
2061 type = TypeManager.uint64_type;
2062 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2064 // If either operand is of type long, the other operand is converted
2067 if (l != TypeManager.int64_type)
2068 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
2069 if (r != TypeManager.int64_type)
2070 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
2072 type = TypeManager.int64_type;
2073 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2075 // If either operand is of type uint, and the other
2076 // operand is of type sbyte, short or int, othe operands are
2077 // converted to type long.
2081 if (l == TypeManager.uint32_type){
2082 if (right is IntConstant){
2083 IntConstant ic = (IntConstant) right;
2087 right = new UIntConstant ((uint) val);
2094 } else if (r == TypeManager.uint32_type){
2095 if (left is IntConstant){
2096 IntConstant ic = (IntConstant) left;
2100 left = new UIntConstant ((uint) val);
2109 if ((other == TypeManager.sbyte_type) ||
2110 (other == TypeManager.short_type) ||
2111 (other == TypeManager.int32_type)){
2112 left = ForceConversion (ec, left, TypeManager.int64_type);
2113 right = ForceConversion (ec, right, TypeManager.int64_type);
2114 type = TypeManager.int64_type;
2117 // if either operand is of type uint, the other
2118 // operand is converd to type uint
2120 left = ForceConversion (ec, left, TypeManager.uint32_type);
2121 right = ForceConversion (ec, right, TypeManager.uint32_type);
2122 type = TypeManager.uint32_type;
2124 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2125 if (l != TypeManager.decimal_type)
2126 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
2128 if (r != TypeManager.decimal_type)
2129 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
2130 type = TypeManager.decimal_type;
2132 left = ForceConversion (ec, left, TypeManager.int32_type);
2133 right = ForceConversion (ec, right, TypeManager.int32_type);
2135 type = TypeManager.int32_type;
2138 return (left != null) && (right != null);
2141 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2143 Report.Error (19, loc,
2144 "Operator " + name + " cannot be applied to operands of type `" +
2145 TypeManager.CSharpName (l) + "' and `" +
2146 TypeManager.CSharpName (r) + "'");
2149 void Error_OperatorCannotBeApplied ()
2151 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2154 static bool is_32_or_64 (Type t)
2156 return (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2157 t == TypeManager.int64_type || t == TypeManager.uint64_type);
2160 static bool is_unsigned (Type t)
2162 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2163 t == TypeManager.short_type || t == TypeManager.byte_type);
2166 static bool is_user_defined (Type t)
2168 if (t.IsSubclassOf (TypeManager.value_type) &&
2169 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2175 Expression CheckShiftArguments (EmitContext ec)
2179 Type r = right.Type;
2181 e = ForceConversion (ec, right, TypeManager.int32_type);
2183 Error_OperatorCannotBeApplied ();
2188 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
2189 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
2190 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
2191 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
2197 Error_OperatorCannotBeApplied ();
2201 Expression ResolveOperator (EmitContext ec)
2204 Type r = right.Type;
2206 bool overload_failed = false;
2209 // Special cases: string comapred to null
2211 if (oper == Operator.Equality || oper == Operator.Inequality){
2212 if ((l == TypeManager.string_type && (right is NullLiteral)) ||
2213 (r == TypeManager.string_type && (left is NullLiteral))){
2214 Type = TypeManager.bool_type;
2221 // Do not perform operator overload resolution when both sides are
2224 if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
2226 // Step 1: Perform Operator Overload location
2228 Expression left_expr, right_expr;
2230 string op = oper_names [(int) oper];
2232 MethodGroupExpr union;
2233 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2235 right_expr = MemberLookup (
2236 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2237 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2239 union = (MethodGroupExpr) left_expr;
2241 if (union != null) {
2242 Arguments = new ArrayList ();
2243 Arguments.Add (new Argument (left, Argument.AType.Expression));
2244 Arguments.Add (new Argument (right, Argument.AType.Expression));
2246 method = Invocation.OverloadResolve (ec, union, Arguments, Location.Null);
2247 if (method != null) {
2248 MethodInfo mi = (MethodInfo) method;
2250 type = mi.ReturnType;
2253 overload_failed = true;
2259 // Step 2: Default operations on CLI native types.
2263 // Step 0: String concatenation (because overloading will get this wrong)
2265 if (oper == Operator.Addition){
2267 // If any of the arguments is a string, cast to string
2270 if (l == TypeManager.string_type){
2272 if (r == TypeManager.void_type) {
2273 Error_OperatorCannotBeApplied ();
2277 if (r == TypeManager.string_type){
2278 if (left is Constant && right is Constant){
2279 StringConstant ls = (StringConstant) left;
2280 StringConstant rs = (StringConstant) right;
2282 return new StringConstant (
2283 ls.Value + rs.Value);
2286 if (left is Binary){
2287 Binary b = (Binary) left;
2290 // Call String.Concat (string, string, string) or
2291 // String.Concat (string, string, string, string)
2294 if (b.oper == Operator.Addition &&
2295 (b.method == TypeManager.string_concat_string_string ||
2296 b.method == TypeManager.string_concat_string_string_string)){
2297 ArrayList bargs = b.Arguments;
2298 int count = bargs.Count;
2302 Arguments.Add (new Argument (right, Argument.AType.Expression));
2303 type = TypeManager.string_type;
2304 method = TypeManager.string_concat_string_string_string;
2307 } else if (count == 3){
2309 Arguments.Add (new Argument (right, Argument.AType.Expression));
2310 type = TypeManager.string_type;
2311 method = TypeManager.string_concat_string_string_string_string;
2318 method = TypeManager.string_concat_string_string;
2321 method = TypeManager.string_concat_object_object;
2322 right = Convert.ImplicitConversion (
2323 ec, right, TypeManager.object_type, loc);
2325 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2329 type = TypeManager.string_type;
2331 Arguments = new ArrayList ();
2332 Arguments.Add (new Argument (left, Argument.AType.Expression));
2333 Arguments.Add (new Argument (right, Argument.AType.Expression));
2337 } else if (r == TypeManager.string_type){
2340 if (l == TypeManager.void_type) {
2341 Error_OperatorCannotBeApplied ();
2345 method = TypeManager.string_concat_object_object;
2346 left = Convert.ImplicitConversion (ec, left, TypeManager.object_type, loc);
2348 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2351 Arguments = new ArrayList ();
2352 Arguments.Add (new Argument (left, Argument.AType.Expression));
2353 Arguments.Add (new Argument (right, Argument.AType.Expression));
2355 type = TypeManager.string_type;
2361 // Transform a + ( - b) into a - b
2363 if (right is Unary){
2364 Unary right_unary = (Unary) right;
2366 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2367 oper = Operator.Subtraction;
2368 right = right_unary.Expr;
2374 if (oper == Operator.Equality || oper == Operator.Inequality){
2375 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2376 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2377 Error_OperatorCannotBeApplied ();
2381 type = TypeManager.bool_type;
2386 // operator != (object a, object b)
2387 // operator == (object a, object b)
2389 // For this to be used, both arguments have to be reference-types.
2390 // Read the rationale on the spec (14.9.6)
2392 // Also, if at compile time we know that the classes do not inherit
2393 // one from the other, then we catch the error there.
2395 if (!(l.IsValueType || r.IsValueType)){
2396 type = TypeManager.bool_type;
2401 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2405 // Also, a standard conversion must exist from either one
2407 if (!(Convert.ImplicitStandardConversionExists (left, r) ||
2408 Convert.ImplicitStandardConversionExists (right, l))){
2409 Error_OperatorCannotBeApplied ();
2413 // We are going to have to convert to an object to compare
2415 if (l != TypeManager.object_type)
2416 left = new EmptyCast (left, TypeManager.object_type);
2417 if (r != TypeManager.object_type)
2418 right = new EmptyCast (right, TypeManager.object_type);
2421 // FIXME: CSC here catches errors cs254 and cs252
2427 // One of them is a valuetype, but the other one is not.
2429 if (!l.IsValueType || !r.IsValueType) {
2430 Error_OperatorCannotBeApplied ();
2435 // Only perform numeric promotions on:
2436 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2438 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2439 if (l.IsSubclassOf (TypeManager.delegate_type) &&
2440 r.IsSubclassOf (TypeManager.delegate_type)) {
2442 Arguments = new ArrayList ();
2443 Arguments.Add (new Argument (left, Argument.AType.Expression));
2444 Arguments.Add (new Argument (right, Argument.AType.Expression));
2446 if (oper == Operator.Addition)
2447 method = TypeManager.delegate_combine_delegate_delegate;
2449 method = TypeManager.delegate_remove_delegate_delegate;
2452 Error_OperatorCannotBeApplied ();
2456 DelegateOperation = true;
2462 // Pointer arithmetic:
2464 // T* operator + (T* x, int y);
2465 // T* operator + (T* x, uint y);
2466 // T* operator + (T* x, long y);
2467 // T* operator + (T* x, ulong y);
2469 // T* operator + (int y, T* x);
2470 // T* operator + (uint y, T *x);
2471 // T* operator + (long y, T *x);
2472 // T* operator + (ulong y, T *x);
2474 // T* operator - (T* x, int y);
2475 // T* operator - (T* x, uint y);
2476 // T* operator - (T* x, long y);
2477 // T* operator - (T* x, ulong y);
2479 // long operator - (T* x, T *y)
2482 if (r.IsPointer && oper == Operator.Subtraction){
2484 return new PointerArithmetic (
2485 false, left, right, TypeManager.int64_type,
2487 } else if (is_32_or_64 (r))
2488 return new PointerArithmetic (
2489 oper == Operator.Addition, left, right, l, loc);
2490 } else if (r.IsPointer && is_32_or_64 (l) && oper == Operator.Addition)
2491 return new PointerArithmetic (
2492 true, right, left, r, loc);
2496 // Enumeration operators
2498 bool lie = TypeManager.IsEnumType (l);
2499 bool rie = TypeManager.IsEnumType (r);
2503 // U operator - (E e, E f)
2504 if (lie && rie && oper == Operator.Subtraction){
2506 type = TypeManager.EnumToUnderlying (l);
2509 Error_OperatorCannotBeApplied ();
2514 // operator + (E e, U x)
2515 // operator - (E e, U x)
2517 if (oper == Operator.Addition || oper == Operator.Subtraction){
2518 Type enum_type = lie ? l : r;
2519 Type other_type = lie ? r : l;
2520 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2523 if (underlying_type != other_type){
2524 Error_OperatorCannotBeApplied ();
2533 temp = Convert.ImplicitConversion (ec, right, l, loc);
2537 Error_OperatorCannotBeApplied ();
2541 temp = Convert.ImplicitConversion (ec, left, r, loc);
2546 Error_OperatorCannotBeApplied ();
2551 if (oper == Operator.Equality || oper == Operator.Inequality ||
2552 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2553 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2554 if (left.Type != right.Type){
2555 Error_OperatorCannotBeApplied ();
2558 type = TypeManager.bool_type;
2562 if (oper == Operator.BitwiseAnd ||
2563 oper == Operator.BitwiseOr ||
2564 oper == Operator.ExclusiveOr){
2568 Error_OperatorCannotBeApplied ();
2572 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2573 return CheckShiftArguments (ec);
2575 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2576 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2577 type = TypeManager.bool_type;
2582 Error_OperatorCannotBeApplied ();
2586 Expression e = new ConditionalLogicalOperator (
2587 oper == Operator.LogicalAnd, left, right, l, loc);
2588 return e.Resolve (ec);
2592 // operator & (bool x, bool y)
2593 // operator | (bool x, bool y)
2594 // operator ^ (bool x, bool y)
2596 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2597 if (oper == Operator.BitwiseAnd ||
2598 oper == Operator.BitwiseOr ||
2599 oper == Operator.ExclusiveOr){
2606 // Pointer comparison
2608 if (l.IsPointer && r.IsPointer){
2609 if (oper == Operator.Equality || oper == Operator.Inequality ||
2610 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2611 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2612 type = TypeManager.bool_type;
2618 // We are dealing with numbers
2620 if (overload_failed){
2621 Error_OperatorCannotBeApplied ();
2626 // This will leave left or right set to null if there is an error
2628 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2629 DoNumericPromotions (ec, l, r, check_user_conv);
2630 if (left == null || right == null){
2631 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2636 // reload our cached types if required
2641 if (oper == Operator.BitwiseAnd ||
2642 oper == Operator.BitwiseOr ||
2643 oper == Operator.ExclusiveOr){
2645 if (!((l == TypeManager.int32_type) ||
2646 (l == TypeManager.uint32_type) ||
2647 (l == TypeManager.short_type) ||
2648 (l == TypeManager.ushort_type) ||
2649 (l == TypeManager.int64_type) ||
2650 (l == TypeManager.uint64_type)))
2653 Error_OperatorCannotBeApplied ();
2658 if (oper == Operator.Equality ||
2659 oper == Operator.Inequality ||
2660 oper == Operator.LessThanOrEqual ||
2661 oper == Operator.LessThan ||
2662 oper == Operator.GreaterThanOrEqual ||
2663 oper == Operator.GreaterThan){
2664 type = TypeManager.bool_type;
2670 public override Expression DoResolve (EmitContext ec)
2672 left = left.Resolve (ec);
2673 right = right.Resolve (ec);
2675 if (left == null || right == null)
2678 eclass = ExprClass.Value;
2680 Constant rc = right as Constant;
2681 Constant lc = left as Constant;
2683 if (rc != null & lc != null){
2684 Expression e = ConstantFold.BinaryFold (
2685 ec, oper, lc, rc, loc);
2690 return ResolveOperator (ec);
2694 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2695 /// context of a conditional bool expression. This function will return
2696 /// false if it is was possible to use EmitBranchable, or true if it was.
2698 /// The expression's code is generated, and we will generate a branch to `target'
2699 /// if the resulting expression value is equal to isTrue
2701 public bool EmitBranchable (EmitContext ec, Label target, bool onTrue)
2706 ILGenerator ig = ec.ig;
2709 // This is more complicated than it looks, but its just to avoid
2710 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2711 // but on top of that we want for == and != to use a special path
2712 // if we are comparing against null
2714 if (oper == Operator.Equality || oper == Operator.Inequality){
2715 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2717 if (left is NullLiteral){
2720 ig.Emit (OpCodes.Brtrue, target);
2722 ig.Emit (OpCodes.Brfalse, target);
2724 } else if (right is NullLiteral){
2727 ig.Emit (OpCodes.Brtrue, target);
2729 ig.Emit (OpCodes.Brfalse, target);
2731 } else if (left is BoolConstant){
2733 if (my_on_true != ((BoolConstant) left).Value)
2734 ig.Emit (OpCodes.Brtrue, target);
2736 ig.Emit (OpCodes.Brfalse, target);
2738 } else if (right is BoolConstant){
2740 if (my_on_true != ((BoolConstant) right).Value)
2741 ig.Emit (OpCodes.Brtrue, target);
2743 ig.Emit (OpCodes.Brfalse, target);
2747 } else if (oper == Operator.LogicalAnd){
2748 if (left is Binary){
2749 Binary left_binary = (Binary) left;
2752 Label tests_end = ig.DefineLabel ();
2754 if (left_binary.EmitBranchable (ec, tests_end, false)){
2755 if (right is Binary){
2756 Binary right_binary = (Binary) right;
2758 if (right_binary.EmitBranchable (ec, target, true)){
2759 ig.MarkLabel (tests_end);
2764 ig.Emit (OpCodes.Brtrue, target);
2765 ig.MarkLabel (tests_end);
2769 if (left_binary.EmitBranchable (ec, target, false)){
2770 if (right is Binary){
2771 Binary right_binary = (Binary) right;
2773 if (right_binary.EmitBranchable (ec, target, false))
2778 ig.Emit (OpCodes.Brtrue, target);
2780 ig.Emit (OpCodes.Brfalse, target);
2785 // Give up, and let the regular Emit work, but we could
2786 // also optimize the left-non-Branchable, but-right-Branchable
2790 } else if (oper == Operator.LogicalOr){
2791 if (left is Binary){
2792 Binary left_binary = (Binary) left;
2795 if (left_binary.EmitBranchable (ec, target, true)){
2796 if (right is Binary){
2797 Binary right_binary = (Binary) right;
2799 if (right_binary.EmitBranchable (ec, target, true))
2803 ig.Emit (OpCodes.Brtrue, target);
2808 // Give up, and let the regular Emit work, but we could
2809 // also optimize the left-non-Branchable, but-right-Branchable
2812 Label tests_end = ig.DefineLabel ();
2814 if (left_binary.EmitBranchable (ec, tests_end, true)){
2815 if (right is Binary){
2816 Binary right_binary = (Binary) right;
2818 if (right_binary.EmitBranchable (ec, target, false)){
2819 ig.MarkLabel (tests_end);
2824 ig.Emit (OpCodes.Brfalse, target);
2825 ig.MarkLabel (tests_end);
2832 } else if (!(oper == Operator.LessThan ||
2833 oper == Operator.GreaterThan ||
2834 oper == Operator.LessThanOrEqual ||
2835 oper == Operator.GreaterThanOrEqual))
2842 bool isUnsigned = is_unsigned (t);
2845 case Operator.Equality:
2847 ig.Emit (OpCodes.Beq, target);
2849 ig.Emit (OpCodes.Bne_Un, target);
2852 case Operator.Inequality:
2854 ig.Emit (OpCodes.Bne_Un, target);
2856 ig.Emit (OpCodes.Beq, target);
2859 case Operator.LessThan:
2862 ig.Emit (OpCodes.Blt_Un, target);
2864 ig.Emit (OpCodes.Blt, target);
2867 ig.Emit (OpCodes.Bge_Un, target);
2869 ig.Emit (OpCodes.Bge, target);
2872 case Operator.GreaterThan:
2875 ig.Emit (OpCodes.Bgt_Un, target);
2877 ig.Emit (OpCodes.Bgt, target);
2880 ig.Emit (OpCodes.Ble_Un, target);
2882 ig.Emit (OpCodes.Ble, target);
2885 case Operator.LessThanOrEqual:
2886 if (t == TypeManager.double_type || t == TypeManager.float_type)
2891 ig.Emit (OpCodes.Ble_Un, target);
2893 ig.Emit (OpCodes.Ble, target);
2896 ig.Emit (OpCodes.Bgt_Un, target);
2898 ig.Emit (OpCodes.Bgt, target);
2902 case Operator.GreaterThanOrEqual:
2903 if (t == TypeManager.double_type || t == TypeManager.float_type)
2907 ig.Emit (OpCodes.Bge_Un, target);
2909 ig.Emit (OpCodes.Bge, target);
2912 ig.Emit (OpCodes.Blt_Un, target);
2914 ig.Emit (OpCodes.Blt, target);
2924 public override void Emit (EmitContext ec)
2926 ILGenerator ig = ec.ig;
2928 Type r = right.Type;
2931 if (method != null) {
2933 // Note that operators are static anyway
2935 if (Arguments != null)
2936 Invocation.EmitArguments (ec, method, Arguments);
2938 if (method is MethodInfo)
2939 ig.Emit (OpCodes.Call, (MethodInfo) method);
2941 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2943 if (DelegateOperation)
2944 ig.Emit (OpCodes.Castclass, type);
2950 // Handle short-circuit operators differently
2953 if (oper == Operator.LogicalAnd){
2954 Label load_zero = ig.DefineLabel ();
2955 Label end = ig.DefineLabel ();
2956 bool process = true;
2958 if (left is Binary){
2959 Binary left_binary = (Binary) left;
2961 if (left_binary.EmitBranchable (ec, load_zero, false)){
2963 ig.Emit (OpCodes.Br, end);
2970 ig.Emit (OpCodes.Brfalse, load_zero);
2972 ig.Emit (OpCodes.Br, end);
2974 ig.MarkLabel (load_zero);
2975 ig.Emit (OpCodes.Ldc_I4_0);
2978 } else if (oper == Operator.LogicalOr){
2979 Label load_one = ig.DefineLabel ();
2980 Label end = ig.DefineLabel ();
2981 bool process = true;
2983 if (left is Binary){
2984 Binary left_binary = (Binary) left;
2986 if (left_binary.EmitBranchable (ec, load_one, true)){
2988 ig.Emit (OpCodes.Br, end);
2995 ig.Emit (OpCodes.Brtrue, load_one);
2997 ig.Emit (OpCodes.Br, end);
2999 ig.MarkLabel (load_one);
3000 ig.Emit (OpCodes.Ldc_I4_1);
3008 bool isUnsigned = is_unsigned (left.Type);
3011 case Operator.Multiply:
3013 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3014 opcode = OpCodes.Mul_Ovf;
3015 else if (isUnsigned)
3016 opcode = OpCodes.Mul_Ovf_Un;
3018 opcode = OpCodes.Mul;
3020 opcode = OpCodes.Mul;
3024 case Operator.Division:
3026 opcode = OpCodes.Div_Un;
3028 opcode = OpCodes.Div;
3031 case Operator.Modulus:
3033 opcode = OpCodes.Rem_Un;
3035 opcode = OpCodes.Rem;
3038 case Operator.Addition:
3040 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3041 opcode = OpCodes.Add_Ovf;
3042 else if (isUnsigned)
3043 opcode = OpCodes.Add_Ovf_Un;
3045 opcode = OpCodes.Add;
3047 opcode = OpCodes.Add;
3050 case Operator.Subtraction:
3052 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3053 opcode = OpCodes.Sub_Ovf;
3054 else if (isUnsigned)
3055 opcode = OpCodes.Sub_Ovf_Un;
3057 opcode = OpCodes.Sub;
3059 opcode = OpCodes.Sub;
3062 case Operator.RightShift:
3064 opcode = OpCodes.Shr_Un;
3066 opcode = OpCodes.Shr;
3069 case Operator.LeftShift:
3070 opcode = OpCodes.Shl;
3073 case Operator.Equality:
3074 opcode = OpCodes.Ceq;
3077 case Operator.Inequality:
3078 ig.Emit (OpCodes.Ceq);
3079 ig.Emit (OpCodes.Ldc_I4_0);
3081 opcode = OpCodes.Ceq;
3084 case Operator.LessThan:
3086 opcode = OpCodes.Clt_Un;
3088 opcode = OpCodes.Clt;
3091 case Operator.GreaterThan:
3093 opcode = OpCodes.Cgt_Un;
3095 opcode = OpCodes.Cgt;
3098 case Operator.LessThanOrEqual:
3099 Type lt = left.Type;
3101 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
3102 ig.Emit (OpCodes.Cgt_Un);
3104 ig.Emit (OpCodes.Cgt);
3105 ig.Emit (OpCodes.Ldc_I4_0);
3107 opcode = OpCodes.Ceq;
3110 case Operator.GreaterThanOrEqual:
3111 Type le = left.Type;
3113 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3114 ig.Emit (OpCodes.Clt_Un);
3116 ig.Emit (OpCodes.Clt);
3118 ig.Emit (OpCodes.Ldc_I4_1);
3120 opcode = OpCodes.Sub;
3123 case Operator.BitwiseOr:
3124 opcode = OpCodes.Or;
3127 case Operator.BitwiseAnd:
3128 opcode = OpCodes.And;
3131 case Operator.ExclusiveOr:
3132 opcode = OpCodes.Xor;
3136 throw new Exception ("This should not happen: Operator = "
3137 + oper.ToString ());
3143 public bool IsBuiltinOperator {
3145 return method == null;
3151 // User-defined conditional logical operator
3152 public class ConditionalLogicalOperator : Expression {
3153 Expression left, right;
3156 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3159 eclass = ExprClass.Value;
3163 this.is_and = is_and;
3166 protected void Error19 ()
3168 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3171 protected void Error218 ()
3173 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3174 "declarations of operator true and operator false");
3177 Expression op_true, op_false, op;
3179 public override Expression DoResolve (EmitContext ec)
3182 Expression operator_group;
3184 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3185 if (operator_group == null) {
3190 ArrayList arguments = new ArrayList ();
3191 arguments.Add (new Argument (left, Argument.AType.Expression));
3192 arguments.Add (new Argument (right, Argument.AType.Expression));
3193 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) operator_group, arguments, loc) as MethodInfo;
3194 if ((method == null) || (method.ReturnType != type)) {
3199 op = new StaticCallExpr (method, arguments, loc);
3201 op_true = GetOperatorTrue (ec, left, loc);
3202 op_false = GetOperatorFalse (ec, left, loc);
3203 if ((op_true == null) || (op_false == null)) {
3211 public override void Emit (EmitContext ec)
3213 ILGenerator ig = ec.ig;
3214 Label false_target = ig.DefineLabel ();
3215 Label end_target = ig.DefineLabel ();
3217 ig.Emit (OpCodes.Nop);
3219 Statement.EmitBoolExpression (ec, is_and ? op_false : op_true, false_target, false);
3221 ig.Emit (OpCodes.Br, end_target);
3222 ig.MarkLabel (false_target);
3224 ig.MarkLabel (end_target);
3226 ig.Emit (OpCodes.Nop);
3230 public class PointerArithmetic : Expression {
3231 Expression left, right;
3235 // We assume that `l' is always a pointer
3237 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3240 eclass = ExprClass.Variable;
3244 is_add = is_addition;
3247 public override Expression DoResolve (EmitContext ec)
3250 // We are born fully resolved
3255 public override void Emit (EmitContext ec)
3257 Type op_type = left.Type;
3258 ILGenerator ig = ec.ig;
3259 int size = GetTypeSize (op_type.GetElementType ());
3260 Type rtype = right.Type;
3262 if (rtype.IsPointer){
3264 // handle (pointer - pointer)
3268 ig.Emit (OpCodes.Sub);
3272 ig.Emit (OpCodes.Sizeof, op_type);
3274 IntLiteral.EmitInt (ig, size);
3275 ig.Emit (OpCodes.Div);
3277 ig.Emit (OpCodes.Conv_I8);
3280 // handle + and - on (pointer op int)
3283 ig.Emit (OpCodes.Conv_I);
3287 ig.Emit (OpCodes.Sizeof, op_type);
3289 IntLiteral.EmitInt (ig, size);
3290 if (rtype == TypeManager.int64_type)
3291 ig.Emit (OpCodes.Conv_I8);
3292 else if (rtype == TypeManager.uint64_type)
3293 ig.Emit (OpCodes.Conv_U8);
3294 ig.Emit (OpCodes.Mul);
3295 ig.Emit (OpCodes.Conv_I);
3298 ig.Emit (OpCodes.Add);
3300 ig.Emit (OpCodes.Sub);
3306 /// Implements the ternary conditional operator (?:)
3308 public class Conditional : Expression {
3309 Expression expr, trueExpr, falseExpr;
3311 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3314 this.trueExpr = trueExpr;
3315 this.falseExpr = falseExpr;
3319 public Expression Expr {
3325 public Expression TrueExpr {
3331 public Expression FalseExpr {
3337 public override Expression DoResolve (EmitContext ec)
3339 expr = expr.Resolve (ec);
3344 if (expr.Type != TypeManager.bool_type){
3345 expr = Expression.ResolveBoolean (
3352 trueExpr = trueExpr.Resolve (ec);
3353 falseExpr = falseExpr.Resolve (ec);
3355 if (trueExpr == null || falseExpr == null)
3358 eclass = ExprClass.Value;
3359 if (trueExpr.Type == falseExpr.Type)
3360 type = trueExpr.Type;
3363 Type true_type = trueExpr.Type;
3364 Type false_type = falseExpr.Type;
3366 if (trueExpr is NullLiteral){
3369 } else if (falseExpr is NullLiteral){
3375 // First, if an implicit conversion exists from trueExpr
3376 // to falseExpr, then the result type is of type falseExpr.Type
3378 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3381 // Check if both can convert implicitl to each other's type
3383 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3385 "Can not compute type of conditional expression " +
3386 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3387 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3388 "' convert implicitly to each other");
3393 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3397 Error (173, "The type of the conditional expression can " +
3398 "not be computed because there is no implicit conversion" +
3399 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3400 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3405 if (expr is BoolConstant){
3406 BoolConstant bc = (BoolConstant) expr;
3417 public override void Emit (EmitContext ec)
3419 ILGenerator ig = ec.ig;
3420 Label false_target = ig.DefineLabel ();
3421 Label end_target = ig.DefineLabel ();
3423 Statement.EmitBoolExpression (ec, expr, false_target, false);
3425 ig.Emit (OpCodes.Br, end_target);
3426 ig.MarkLabel (false_target);
3427 falseExpr.Emit (ec);
3428 ig.MarkLabel (end_target);
3436 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3437 public readonly string Name;
3438 public readonly Block Block;
3439 LocalInfo local_info;
3440 VariableInfo variable_info;
3443 public LocalVariableReference (Block block, string name, Location l)
3448 eclass = ExprClass.Variable;
3451 // Setting `is_readonly' to false will allow you to create a writable
3452 // reference to a read-only variable. This is used by foreach and using.
3453 public LocalVariableReference (Block block, string name, Location l,
3454 LocalInfo local_info, bool is_readonly)
3455 : this (block, name, l)
3457 this.local_info = local_info;
3458 this.is_readonly = is_readonly;
3461 public VariableInfo VariableInfo {
3462 get { return variable_info; }
3465 public bool IsReadOnly {
3471 protected void DoResolveBase (EmitContext ec)
3473 if (local_info == null) {
3474 local_info = Block.GetLocalInfo (Name);
3475 is_readonly = local_info.ReadOnly;
3478 variable_info = Block.GetVariableInfo (local_info);
3479 type = local_info.VariableType;
3482 public override Expression DoResolve (EmitContext ec)
3486 Expression e = Block.GetConstantExpression (Name);
3488 local_info.Used = true;
3489 eclass = ExprClass.Value;
3493 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3499 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3503 if (variable_info != null)
3504 variable_info.SetAssigned (ec);
3506 Expression e = DoResolve (ec);
3512 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3519 public bool VerifyFixed (bool is_expression)
3521 return !is_expression || local_info.IsFixed;
3524 public override void Emit (EmitContext ec)
3526 ILGenerator ig = ec.ig;
3528 if (local_info.LocalBuilder == null){
3529 ig.Emit (OpCodes.Ldarg_0);
3530 ig.Emit (OpCodes.Ldfld, local_info.FieldBuilder);
3532 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3534 local_info.Used = true;
3537 public void EmitAssign (EmitContext ec, Expression source)
3539 ILGenerator ig = ec.ig;
3541 local_info.Assigned = true;
3543 if (local_info.LocalBuilder == null){
3544 ig.Emit (OpCodes.Ldarg_0);
3546 ig.Emit (OpCodes.Stfld, local_info.FieldBuilder);
3549 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3553 public void AddressOf (EmitContext ec, AddressOp mode)
3555 ILGenerator ig = ec.ig;
3557 if (local_info.LocalBuilder == null){
3558 ig.Emit (OpCodes.Ldarg_0);
3559 ig.Emit (OpCodes.Ldflda, local_info.FieldBuilder);
3561 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3564 public override string ToString ()
3566 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3571 /// This represents a reference to a parameter in the intermediate
3574 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3580 public Parameter.Modifier mod;
3581 public bool is_ref, is_out;
3583 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3590 eclass = ExprClass.Variable;
3593 public VariableInfo VariableInfo {
3597 public bool VerifyFixed (bool is_expression)
3599 return !is_expression;
3602 public bool IsAssigned (EmitContext ec, Location loc)
3604 if (!ec.DoFlowAnalysis || !is_out ||
3605 ec.CurrentBranching.IsAssigned (vi))
3608 Report.Error (165, loc,
3609 "Use of unassigned parameter `" + name + "'");
3613 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3615 if (!ec.DoFlowAnalysis || !is_out ||
3616 ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3619 Report.Error (170, loc,
3620 "Use of possibly unassigned field `" + field_name + "'");
3624 public void SetAssigned (EmitContext ec)
3626 if (is_out && ec.DoFlowAnalysis)
3627 ec.CurrentBranching.SetAssigned (vi);
3630 public void SetFieldAssigned (EmitContext ec, string field_name)
3632 if (is_out && ec.DoFlowAnalysis)
3633 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3636 protected void DoResolveBase (EmitContext ec)
3638 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
3639 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3640 is_out = (mod & Parameter.Modifier.OUT) != 0;
3641 eclass = ExprClass.Variable;
3644 vi = block.ParameterMap [idx];
3648 // Notice that for ref/out parameters, the type exposed is not the
3649 // same type exposed externally.
3652 // externally we expose "int&"
3653 // here we expose "int".
3655 // We record this in "is_ref". This means that the type system can treat
3656 // the type as it is expected, but when we generate the code, we generate
3657 // the alternate kind of code.
3659 public override Expression DoResolve (EmitContext ec)
3663 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3669 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3678 static public void EmitLdArg (ILGenerator ig, int x)
3682 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3683 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3684 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3685 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3686 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3689 ig.Emit (OpCodes.Ldarg, x);
3693 // This method is used by parameters that are references, that are
3694 // being passed as references: we only want to pass the pointer (that
3695 // is already stored in the parameter, not the address of the pointer,
3696 // and not the value of the variable).
3698 public void EmitLoad (EmitContext ec)
3700 ILGenerator ig = ec.ig;
3706 EmitLdArg (ig, arg_idx);
3709 public override void Emit (EmitContext ec)
3711 ILGenerator ig = ec.ig;
3713 if (ec.RemapToProxy){
3714 ig.Emit (OpCodes.Ldarg_0);
3715 ec.EmitArgument (idx);
3724 EmitLdArg (ig, arg_idx);
3730 // If we are a reference, we loaded on the stack a pointer
3731 // Now lets load the real value
3733 LoadFromPtr (ig, type);
3736 public void EmitAssign (EmitContext ec, Expression source)
3738 ILGenerator ig = ec.ig;
3740 if (ec.RemapToProxy){
3741 ig.Emit (OpCodes.Ldarg_0);
3743 ec.EmitStoreArgument (idx);
3753 EmitLdArg (ig, arg_idx);
3758 StoreFromPtr (ig, type);
3761 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
3763 ig.Emit (OpCodes.Starg, arg_idx);
3767 public void AddressOf (EmitContext ec, AddressOp mode)
3769 if (ec.RemapToProxy){
3770 Report.Error (-1, "Report this: Taking the address of a remapped parameter not supported");
3781 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
3783 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
3786 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
3788 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
3795 /// Used for arguments to New(), Invocation()
3797 public class Argument {
3798 public enum AType : byte {
3804 public readonly AType ArgType;
3805 public Expression Expr;
3807 public Argument (Expression expr, AType type)
3810 this.ArgType = type;
3815 if (ArgType == AType.Ref || ArgType == AType.Out)
3816 return TypeManager.GetReferenceType (Expr.Type);
3822 public Parameter.Modifier GetParameterModifier ()
3826 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
3829 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
3832 return Parameter.Modifier.NONE;
3836 public static string FullDesc (Argument a)
3838 return (a.ArgType == AType.Ref ? "ref " :
3839 (a.ArgType == AType.Out ? "out " : "")) +
3840 TypeManager.CSharpName (a.Expr.Type);
3843 public bool ResolveMethodGroup (EmitContext ec, Location loc)
3845 // FIXME: csc doesn't report any error if you try to use `ref' or
3846 // `out' in a delegate creation expression.
3847 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
3854 public bool Resolve (EmitContext ec, Location loc)
3856 if (ArgType == AType.Ref) {
3857 Expr = Expr.Resolve (ec);
3861 Expr = Expr.ResolveLValue (ec, Expr);
3862 } else if (ArgType == AType.Out)
3863 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
3865 Expr = Expr.Resolve (ec);
3870 if (ArgType == AType.Expression)
3873 if (Expr.eclass != ExprClass.Variable){
3875 // We just probe to match the CSC output
3877 if (Expr.eclass == ExprClass.PropertyAccess ||
3878 Expr.eclass == ExprClass.IndexerAccess){
3881 "A property or indexer can not be passed as an out or ref " +
3886 "An lvalue is required as an argument to out or ref");
3894 public void Emit (EmitContext ec)
3897 // Ref and Out parameters need to have their addresses taken.
3899 // ParameterReferences might already be references, so we want
3900 // to pass just the value
3902 if (ArgType == AType.Ref || ArgType == AType.Out){
3903 AddressOp mode = AddressOp.Store;
3905 if (ArgType == AType.Ref)
3906 mode |= AddressOp.Load;
3908 if (Expr is ParameterReference){
3909 ParameterReference pr = (ParameterReference) Expr;
3915 pr.AddressOf (ec, mode);
3918 ((IMemoryLocation)Expr).AddressOf (ec, mode);
3925 /// Invocation of methods or delegates.
3927 public class Invocation : ExpressionStatement {
3928 public readonly ArrayList Arguments;
3931 MethodBase method = null;
3934 static Hashtable method_parameter_cache;
3936 static Invocation ()
3938 method_parameter_cache = new PtrHashtable ();
3942 // arguments is an ArrayList, but we do not want to typecast,
3943 // as it might be null.
3945 // FIXME: only allow expr to be a method invocation or a
3946 // delegate invocation (7.5.5)
3948 public Invocation (Expression expr, ArrayList arguments, Location l)
3951 Arguments = arguments;
3955 public Expression Expr {
3962 /// Returns the Parameters (a ParameterData interface) for the
3965 public static ParameterData GetParameterData (MethodBase mb)
3967 object pd = method_parameter_cache [mb];
3971 return (ParameterData) pd;
3974 ip = TypeManager.LookupParametersByBuilder (mb);
3976 method_parameter_cache [mb] = ip;
3978 return (ParameterData) ip;
3980 ParameterInfo [] pi = mb.GetParameters ();
3981 ReflectionParameters rp = new ReflectionParameters (pi);
3982 method_parameter_cache [mb] = rp;
3984 return (ParameterData) rp;
3989 /// Determines "better conversion" as specified in 7.4.2.3
3990 /// Returns : 1 if a->p is better
3991 /// 0 if a->q or neither is better
3993 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
3995 Type argument_type = a.Type;
3996 Expression argument_expr = a.Expr;
3998 if (argument_type == null)
3999 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
4002 // This is a special case since csc behaves this way. I can't find
4003 // it anywhere in the spec but oh well ...
4005 if (argument_expr is NullLiteral && p == TypeManager.string_type && q == TypeManager.object_type)
4007 else if (argument_expr is NullLiteral && p == TypeManager.object_type && q == TypeManager.string_type)
4013 if (argument_type == p)
4016 if (argument_type == q)
4020 // Now probe whether an implicit constant expression conversion
4023 // An implicit constant expression conversion permits the following
4026 // * A constant-expression of type `int' can be converted to type
4027 // sbyte, byute, short, ushort, uint, ulong provided the value of
4028 // of the expression is withing the range of the destination type.
4030 // * A constant-expression of type long can be converted to type
4031 // ulong, provided the value of the constant expression is not negative
4033 // FIXME: Note that this assumes that constant folding has
4034 // taken place. We dont do constant folding yet.
4037 if (argument_expr is IntConstant){
4038 IntConstant ei = (IntConstant) argument_expr;
4039 int value = ei.Value;
4041 if (p == TypeManager.sbyte_type){
4042 if (value >= SByte.MinValue && value <= SByte.MaxValue)
4044 } else if (p == TypeManager.byte_type){
4045 if (q == TypeManager.sbyte_type &&
4046 value >= SByte.MinValue && value <= SByte.MaxValue)
4048 else if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
4050 } else if (p == TypeManager.short_type){
4051 if (value >= Int16.MinValue && value <= Int16.MaxValue)
4053 } else if (p == TypeManager.ushort_type){
4054 if (q == TypeManager.short_type &&
4055 value >= Int16.MinValue && value <= Int16.MaxValue)
4057 else if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
4059 } else if (p == TypeManager.int32_type){
4060 if (value >= Int32.MinValue && value <= Int32.MaxValue)
4062 } else if (p == TypeManager.uint32_type){
4064 // we can optimize this case: a positive int32
4065 // always fits on a uint32
4069 } else if (p == TypeManager.uint64_type){
4071 // we can optimize this case: a positive int32
4072 // always fits on a uint64
4074 if (q == TypeManager.int64_type)
4076 else if (value >= 0)
4078 } else if (p == TypeManager.int64_type){
4081 } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
4082 LongConstant lc = (LongConstant) argument_expr;
4084 if (p == TypeManager.uint64_type){
4091 Expression tmp = Convert.ImplicitConversion (ec, argument_expr, p, loc);
4099 Expression p_tmp = new EmptyExpression (p);
4100 Expression q_tmp = new EmptyExpression (q);
4102 if (Convert.ImplicitConversionExists (ec, p_tmp, q) == true &&
4103 Convert.ImplicitConversionExists (ec, q_tmp, p) == false)
4106 if (p == TypeManager.sbyte_type)
4107 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4108 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4111 if (p == TypeManager.short_type)
4112 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4113 q == TypeManager.uint64_type)
4116 if (p == TypeManager.int32_type)
4117 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4120 if (p == TypeManager.int64_type)
4121 if (q == TypeManager.uint64_type)
4128 /// Determines "Better function"
4131 /// and returns an integer indicating :
4132 /// 0 if candidate ain't better
4133 /// 1 if candidate is better than the current best match
4135 static int BetterFunction (EmitContext ec, ArrayList args,
4136 MethodBase candidate, MethodBase best,
4137 bool expanded_form, Location loc)
4139 ParameterData candidate_pd = GetParameterData (candidate);
4140 ParameterData best_pd;
4146 argument_count = args.Count;
4148 int cand_count = candidate_pd.Count;
4150 if (cand_count == 0 && argument_count == 0)
4153 if (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS)
4154 if (cand_count != argument_count)
4160 if (argument_count == 0 && cand_count == 1 &&
4161 candidate_pd.ParameterModifier (cand_count - 1) == Parameter.Modifier.PARAMS)
4164 for (int j = argument_count; j > 0;) {
4167 Argument a = (Argument) args [j];
4168 Type t = candidate_pd.ParameterType (j);
4170 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4172 t = t.GetElementType ();
4174 x = BetterConversion (ec, a, t, null, loc);
4186 best_pd = GetParameterData (best);
4188 int rating1 = 0, rating2 = 0;
4190 for (int j = 0; j < argument_count; ++j) {
4193 Argument a = (Argument) args [j];
4195 Type ct = candidate_pd.ParameterType (j);
4196 Type bt = best_pd.ParameterType (j);
4198 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4200 ct = ct.GetElementType ();
4202 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4204 bt = bt.GetElementType ();
4206 x = BetterConversion (ec, a, ct, bt, loc);
4207 y = BetterConversion (ec, a, bt, ct, loc);
4216 if (rating1 > rating2)
4222 public static string FullMethodDesc (MethodBase mb)
4224 string ret_type = "";
4226 if (mb is MethodInfo)
4227 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
4229 StringBuilder sb = new StringBuilder (ret_type);
4231 sb.Append (mb.ReflectedType.ToString ());
4233 sb.Append (mb.Name);
4235 ParameterData pd = GetParameterData (mb);
4237 int count = pd.Count;
4240 for (int i = count; i > 0; ) {
4243 sb.Append (pd.ParameterDesc (count - i - 1));
4249 return sb.ToString ();
4252 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4254 MemberInfo [] miset;
4255 MethodGroupExpr union;
4260 return (MethodGroupExpr) mg2;
4263 return (MethodGroupExpr) mg1;
4266 MethodGroupExpr left_set = null, right_set = null;
4267 int length1 = 0, length2 = 0;
4269 left_set = (MethodGroupExpr) mg1;
4270 length1 = left_set.Methods.Length;
4272 right_set = (MethodGroupExpr) mg2;
4273 length2 = right_set.Methods.Length;
4275 ArrayList common = new ArrayList ();
4277 foreach (MethodBase l in left_set.Methods){
4278 foreach (MethodBase r in right_set.Methods){
4286 miset = new MemberInfo [length1 + length2 - common.Count];
4287 left_set.Methods.CopyTo (miset, 0);
4291 foreach (MemberInfo mi in right_set.Methods){
4292 if (!common.Contains (mi))
4296 union = new MethodGroupExpr (miset, loc);
4302 /// Determines is the candidate method, if a params method, is applicable
4303 /// in its expanded form to the given set of arguments
4305 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
4309 if (arguments == null)
4312 arg_count = arguments.Count;
4314 ParameterData pd = GetParameterData (candidate);
4316 int pd_count = pd.Count;
4321 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
4324 if (pd_count - 1 > arg_count)
4327 if (pd_count == 1 && arg_count == 0)
4331 // If we have come this far, the case which remains is when the number of parameters
4332 // is less than or equal to the argument count.
4334 for (int i = 0; i < pd_count - 1; ++i) {
4336 Argument a = (Argument) arguments [i];
4338 Parameter.Modifier a_mod = a.GetParameterModifier () &
4339 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4340 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4341 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4343 if (a_mod == p_mod) {
4345 if (a_mod == Parameter.Modifier.NONE)
4346 if (!Convert.ImplicitConversionExists (ec, a.Expr, pd.ParameterType (i)))
4349 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4350 Type pt = pd.ParameterType (i);
4353 pt = TypeManager.GetReferenceType (pt);
4363 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
4365 for (int i = pd_count - 1; i < arg_count; i++) {
4366 Argument a = (Argument) arguments [i];
4368 if (!Convert.ImplicitStandardConversionExists (a.Expr, element_type))
4376 /// Determines if the candidate method is applicable (section 14.4.2.1)
4377 /// to the given set of arguments
4379 static bool IsApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
4383 if (arguments == null)
4386 arg_count = arguments.Count;
4389 ParameterData pd = GetParameterData (candidate);
4391 int pd_count = pd.Count;
4393 if (arg_count != pd.Count)
4396 for (int i = arg_count; i > 0; ) {
4399 Argument a = (Argument) arguments [i];
4401 Parameter.Modifier a_mod = a.GetParameterModifier () &
4402 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4403 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4404 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4407 if (a_mod == p_mod ||
4408 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4409 if (a_mod == Parameter.Modifier.NONE)
4410 if (!Convert.ImplicitConversionExists (ec, a.Expr, pd.ParameterType (i)))
4413 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4414 Type pt = pd.ParameterType (i);
4417 pt = TypeManager.GetReferenceType (pt);
4432 /// Find the Applicable Function Members (7.4.2.1)
4434 /// me: Method Group expression with the members to select.
4435 /// it might contain constructors or methods (or anything
4436 /// that maps to a method).
4438 /// Arguments: ArrayList containing resolved Argument objects.
4440 /// loc: The location if we want an error to be reported, or a Null
4441 /// location for "probing" purposes.
4443 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4444 /// that is the best match of me on Arguments.
4447 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4448 ArrayList Arguments, Location loc)
4450 MethodBase method = null;
4451 Type current_type = null;
4453 ArrayList candidates = new ArrayList ();
4456 foreach (MethodBase candidate in me.Methods){
4459 // If we're going one level higher in the class hierarchy, abort if
4460 // we already found an applicable method.
4461 if (candidate.DeclaringType != current_type) {
4462 current_type = candidate.DeclaringType;
4467 // Check if candidate is applicable (section 14.4.2.1)
4468 if (!IsApplicable (ec, Arguments, candidate))
4471 candidates.Add (candidate);
4472 x = BetterFunction (ec, Arguments, candidate, method, false, loc);
4480 if (Arguments == null)
4483 argument_count = Arguments.Count;
4486 // Now we see if we can find params functions, applicable in their expanded form
4487 // since if they were applicable in their normal form, they would have been selected
4490 bool chose_params_expanded = false;
4492 if (method == null) {
4493 candidates = new ArrayList ();
4494 foreach (MethodBase candidate in me.Methods){
4495 if (!IsParamsMethodApplicable (ec, Arguments, candidate))
4498 candidates.Add (candidate);
4500 int x = BetterFunction (ec, Arguments, candidate, method, true, loc);
4505 chose_params_expanded = true;
4509 if (method == null) {
4511 // Okay so we have failed to find anything so we
4512 // return by providing info about the closest match
4514 for (int i = 0; i < me.Methods.Length; ++i) {
4516 MethodBase c = (MethodBase) me.Methods [i];
4517 ParameterData pd = GetParameterData (c);
4519 if (pd.Count != argument_count)
4522 VerifyArgumentsCompat (ec, Arguments, argument_count, c, false,
4526 if (!Location.IsNull (loc)) {
4527 string report_name = me.Name;
4528 if (report_name == ".ctor")
4529 report_name = me.DeclaringType.ToString ();
4531 Error_WrongNumArguments (loc, report_name, argument_count);
4538 // Now check that there are no ambiguities i.e the selected method
4539 // should be better than all the others
4542 foreach (MethodBase candidate in candidates){
4543 if (candidate == method)
4547 // If a normal method is applicable in the sense that it has the same
4548 // number of arguments, then the expanded params method is never applicable
4549 // so we debar the params method.
4551 if (IsParamsMethodApplicable (ec, Arguments, candidate) &&
4552 IsApplicable (ec, Arguments, method))
4555 int x = BetterFunction (ec, Arguments, method, candidate,
4556 chose_params_expanded, loc);
4561 "Ambiguous call when selecting function due to implicit casts");
4567 // And now check if the arguments are all compatible, perform conversions
4568 // if necessary etc. and return if everything is all right
4571 if (!VerifyArgumentsCompat (ec, Arguments, argument_count, method,
4572 chose_params_expanded, null, loc))
4578 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
4580 Report.Error (1501, loc,
4581 "No overload for method `" + name + "' takes `" +
4582 arg_count + "' arguments");
4585 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
4586 Type delegate_type, string arg_sig, string par_desc)
4588 if (delegate_type == null)
4589 Report.Error (1502, loc,
4590 "The best overloaded match for method '" +
4591 FullMethodDesc (method) +
4592 "' has some invalid arguments");
4594 Report.Error (1594, loc,
4595 "Delegate '" + delegate_type.ToString () +
4596 "' has some invalid arguments.");
4597 Report.Error (1503, loc,
4598 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
4599 idx, arg_sig, par_desc));
4602 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
4605 bool chose_params_expanded,
4609 ParameterData pd = GetParameterData (method);
4610 int pd_count = pd.Count;
4612 for (int j = 0; j < argument_count; j++) {
4613 Argument a = (Argument) Arguments [j];
4614 Expression a_expr = a.Expr;
4615 Type parameter_type = pd.ParameterType (j);
4616 Parameter.Modifier pm = pd.ParameterModifier (j);
4618 if (pm == Parameter.Modifier.PARAMS){
4619 Parameter.Modifier am = a.GetParameterModifier ();
4621 if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
4622 if (!Location.IsNull (loc))
4623 Error_InvalidArguments (
4624 loc, j, method, delegate_type,
4625 Argument.FullDesc (a), pd.ParameterDesc (j));
4629 if (chose_params_expanded)
4630 parameter_type = TypeManager.TypeToCoreType (parameter_type.GetElementType ());
4635 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
4636 if (!Location.IsNull (loc))
4637 Error_InvalidArguments (
4638 loc, j, method, delegate_type,
4639 Argument.FullDesc (a), pd.ParameterDesc (j));
4647 if (a.Type != parameter_type){
4650 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
4653 if (!Location.IsNull (loc))
4654 Error_InvalidArguments (
4655 loc, j, method, delegate_type,
4656 Argument.FullDesc (a), pd.ParameterDesc (j));
4661 // Update the argument with the implicit conversion
4667 Parameter.Modifier a_mod = a.GetParameterModifier () &
4668 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4669 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
4670 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4672 if (a_mod != p_mod &&
4673 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
4674 if (!Location.IsNull (loc)) {
4675 Console.WriteLine ("A:P: " + a.GetParameterModifier ());
4676 Console.WriteLine ("PP:: " + pd.ParameterModifier (j));
4677 Console.WriteLine ("PT: " + parameter_type.IsByRef);
4678 Report.Error (1502, loc,
4679 "The best overloaded match for method '" + FullMethodDesc (method)+
4680 "' has some invalid arguments");
4681 Report.Error (1503, loc,
4682 "Argument " + (j+1) +
4683 ": Cannot convert from '" + Argument.FullDesc (a)
4684 + "' to '" + pd.ParameterDesc (j) + "'");
4694 public override Expression DoResolve (EmitContext ec)
4697 // First, resolve the expression that is used to
4698 // trigger the invocation
4700 if (expr is BaseAccess)
4703 Expression old = expr;
4705 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4709 if (!(expr is MethodGroupExpr)) {
4710 Type expr_type = expr.Type;
4712 if (expr_type != null){
4713 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
4715 return (new DelegateInvocation (
4716 this.expr, Arguments, loc)).Resolve (ec);
4720 if (!(expr is MethodGroupExpr)){
4721 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup);
4726 // Next, evaluate all the expressions in the argument list
4728 if (Arguments != null){
4729 foreach (Argument a in Arguments){
4730 if (!a.Resolve (ec, loc))
4735 MethodGroupExpr mg = (MethodGroupExpr) expr;
4736 method = OverloadResolve (ec, mg, Arguments, loc);
4738 if (method == null){
4740 "Could not find any applicable function for this argument list");
4744 MethodInfo mi = method as MethodInfo;
4746 type = TypeManager.TypeToCoreType (mi.ReturnType);
4747 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null))
4748 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
4751 if (type.IsPointer){
4759 // Only base will allow this invocation to happen.
4761 if (is_base && method.IsAbstract){
4762 Report.Error (205, loc, "Cannot call an abstract base member: " +
4763 FullMethodDesc (method));
4767 if ((method.Attributes & MethodAttributes.SpecialName) != 0){
4768 if (TypeManager.IsSpecialMethod (method))
4769 Report.Error (571, loc, method.Name + ": can not call operator or accessor");
4772 eclass = ExprClass.Value;
4777 // Emits the list of arguments as an array
4779 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
4781 ILGenerator ig = ec.ig;
4782 int count = arguments.Count - idx;
4783 Argument a = (Argument) arguments [idx];
4784 Type t = a.Expr.Type;
4785 string array_type = t.FullName + "[]";
4788 array = ig.DeclareLocal (TypeManager.LookupType (array_type));
4789 IntConstant.EmitInt (ig, count);
4790 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
4791 ig.Emit (OpCodes.Stloc, array);
4793 int top = arguments.Count;
4794 for (int j = idx; j < top; j++){
4795 a = (Argument) arguments [j];
4797 ig.Emit (OpCodes.Ldloc, array);
4798 IntConstant.EmitInt (ig, j - idx);
4801 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj);
4803 ig.Emit (OpCodes.Ldelema, t);
4808 ig.Emit (OpCodes.Stobj, t);
4812 ig.Emit (OpCodes.Ldloc, array);
4816 /// Emits a list of resolved Arguments that are in the arguments
4819 /// The MethodBase argument might be null if the
4820 /// emission of the arguments is known not to contain
4821 /// a `params' field (for example in constructors or other routines
4822 /// that keep their arguments in this structure)
4824 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
4828 pd = GetParameterData (mb);
4833 // If we are calling a params method with no arguments, special case it
4835 if (arguments == null){
4836 if (pd != null && pd.Count > 0 &&
4837 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
4838 ILGenerator ig = ec.ig;
4840 IntConstant.EmitInt (ig, 0);
4841 ig.Emit (OpCodes.Newarr, pd.ParameterType (0).GetElementType ());
4847 int top = arguments.Count;
4849 for (int i = 0; i < top; i++){
4850 Argument a = (Argument) arguments [i];
4853 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
4855 // Special case if we are passing the same data as the
4856 // params argument, do not put it in an array.
4858 if (pd.ParameterType (i) == a.Type)
4861 EmitParams (ec, i, arguments);
4869 if (pd != null && pd.Count > top &&
4870 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
4871 ILGenerator ig = ec.ig;
4873 IntConstant.EmitInt (ig, 0);
4874 ig.Emit (OpCodes.Newarr, pd.ParameterType (top).GetElementType ());
4879 /// is_base tells whether we want to force the use of the `call'
4880 /// opcode instead of using callvirt. Call is required to call
4881 /// a specific method, while callvirt will always use the most
4882 /// recent method in the vtable.
4884 /// is_static tells whether this is an invocation on a static method
4886 /// instance_expr is an expression that represents the instance
4887 /// it must be non-null if is_static is false.
4889 /// method is the method to invoke.
4891 /// Arguments is the list of arguments to pass to the method or constructor.
4893 public static void EmitCall (EmitContext ec, bool is_base,
4894 bool is_static, Expression instance_expr,
4895 MethodBase method, ArrayList Arguments, Location loc)
4897 ILGenerator ig = ec.ig;
4898 bool struct_call = false;
4900 Type decl_type = method.DeclaringType;
4902 if (!RootContext.StdLib) {
4903 // Replace any calls to the system's System.Array type with calls to
4904 // the newly created one.
4905 if (method == TypeManager.system_int_array_get_length)
4906 method = TypeManager.int_array_get_length;
4907 else if (method == TypeManager.system_int_array_get_rank)
4908 method = TypeManager.int_array_get_rank;
4909 else if (method == TypeManager.system_object_array_clone)
4910 method = TypeManager.object_array_clone;
4911 else if (method == TypeManager.system_int_array_get_length_int)
4912 method = TypeManager.int_array_get_length_int;
4913 else if (method == TypeManager.system_int_array_get_lower_bound_int)
4914 method = TypeManager.int_array_get_lower_bound_int;
4915 else if (method == TypeManager.system_int_array_get_upper_bound_int)
4916 method = TypeManager.int_array_get_upper_bound_int;
4917 else if (method == TypeManager.system_void_array_copyto_array_int)
4918 method = TypeManager.void_array_copyto_array_int;
4922 // This checks the `ConditionalAttribute' on the method, and the
4923 // ObsoleteAttribute
4925 TypeManager.MethodFlags flags = TypeManager.GetMethodFlags (method, loc);
4926 if ((flags & TypeManager.MethodFlags.IsObsoleteError) != 0)
4928 if ((flags & TypeManager.MethodFlags.ShouldIgnore) != 0)
4932 if (decl_type.IsValueType)
4935 // If this is ourselves, push "this"
4937 if (instance_expr == null){
4938 ig.Emit (OpCodes.Ldarg_0);
4941 // Push the instance expression
4943 if (instance_expr.Type.IsValueType){
4945 // Special case: calls to a function declared in a
4946 // reference-type with a value-type argument need
4947 // to have their value boxed.
4950 if (decl_type.IsValueType){
4952 // If the expression implements IMemoryLocation, then
4953 // we can optimize and use AddressOf on the
4956 // If not we have to use some temporary storage for
4958 if (instance_expr is IMemoryLocation){
4959 ((IMemoryLocation)instance_expr).
4960 AddressOf (ec, AddressOp.LoadStore);
4963 Type t = instance_expr.Type;
4965 instance_expr.Emit (ec);
4966 LocalBuilder temp = ig.DeclareLocal (t);
4967 ig.Emit (OpCodes.Stloc, temp);
4968 ig.Emit (OpCodes.Ldloca, temp);
4971 instance_expr.Emit (ec);
4972 ig.Emit (OpCodes.Box, instance_expr.Type);
4975 instance_expr.Emit (ec);
4979 EmitArguments (ec, method, Arguments);
4981 if (is_static || struct_call || is_base){
4982 if (method is MethodInfo) {
4983 ig.Emit (OpCodes.Call, (MethodInfo) method);
4985 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4987 if (method is MethodInfo)
4988 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
4990 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
4994 public override void Emit (EmitContext ec)
4996 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
4998 EmitCall (ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5001 public override void EmitStatement (EmitContext ec)
5006 // Pop the return value if there is one
5008 if (method is MethodInfo){
5009 Type ret = ((MethodInfo)method).ReturnType;
5010 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5011 ec.ig.Emit (OpCodes.Pop);
5017 // This class is used to "disable" the code generation for the
5018 // temporary variable when initializing value types.
5020 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5021 public void AddressOf (EmitContext ec, AddressOp Mode)
5028 /// Implements the new expression
5030 public class New : ExpressionStatement, IMemoryLocation {
5031 public readonly ArrayList Arguments;
5032 public readonly Expression RequestedType;
5034 MethodBase method = null;
5037 // If set, the new expression is for a value_target, and
5038 // we will not leave anything on the stack.
5040 Expression value_target;
5041 bool value_target_set = false;
5043 public New (Expression requested_type, ArrayList arguments, Location l)
5045 RequestedType = requested_type;
5046 Arguments = arguments;
5050 public bool SetValueTypeVariable (Expression value)
5052 value_target = value;
5053 value_target_set = true;
5054 if (!(value_target is IMemoryLocation)){
5055 Error_UnexpectedKind ("variable");
5062 // This function is used to disable the following code sequence for
5063 // value type initialization:
5065 // AddressOf (temporary)
5069 // Instead the provide will have provided us with the address on the
5070 // stack to store the results.
5072 static Expression MyEmptyExpression;
5074 public void DisableTemporaryValueType ()
5076 if (MyEmptyExpression == null)
5077 MyEmptyExpression = new EmptyAddressOf ();
5080 // To enable this, look into:
5081 // test-34 and test-89 and self bootstrapping.
5083 // For instance, we can avoid a copy by using `newobj'
5084 // instead of Call + Push-temp on value types.
5085 // value_target = MyEmptyExpression;
5088 public override Expression DoResolve (EmitContext ec)
5091 // The New DoResolve might be called twice when initializing field
5092 // expressions (see EmitFieldInitializers, the call to
5093 // GetInitializerExpression will perform a resolve on the expression,
5094 // and later the assign will trigger another resolution
5096 // This leads to bugs (#37014)
5101 type = ec.DeclSpace.ResolveType (RequestedType, false, loc);
5106 bool IsDelegate = TypeManager.IsDelegateType (type);
5109 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5111 if (type.IsInterface || type.IsAbstract){
5112 Error (144, "It is not possible to create instances of interfaces or abstract classes");
5116 bool is_struct = type.IsValueType;
5117 eclass = ExprClass.Value;
5120 // SRE returns a match for .ctor () on structs (the object constructor),
5121 // so we have to manually ignore it.
5123 if (is_struct && Arguments == null)
5127 ml = MemberLookupFinal (ec, null, type, ".ctor",
5128 MemberTypes.Constructor,
5129 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5134 if (! (ml is MethodGroupExpr)){
5136 ml.Error_UnexpectedKind ("method group");
5142 if (Arguments != null){
5143 foreach (Argument a in Arguments){
5144 if (!a.Resolve (ec, loc))
5149 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
5153 if (method == null) {
5154 if (!is_struct || Arguments.Count > 0) {
5155 Error (1501, String.Format (
5156 "New invocation: Can not find a constructor in `{0}' for this argument list",
5157 TypeManager.CSharpName (type)));
5166 // This DoEmit can be invoked in two contexts:
5167 // * As a mechanism that will leave a value on the stack (new object)
5168 // * As one that wont (init struct)
5170 // You can control whether a value is required on the stack by passing
5171 // need_value_on_stack. The code *might* leave a value on the stack
5172 // so it must be popped manually
5174 // If we are dealing with a ValueType, we have a few
5175 // situations to deal with:
5177 // * The target is a ValueType, and we have been provided
5178 // the instance (this is easy, we are being assigned).
5180 // * The target of New is being passed as an argument,
5181 // to a boxing operation or a function that takes a
5184 // In this case, we need to create a temporary variable
5185 // that is the argument of New.
5187 // Returns whether a value is left on the stack
5189 bool DoEmit (EmitContext ec, bool need_value_on_stack)
5191 bool is_value_type = type.IsValueType;
5192 ILGenerator ig = ec.ig;
5197 // Allow DoEmit() to be called multiple times.
5198 // We need to create a new LocalTemporary each time since
5199 // you can't share LocalBuilders among ILGeneators.
5200 if (!value_target_set)
5201 value_target = new LocalTemporary (ec, type);
5203 ml = (IMemoryLocation) value_target;
5204 ml.AddressOf (ec, AddressOp.Store);
5208 Invocation.EmitArguments (ec, method, Arguments);
5212 ig.Emit (OpCodes.Initobj, type);
5214 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5215 if (need_value_on_stack){
5216 value_target.Emit (ec);
5221 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
5226 public override void Emit (EmitContext ec)
5231 public override void EmitStatement (EmitContext ec)
5233 if (DoEmit (ec, false))
5234 ec.ig.Emit (OpCodes.Pop);
5237 public void AddressOf (EmitContext ec, AddressOp Mode)
5239 if (!type.IsValueType){
5241 // We throw an exception. So far, I believe we only need to support
5243 // foreach (int j in new StructType ())
5246 throw new Exception ("AddressOf should not be used for classes");
5249 if (!value_target_set)
5250 value_target = new LocalTemporary (ec, type);
5252 IMemoryLocation ml = (IMemoryLocation) value_target;
5253 ml.AddressOf (ec, AddressOp.Store);
5255 Invocation.EmitArguments (ec, method, Arguments);
5258 ec.ig.Emit (OpCodes.Initobj, type);
5260 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5262 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
5267 /// 14.5.10.2: Represents an array creation expression.
5271 /// There are two possible scenarios here: one is an array creation
5272 /// expression that specifies the dimensions and optionally the
5273 /// initialization data and the other which does not need dimensions
5274 /// specified but where initialization data is mandatory.
5276 public class ArrayCreation : ExpressionStatement {
5277 Expression requested_base_type;
5278 ArrayList initializers;
5281 // The list of Argument types.
5282 // This is used to construct the `newarray' or constructor signature
5284 ArrayList arguments;
5287 // Method used to create the array object.
5289 MethodBase new_method = null;
5291 Type array_element_type;
5292 Type underlying_type;
5293 bool is_one_dimensional = false;
5294 bool is_builtin_type = false;
5295 bool expect_initializers = false;
5296 int num_arguments = 0;
5300 ArrayList array_data;
5305 // The number of array initializers that we can handle
5306 // via the InitializeArray method - through EmitStaticInitializers
5308 int num_automatic_initializers;
5310 const int max_automatic_initializers = 6;
5312 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
5314 this.requested_base_type = requested_base_type;
5315 this.initializers = initializers;
5319 arguments = new ArrayList ();
5321 foreach (Expression e in exprs) {
5322 arguments.Add (new Argument (e, Argument.AType.Expression));
5327 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
5329 this.requested_base_type = requested_base_type;
5330 this.initializers = initializers;
5334 //this.rank = rank.Substring (0, rank.LastIndexOf ("["));
5336 //string tmp = rank.Substring (rank.LastIndexOf ("["));
5338 //dimensions = tmp.Length - 1;
5339 expect_initializers = true;
5342 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
5344 StringBuilder sb = new StringBuilder (rank);
5347 for (int i = 1; i < idx_count; i++)
5352 return new ComposedCast (base_type, sb.ToString (), loc);
5355 void Error_IncorrectArrayInitializer ()
5357 Error (178, "Incorrectly structured array initializer");
5360 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
5362 if (specified_dims) {
5363 Argument a = (Argument) arguments [idx];
5365 if (!a.Resolve (ec, loc))
5368 if (!(a.Expr is Constant)) {
5369 Error (150, "A constant value is expected");
5373 int value = (int) ((Constant) a.Expr).GetValue ();
5375 if (value != probe.Count) {
5376 Error_IncorrectArrayInitializer ();
5380 bounds [idx] = value;
5383 int child_bounds = -1;
5384 foreach (object o in probe) {
5385 if (o is ArrayList) {
5386 int current_bounds = ((ArrayList) o).Count;
5388 if (child_bounds == -1)
5389 child_bounds = current_bounds;
5391 else if (child_bounds != current_bounds){
5392 Error_IncorrectArrayInitializer ();
5395 if (specified_dims && (idx + 1 >= arguments.Count)){
5396 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
5400 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
5404 if (child_bounds != -1){
5405 Error_IncorrectArrayInitializer ();
5409 Expression tmp = (Expression) o;
5410 tmp = tmp.Resolve (ec);
5414 // Console.WriteLine ("I got: " + tmp);
5415 // Handle initialization from vars, fields etc.
5417 Expression conv = Convert.ImplicitConversionRequired (
5418 ec, tmp, underlying_type, loc);
5423 if (conv is StringConstant)
5424 array_data.Add (conv);
5425 else if (conv is Constant) {
5426 array_data.Add (conv);
5427 num_automatic_initializers++;
5429 array_data.Add (conv);
5436 public void UpdateIndices (EmitContext ec)
5439 for (ArrayList probe = initializers; probe != null;) {
5440 if (probe.Count > 0 && probe [0] is ArrayList) {
5441 Expression e = new IntConstant (probe.Count);
5442 arguments.Add (new Argument (e, Argument.AType.Expression));
5444 bounds [i++] = probe.Count;
5446 probe = (ArrayList) probe [0];
5449 Expression e = new IntConstant (probe.Count);
5450 arguments.Add (new Argument (e, Argument.AType.Expression));
5452 bounds [i++] = probe.Count;
5459 public bool ValidateInitializers (EmitContext ec, Type array_type)
5461 if (initializers == null) {
5462 if (expect_initializers)
5468 if (underlying_type == null)
5472 // We use this to store all the date values in the order in which we
5473 // will need to store them in the byte blob later
5475 array_data = new ArrayList ();
5476 bounds = new Hashtable ();
5480 if (arguments != null) {
5481 ret = CheckIndices (ec, initializers, 0, true);
5484 arguments = new ArrayList ();
5486 ret = CheckIndices (ec, initializers, 0, false);
5493 if (arguments.Count != dimensions) {
5494 Error_IncorrectArrayInitializer ();
5502 void Error_NegativeArrayIndex ()
5504 Error (284, "Can not create array with a negative size");
5508 // Converts `source' to an int, uint, long or ulong.
5510 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
5514 bool old_checked = ec.CheckState;
5515 ec.CheckState = true;
5517 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
5518 if (target == null){
5519 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
5520 if (target == null){
5521 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
5522 if (target == null){
5523 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
5525 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
5529 ec.CheckState = old_checked;
5532 // Only positive constants are allowed at compile time
5534 if (target is Constant){
5535 if (target is IntConstant){
5536 if (((IntConstant) target).Value < 0){
5537 Error_NegativeArrayIndex ();
5542 if (target is LongConstant){
5543 if (((LongConstant) target).Value < 0){
5544 Error_NegativeArrayIndex ();
5555 // Creates the type of the array
5557 bool LookupType (EmitContext ec)
5559 StringBuilder array_qualifier = new StringBuilder (rank);
5562 // `In the first form allocates an array instace of the type that results
5563 // from deleting each of the individual expression from the expression list'
5565 if (num_arguments > 0) {
5566 array_qualifier.Append ("[");
5567 for (int i = num_arguments-1; i > 0; i--)
5568 array_qualifier.Append (",");
5569 array_qualifier.Append ("]");
5575 Expression array_type_expr;
5576 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
5577 type = ec.DeclSpace.ResolveType (array_type_expr, false, loc);
5582 underlying_type = type;
5583 if (underlying_type.IsArray)
5584 underlying_type = TypeManager.TypeToCoreType (underlying_type.GetElementType ());
5585 dimensions = type.GetArrayRank ();
5590 public override Expression DoResolve (EmitContext ec)
5594 if (!LookupType (ec))
5598 // First step is to validate the initializers and fill
5599 // in any missing bits
5601 if (!ValidateInitializers (ec, type))
5604 if (arguments == null)
5607 arg_count = arguments.Count;
5608 foreach (Argument a in arguments){
5609 if (!a.Resolve (ec, loc))
5612 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
5613 if (real_arg == null)
5620 array_element_type = TypeManager.TypeToCoreType (type.GetElementType ());
5622 if (arg_count == 1) {
5623 is_one_dimensional = true;
5624 eclass = ExprClass.Value;
5628 is_builtin_type = TypeManager.IsBuiltinType (type);
5630 if (is_builtin_type) {
5633 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
5634 AllBindingFlags, loc);
5636 if (!(ml is MethodGroupExpr)) {
5637 ml.Error_UnexpectedKind ("method group");
5642 Error (-6, "New invocation: Can not find a constructor for " +
5643 "this argument list");
5647 new_method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, arguments, loc);
5649 if (new_method == null) {
5650 Error (-6, "New invocation: Can not find a constructor for " +
5651 "this argument list");
5655 eclass = ExprClass.Value;
5658 ModuleBuilder mb = CodeGen.ModuleBuilder;
5659 ArrayList args = new ArrayList ();
5661 if (arguments != null) {
5662 for (int i = 0; i < arg_count; i++)
5663 args.Add (TypeManager.int32_type);
5666 Type [] arg_types = null;
5669 arg_types = new Type [args.Count];
5671 args.CopyTo (arg_types, 0);
5673 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
5676 if (new_method == null) {
5677 Error (-6, "New invocation: Can not find a constructor for " +
5678 "this argument list");
5682 eclass = ExprClass.Value;
5687 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
5692 int count = array_data.Count;
5694 if (underlying_type.IsEnum)
5695 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
5697 factor = GetTypeSize (underlying_type);
5699 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
5701 data = new byte [(count * factor + 4) & ~3];
5704 for (int i = 0; i < count; ++i) {
5705 object v = array_data [i];
5707 if (v is EnumConstant)
5708 v = ((EnumConstant) v).Child;
5710 if (v is Constant && !(v is StringConstant))
5711 v = ((Constant) v).GetValue ();
5717 if (underlying_type == TypeManager.int64_type){
5718 if (!(v is Expression)){
5719 long val = (long) v;
5721 for (int j = 0; j < factor; ++j) {
5722 data [idx + j] = (byte) (val & 0xFF);
5726 } else if (underlying_type == TypeManager.uint64_type){
5727 if (!(v is Expression)){
5728 ulong val = (ulong) v;
5730 for (int j = 0; j < factor; ++j) {
5731 data [idx + j] = (byte) (val & 0xFF);
5735 } else if (underlying_type == TypeManager.float_type) {
5736 if (!(v is Expression)){
5737 element = BitConverter.GetBytes ((float) v);
5739 for (int j = 0; j < factor; ++j)
5740 data [idx + j] = element [j];
5742 } else if (underlying_type == TypeManager.double_type) {
5743 if (!(v is Expression)){
5744 element = BitConverter.GetBytes ((double) v);
5746 for (int j = 0; j < factor; ++j)
5747 data [idx + j] = element [j];
5749 } else if (underlying_type == TypeManager.char_type){
5750 if (!(v is Expression)){
5751 int val = (int) ((char) v);
5753 data [idx] = (byte) (val & 0xff);
5754 data [idx+1] = (byte) (val >> 8);
5756 } else if (underlying_type == TypeManager.short_type){
5757 if (!(v is Expression)){
5758 int val = (int) ((short) v);
5760 data [idx] = (byte) (val & 0xff);
5761 data [idx+1] = (byte) (val >> 8);
5763 } else if (underlying_type == TypeManager.ushort_type){
5764 if (!(v is Expression)){
5765 int val = (int) ((ushort) v);
5767 data [idx] = (byte) (val & 0xff);
5768 data [idx+1] = (byte) (val >> 8);
5770 } else if (underlying_type == TypeManager.int32_type) {
5771 if (!(v is Expression)){
5774 data [idx] = (byte) (val & 0xff);
5775 data [idx+1] = (byte) ((val >> 8) & 0xff);
5776 data [idx+2] = (byte) ((val >> 16) & 0xff);
5777 data [idx+3] = (byte) (val >> 24);
5779 } else if (underlying_type == TypeManager.uint32_type) {
5780 if (!(v is Expression)){
5781 uint val = (uint) v;
5783 data [idx] = (byte) (val & 0xff);
5784 data [idx+1] = (byte) ((val >> 8) & 0xff);
5785 data [idx+2] = (byte) ((val >> 16) & 0xff);
5786 data [idx+3] = (byte) (val >> 24);
5788 } else if (underlying_type == TypeManager.sbyte_type) {
5789 if (!(v is Expression)){
5790 sbyte val = (sbyte) v;
5791 data [idx] = (byte) val;
5793 } else if (underlying_type == TypeManager.byte_type) {
5794 if (!(v is Expression)){
5795 byte val = (byte) v;
5796 data [idx] = (byte) val;
5798 } else if (underlying_type == TypeManager.bool_type) {
5799 if (!(v is Expression)){
5800 bool val = (bool) v;
5801 data [idx] = (byte) (val ? 1 : 0);
5803 } else if (underlying_type == TypeManager.decimal_type){
5804 if (!(v is Expression)){
5805 int [] bits = Decimal.GetBits ((decimal) v);
5808 // FIXME: For some reason, this doesn't work on the MS runtime.
5809 int [] nbits = new int [4];
5810 nbits [0] = bits [3];
5811 nbits [1] = bits [2];
5812 nbits [2] = bits [0];
5813 nbits [3] = bits [1];
5815 for (int j = 0; j < 4; j++){
5816 data [p++] = (byte) (nbits [j] & 0xff);
5817 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
5818 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
5819 data [p++] = (byte) (nbits [j] >> 24);
5823 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
5832 // Emits the initializers for the array
5834 void EmitStaticInitializers (EmitContext ec, bool is_expression)
5837 // First, the static data
5840 ILGenerator ig = ec.ig;
5842 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
5844 fb = RootContext.MakeStaticData (data);
5847 ig.Emit (OpCodes.Dup);
5848 ig.Emit (OpCodes.Ldtoken, fb);
5849 ig.Emit (OpCodes.Call,
5850 TypeManager.void_initializearray_array_fieldhandle);
5854 // Emits pieces of the array that can not be computed at compile
5855 // time (variables and string locations).
5857 // This always expect the top value on the stack to be the array
5859 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
5861 ILGenerator ig = ec.ig;
5862 int dims = bounds.Count;
5863 int [] current_pos = new int [dims];
5864 int top = array_data.Count;
5865 LocalBuilder temp = ig.DeclareLocal (type);
5867 ig.Emit (OpCodes.Stloc, temp);
5869 MethodInfo set = null;
5873 ModuleBuilder mb = null;
5874 mb = CodeGen.ModuleBuilder;
5875 args = new Type [dims + 1];
5878 for (j = 0; j < dims; j++)
5879 args [j] = TypeManager.int32_type;
5881 args [j] = array_element_type;
5883 set = mb.GetArrayMethod (
5885 CallingConventions.HasThis | CallingConventions.Standard,
5886 TypeManager.void_type, args);
5889 for (int i = 0; i < top; i++){
5891 Expression e = null;
5893 if (array_data [i] is Expression)
5894 e = (Expression) array_data [i];
5898 // Basically we do this for string literals and
5899 // other non-literal expressions
5901 if (e is EnumConstant){
5902 e = ((EnumConstant) e).Child;
5905 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
5906 num_automatic_initializers <= max_automatic_initializers) {
5907 Type etype = e.Type;
5909 ig.Emit (OpCodes.Ldloc, temp);
5911 for (int idx = 0; idx < dims; idx++)
5912 IntConstant.EmitInt (ig, current_pos [idx]);
5915 // If we are dealing with a struct, get the
5916 // address of it, so we can store it.
5919 etype.IsSubclassOf (TypeManager.value_type) &&
5920 (!TypeManager.IsBuiltinType (etype) ||
5921 etype == TypeManager.decimal_type)) {
5926 // Let new know that we are providing
5927 // the address where to store the results
5929 n.DisableTemporaryValueType ();
5932 ig.Emit (OpCodes.Ldelema, etype);
5938 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
5940 ig.Emit (OpCodes.Call, set);
5948 for (int j = dims - 1; j >= 0; j--){
5950 if (current_pos [j] < (int) bounds [j])
5952 current_pos [j] = 0;
5957 ig.Emit (OpCodes.Ldloc, temp);
5960 void EmitArrayArguments (EmitContext ec)
5962 ILGenerator ig = ec.ig;
5964 foreach (Argument a in arguments) {
5965 Type atype = a.Type;
5968 if (atype == TypeManager.uint64_type)
5969 ig.Emit (OpCodes.Conv_Ovf_U4);
5970 else if (atype == TypeManager.int64_type)
5971 ig.Emit (OpCodes.Conv_Ovf_I4);
5975 void DoEmit (EmitContext ec, bool is_statement)
5977 ILGenerator ig = ec.ig;
5979 EmitArrayArguments (ec);
5980 if (is_one_dimensional)
5981 ig.Emit (OpCodes.Newarr, array_element_type);
5983 if (is_builtin_type)
5984 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
5986 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
5989 if (initializers != null){
5991 // FIXME: Set this variable correctly.
5993 bool dynamic_initializers = true;
5995 if (underlying_type != TypeManager.string_type &&
5996 underlying_type != TypeManager.decimal_type &&
5997 underlying_type != TypeManager.object_type) {
5998 if (num_automatic_initializers > max_automatic_initializers)
5999 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
6002 if (dynamic_initializers)
6003 EmitDynamicInitializers (ec, !is_statement);
6007 public override void Emit (EmitContext ec)
6012 public override void EmitStatement (EmitContext ec)
6017 public object EncodeAsAttribute ()
6019 if (!is_one_dimensional){
6020 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6024 if (array_data == null){
6025 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6029 object [] ret = new object [array_data.Count];
6031 foreach (Expression e in array_data){
6034 if (e is NullLiteral)
6037 if (!Attribute.GetAttributeArgumentExpression (e, Location, out v))
6047 /// Represents the `this' construct
6049 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6052 VariableInfo variable_info;
6054 public This (Block block, Location loc)
6060 public This (Location loc)
6065 public VariableInfo VariableInfo {
6066 get { return variable_info; }
6069 public bool VerifyFixed (bool is_expression)
6071 return variable_info.LocalInfo.IsFixed;
6074 public bool ResolveBase (EmitContext ec)
6076 eclass = ExprClass.Variable;
6077 type = ec.ContainerType;
6080 Error (26, "Keyword this not valid in static code");
6084 if ((block != null) && (block.ThisVariable != null))
6085 variable_info = block.GetVariableInfo (block.ThisVariable);
6090 public override Expression DoResolve (EmitContext ec)
6092 if (!ResolveBase (ec))
6095 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
6096 Error (188, "The this object cannot be used before all " +
6097 "of its fields are assigned to");
6098 variable_info.SetAssigned (ec);
6102 if (ec.IsFieldInitializer) {
6103 Error (27, "Keyword `this' can't be used outside a constructor, " +
6104 "a method or a property.");
6111 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6113 if (!ResolveBase (ec))
6116 if (variable_info != null)
6117 variable_info.SetAssigned (ec);
6119 if (ec.TypeContainer is Class){
6120 Error (1604, "Cannot assign to `this'");
6127 public override void Emit (EmitContext ec)
6129 ILGenerator ig = ec.ig;
6131 ig.Emit (OpCodes.Ldarg_0);
6132 if (ec.TypeContainer is Struct)
6133 ig.Emit (OpCodes.Ldobj, type);
6136 public void EmitAssign (EmitContext ec, Expression source)
6138 ILGenerator ig = ec.ig;
6140 if (ec.TypeContainer is Struct){
6141 ig.Emit (OpCodes.Ldarg_0);
6143 ig.Emit (OpCodes.Stobj, type);
6146 ig.Emit (OpCodes.Starg, 0);
6150 public void AddressOf (EmitContext ec, AddressOp mode)
6152 ec.ig.Emit (OpCodes.Ldarg_0);
6155 // FIGURE OUT WHY LDARG_S does not work
6157 // consider: struct X { int val; int P { set { val = value; }}}
6159 // Yes, this looks very bad. Look at `NOTAS' for
6161 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
6166 /// Implements the typeof operator
6168 public class TypeOf : Expression {
6169 public readonly Expression QueriedType;
6172 public TypeOf (Expression queried_type, Location l)
6174 QueriedType = queried_type;
6178 public override Expression DoResolve (EmitContext ec)
6180 typearg = ec.DeclSpace.ResolveType (QueriedType, false, loc);
6182 if (typearg == null)
6185 if (typearg == TypeManager.void_type) {
6186 Error (673, "System.Void cannot be used from C# - " +
6187 "use typeof (void) to get the void type object");
6191 type = TypeManager.type_type;
6192 eclass = ExprClass.Type;
6196 public override void Emit (EmitContext ec)
6198 ec.ig.Emit (OpCodes.Ldtoken, typearg);
6199 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6202 public Type TypeArg {
6203 get { return typearg; }
6208 /// Implements the `typeof (void)' operator
6210 public class TypeOfVoid : Expression {
6211 public TypeOfVoid (Location l)
6216 public override Expression DoResolve (EmitContext ec)
6218 type = TypeManager.type_type;
6219 eclass = ExprClass.Type;
6223 public override void Emit (EmitContext ec)
6225 ec.ig.Emit (OpCodes.Ldtoken, TypeManager.void_type);
6226 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6229 public Type TypeArg {
6230 get { return TypeManager.void_type; }
6235 /// Implements the sizeof expression
6237 public class SizeOf : Expression {
6238 public readonly Expression QueriedType;
6241 public SizeOf (Expression queried_type, Location l)
6243 this.QueriedType = queried_type;
6247 public override Expression DoResolve (EmitContext ec)
6251 233, loc, "Sizeof may only be used in an unsafe context " +
6252 "(consider using System.Runtime.InteropServices.Marshal.Sizeof");
6256 type_queried = ec.DeclSpace.ResolveType (QueriedType, false, loc);
6257 if (type_queried == null)
6260 if (!TypeManager.IsUnmanagedType (type_queried)){
6261 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
6265 type = TypeManager.int32_type;
6266 eclass = ExprClass.Value;
6270 public override void Emit (EmitContext ec)
6272 int size = GetTypeSize (type_queried);
6275 ec.ig.Emit (OpCodes.Sizeof, type_queried);
6277 IntConstant.EmitInt (ec.ig, size);
6282 /// Implements the member access expression
6284 public class MemberAccess : Expression {
6285 public readonly string Identifier;
6288 public MemberAccess (Expression expr, string id, Location l)
6295 public Expression Expr {
6301 static void error176 (Location loc, string name)
6303 Report.Error (176, loc, "Static member `" +
6304 name + "' cannot be accessed " +
6305 "with an instance reference, qualify with a " +
6306 "type name instead");
6309 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
6311 if (left_original == null)
6314 if (!(left_original is SimpleName))
6317 SimpleName sn = (SimpleName) left_original;
6319 Type t = RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc);
6326 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
6327 Expression left, Location loc,
6328 Expression left_original)
6330 bool left_is_type, left_is_explicit;
6332 // If `left' is null, then we're called from SimpleNameResolve and this is
6333 // a member in the currently defining class.
6335 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
6336 left_is_explicit = false;
6338 // Implicitly default to `this' unless we're static.
6339 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
6340 left = ec.GetThis (loc);
6342 left_is_type = left is TypeExpr;
6343 left_is_explicit = true;
6346 if (member_lookup is FieldExpr){
6347 FieldExpr fe = (FieldExpr) member_lookup;
6348 FieldInfo fi = fe.FieldInfo;
6349 Type decl_type = fi.DeclaringType;
6351 if (fi is FieldBuilder) {
6352 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
6355 object o = c.LookupConstantValue ();
6359 object real_value = ((Constant) c.Expr).GetValue ();
6361 return Constantify (real_value, fi.FieldType);
6366 Type t = fi.FieldType;
6370 if (fi is FieldBuilder)
6371 o = TypeManager.GetValue ((FieldBuilder) fi);
6373 o = fi.GetValue (fi);
6375 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
6376 if (left_is_explicit && !left_is_type &&
6377 !IdenticalNameAndTypeName (ec, left_original, loc)) {
6378 error176 (loc, fe.FieldInfo.Name);
6382 Expression enum_member = MemberLookup (
6383 ec, decl_type, "value__", MemberTypes.Field,
6384 AllBindingFlags, loc);
6386 Enum en = TypeManager.LookupEnum (decl_type);
6390 c = Constantify (o, en.UnderlyingType);
6392 c = Constantify (o, enum_member.Type);
6394 return new EnumConstant (c, decl_type);
6397 Expression exp = Constantify (o, t);
6399 if (left_is_explicit && !left_is_type) {
6400 error176 (loc, fe.FieldInfo.Name);
6407 if (fi.FieldType.IsPointer && !ec.InUnsafe){
6413 if (member_lookup is EventExpr) {
6414 EventExpr ee = (EventExpr) member_lookup;
6417 // If the event is local to this class, we transform ourselves into
6421 if (ee.EventInfo.DeclaringType == ec.ContainerType) {
6422 MemberInfo mi = GetFieldFromEvent (ee);
6426 // If this happens, then we have an event with its own
6427 // accessors and private field etc so there's no need
6428 // to transform ourselves.
6433 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
6436 Report.Error (-200, loc, "Internal error!!");
6440 if (!left_is_explicit)
6443 return ResolveMemberAccess (ec, ml, left, loc, left_original);
6447 if (member_lookup is IMemberExpr) {
6448 IMemberExpr me = (IMemberExpr) member_lookup;
6451 MethodGroupExpr mg = me as MethodGroupExpr;
6452 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
6453 mg.IsExplicitImpl = left_is_explicit;
6456 if ((ec.IsFieldInitializer || ec.IsStatic) &&
6457 IdenticalNameAndTypeName (ec, left_original, loc))
6458 return member_lookup;
6460 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
6465 if (!me.IsInstance){
6466 if (IdenticalNameAndTypeName (ec, left_original, loc))
6467 return member_lookup;
6469 if (left_is_explicit) {
6470 error176 (loc, me.Name);
6476 // Since we can not check for instance objects in SimpleName,
6477 // becaue of the rule that allows types and variables to share
6478 // the name (as long as they can be de-ambiguated later, see
6479 // IdenticalNameAndTypeName), we have to check whether left
6480 // is an instance variable in a static context
6482 // However, if the left-hand value is explicitly given, then
6483 // it is already our instance expression, so we aren't in
6487 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
6488 IMemberExpr mexp = (IMemberExpr) left;
6490 if (!mexp.IsStatic){
6491 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
6496 me.InstanceExpression = left;
6499 return member_lookup;
6502 Console.WriteLine ("Left is: " + left);
6503 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
6504 Environment.Exit (0);
6508 public Expression DoResolve (EmitContext ec, Expression right_side, ResolveFlags flags)
6511 throw new Exception ();
6514 // Resolve the expression with flow analysis turned off, we'll do the definite
6515 // assignment checks later. This is because we don't know yet what the expression
6516 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
6517 // definite assignment check on the actual field and not on the whole struct.
6520 Expression original = expr;
6521 expr = expr.Resolve (ec, flags | ResolveFlags.DisableFlowAnalysis);
6525 if (expr is SimpleName){
6526 SimpleName child_expr = (SimpleName) expr;
6528 Expression new_expr = new SimpleName (child_expr.Name, Identifier, loc);
6530 return new_expr.Resolve (ec, flags);
6534 // TODO: I mailed Ravi about this, and apparently we can get rid
6535 // of this and put it in the right place.
6537 // Handle enums here when they are in transit.
6538 // Note that we cannot afford to hit MemberLookup in this case because
6539 // it will fail to find any members at all
6542 int errors = Report.Errors;
6544 Type expr_type = expr.Type;
6545 if (expr is TypeExpr){
6546 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
6547 Error (122, "`" + expr_type + "' " +
6548 "is inaccessible because of its protection level");
6552 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
6553 Enum en = TypeManager.LookupEnum (expr_type);
6556 object value = en.LookupEnumValue (ec, Identifier, loc);
6559 Constant c = Constantify (value, en.UnderlyingType);
6560 return new EnumConstant (c, expr_type);
6566 if (expr_type.IsPointer){
6567 Error (23, "The `.' operator can not be applied to pointer operands (" +
6568 TypeManager.CSharpName (expr_type) + ")");
6572 Expression member_lookup;
6573 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
6574 if (member_lookup == null)
6577 if (member_lookup is TypeExpr) {
6578 if (!(expr is TypeExpr) && !(expr is SimpleName)) {
6579 Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
6580 member_lookup.Type + "' instead");
6584 return member_lookup;
6587 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
6588 if (member_lookup == null)
6591 // The following DoResolve/DoResolveLValue will do the definite assignment
6594 if (right_side != null)
6595 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
6597 member_lookup = member_lookup.DoResolve (ec);
6599 return member_lookup;
6602 public override Expression DoResolve (EmitContext ec)
6604 return DoResolve (ec, null, ResolveFlags.VariableOrValue |
6605 ResolveFlags.SimpleName | ResolveFlags.Type);
6608 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
6610 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
6611 ResolveFlags.SimpleName | ResolveFlags.Type);
6614 public override Expression ResolveAsTypeStep (EmitContext ec)
6616 string fname = null;
6617 MemberAccess full_expr = this;
6618 while (full_expr != null) {
6620 fname = String.Concat (full_expr.Identifier, ".", fname);
6622 fname = full_expr.Identifier;
6624 if (full_expr.Expr is SimpleName) {
6625 string full_name = String.Concat (((SimpleName) full_expr.Expr).Name, ".", fname);
6626 Type fully_qualified = ec.DeclSpace.FindType (loc, full_name);
6627 if (fully_qualified != null)
6628 return new TypeExpr (fully_qualified, loc);
6631 full_expr = full_expr.Expr as MemberAccess;
6634 Expression new_expr = expr.ResolveAsTypeStep (ec);
6636 if (new_expr == null)
6639 if (new_expr is SimpleName){
6640 SimpleName child_expr = (SimpleName) new_expr;
6642 new_expr = new SimpleName (child_expr.Name, Identifier, loc);
6644 return new_expr.ResolveAsTypeStep (ec);
6647 Type expr_type = new_expr.Type;
6649 if (expr_type.IsPointer){
6650 Error (23, "The `.' operator can not be applied to pointer operands (" +
6651 TypeManager.CSharpName (expr_type) + ")");
6655 Expression member_lookup;
6656 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
6657 if (member_lookup == null)
6660 if (member_lookup is TypeExpr){
6661 member_lookup.Resolve (ec, ResolveFlags.Type);
6662 return member_lookup;
6668 public override void Emit (EmitContext ec)
6670 throw new Exception ("Should not happen");
6673 public override string ToString ()
6675 return expr + "." + Identifier;
6680 /// Implements checked expressions
6682 public class CheckedExpr : Expression {
6684 public Expression Expr;
6686 public CheckedExpr (Expression e, Location l)
6692 public override Expression DoResolve (EmitContext ec)
6694 bool last_check = ec.CheckState;
6695 bool last_const_check = ec.ConstantCheckState;
6697 ec.CheckState = true;
6698 ec.ConstantCheckState = true;
6699 Expr = Expr.Resolve (ec);
6700 ec.CheckState = last_check;
6701 ec.ConstantCheckState = last_const_check;
6706 if (Expr is Constant)
6709 eclass = Expr.eclass;
6714 public override void Emit (EmitContext ec)
6716 bool last_check = ec.CheckState;
6717 bool last_const_check = ec.ConstantCheckState;
6719 ec.CheckState = true;
6720 ec.ConstantCheckState = true;
6722 ec.CheckState = last_check;
6723 ec.ConstantCheckState = last_const_check;
6729 /// Implements the unchecked expression
6731 public class UnCheckedExpr : Expression {
6733 public Expression Expr;
6735 public UnCheckedExpr (Expression e, Location l)
6741 public override Expression DoResolve (EmitContext ec)
6743 bool last_check = ec.CheckState;
6744 bool last_const_check = ec.ConstantCheckState;
6746 ec.CheckState = false;
6747 ec.ConstantCheckState = false;
6748 Expr = Expr.Resolve (ec);
6749 ec.CheckState = last_check;
6750 ec.ConstantCheckState = last_const_check;
6755 if (Expr is Constant)
6758 eclass = Expr.eclass;
6763 public override void Emit (EmitContext ec)
6765 bool last_check = ec.CheckState;
6766 bool last_const_check = ec.ConstantCheckState;
6768 ec.CheckState = false;
6769 ec.ConstantCheckState = false;
6771 ec.CheckState = last_check;
6772 ec.ConstantCheckState = last_const_check;
6778 /// An Element Access expression.
6780 /// During semantic analysis these are transformed into
6781 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
6783 public class ElementAccess : Expression {
6784 public ArrayList Arguments;
6785 public Expression Expr;
6787 public ElementAccess (Expression e, ArrayList e_list, Location l)
6796 Arguments = new ArrayList ();
6797 foreach (Expression tmp in e_list)
6798 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
6802 bool CommonResolve (EmitContext ec)
6804 Expr = Expr.Resolve (ec);
6809 if (Arguments == null)
6812 foreach (Argument a in Arguments){
6813 if (!a.Resolve (ec, loc))
6820 Expression MakePointerAccess ()
6824 if (t == TypeManager.void_ptr_type){
6825 Error (242, "The array index operation is not valid for void pointers");
6828 if (Arguments.Count != 1){
6829 Error (196, "A pointer must be indexed by a single value");
6834 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc);
6835 return new Indirection (p, loc);
6838 public override Expression DoResolve (EmitContext ec)
6840 if (!CommonResolve (ec))
6844 // We perform some simple tests, and then to "split" the emit and store
6845 // code we create an instance of a different class, and return that.
6847 // I am experimenting with this pattern.
6851 if (t == TypeManager.array_type){
6852 Report.Error (21, loc, "Cannot use indexer on System.Array");
6857 return (new ArrayAccess (this, loc)).Resolve (ec);
6858 else if (t.IsPointer)
6859 return MakePointerAccess ();
6861 return (new IndexerAccess (this, loc)).Resolve (ec);
6864 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
6866 if (!CommonResolve (ec))
6871 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
6872 else if (t.IsPointer)
6873 return MakePointerAccess ();
6875 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
6878 public override void Emit (EmitContext ec)
6880 throw new Exception ("Should never be reached");
6885 /// Implements array access
6887 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
6889 // Points to our "data" repository
6893 LocalTemporary [] cached_locations;
6895 public ArrayAccess (ElementAccess ea_data, Location l)
6898 eclass = ExprClass.Variable;
6902 public override Expression DoResolve (EmitContext ec)
6904 ExprClass eclass = ea.Expr.eclass;
6907 // As long as the type is valid
6908 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
6909 eclass == ExprClass.Value)) {
6910 ea.Expr.Error_UnexpectedKind ("variable or value");
6915 Type t = ea.Expr.Type;
6916 if (t.GetArrayRank () != ea.Arguments.Count){
6918 "Incorrect number of indexes for array " +
6919 " expected: " + t.GetArrayRank () + " got: " +
6920 ea.Arguments.Count);
6923 type = TypeManager.TypeToCoreType (t.GetElementType ());
6924 if (type.IsPointer && !ec.InUnsafe){
6925 UnsafeError (ea.Location);
6929 foreach (Argument a in ea.Arguments){
6930 Type argtype = a.Type;
6932 if (argtype == TypeManager.int32_type ||
6933 argtype == TypeManager.uint32_type ||
6934 argtype == TypeManager.int64_type ||
6935 argtype == TypeManager.uint64_type)
6939 // Mhm. This is strage, because the Argument.Type is not the same as
6940 // Argument.Expr.Type: the value changes depending on the ref/out setting.
6942 // Wonder if I will run into trouble for this.
6944 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
6949 eclass = ExprClass.Variable;
6955 /// Emits the right opcode to load an object of Type `t'
6956 /// from an array of T
6958 static public void EmitLoadOpcode (ILGenerator ig, Type type)
6960 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
6961 ig.Emit (OpCodes.Ldelem_U1);
6962 else if (type == TypeManager.sbyte_type)
6963 ig.Emit (OpCodes.Ldelem_I1);
6964 else if (type == TypeManager.short_type)
6965 ig.Emit (OpCodes.Ldelem_I2);
6966 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
6967 ig.Emit (OpCodes.Ldelem_U2);
6968 else if (type == TypeManager.int32_type)
6969 ig.Emit (OpCodes.Ldelem_I4);
6970 else if (type == TypeManager.uint32_type)
6971 ig.Emit (OpCodes.Ldelem_U4);
6972 else if (type == TypeManager.uint64_type)
6973 ig.Emit (OpCodes.Ldelem_I8);
6974 else if (type == TypeManager.int64_type)
6975 ig.Emit (OpCodes.Ldelem_I8);
6976 else if (type == TypeManager.float_type)
6977 ig.Emit (OpCodes.Ldelem_R4);
6978 else if (type == TypeManager.double_type)
6979 ig.Emit (OpCodes.Ldelem_R8);
6980 else if (type == TypeManager.intptr_type)
6981 ig.Emit (OpCodes.Ldelem_I);
6982 else if (type.IsValueType){
6983 ig.Emit (OpCodes.Ldelema, type);
6984 ig.Emit (OpCodes.Ldobj, type);
6986 ig.Emit (OpCodes.Ldelem_Ref);
6990 /// Emits the right opcode to store an object of Type `t'
6991 /// from an array of T.
6993 static public void EmitStoreOpcode (ILGenerator ig, Type t)
6996 OpCode op = GetStoreOpcode (t, out is_stobj);
6998 ig.Emit (OpCodes.Stobj, t);
7004 /// Returns the right opcode to store an object of Type `t'
7005 /// from an array of T.
7007 static public OpCode GetStoreOpcode (Type t, out bool is_stobj)
7009 //Console.WriteLine (new System.Diagnostics.StackTrace ());
7011 t = TypeManager.TypeToCoreType (t);
7012 if (TypeManager.IsEnumType (t) && t != TypeManager.enum_type)
7013 t = TypeManager.EnumToUnderlying (t);
7014 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
7015 t == TypeManager.bool_type)
7016 return OpCodes.Stelem_I1;
7017 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
7018 t == TypeManager.char_type)
7019 return OpCodes.Stelem_I2;
7020 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
7021 return OpCodes.Stelem_I4;
7022 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
7023 return OpCodes.Stelem_I8;
7024 else if (t == TypeManager.float_type)
7025 return OpCodes.Stelem_R4;
7026 else if (t == TypeManager.double_type)
7027 return OpCodes.Stelem_R8;
7028 else if (t == TypeManager.intptr_type) {
7030 return OpCodes.Stobj;
7031 } else if (t.IsValueType) {
7033 return OpCodes.Stobj;
7035 return OpCodes.Stelem_Ref;
7038 MethodInfo FetchGetMethod ()
7040 ModuleBuilder mb = CodeGen.ModuleBuilder;
7041 int arg_count = ea.Arguments.Count;
7042 Type [] args = new Type [arg_count];
7045 for (int i = 0; i < arg_count; i++){
7046 //args [i++] = a.Type;
7047 args [i] = TypeManager.int32_type;
7050 get = mb.GetArrayMethod (
7051 ea.Expr.Type, "Get",
7052 CallingConventions.HasThis |
7053 CallingConventions.Standard,
7059 MethodInfo FetchAddressMethod ()
7061 ModuleBuilder mb = CodeGen.ModuleBuilder;
7062 int arg_count = ea.Arguments.Count;
7063 Type [] args = new Type [arg_count];
7067 ret_type = TypeManager.GetReferenceType (type);
7069 for (int i = 0; i < arg_count; i++){
7070 //args [i++] = a.Type;
7071 args [i] = TypeManager.int32_type;
7074 address = mb.GetArrayMethod (
7075 ea.Expr.Type, "Address",
7076 CallingConventions.HasThis |
7077 CallingConventions.Standard,
7084 // Load the array arguments into the stack.
7086 // If we have been requested to cache the values (cached_locations array
7087 // initialized), then load the arguments the first time and store them
7088 // in locals. otherwise load from local variables.
7090 void LoadArrayAndArguments (EmitContext ec)
7092 ILGenerator ig = ec.ig;
7094 if (cached_locations == null){
7096 foreach (Argument a in ea.Arguments){
7097 Type argtype = a.Expr.Type;
7101 if (argtype == TypeManager.int64_type)
7102 ig.Emit (OpCodes.Conv_Ovf_I);
7103 else if (argtype == TypeManager.uint64_type)
7104 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7109 if (cached_locations [0] == null){
7110 cached_locations [0] = new LocalTemporary (ec, ea.Expr.Type);
7112 ig.Emit (OpCodes.Dup);
7113 cached_locations [0].Store (ec);
7117 foreach (Argument a in ea.Arguments){
7118 Type argtype = a.Expr.Type;
7120 cached_locations [j] = new LocalTemporary (ec, TypeManager.intptr_type /* a.Expr.Type */);
7122 if (argtype == TypeManager.int64_type)
7123 ig.Emit (OpCodes.Conv_Ovf_I);
7124 else if (argtype == TypeManager.uint64_type)
7125 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7127 ig.Emit (OpCodes.Dup);
7128 cached_locations [j].Store (ec);
7134 foreach (LocalTemporary lt in cached_locations)
7138 public new void CacheTemporaries (EmitContext ec)
7140 cached_locations = new LocalTemporary [ea.Arguments.Count + 1];
7143 public override void Emit (EmitContext ec)
7145 int rank = ea.Expr.Type.GetArrayRank ();
7146 ILGenerator ig = ec.ig;
7148 LoadArrayAndArguments (ec);
7151 EmitLoadOpcode (ig, type);
7155 method = FetchGetMethod ();
7156 ig.Emit (OpCodes.Call, method);
7160 public void EmitAssign (EmitContext ec, Expression source)
7162 int rank = ea.Expr.Type.GetArrayRank ();
7163 ILGenerator ig = ec.ig;
7164 Type t = source.Type;
7166 LoadArrayAndArguments (ec);
7169 // The stobj opcode used by value types will need
7170 // an address on the stack, not really an array/array
7174 if (t == TypeManager.enum_type || t == TypeManager.decimal_type ||
7175 (t.IsSubclassOf (TypeManager.value_type) && !TypeManager.IsEnumType (t) && !TypeManager.IsBuiltinType (t)))
7176 ig.Emit (OpCodes.Ldelema, t);
7182 EmitStoreOpcode (ig, t);
7184 ModuleBuilder mb = CodeGen.ModuleBuilder;
7185 int arg_count = ea.Arguments.Count;
7186 Type [] args = new Type [arg_count + 1];
7189 for (int i = 0; i < arg_count; i++){
7190 //args [i++] = a.Type;
7191 args [i] = TypeManager.int32_type;
7194 args [arg_count] = type;
7196 set = mb.GetArrayMethod (
7197 ea.Expr.Type, "Set",
7198 CallingConventions.HasThis |
7199 CallingConventions.Standard,
7200 TypeManager.void_type, args);
7202 ig.Emit (OpCodes.Call, set);
7206 public void AddressOf (EmitContext ec, AddressOp mode)
7208 int rank = ea.Expr.Type.GetArrayRank ();
7209 ILGenerator ig = ec.ig;
7211 LoadArrayAndArguments (ec);
7214 ig.Emit (OpCodes.Ldelema, type);
7216 MethodInfo address = FetchAddressMethod ();
7217 ig.Emit (OpCodes.Call, address);
7224 public ArrayList properties;
7225 static Hashtable map;
7229 map = new Hashtable ();
7234 properties = new ArrayList ();
7237 void Append (MemberInfo [] mi)
7239 foreach (PropertyInfo property in mi){
7240 MethodInfo get, set;
7242 get = property.GetGetMethod (true);
7243 set = property.GetSetMethod (true);
7244 properties.Add (new Pair (get, set));
7248 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
7250 string p_name = TypeManager.IndexerPropertyName (lookup_type);
7252 MemberInfo [] mi = TypeManager.MemberLookup (
7253 caller_type, caller_type, lookup_type, MemberTypes.Property,
7254 BindingFlags.Public | BindingFlags.Instance |
7255 BindingFlags.DeclaredOnly, p_name);
7257 if (mi == null || mi.Length == 0)
7263 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
7265 Indexers ix = (Indexers) map [lookup_type];
7270 Type copy = lookup_type;
7271 while (copy != TypeManager.object_type && copy != null){
7272 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
7276 ix = new Indexers ();
7281 copy = copy.BaseType;
7289 /// Expressions that represent an indexer call.
7291 public class IndexerAccess : Expression, IAssignMethod {
7293 // Points to our "data" repository
7295 MethodInfo get, set;
7296 ArrayList set_arguments;
7297 bool is_base_indexer;
7299 protected Type indexer_type;
7300 protected Type current_type;
7301 protected Expression instance_expr;
7302 protected ArrayList arguments;
7304 public IndexerAccess (ElementAccess ea, Location loc)
7305 : this (ea.Expr, false, loc)
7307 this.arguments = ea.Arguments;
7310 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
7313 this.instance_expr = instance_expr;
7314 this.is_base_indexer = is_base_indexer;
7315 this.eclass = ExprClass.Value;
7319 protected virtual bool CommonResolve (EmitContext ec)
7321 indexer_type = instance_expr.Type;
7322 current_type = ec.ContainerType;
7327 public override Expression DoResolve (EmitContext ec)
7329 ArrayList AllGetters = new ArrayList();
7330 if (!CommonResolve (ec))
7334 // Step 1: Query for all `Item' *properties*. Notice
7335 // that the actual methods are pointed from here.
7337 // This is a group of properties, piles of them.
7339 bool found_any = false, found_any_getters = false;
7340 Type lookup_type = indexer_type;
7343 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
7344 if (ilist != null) {
7346 if (ilist.properties != null) {
7347 foreach (Pair o in ilist.properties) {
7348 if (o.First != null)
7349 AllGetters.Add(o.First);
7354 if (AllGetters.Count > 0) {
7355 found_any_getters = true;
7356 get = (MethodInfo) Invocation.OverloadResolve (
7357 ec, new MethodGroupExpr (AllGetters, loc), arguments, loc);
7361 Report.Error (21, loc,
7362 "Type `" + TypeManager.CSharpName (indexer_type) +
7363 "' does not have any indexers defined");
7367 if (!found_any_getters) {
7368 Error (154, "indexer can not be used in this context, because " +
7369 "it lacks a `get' accessor");
7374 Error (1501, "No Overload for method `this' takes `" +
7375 arguments.Count + "' arguments");
7380 // Only base will allow this invocation to happen.
7382 if (get.IsAbstract && this is BaseIndexerAccess){
7383 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
7387 type = get.ReturnType;
7388 if (type.IsPointer && !ec.InUnsafe){
7393 eclass = ExprClass.IndexerAccess;
7397 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7399 ArrayList AllSetters = new ArrayList();
7400 if (!CommonResolve (ec))
7403 Type right_type = right_side.Type;
7405 bool found_any = false, found_any_setters = false;
7407 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
7408 if (ilist != null) {
7410 if (ilist.properties != null) {
7411 foreach (Pair o in ilist.properties) {
7412 if (o.Second != null)
7413 AllSetters.Add(o.Second);
7417 if (AllSetters.Count > 0) {
7418 found_any_setters = true;
7419 set_arguments = (ArrayList) arguments.Clone ();
7420 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
7421 set = (MethodInfo) Invocation.OverloadResolve (
7422 ec, new MethodGroupExpr (AllSetters, loc),
7423 set_arguments, loc);
7427 Report.Error (21, loc,
7428 "Type `" + TypeManager.CSharpName (indexer_type) +
7429 "' does not have any indexers defined");
7433 if (!found_any_setters) {
7434 Error (154, "indexer can not be used in this context, because " +
7435 "it lacks a `set' accessor");
7440 Error (1501, "No Overload for method `this' takes `" +
7441 arguments.Count + "' arguments");
7446 // Only base will allow this invocation to happen.
7448 if (set.IsAbstract && this is BaseIndexerAccess){
7449 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
7454 // Now look for the actual match in the list of indexers to set our "return" type
7456 type = TypeManager.void_type; // default value
7457 foreach (Pair t in ilist.properties){
7458 if (t.Second == set){
7459 if (t.First != null)
7460 type = ((MethodInfo) t.First).ReturnType;
7465 eclass = ExprClass.IndexerAccess;
7469 public override void Emit (EmitContext ec)
7471 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc);
7475 // source is ignored, because we already have a copy of it from the
7476 // LValue resolution and we have already constructed a pre-cached
7477 // version of the arguments (ea.set_arguments);
7479 public void EmitAssign (EmitContext ec, Expression source)
7481 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc);
7486 /// The base operator for method names
7488 public class BaseAccess : Expression {
7491 public BaseAccess (string member, Location l)
7493 this.member = member;
7497 public override Expression DoResolve (EmitContext ec)
7499 Expression c = CommonResolve (ec);
7505 // MethodGroups use this opportunity to flag an error on lacking ()
7507 if (!(c is MethodGroupExpr))
7508 return c.Resolve (ec);
7512 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7514 Expression c = CommonResolve (ec);
7520 // MethodGroups use this opportunity to flag an error on lacking ()
7522 if (! (c is MethodGroupExpr))
7523 return c.DoResolveLValue (ec, right_side);
7528 Expression CommonResolve (EmitContext ec)
7530 Expression member_lookup;
7531 Type current_type = ec.ContainerType;
7532 Type base_type = current_type.BaseType;
7536 Error (1511, "Keyword base is not allowed in static method");
7540 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type, member,
7541 AllMemberTypes, AllBindingFlags, loc);
7542 if (member_lookup == null) {
7543 MemberLookupFailed (ec, base_type, base_type, member, null, loc);
7550 left = new TypeExpr (base_type, loc);
7552 left = ec.GetThis (loc);
7554 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
7556 if (e is PropertyExpr){
7557 PropertyExpr pe = (PropertyExpr) e;
7565 public override void Emit (EmitContext ec)
7567 throw new Exception ("Should never be called");
7572 /// The base indexer operator
7574 public class BaseIndexerAccess : IndexerAccess {
7575 public BaseIndexerAccess (ArrayList args, Location loc)
7576 : base (null, true, loc)
7578 arguments = new ArrayList ();
7579 foreach (Expression tmp in args)
7580 arguments.Add (new Argument (tmp, Argument.AType.Expression));
7583 protected override bool CommonResolve (EmitContext ec)
7585 instance_expr = ec.GetThis (loc);
7587 current_type = ec.ContainerType.BaseType;
7588 indexer_type = current_type;
7590 foreach (Argument a in arguments){
7591 if (!a.Resolve (ec, loc))
7600 /// This class exists solely to pass the Type around and to be a dummy
7601 /// that can be passed to the conversion functions (this is used by
7602 /// foreach implementation to typecast the object return value from
7603 /// get_Current into the proper type. All code has been generated and
7604 /// we only care about the side effect conversions to be performed
7606 /// This is also now used as a placeholder where a no-action expression
7607 /// is needed (the `New' class).
7609 public class EmptyExpression : Expression {
7610 public EmptyExpression ()
7612 type = TypeManager.object_type;
7613 eclass = ExprClass.Value;
7614 loc = Location.Null;
7617 public EmptyExpression (Type t)
7620 eclass = ExprClass.Value;
7621 loc = Location.Null;
7624 public override Expression DoResolve (EmitContext ec)
7629 public override void Emit (EmitContext ec)
7631 // nothing, as we only exist to not do anything.
7635 // This is just because we might want to reuse this bad boy
7636 // instead of creating gazillions of EmptyExpressions.
7637 // (CanImplicitConversion uses it)
7639 public void SetType (Type t)
7645 public class UserCast : Expression {
7649 public UserCast (MethodInfo method, Expression source, Location l)
7651 this.method = method;
7652 this.source = source;
7653 type = method.ReturnType;
7654 eclass = ExprClass.Value;
7658 public override Expression DoResolve (EmitContext ec)
7661 // We are born fully resolved
7666 public override void Emit (EmitContext ec)
7668 ILGenerator ig = ec.ig;
7672 if (method is MethodInfo)
7673 ig.Emit (OpCodes.Call, (MethodInfo) method);
7675 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
7681 // This class is used to "construct" the type during a typecast
7682 // operation. Since the Type.GetType class in .NET can parse
7683 // the type specification, we just use this to construct the type
7684 // one bit at a time.
7686 public class ComposedCast : Expression {
7690 public ComposedCast (Expression left, string dim, Location l)
7697 public override Expression ResolveAsTypeStep (EmitContext ec)
7699 Type ltype = ec.DeclSpace.ResolveType (left, false, loc);
7704 // ltype.Fullname is already fully qualified, so we can skip
7705 // a lot of probes, and go directly to TypeManager.LookupType
7707 string cname = ltype.FullName + dim;
7708 type = TypeManager.LookupTypeDirect (cname);
7711 // For arrays of enumerations we are having a problem
7712 // with the direct lookup. Need to investigate.
7714 // For now, fall back to the full lookup in that case.
7716 type = RootContext.LookupType (
7717 ec.DeclSpace, cname, false, loc);
7723 if (!ec.ResolvingTypeTree){
7725 // If the above flag is set, this is being invoked from the ResolveType function.
7726 // Upper layers take care of the type validity in this context.
7728 if (!ec.InUnsafe && type.IsPointer){
7734 eclass = ExprClass.Type;
7738 public override Expression DoResolve (EmitContext ec)
7740 return ResolveAsTypeStep (ec);
7743 public override void Emit (EmitContext ec)
7745 throw new Exception ("This should never be called");
7748 public override string ToString ()
7755 // This class is used to represent the address of an array, used
7756 // only by the Fixed statement, this is like the C "&a [0]" construct.
7758 public class ArrayPtr : Expression {
7761 public ArrayPtr (Expression array, Location l)
7763 Type array_type = array.Type.GetElementType ();
7767 type = TypeManager.GetPointerType (array_type);
7768 eclass = ExprClass.Value;
7772 public override void Emit (EmitContext ec)
7774 ILGenerator ig = ec.ig;
7777 IntLiteral.EmitInt (ig, 0);
7778 ig.Emit (OpCodes.Ldelema, array.Type.GetElementType ());
7781 public override Expression DoResolve (EmitContext ec)
7784 // We are born fully resolved
7791 // Used by the fixed statement
7793 public class StringPtr : Expression {
7796 public StringPtr (LocalBuilder b, Location l)
7799 eclass = ExprClass.Value;
7800 type = TypeManager.char_ptr_type;
7804 public override Expression DoResolve (EmitContext ec)
7806 // This should never be invoked, we are born in fully
7807 // initialized state.
7812 public override void Emit (EmitContext ec)
7814 ILGenerator ig = ec.ig;
7816 ig.Emit (OpCodes.Ldloc, b);
7817 ig.Emit (OpCodes.Conv_I);
7818 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
7819 ig.Emit (OpCodes.Add);
7824 // Implements the `stackalloc' keyword
7826 public class StackAlloc : Expression {
7831 public StackAlloc (Expression type, Expression count, Location l)
7838 public override Expression DoResolve (EmitContext ec)
7840 count = count.Resolve (ec);
7844 if (count.Type != TypeManager.int32_type){
7845 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
7850 if (ec.InCatch || ec.InFinally){
7852 "stackalloc can not be used in a catch or finally block");
7856 otype = ec.DeclSpace.ResolveType (t, false, loc);
7861 if (!TypeManager.VerifyUnManaged (otype, loc))
7864 type = TypeManager.GetPointerType (otype);
7865 eclass = ExprClass.Value;
7870 public override void Emit (EmitContext ec)
7872 int size = GetTypeSize (otype);
7873 ILGenerator ig = ec.ig;
7876 ig.Emit (OpCodes.Sizeof, otype);
7878 IntConstant.EmitInt (ig, size);
7880 ig.Emit (OpCodes.Mul);
7881 ig.Emit (OpCodes.Localloc);