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);
85 public class ParenthesizedExpression : Expression
87 public Expression Expr;
89 public ParenthesizedExpression (Expression expr, Location loc)
95 public override Expression DoResolve (EmitContext ec)
97 Expr = Expr.Resolve (ec);
101 public override void Emit (EmitContext ec)
103 throw new Exception ("Should not happen");
108 /// Unary expressions.
112 /// Unary implements unary expressions. It derives from
113 /// ExpressionStatement becuase the pre/post increment/decrement
114 /// operators can be used in a statement context.
116 public class Unary : Expression {
117 public enum Operator : byte {
118 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
119 Indirection, AddressOf, TOP
122 public Operator Oper;
123 public Expression Expr;
125 public Unary (Operator op, Expression expr, Location loc)
133 /// Returns a stringified representation of the Operator
135 static public string OperName (Operator oper)
138 case Operator.UnaryPlus:
140 case Operator.UnaryNegation:
142 case Operator.LogicalNot:
144 case Operator.OnesComplement:
146 case Operator.AddressOf:
148 case Operator.Indirection:
152 return oper.ToString ();
155 public static readonly string [] oper_names;
159 oper_names = new string [(int)Operator.TOP];
161 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
162 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
163 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
164 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
165 oper_names [(int) Operator.Indirection] = "op_Indirection";
166 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
169 void Error23 (Type t)
172 23, "Operator " + OperName (Oper) +
173 " cannot be applied to operand of type `" +
174 TypeManager.CSharpName (t) + "'");
178 /// The result has been already resolved:
180 /// FIXME: a minus constant -128 sbyte cant be turned into a
183 static Expression TryReduceNegative (Constant expr)
187 if (expr is IntConstant)
188 e = new IntConstant (-((IntConstant) expr).Value);
189 else if (expr is UIntConstant){
190 uint value = ((UIntConstant) expr).Value;
192 if (value < 2147483649)
193 return new IntConstant (-(int)value);
195 e = new LongConstant (-value);
197 else if (expr is LongConstant)
198 e = new LongConstant (-((LongConstant) expr).Value);
199 else if (expr is ULongConstant){
200 ulong value = ((ULongConstant) expr).Value;
202 if (value < 9223372036854775809)
203 return new LongConstant(-(long)value);
205 else if (expr is FloatConstant)
206 e = new FloatConstant (-((FloatConstant) expr).Value);
207 else if (expr is DoubleConstant)
208 e = new DoubleConstant (-((DoubleConstant) expr).Value);
209 else if (expr is DecimalConstant)
210 e = new DecimalConstant (-((DecimalConstant) expr).Value);
211 else if (expr is ShortConstant)
212 e = new IntConstant (-((ShortConstant) expr).Value);
213 else if (expr is UShortConstant)
214 e = new IntConstant (-((UShortConstant) expr).Value);
219 // This routine will attempt to simplify the unary expression when the
220 // argument is a constant. The result is returned in `result' and the
221 // function returns true or false depending on whether a reduction
222 // was performed or not
224 bool Reduce (EmitContext ec, Constant e, out Expression result)
226 Type expr_type = e.Type;
229 case Operator.UnaryPlus:
233 case Operator.UnaryNegation:
234 result = TryReduceNegative (e);
237 case Operator.LogicalNot:
238 if (expr_type != TypeManager.bool_type) {
244 BoolConstant b = (BoolConstant) e;
245 result = new BoolConstant (!(b.Value));
248 case Operator.OnesComplement:
249 if (!((expr_type == TypeManager.int32_type) ||
250 (expr_type == TypeManager.uint32_type) ||
251 (expr_type == TypeManager.int64_type) ||
252 (expr_type == TypeManager.uint64_type) ||
253 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
256 if (Convert.ImplicitConversionExists (ec, e, TypeManager.int32_type)){
257 result = new Cast (new TypeExpression (TypeManager.int32_type, loc), e, loc);
258 result = result.Resolve (ec);
259 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint32_type)){
260 result = new Cast (new TypeExpression (TypeManager.uint32_type, loc), e, loc);
261 result = result.Resolve (ec);
262 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.int64_type)){
263 result = new Cast (new TypeExpression (TypeManager.int64_type, loc), e, loc);
264 result = result.Resolve (ec);
265 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint64_type)){
266 result = new Cast (new TypeExpression (TypeManager.uint64_type, loc), e, loc);
267 result = result.Resolve (ec);
270 if (result == null || !(result is Constant)){
276 expr_type = result.Type;
277 e = (Constant) result;
280 if (e is EnumConstant){
281 EnumConstant enum_constant = (EnumConstant) e;
284 if (Reduce (ec, enum_constant.Child, out reduced)){
285 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
293 if (expr_type == TypeManager.int32_type){
294 result = new IntConstant (~ ((IntConstant) e).Value);
295 } else if (expr_type == TypeManager.uint32_type){
296 result = new UIntConstant (~ ((UIntConstant) e).Value);
297 } else if (expr_type == TypeManager.int64_type){
298 result = new LongConstant (~ ((LongConstant) e).Value);
299 } else if (expr_type == TypeManager.uint64_type){
300 result = new ULongConstant (~ ((ULongConstant) e).Value);
308 case Operator.AddressOf:
312 case Operator.Indirection:
316 throw new Exception ("Can not constant fold: " + Oper.ToString());
319 Expression ResolveOperator (EmitContext ec)
321 Type expr_type = Expr.Type;
324 // Step 1: Perform Operator Overload location
329 op_name = oper_names [(int) Oper];
331 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
334 Expression e = StaticCallExpr.MakeSimpleCall (
335 ec, (MethodGroupExpr) mg, Expr, loc);
345 // Only perform numeric promotions on:
348 if (expr_type == null)
352 // Step 2: Default operations on CLI native types.
355 // Attempt to use a constant folding operation.
356 if (Expr is Constant){
359 if (Reduce (ec, (Constant) Expr, out result))
364 case Operator.LogicalNot:
365 if (expr_type != TypeManager.bool_type) {
366 Expr = ResolveBoolean (ec, Expr, loc);
373 type = TypeManager.bool_type;
376 case Operator.OnesComplement:
377 if (!((expr_type == TypeManager.int32_type) ||
378 (expr_type == TypeManager.uint32_type) ||
379 (expr_type == TypeManager.int64_type) ||
380 (expr_type == TypeManager.uint64_type) ||
381 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
384 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
386 type = TypeManager.int32_type;
389 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint32_type, loc);
391 type = TypeManager.uint32_type;
394 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
396 type = TypeManager.int64_type;
399 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint64_type, loc);
401 type = TypeManager.uint64_type;
410 case Operator.AddressOf:
411 if (Expr.eclass != ExprClass.Variable){
412 Error (211, "Cannot take the address of non-variables");
421 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
425 IVariable variable = Expr as IVariable;
426 if (!ec.InFixedInitializer && ((variable == null) || !variable.VerifyFixed (false))) {
427 Error (212, "You can only take the address of an unfixed expression inside " +
428 "of a fixed statement initializer");
432 // According to the specs, a variable is considered definitely assigned if you take
434 if ((variable != null) && (variable.VariableInfo != null))
435 variable.VariableInfo.SetAssigned (ec);
437 type = TypeManager.GetPointerType (Expr.Type);
440 case Operator.Indirection:
446 if (!expr_type.IsPointer){
447 Error (193, "The * or -> operator can only be applied to pointers");
452 // We create an Indirection expression, because
453 // it can implement the IMemoryLocation.
455 return new Indirection (Expr, loc);
457 case Operator.UnaryPlus:
459 // A plus in front of something is just a no-op, so return the child.
463 case Operator.UnaryNegation:
465 // Deals with -literals
466 // int operator- (int x)
467 // long operator- (long x)
468 // float operator- (float f)
469 // double operator- (double d)
470 // decimal operator- (decimal d)
472 Expression expr = null;
475 // transform - - expr into expr
478 Unary unary = (Unary) Expr;
480 if (unary.Oper == Operator.UnaryNegation)
485 // perform numeric promotions to int,
489 // The following is inneficient, because we call
490 // ImplicitConversion too many times.
492 // It is also not clear if we should convert to Float
493 // or Double initially.
495 if (expr_type == TypeManager.uint32_type){
497 // FIXME: handle exception to this rule that
498 // permits the int value -2147483648 (-2^31) to
499 // bt wrote as a decimal interger literal
501 type = TypeManager.int64_type;
502 Expr = Convert.ImplicitConversion (ec, Expr, type, loc);
506 if (expr_type == TypeManager.uint64_type){
508 // FIXME: Handle exception of `long value'
509 // -92233720368547758087 (-2^63) to be wrote as
510 // decimal integer literal.
516 if (expr_type == TypeManager.float_type){
521 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
528 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
535 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.double_type, loc);
546 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
547 TypeManager.CSharpName (expr_type) + "'");
551 public override Expression DoResolve (EmitContext ec)
553 if (Oper == Operator.AddressOf)
554 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
556 Expr = Expr.Resolve (ec);
561 eclass = ExprClass.Value;
562 return ResolveOperator (ec);
565 public override void Emit (EmitContext ec)
567 ILGenerator ig = ec.ig;
570 case Operator.UnaryPlus:
571 throw new Exception ("This should be caught by Resolve");
573 case Operator.UnaryNegation:
575 ig.Emit (OpCodes.Ldc_I4_0);
576 if (type == TypeManager.int64_type)
577 ig.Emit (OpCodes.Conv_U8);
579 ig.Emit (OpCodes.Sub_Ovf);
582 ig.Emit (OpCodes.Neg);
587 case Operator.LogicalNot:
589 ig.Emit (OpCodes.Ldc_I4_0);
590 ig.Emit (OpCodes.Ceq);
593 case Operator.OnesComplement:
595 ig.Emit (OpCodes.Not);
598 case Operator.AddressOf:
599 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
603 throw new Exception ("This should not happen: Operator = "
608 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
610 if (Oper == Operator.LogicalNot)
611 Expr.EmitBranchable (ec, target, !onTrue);
613 base.EmitBranchable (ec, target, onTrue);
616 public override string ToString ()
618 return "Unary (" + Oper + ", " + Expr + ")";
624 // Unary operators are turned into Indirection expressions
625 // after semantic analysis (this is so we can take the address
626 // of an indirection).
628 public class Indirection : Expression, IMemoryLocation, IAssignMethod {
630 LocalTemporary temporary;
633 public Indirection (Expression expr, Location l)
636 this.type = TypeManager.GetElementType (expr.Type);
637 eclass = ExprClass.Variable;
641 void LoadExprValue (EmitContext ec)
645 public override void Emit (EmitContext ec)
647 ILGenerator ig = ec.ig;
649 if (temporary != null){
655 ec.ig.Emit (OpCodes.Dup);
656 temporary.Store (ec);
657 have_temporary = true;
661 LoadFromPtr (ig, Type);
664 public void EmitAssign (EmitContext ec, Expression source)
666 if (temporary != null){
671 ec.ig.Emit (OpCodes.Dup);
672 temporary.Store (ec);
673 have_temporary = true;
679 StoreFromPtr (ec.ig, type);
682 public void AddressOf (EmitContext ec, AddressOp Mode)
684 if (temporary != null){
690 ec.ig.Emit (OpCodes.Dup);
691 temporary.Store (ec);
692 have_temporary = true;
697 public override Expression DoResolve (EmitContext ec)
700 // Born fully resolved
705 public new void CacheTemporaries (EmitContext ec)
707 temporary = new LocalTemporary (ec, expr.Type);
710 public override string ToString ()
712 return "*(" + expr + ")";
717 /// Unary Mutator expressions (pre and post ++ and --)
721 /// UnaryMutator implements ++ and -- expressions. It derives from
722 /// ExpressionStatement becuase the pre/post increment/decrement
723 /// operators can be used in a statement context.
725 /// FIXME: Idea, we could split this up in two classes, one simpler
726 /// for the common case, and one with the extra fields for more complex
727 /// classes (indexers require temporary access; overloaded require method)
730 public class UnaryMutator : ExpressionStatement {
732 public enum Mode : byte {
739 PreDecrement = IsDecrement,
740 PostIncrement = IsPost,
741 PostDecrement = IsPost | IsDecrement
746 LocalTemporary temp_storage;
749 // This is expensive for the simplest case.
753 public UnaryMutator (Mode m, Expression e, Location l)
760 static string OperName (Mode mode)
762 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
766 void Error23 (Type t)
769 23, "Operator " + OperName (mode) +
770 " cannot be applied to operand of type `" +
771 TypeManager.CSharpName (t) + "'");
775 /// Returns whether an object of type `t' can be incremented
776 /// or decremented with add/sub (ie, basically whether we can
777 /// use pre-post incr-decr operations on it, but it is not a
778 /// System.Decimal, which we require operator overloading to catch)
780 static bool IsIncrementableNumber (Type t)
782 return (t == TypeManager.sbyte_type) ||
783 (t == TypeManager.byte_type) ||
784 (t == TypeManager.short_type) ||
785 (t == TypeManager.ushort_type) ||
786 (t == TypeManager.int32_type) ||
787 (t == TypeManager.uint32_type) ||
788 (t == TypeManager.int64_type) ||
789 (t == TypeManager.uint64_type) ||
790 (t == TypeManager.char_type) ||
791 (t.IsSubclassOf (TypeManager.enum_type)) ||
792 (t == TypeManager.float_type) ||
793 (t == TypeManager.double_type) ||
794 (t.IsPointer && t != TypeManager.void_ptr_type);
797 Expression ResolveOperator (EmitContext ec)
799 Type expr_type = expr.Type;
802 // Step 1: Perform Operator Overload location
807 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
808 op_name = "op_Increment";
810 op_name = "op_Decrement";
812 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
814 if (mg == null && expr_type.BaseType != null)
815 mg = MemberLookup (ec, expr_type.BaseType, op_name,
816 MemberTypes.Method, AllBindingFlags, loc);
819 method = StaticCallExpr.MakeSimpleCall (
820 ec, (MethodGroupExpr) mg, expr, loc);
827 // The operand of the prefix/postfix increment decrement operators
828 // should be an expression that is classified as a variable,
829 // a property access or an indexer access
832 if (expr.eclass == ExprClass.Variable){
833 LocalVariableReference var = expr as LocalVariableReference;
834 if ((var != null) && var.IsReadOnly)
835 Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
836 if (IsIncrementableNumber (expr_type) ||
837 expr_type == TypeManager.decimal_type){
840 } else if (expr.eclass == ExprClass.IndexerAccess){
841 IndexerAccess ia = (IndexerAccess) expr;
843 temp_storage = new LocalTemporary (ec, expr.Type);
845 expr = ia.ResolveLValue (ec, temp_storage);
850 } else if (expr.eclass == ExprClass.PropertyAccess){
851 PropertyExpr pe = (PropertyExpr) expr;
853 if (pe.VerifyAssignable ())
858 expr.Error_UnexpectedKind ("variable, indexer or property access");
862 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
863 TypeManager.CSharpName (expr_type) + "'");
867 public override Expression DoResolve (EmitContext ec)
869 expr = expr.Resolve (ec);
874 eclass = ExprClass.Value;
875 return ResolveOperator (ec);
878 static int PtrTypeSize (Type t)
880 return GetTypeSize (TypeManager.GetElementType (t));
884 // Loads the proper "1" into the stack based on the type, then it emits the
885 // opcode for the operation requested
887 void LoadOneAndEmitOp (EmitContext ec, Type t)
890 // Measure if getting the typecode and using that is more/less efficient
891 // that comparing types. t.GetTypeCode() is an internal call.
893 ILGenerator ig = ec.ig;
895 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
896 LongConstant.EmitLong (ig, 1);
897 else if (t == TypeManager.double_type)
898 ig.Emit (OpCodes.Ldc_R8, 1.0);
899 else if (t == TypeManager.float_type)
900 ig.Emit (OpCodes.Ldc_R4, 1.0F);
901 else if (t.IsPointer){
902 int n = PtrTypeSize (t);
905 ig.Emit (OpCodes.Sizeof, t);
907 IntConstant.EmitInt (ig, n);
909 ig.Emit (OpCodes.Ldc_I4_1);
912 // Now emit the operation
915 if (t == TypeManager.int32_type ||
916 t == TypeManager.int64_type){
917 if ((mode & Mode.IsDecrement) != 0)
918 ig.Emit (OpCodes.Sub_Ovf);
920 ig.Emit (OpCodes.Add_Ovf);
921 } else if (t == TypeManager.uint32_type ||
922 t == TypeManager.uint64_type){
923 if ((mode & Mode.IsDecrement) != 0)
924 ig.Emit (OpCodes.Sub_Ovf_Un);
926 ig.Emit (OpCodes.Add_Ovf_Un);
928 if ((mode & Mode.IsDecrement) != 0)
929 ig.Emit (OpCodes.Sub_Ovf);
931 ig.Emit (OpCodes.Add_Ovf);
934 if ((mode & Mode.IsDecrement) != 0)
935 ig.Emit (OpCodes.Sub);
937 ig.Emit (OpCodes.Add);
940 if (t == TypeManager.sbyte_type){
942 ig.Emit (OpCodes.Conv_Ovf_I1);
944 ig.Emit (OpCodes.Conv_I1);
945 } else if (t == TypeManager.byte_type){
947 ig.Emit (OpCodes.Conv_Ovf_U1);
949 ig.Emit (OpCodes.Conv_U1);
950 } else if (t == TypeManager.short_type){
952 ig.Emit (OpCodes.Conv_Ovf_I2);
954 ig.Emit (OpCodes.Conv_I2);
955 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
957 ig.Emit (OpCodes.Conv_Ovf_U2);
959 ig.Emit (OpCodes.Conv_U2);
964 static EmptyExpression empty_expr;
966 void EmitCode (EmitContext ec, bool is_expr)
968 ILGenerator ig = ec.ig;
969 IAssignMethod ia = (IAssignMethod) expr;
970 Type expr_type = expr.Type;
972 ia.CacheTemporaries (ec);
974 if (temp_storage == null){
976 // Temporary improvement: if we are dealing with something that does
977 // not require complicated instance setup, avoid using a temporary
979 // For now: only localvariables when not remapped
982 if (method == null &&
983 ((expr is LocalVariableReference) ||(expr is FieldExpr && ((FieldExpr) expr).FieldInfo.IsStatic))){
984 if (empty_expr == null)
985 empty_expr = new EmptyExpression ();
988 case Mode.PreIncrement:
989 case Mode.PreDecrement:
992 LoadOneAndEmitOp (ec, expr_type);
994 ig.Emit (OpCodes.Dup);
995 ia.EmitAssign (ec, empty_expr);
998 case Mode.PostIncrement:
999 case Mode.PostDecrement:
1002 ig.Emit (OpCodes.Dup);
1004 LoadOneAndEmitOp (ec, expr_type);
1005 ia.EmitAssign (ec, empty_expr);
1010 temp_storage = new LocalTemporary (ec, expr_type);
1014 case Mode.PreIncrement:
1015 case Mode.PreDecrement:
1016 if (method == null){
1019 LoadOneAndEmitOp (ec, expr_type);
1023 temp_storage.Store (ec);
1024 ia.EmitAssign (ec, temp_storage);
1026 temp_storage.Emit (ec);
1029 case Mode.PostIncrement:
1030 case Mode.PostDecrement:
1034 if (method == null){
1038 ig.Emit (OpCodes.Dup);
1040 LoadOneAndEmitOp (ec, expr_type);
1045 temp_storage.Store (ec);
1046 ia.EmitAssign (ec, temp_storage);
1051 public override void Emit (EmitContext ec)
1053 EmitCode (ec, true);
1057 public override void EmitStatement (EmitContext ec)
1059 EmitCode (ec, false);
1065 /// Base class for the `Is' and `As' classes.
1069 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1072 public abstract class Probe : Expression {
1073 public readonly Expression ProbeType;
1074 protected Expression expr;
1075 protected Type probe_type;
1077 public Probe (Expression expr, Expression probe_type, Location l)
1079 ProbeType = probe_type;
1084 public Expression Expr {
1090 public override Expression DoResolve (EmitContext ec)
1092 probe_type = ec.DeclSpace.ResolveType (ProbeType, false, loc);
1094 if (probe_type == null)
1097 expr = expr.Resolve (ec);
1106 /// Implementation of the `is' operator.
1108 public class Is : Probe {
1109 public Is (Expression expr, Expression probe_type, Location l)
1110 : base (expr, probe_type, l)
1115 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1120 public override void Emit (EmitContext ec)
1122 ILGenerator ig = ec.ig;
1127 case Action.AlwaysFalse:
1128 ig.Emit (OpCodes.Pop);
1129 IntConstant.EmitInt (ig, 0);
1131 case Action.AlwaysTrue:
1132 ig.Emit (OpCodes.Pop);
1133 IntConstant.EmitInt (ig, 1);
1135 case Action.LeaveOnStack:
1136 // the `e != null' rule.
1137 ig.Emit (OpCodes.Ldnull);
1138 ig.Emit (OpCodes.Ceq);
1139 ig.Emit (OpCodes.Ldc_I4_0);
1140 ig.Emit (OpCodes.Ceq);
1143 ig.Emit (OpCodes.Isinst, probe_type);
1144 ig.Emit (OpCodes.Ldnull);
1145 ig.Emit (OpCodes.Cgt_Un);
1148 throw new Exception ("never reached");
1151 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
1153 ILGenerator ig = ec.ig;
1156 case Action.AlwaysFalse:
1158 ig.Emit (OpCodes.Br, target);
1161 case Action.AlwaysTrue:
1163 ig.Emit (OpCodes.Br, target);
1166 case Action.LeaveOnStack:
1167 // the `e != null' rule.
1169 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1173 ig.Emit (OpCodes.Isinst, probe_type);
1174 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1177 throw new Exception ("never reached");
1180 public override Expression DoResolve (EmitContext ec)
1182 Expression e = base.DoResolve (ec);
1184 if ((e == null) || (expr == null))
1187 Type etype = expr.Type;
1188 bool warning_always_matches = false;
1189 bool warning_never_matches = false;
1191 type = TypeManager.bool_type;
1192 eclass = ExprClass.Value;
1195 // First case, if at compile time, there is an implicit conversion
1196 // then e != null (objects) or true (value types)
1198 e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1201 if (etype.IsValueType)
1202 action = Action.AlwaysTrue;
1204 action = Action.LeaveOnStack;
1206 warning_always_matches = true;
1207 } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1209 // Second case: explicit reference convresion
1211 if (expr is NullLiteral)
1212 action = Action.AlwaysFalse;
1214 action = Action.Probe;
1216 action = Action.AlwaysFalse;
1217 warning_never_matches = true;
1220 if (RootContext.WarningLevel >= 1){
1221 if (warning_always_matches)
1222 Warning (183, "The expression is always of type `" +
1223 TypeManager.CSharpName (probe_type) + "'");
1224 else if (warning_never_matches){
1225 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1227 "The expression is never of type `" +
1228 TypeManager.CSharpName (probe_type) + "'");
1237 /// Implementation of the `as' operator.
1239 public class As : Probe {
1240 public As (Expression expr, Expression probe_type, Location l)
1241 : base (expr, probe_type, l)
1245 bool do_isinst = false;
1247 public override void Emit (EmitContext ec)
1249 ILGenerator ig = ec.ig;
1254 ig.Emit (OpCodes.Isinst, probe_type);
1257 static void Error_CannotConvertType (Type source, Type target, Location loc)
1260 39, loc, "as operator can not convert from `" +
1261 TypeManager.CSharpName (source) + "' to `" +
1262 TypeManager.CSharpName (target) + "'");
1265 public override Expression DoResolve (EmitContext ec)
1267 Expression e = base.DoResolve (ec);
1273 eclass = ExprClass.Value;
1274 Type etype = expr.Type;
1276 if (TypeManager.IsValueType (probe_type)){
1277 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1278 TypeManager.CSharpName (probe_type) + " is a value type)");
1283 e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1290 if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1295 Error_CannotConvertType (etype, probe_type, loc);
1301 /// This represents a typecast in the source language.
1303 /// FIXME: Cast expressions have an unusual set of parsing
1304 /// rules, we need to figure those out.
1306 public class Cast : Expression {
1307 Expression target_type;
1310 public Cast (Expression cast_type, Expression expr, Location loc)
1312 this.target_type = cast_type;
1317 public Expression TargetType {
1323 public Expression Expr {
1332 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1334 if (!ec.ConstantCheckState)
1337 if ((value < min) || (value > max)) {
1338 Error (221, "Constant value `" + value + "' cannot be converted " +
1339 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1340 "syntax to override)");
1347 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1349 if (!ec.ConstantCheckState)
1353 Error (221, "Constant value `" + value + "' cannot be converted " +
1354 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1355 "syntax to override)");
1362 bool CheckUnsigned (EmitContext ec, long value, Type type)
1364 if (!ec.ConstantCheckState)
1368 Error (221, "Constant value `" + value + "' cannot be converted " +
1369 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1370 "syntax to override)");
1378 /// Attempts to do a compile-time folding of a constant cast.
1380 Expression TryReduce (EmitContext ec, Type target_type)
1382 Expression real_expr = expr;
1383 if (real_expr is EnumConstant)
1384 real_expr = ((EnumConstant) real_expr).Child;
1386 if (real_expr is ByteConstant){
1387 byte v = ((ByteConstant) real_expr).Value;
1389 if (target_type == TypeManager.sbyte_type) {
1390 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1392 return new SByteConstant ((sbyte) v);
1394 if (target_type == TypeManager.short_type)
1395 return new ShortConstant ((short) v);
1396 if (target_type == TypeManager.ushort_type)
1397 return new UShortConstant ((ushort) v);
1398 if (target_type == TypeManager.int32_type)
1399 return new IntConstant ((int) v);
1400 if (target_type == TypeManager.uint32_type)
1401 return new UIntConstant ((uint) v);
1402 if (target_type == TypeManager.int64_type)
1403 return new LongConstant ((long) v);
1404 if (target_type == TypeManager.uint64_type)
1405 return new ULongConstant ((ulong) v);
1406 if (target_type == TypeManager.float_type)
1407 return new FloatConstant ((float) v);
1408 if (target_type == TypeManager.double_type)
1409 return new DoubleConstant ((double) v);
1410 if (target_type == TypeManager.char_type)
1411 return new CharConstant ((char) v);
1412 if (target_type == TypeManager.decimal_type)
1413 return new DecimalConstant ((decimal) v);
1415 if (real_expr is SByteConstant){
1416 sbyte v = ((SByteConstant) real_expr).Value;
1418 if (target_type == TypeManager.byte_type) {
1419 if (!CheckUnsigned (ec, v, target_type))
1421 return new ByteConstant ((byte) v);
1423 if (target_type == TypeManager.short_type)
1424 return new ShortConstant ((short) v);
1425 if (target_type == TypeManager.ushort_type) {
1426 if (!CheckUnsigned (ec, v, target_type))
1428 return new UShortConstant ((ushort) v);
1429 } if (target_type == TypeManager.int32_type)
1430 return new IntConstant ((int) v);
1431 if (target_type == TypeManager.uint32_type) {
1432 if (!CheckUnsigned (ec, v, target_type))
1434 return new UIntConstant ((uint) v);
1435 } if (target_type == TypeManager.int64_type)
1436 return new LongConstant ((long) v);
1437 if (target_type == TypeManager.uint64_type) {
1438 if (!CheckUnsigned (ec, v, target_type))
1440 return new ULongConstant ((ulong) v);
1442 if (target_type == TypeManager.float_type)
1443 return new FloatConstant ((float) v);
1444 if (target_type == TypeManager.double_type)
1445 return new DoubleConstant ((double) v);
1446 if (target_type == TypeManager.char_type) {
1447 if (!CheckUnsigned (ec, v, target_type))
1449 return new CharConstant ((char) v);
1451 if (target_type == TypeManager.decimal_type)
1452 return new DecimalConstant ((decimal) v);
1454 if (real_expr is ShortConstant){
1455 short v = ((ShortConstant) real_expr).Value;
1457 if (target_type == TypeManager.byte_type) {
1458 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1460 return new ByteConstant ((byte) v);
1462 if (target_type == TypeManager.sbyte_type) {
1463 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1465 return new SByteConstant ((sbyte) v);
1467 if (target_type == TypeManager.ushort_type) {
1468 if (!CheckUnsigned (ec, v, target_type))
1470 return new UShortConstant ((ushort) v);
1472 if (target_type == TypeManager.int32_type)
1473 return new IntConstant ((int) v);
1474 if (target_type == TypeManager.uint32_type) {
1475 if (!CheckUnsigned (ec, v, target_type))
1477 return new UIntConstant ((uint) v);
1479 if (target_type == TypeManager.int64_type)
1480 return new LongConstant ((long) v);
1481 if (target_type == TypeManager.uint64_type) {
1482 if (!CheckUnsigned (ec, v, target_type))
1484 return new ULongConstant ((ulong) v);
1486 if (target_type == TypeManager.float_type)
1487 return new FloatConstant ((float) v);
1488 if (target_type == TypeManager.double_type)
1489 return new DoubleConstant ((double) v);
1490 if (target_type == TypeManager.char_type) {
1491 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1493 return new CharConstant ((char) v);
1495 if (target_type == TypeManager.decimal_type)
1496 return new DecimalConstant ((decimal) v);
1498 if (real_expr is UShortConstant){
1499 ushort v = ((UShortConstant) real_expr).Value;
1501 if (target_type == TypeManager.byte_type) {
1502 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1504 return new ByteConstant ((byte) v);
1506 if (target_type == TypeManager.sbyte_type) {
1507 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1509 return new SByteConstant ((sbyte) v);
1511 if (target_type == TypeManager.short_type) {
1512 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1514 return new ShortConstant ((short) v);
1516 if (target_type == TypeManager.int32_type)
1517 return new IntConstant ((int) v);
1518 if (target_type == TypeManager.uint32_type)
1519 return new UIntConstant ((uint) v);
1520 if (target_type == TypeManager.int64_type)
1521 return new LongConstant ((long) v);
1522 if (target_type == TypeManager.uint64_type)
1523 return new ULongConstant ((ulong) v);
1524 if (target_type == TypeManager.float_type)
1525 return new FloatConstant ((float) v);
1526 if (target_type == TypeManager.double_type)
1527 return new DoubleConstant ((double) v);
1528 if (target_type == TypeManager.char_type) {
1529 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1531 return new CharConstant ((char) v);
1533 if (target_type == TypeManager.decimal_type)
1534 return new DecimalConstant ((decimal) v);
1536 if (real_expr is IntConstant){
1537 int v = ((IntConstant) real_expr).Value;
1539 if (target_type == TypeManager.byte_type) {
1540 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1542 return new ByteConstant ((byte) v);
1544 if (target_type == TypeManager.sbyte_type) {
1545 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1547 return new SByteConstant ((sbyte) v);
1549 if (target_type == TypeManager.short_type) {
1550 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1552 return new ShortConstant ((short) v);
1554 if (target_type == TypeManager.ushort_type) {
1555 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1557 return new UShortConstant ((ushort) v);
1559 if (target_type == TypeManager.uint32_type) {
1560 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1562 return new UIntConstant ((uint) v);
1564 if (target_type == TypeManager.int64_type)
1565 return new LongConstant ((long) v);
1566 if (target_type == TypeManager.uint64_type) {
1567 if (!CheckUnsigned (ec, v, target_type))
1569 return new ULongConstant ((ulong) v);
1571 if (target_type == TypeManager.float_type)
1572 return new FloatConstant ((float) v);
1573 if (target_type == TypeManager.double_type)
1574 return new DoubleConstant ((double) v);
1575 if (target_type == TypeManager.char_type) {
1576 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1578 return new CharConstant ((char) v);
1580 if (target_type == TypeManager.decimal_type)
1581 return new DecimalConstant ((decimal) v);
1583 if (real_expr is UIntConstant){
1584 uint v = ((UIntConstant) real_expr).Value;
1586 if (target_type == TypeManager.byte_type) {
1587 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1589 return new ByteConstant ((byte) v);
1591 if (target_type == TypeManager.sbyte_type) {
1592 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1594 return new SByteConstant ((sbyte) v);
1596 if (target_type == TypeManager.short_type) {
1597 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1599 return new ShortConstant ((short) v);
1601 if (target_type == TypeManager.ushort_type) {
1602 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1604 return new UShortConstant ((ushort) v);
1606 if (target_type == TypeManager.int32_type) {
1607 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1609 return new IntConstant ((int) v);
1611 if (target_type == TypeManager.int64_type)
1612 return new LongConstant ((long) v);
1613 if (target_type == TypeManager.uint64_type)
1614 return new ULongConstant ((ulong) v);
1615 if (target_type == TypeManager.float_type)
1616 return new FloatConstant ((float) v);
1617 if (target_type == TypeManager.double_type)
1618 return new DoubleConstant ((double) v);
1619 if (target_type == TypeManager.char_type) {
1620 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1622 return new CharConstant ((char) v);
1624 if (target_type == TypeManager.decimal_type)
1625 return new DecimalConstant ((decimal) v);
1627 if (real_expr is LongConstant){
1628 long v = ((LongConstant) real_expr).Value;
1630 if (target_type == TypeManager.byte_type) {
1631 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1633 return new ByteConstant ((byte) v);
1635 if (target_type == TypeManager.sbyte_type) {
1636 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1638 return new SByteConstant ((sbyte) v);
1640 if (target_type == TypeManager.short_type) {
1641 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1643 return new ShortConstant ((short) v);
1645 if (target_type == TypeManager.ushort_type) {
1646 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1648 return new UShortConstant ((ushort) v);
1650 if (target_type == TypeManager.int32_type) {
1651 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1653 return new IntConstant ((int) v);
1655 if (target_type == TypeManager.uint32_type) {
1656 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1658 return new UIntConstant ((uint) v);
1660 if (target_type == TypeManager.uint64_type) {
1661 if (!CheckUnsigned (ec, v, target_type))
1663 return new ULongConstant ((ulong) v);
1665 if (target_type == TypeManager.float_type)
1666 return new FloatConstant ((float) v);
1667 if (target_type == TypeManager.double_type)
1668 return new DoubleConstant ((double) v);
1669 if (target_type == TypeManager.char_type) {
1670 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1672 return new CharConstant ((char) v);
1674 if (target_type == TypeManager.decimal_type)
1675 return new DecimalConstant ((decimal) v);
1677 if (real_expr is ULongConstant){
1678 ulong v = ((ULongConstant) real_expr).Value;
1680 if (target_type == TypeManager.byte_type) {
1681 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1683 return new ByteConstant ((byte) v);
1685 if (target_type == TypeManager.sbyte_type) {
1686 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1688 return new SByteConstant ((sbyte) v);
1690 if (target_type == TypeManager.short_type) {
1691 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1693 return new ShortConstant ((short) v);
1695 if (target_type == TypeManager.ushort_type) {
1696 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1698 return new UShortConstant ((ushort) v);
1700 if (target_type == TypeManager.int32_type) {
1701 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1703 return new IntConstant ((int) v);
1705 if (target_type == TypeManager.uint32_type) {
1706 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1708 return new UIntConstant ((uint) v);
1710 if (target_type == TypeManager.int64_type) {
1711 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1713 return new LongConstant ((long) v);
1715 if (target_type == TypeManager.float_type)
1716 return new FloatConstant ((float) v);
1717 if (target_type == TypeManager.double_type)
1718 return new DoubleConstant ((double) v);
1719 if (target_type == TypeManager.char_type) {
1720 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1722 return new CharConstant ((char) v);
1724 if (target_type == TypeManager.decimal_type)
1725 return new DecimalConstant ((decimal) v);
1727 if (real_expr is FloatConstant){
1728 float v = ((FloatConstant) real_expr).Value;
1730 if (target_type == TypeManager.byte_type)
1731 return new ByteConstant ((byte) v);
1732 if (target_type == TypeManager.sbyte_type)
1733 return new SByteConstant ((sbyte) v);
1734 if (target_type == TypeManager.short_type)
1735 return new ShortConstant ((short) v);
1736 if (target_type == TypeManager.ushort_type)
1737 return new UShortConstant ((ushort) v);
1738 if (target_type == TypeManager.int32_type)
1739 return new IntConstant ((int) v);
1740 if (target_type == TypeManager.uint32_type)
1741 return new UIntConstant ((uint) v);
1742 if (target_type == TypeManager.int64_type)
1743 return new LongConstant ((long) v);
1744 if (target_type == TypeManager.uint64_type)
1745 return new ULongConstant ((ulong) v);
1746 if (target_type == TypeManager.double_type)
1747 return new DoubleConstant ((double) v);
1748 if (target_type == TypeManager.char_type)
1749 return new CharConstant ((char) v);
1750 if (target_type == TypeManager.decimal_type)
1751 return new DecimalConstant ((decimal) v);
1753 if (real_expr is DoubleConstant){
1754 double v = ((DoubleConstant) real_expr).Value;
1756 if (target_type == TypeManager.byte_type){
1757 return new ByteConstant ((byte) v);
1758 } if (target_type == TypeManager.sbyte_type)
1759 return new SByteConstant ((sbyte) v);
1760 if (target_type == TypeManager.short_type)
1761 return new ShortConstant ((short) v);
1762 if (target_type == TypeManager.ushort_type)
1763 return new UShortConstant ((ushort) v);
1764 if (target_type == TypeManager.int32_type)
1765 return new IntConstant ((int) v);
1766 if (target_type == TypeManager.uint32_type)
1767 return new UIntConstant ((uint) v);
1768 if (target_type == TypeManager.int64_type)
1769 return new LongConstant ((long) v);
1770 if (target_type == TypeManager.uint64_type)
1771 return new ULongConstant ((ulong) v);
1772 if (target_type == TypeManager.float_type)
1773 return new FloatConstant ((float) v);
1774 if (target_type == TypeManager.char_type)
1775 return new CharConstant ((char) v);
1776 if (target_type == TypeManager.decimal_type)
1777 return new DecimalConstant ((decimal) v);
1780 if (real_expr is CharConstant){
1781 char v = ((CharConstant) real_expr).Value;
1783 if (target_type == TypeManager.byte_type) {
1784 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1786 return new ByteConstant ((byte) v);
1788 if (target_type == TypeManager.sbyte_type) {
1789 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1791 return new SByteConstant ((sbyte) v);
1793 if (target_type == TypeManager.short_type) {
1794 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1796 return new ShortConstant ((short) v);
1798 if (target_type == TypeManager.int32_type)
1799 return new IntConstant ((int) v);
1800 if (target_type == TypeManager.uint32_type)
1801 return new UIntConstant ((uint) v);
1802 if (target_type == TypeManager.int64_type)
1803 return new LongConstant ((long) v);
1804 if (target_type == TypeManager.uint64_type)
1805 return new ULongConstant ((ulong) v);
1806 if (target_type == TypeManager.float_type)
1807 return new FloatConstant ((float) v);
1808 if (target_type == TypeManager.double_type)
1809 return new DoubleConstant ((double) v);
1810 if (target_type == TypeManager.char_type) {
1811 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1813 return new CharConstant ((char) v);
1815 if (target_type == TypeManager.decimal_type)
1816 return new DecimalConstant ((decimal) v);
1822 public override Expression DoResolve (EmitContext ec)
1824 expr = expr.Resolve (ec);
1828 type = ec.DeclSpace.ResolveType (target_type, false, Location);
1833 eclass = ExprClass.Value;
1835 if (expr is Constant){
1836 Expression e = TryReduce (ec, type);
1842 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1846 public override void Emit (EmitContext ec)
1849 // This one will never happen
1851 throw new Exception ("Should not happen");
1856 /// Binary operators
1858 public class Binary : Expression {
1859 public enum Operator : byte {
1860 Multiply, Division, Modulus,
1861 Addition, Subtraction,
1862 LeftShift, RightShift,
1863 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1864 Equality, Inequality,
1874 Expression left, right;
1876 // This must be kept in sync with Operator!!!
1877 public static readonly string [] oper_names;
1881 oper_names = new string [(int) Operator.TOP];
1883 oper_names [(int) Operator.Multiply] = "op_Multiply";
1884 oper_names [(int) Operator.Division] = "op_Division";
1885 oper_names [(int) Operator.Modulus] = "op_Modulus";
1886 oper_names [(int) Operator.Addition] = "op_Addition";
1887 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1888 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1889 oper_names [(int) Operator.RightShift] = "op_RightShift";
1890 oper_names [(int) Operator.LessThan] = "op_LessThan";
1891 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1892 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1893 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1894 oper_names [(int) Operator.Equality] = "op_Equality";
1895 oper_names [(int) Operator.Inequality] = "op_Inequality";
1896 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1897 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1898 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1899 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1900 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1903 public Binary (Operator oper, Expression left, Expression right, Location loc)
1911 public Operator Oper {
1920 public Expression Left {
1929 public Expression Right {
1940 /// Returns a stringified representation of the Operator
1942 static string OperName (Operator oper)
1945 case Operator.Multiply:
1947 case Operator.Division:
1949 case Operator.Modulus:
1951 case Operator.Addition:
1953 case Operator.Subtraction:
1955 case Operator.LeftShift:
1957 case Operator.RightShift:
1959 case Operator.LessThan:
1961 case Operator.GreaterThan:
1963 case Operator.LessThanOrEqual:
1965 case Operator.GreaterThanOrEqual:
1967 case Operator.Equality:
1969 case Operator.Inequality:
1971 case Operator.BitwiseAnd:
1973 case Operator.BitwiseOr:
1975 case Operator.ExclusiveOr:
1977 case Operator.LogicalOr:
1979 case Operator.LogicalAnd:
1983 return oper.ToString ();
1986 public override string ToString ()
1988 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1989 right.ToString () + ")";
1992 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1994 if (expr.Type == target_type)
1997 return Convert.ImplicitConversion (ec, expr, target_type, loc);
2000 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
2003 34, loc, "Operator `" + OperName (oper)
2004 + "' is ambiguous on operands of type `"
2005 + TypeManager.CSharpName (l) + "' "
2006 + "and `" + TypeManager.CSharpName (r)
2010 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
2012 if ((l == t) || (r == t))
2015 if (!check_user_conversions)
2018 if (Convert.ImplicitUserConversionExists (ec, l, t))
2020 else if (Convert.ImplicitUserConversionExists (ec, r, t))
2027 // Note that handling the case l == Decimal || r == Decimal
2028 // is taken care of by the Step 1 Operator Overload resolution.
2030 // If `check_user_conv' is true, we also check whether a user-defined conversion
2031 // exists. Note that we only need to do this if both arguments are of a user-defined
2032 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
2033 // so we don't explicitly check for performance reasons.
2035 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
2037 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
2039 // If either operand is of type double, the other operand is
2040 // conveted to type double.
2042 if (r != TypeManager.double_type)
2043 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
2044 if (l != TypeManager.double_type)
2045 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
2047 type = TypeManager.double_type;
2048 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
2050 // if either operand is of type float, the other operand is
2051 // converted to type float.
2053 if (r != TypeManager.double_type)
2054 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
2055 if (l != TypeManager.double_type)
2056 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
2057 type = TypeManager.float_type;
2058 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2062 // If either operand is of type ulong, the other operand is
2063 // converted to type ulong. or an error ocurrs if the other
2064 // operand is of type sbyte, short, int or long
2066 if (l == TypeManager.uint64_type){
2067 if (r != TypeManager.uint64_type){
2068 if (right is IntConstant){
2069 IntConstant ic = (IntConstant) right;
2071 e = Convert.TryImplicitIntConversion (l, ic);
2074 } else if (right is LongConstant){
2075 long ll = ((LongConstant) right).Value;
2078 right = new ULongConstant ((ulong) ll);
2080 e = Convert.ImplicitNumericConversion (ec, right, l, loc);
2087 if (left is IntConstant){
2088 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
2091 } else if (left is LongConstant){
2092 long ll = ((LongConstant) left).Value;
2095 left = new ULongConstant ((ulong) ll);
2097 e = Convert.ImplicitNumericConversion (ec, left, r, loc);
2104 if ((other == TypeManager.sbyte_type) ||
2105 (other == TypeManager.short_type) ||
2106 (other == TypeManager.int32_type) ||
2107 (other == TypeManager.int64_type))
2108 Error_OperatorAmbiguous (loc, oper, l, r);
2109 type = TypeManager.uint64_type;
2110 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2112 // If either operand is of type long, the other operand is converted
2115 if (l != TypeManager.int64_type)
2116 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
2117 if (r != TypeManager.int64_type)
2118 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
2120 type = TypeManager.int64_type;
2121 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2123 // If either operand is of type uint, and the other
2124 // operand is of type sbyte, short or int, othe operands are
2125 // converted to type long (unless we have an int constant).
2129 if (l == TypeManager.uint32_type){
2130 if (right is IntConstant){
2131 IntConstant ic = (IntConstant) right;
2135 right = new UIntConstant ((uint) val);
2142 } else if (r == TypeManager.uint32_type){
2143 if (left is IntConstant){
2144 IntConstant ic = (IntConstant) left;
2148 left = new UIntConstant ((uint) val);
2157 if ((other == TypeManager.sbyte_type) ||
2158 (other == TypeManager.short_type) ||
2159 (other == TypeManager.int32_type)){
2160 left = ForceConversion (ec, left, TypeManager.int64_type);
2161 right = ForceConversion (ec, right, TypeManager.int64_type);
2162 type = TypeManager.int64_type;
2165 // if either operand is of type uint, the other
2166 // operand is converd to type uint
2168 left = ForceConversion (ec, left, TypeManager.uint32_type);
2169 right = ForceConversion (ec, right, TypeManager.uint32_type);
2170 type = TypeManager.uint32_type;
2172 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2173 if (l != TypeManager.decimal_type)
2174 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
2176 if (r != TypeManager.decimal_type)
2177 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
2178 type = TypeManager.decimal_type;
2180 left = ForceConversion (ec, left, TypeManager.int32_type);
2181 right = ForceConversion (ec, right, TypeManager.int32_type);
2183 type = TypeManager.int32_type;
2186 return (left != null) && (right != null);
2189 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2191 Report.Error (19, loc,
2192 "Operator " + name + " cannot be applied to operands of type `" +
2193 TypeManager.CSharpName (l) + "' and `" +
2194 TypeManager.CSharpName (r) + "'");
2197 void Error_OperatorCannotBeApplied ()
2199 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2202 static bool is_32_or_64 (Type t)
2204 return (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2205 t == TypeManager.int64_type || t == TypeManager.uint64_type);
2208 static bool is_unsigned (Type t)
2210 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2211 t == TypeManager.short_type || t == TypeManager.byte_type);
2214 static bool is_user_defined (Type t)
2216 if (t.IsSubclassOf (TypeManager.value_type) &&
2217 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2223 Expression CheckShiftArguments (EmitContext ec)
2227 e = ForceConversion (ec, right, TypeManager.int32_type);
2229 Error_OperatorCannotBeApplied ();
2234 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
2235 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
2236 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
2237 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
2241 if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
2242 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (31), loc);
2243 right = right.DoResolve (ec);
2245 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (63), loc);
2246 right = right.DoResolve (ec);
2251 Error_OperatorCannotBeApplied ();
2255 Expression ResolveOperator (EmitContext ec)
2258 Type r = right.Type;
2260 bool overload_failed = false;
2263 // Special cases: string comapred to null
2265 if (oper == Operator.Equality || oper == Operator.Inequality){
2266 if ((l == TypeManager.string_type && (right is NullLiteral)) ||
2267 (r == TypeManager.string_type && (left is NullLiteral))){
2268 Type = TypeManager.bool_type;
2275 // Do not perform operator overload resolution when both sides are
2278 if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
2280 // Step 1: Perform Operator Overload location
2282 Expression left_expr, right_expr;
2284 string op = oper_names [(int) oper];
2286 MethodGroupExpr union;
2287 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2289 right_expr = MemberLookup (
2290 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2291 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2293 union = (MethodGroupExpr) left_expr;
2295 if (union != null) {
2296 ArrayList args = new ArrayList (2);
2297 args.Add (new Argument (left, Argument.AType.Expression));
2298 args.Add (new Argument (right, Argument.AType.Expression));
2300 MethodBase method = Invocation.OverloadResolve (ec, union, args, Location.Null);
2301 if (method != null) {
2302 MethodInfo mi = (MethodInfo) method;
2304 return new BinaryMethod (mi.ReturnType, method, args);
2306 overload_failed = true;
2312 // Step 2: Default operations on CLI native types.
2316 // Step 0: String concatenation (because overloading will get this wrong)
2318 if (oper == Operator.Addition){
2320 // If any of the arguments is a string, cast to string
2323 if (l == TypeManager.string_type){
2326 if (r == TypeManager.void_type) {
2327 Error_OperatorCannotBeApplied ();
2331 if (r == TypeManager.string_type){
2332 if (left is Constant && right is Constant){
2333 StringConstant ls = (StringConstant) left;
2334 StringConstant rs = (StringConstant) right;
2336 return new StringConstant (
2337 ls.Value + rs.Value);
2340 if (left is BinaryMethod){
2341 BinaryMethod b = (BinaryMethod) left;
2344 // Call String.Concat (string, string, string) or
2345 // String.Concat (string, string, string, string)
2348 if (b.method == TypeManager.string_concat_string_string ||
2349 b.method == TypeManager.string_concat_string_string_string){
2350 int count = b.Arguments.Count;
2353 ArrayList bargs = new ArrayList (3);
2354 bargs.AddRange (b.Arguments);
2355 bargs.Add (new Argument (right, Argument.AType.Expression));
2356 return new BinaryMethod (
2357 TypeManager.string_type,
2358 TypeManager.string_concat_string_string_string, bargs);
2359 } else if (count == 3){
2360 ArrayList bargs = new ArrayList (4);
2361 bargs.AddRange (b.Arguments);
2362 bargs.Add (new Argument (right, Argument.AType.Expression));
2363 return new BinaryMethod (
2364 TypeManager.string_type,
2365 TypeManager.string_concat_string_string_string_string, bargs);
2371 method = TypeManager.string_concat_string_string;
2374 method = TypeManager.string_concat_object_object;
2375 right = Convert.ImplicitConversion (
2376 ec, right, TypeManager.object_type, loc);
2378 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2384 // Cascading concats will hold up to 2 arguments, any extras will be
2385 // reallocated above.
2387 ArrayList args = new ArrayList (2);
2388 args.Add (new Argument (left, Argument.AType.Expression));
2389 args.Add (new Argument (right, Argument.AType.Expression));
2391 return new BinaryMethod (TypeManager.string_type, method, args);
2392 } else if (r == TypeManager.string_type){
2395 if (l == TypeManager.void_type) {
2396 Error_OperatorCannotBeApplied ();
2400 left = Convert.ImplicitConversion (ec, left, TypeManager.object_type, loc);
2402 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2405 ArrayList args = new ArrayList (2);
2406 args.Add (new Argument (left, Argument.AType.Expression));
2407 args.Add (new Argument (right, Argument.AType.Expression));
2409 return new BinaryMethod (TypeManager.string_type, TypeManager.string_concat_object_object, args);
2413 // Transform a + ( - b) into a - b
2415 if (right is Unary){
2416 Unary right_unary = (Unary) right;
2418 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2419 oper = Operator.Subtraction;
2420 right = right_unary.Expr;
2426 if (oper == Operator.Equality || oper == Operator.Inequality){
2427 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2428 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2429 Error_OperatorCannotBeApplied ();
2433 type = TypeManager.bool_type;
2438 // operator != (object a, object b)
2439 // operator == (object a, object b)
2441 // For this to be used, both arguments have to be reference-types.
2442 // Read the rationale on the spec (14.9.6)
2444 // Also, if at compile time we know that the classes do not inherit
2445 // one from the other, then we catch the error there.
2447 if (!(l.IsValueType || r.IsValueType)){
2448 type = TypeManager.bool_type;
2453 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2457 // Also, a standard conversion must exist from either one
2459 if (!(Convert.ImplicitStandardConversionExists (left, r) ||
2460 Convert.ImplicitStandardConversionExists (right, l))){
2461 Error_OperatorCannotBeApplied ();
2465 // We are going to have to convert to an object to compare
2467 if (l != TypeManager.object_type)
2468 left = new EmptyCast (left, TypeManager.object_type);
2469 if (r != TypeManager.object_type)
2470 right = new EmptyCast (right, TypeManager.object_type);
2473 // FIXME: CSC here catches errors cs254 and cs252
2479 // One of them is a valuetype, but the other one is not.
2481 if (!l.IsValueType || !r.IsValueType) {
2482 Error_OperatorCannotBeApplied ();
2487 // Only perform numeric promotions on:
2488 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2490 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2491 if (l.IsSubclassOf (TypeManager.delegate_type) &&
2492 r.IsSubclassOf (TypeManager.delegate_type)) {
2494 ArrayList args = new ArrayList (2);
2496 args = new ArrayList (2);
2497 args.Add (new Argument (left, Argument.AType.Expression));
2498 args.Add (new Argument (right, Argument.AType.Expression));
2500 if (oper == Operator.Addition)
2501 method = TypeManager.delegate_combine_delegate_delegate;
2503 method = TypeManager.delegate_remove_delegate_delegate;
2506 Error_OperatorCannotBeApplied ();
2510 return new BinaryDelegate (l, method, args);
2514 // Pointer arithmetic:
2516 // T* operator + (T* x, int y);
2517 // T* operator + (T* x, uint y);
2518 // T* operator + (T* x, long y);
2519 // T* operator + (T* x, ulong y);
2521 // T* operator + (int y, T* x);
2522 // T* operator + (uint y, T *x);
2523 // T* operator + (long y, T *x);
2524 // T* operator + (ulong y, T *x);
2526 // T* operator - (T* x, int y);
2527 // T* operator - (T* x, uint y);
2528 // T* operator - (T* x, long y);
2529 // T* operator - (T* x, ulong y);
2531 // long operator - (T* x, T *y)
2534 if (r.IsPointer && oper == Operator.Subtraction){
2536 return new PointerArithmetic (
2537 false, left, right, TypeManager.int64_type,
2539 } else if (is_32_or_64 (r))
2540 return new PointerArithmetic (
2541 oper == Operator.Addition, left, right, l, loc);
2542 } else if (r.IsPointer && is_32_or_64 (l) && oper == Operator.Addition)
2543 return new PointerArithmetic (
2544 true, right, left, r, loc);
2548 // Enumeration operators
2550 bool lie = TypeManager.IsEnumType (l);
2551 bool rie = TypeManager.IsEnumType (r);
2555 // U operator - (E e, E f)
2557 if (oper == Operator.Subtraction){
2559 type = TypeManager.EnumToUnderlying (l);
2562 Error_OperatorCannotBeApplied ();
2568 // operator + (E e, U x)
2569 // operator - (E e, U x)
2571 if (oper == Operator.Addition || oper == Operator.Subtraction){
2572 Type enum_type = lie ? l : r;
2573 Type other_type = lie ? r : l;
2574 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2576 if (underlying_type != other_type){
2577 temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
2587 Error_OperatorCannotBeApplied ();
2596 temp = Convert.ImplicitConversion (ec, right, l, loc);
2600 Error_OperatorCannotBeApplied ();
2604 temp = Convert.ImplicitConversion (ec, left, r, loc);
2609 Error_OperatorCannotBeApplied ();
2614 if (oper == Operator.Equality || oper == Operator.Inequality ||
2615 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2616 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2617 if (left.Type != right.Type){
2618 Error_OperatorCannotBeApplied ();
2621 type = TypeManager.bool_type;
2625 if (oper == Operator.BitwiseAnd ||
2626 oper == Operator.BitwiseOr ||
2627 oper == Operator.ExclusiveOr){
2631 Error_OperatorCannotBeApplied ();
2635 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2636 return CheckShiftArguments (ec);
2638 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2639 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2640 type = TypeManager.bool_type;
2645 Error_OperatorCannotBeApplied ();
2649 Expression e = new ConditionalLogicalOperator (
2650 oper == Operator.LogicalAnd, left, right, l, loc);
2651 return e.Resolve (ec);
2655 // operator & (bool x, bool y)
2656 // operator | (bool x, bool y)
2657 // operator ^ (bool x, bool y)
2659 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2660 if (oper == Operator.BitwiseAnd ||
2661 oper == Operator.BitwiseOr ||
2662 oper == Operator.ExclusiveOr){
2669 // Pointer comparison
2671 if (l.IsPointer && r.IsPointer){
2672 if (oper == Operator.Equality || oper == Operator.Inequality ||
2673 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2674 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2675 type = TypeManager.bool_type;
2681 // We are dealing with numbers
2683 if (overload_failed){
2684 Error_OperatorCannotBeApplied ();
2689 // This will leave left or right set to null if there is an error
2691 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2692 DoNumericPromotions (ec, l, r, check_user_conv);
2693 if (left == null || right == null){
2694 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2699 // reload our cached types if required
2704 if (oper == Operator.BitwiseAnd ||
2705 oper == Operator.BitwiseOr ||
2706 oper == Operator.ExclusiveOr){
2708 if (!((l == TypeManager.int32_type) ||
2709 (l == TypeManager.uint32_type) ||
2710 (l == TypeManager.short_type) ||
2711 (l == TypeManager.ushort_type) ||
2712 (l == TypeManager.int64_type) ||
2713 (l == TypeManager.uint64_type))){
2717 Error_OperatorCannotBeApplied ();
2722 if (oper == Operator.Equality ||
2723 oper == Operator.Inequality ||
2724 oper == Operator.LessThanOrEqual ||
2725 oper == Operator.LessThan ||
2726 oper == Operator.GreaterThanOrEqual ||
2727 oper == Operator.GreaterThan){
2728 type = TypeManager.bool_type;
2734 public override Expression DoResolve (EmitContext ec)
2736 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2737 left = ((ParenthesizedExpression) left).Expr;
2738 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2742 if (left.eclass == ExprClass.Type) {
2743 Error (75, "Casting a negative value needs to have the value in parentheses.");
2747 left = left.Resolve (ec);
2748 right = right.Resolve (ec);
2750 if (left == null || right == null)
2753 eclass = ExprClass.Value;
2755 Constant rc = right as Constant;
2756 Constant lc = left as Constant;
2758 if (rc != null & lc != null){
2759 Expression e = ConstantFold.BinaryFold (
2760 ec, oper, lc, rc, loc);
2765 return ResolveOperator (ec);
2769 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2770 /// context of a conditional bool expression. This function will return
2771 /// false if it is was possible to use EmitBranchable, or true if it was.
2773 /// The expression's code is generated, and we will generate a branch to `target'
2774 /// if the resulting expression value is equal to isTrue
2776 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2778 ILGenerator ig = ec.ig;
2781 // This is more complicated than it looks, but its just to avoid
2782 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2783 // but on top of that we want for == and != to use a special path
2784 // if we are comparing against null
2786 if (oper == Operator.Equality || oper == Operator.Inequality) {
2787 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2789 if (left is NullLiteral || left is IntConstant && ((IntConstant) left).Value == 0) {
2792 ig.Emit (OpCodes.Brtrue, target);
2794 ig.Emit (OpCodes.Brfalse, target);
2797 } else if (right is NullLiteral || right is IntConstant && ((IntConstant) right).Value == 0){
2800 ig.Emit (OpCodes.Brtrue, target);
2802 ig.Emit (OpCodes.Brfalse, target);
2805 } else if (left is BoolConstant){
2807 if (my_on_true != ((BoolConstant) left).Value)
2808 ig.Emit (OpCodes.Brtrue, target);
2810 ig.Emit (OpCodes.Brfalse, target);
2813 } else if (right is BoolConstant){
2815 if (my_on_true != ((BoolConstant) right).Value)
2816 ig.Emit (OpCodes.Brtrue, target);
2818 ig.Emit (OpCodes.Brfalse, target);
2823 } else if (oper == Operator.LogicalAnd) {
2826 Label tests_end = ig.DefineLabel ();
2828 left.EmitBranchable (ec, tests_end, false);
2829 right.EmitBranchable (ec, target, true);
2830 ig.MarkLabel (tests_end);
2832 left.EmitBranchable (ec, target, false);
2833 right.EmitBranchable (ec, target, false);
2838 } else if (oper == Operator.LogicalOr){
2840 left.EmitBranchable (ec, target, true);
2841 right.EmitBranchable (ec, target, true);
2844 Label tests_end = ig.DefineLabel ();
2845 left.EmitBranchable (ec, tests_end, true);
2846 right.EmitBranchable (ec, target, false);
2847 ig.MarkLabel (tests_end);
2852 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2853 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2854 oper == Operator.Equality || oper == Operator.Inequality)) {
2855 base.EmitBranchable (ec, target, onTrue);
2863 bool isUnsigned = is_unsigned (t);
2866 case Operator.Equality:
2868 ig.Emit (OpCodes.Beq, target);
2870 ig.Emit (OpCodes.Bne_Un, target);
2873 case Operator.Inequality:
2875 ig.Emit (OpCodes.Bne_Un, target);
2877 ig.Emit (OpCodes.Beq, target);
2880 case Operator.LessThan:
2883 ig.Emit (OpCodes.Blt_Un, target);
2885 ig.Emit (OpCodes.Blt, target);
2888 ig.Emit (OpCodes.Bge_Un, target);
2890 ig.Emit (OpCodes.Bge, target);
2893 case Operator.GreaterThan:
2896 ig.Emit (OpCodes.Bgt_Un, target);
2898 ig.Emit (OpCodes.Bgt, target);
2901 ig.Emit (OpCodes.Ble_Un, target);
2903 ig.Emit (OpCodes.Ble, target);
2906 case Operator.LessThanOrEqual:
2907 if (t == TypeManager.double_type || t == TypeManager.float_type)
2912 ig.Emit (OpCodes.Ble_Un, target);
2914 ig.Emit (OpCodes.Ble, target);
2917 ig.Emit (OpCodes.Bgt_Un, target);
2919 ig.Emit (OpCodes.Bgt, target);
2923 case Operator.GreaterThanOrEqual:
2924 if (t == TypeManager.double_type || t == TypeManager.float_type)
2928 ig.Emit (OpCodes.Bge_Un, target);
2930 ig.Emit (OpCodes.Bge, target);
2933 ig.Emit (OpCodes.Blt_Un, target);
2935 ig.Emit (OpCodes.Blt, target);
2938 Console.WriteLine (oper);
2939 throw new Exception ("what is THAT");
2943 public override void Emit (EmitContext ec)
2945 ILGenerator ig = ec.ig;
2950 // Handle short-circuit operators differently
2953 if (oper == Operator.LogicalAnd) {
2954 Label load_zero = ig.DefineLabel ();
2955 Label end = ig.DefineLabel ();
2957 left.EmitBranchable (ec, load_zero, false);
2959 ig.Emit (OpCodes.Br, end);
2961 ig.MarkLabel (load_zero);
2962 ig.Emit (OpCodes.Ldc_I4_0);
2965 } else if (oper == Operator.LogicalOr) {
2966 Label load_one = ig.DefineLabel ();
2967 Label end = ig.DefineLabel ();
2969 left.EmitBranchable (ec, load_one, true);
2971 ig.Emit (OpCodes.Br, end);
2973 ig.MarkLabel (load_one);
2974 ig.Emit (OpCodes.Ldc_I4_1);
2982 bool isUnsigned = is_unsigned (left.Type);
2985 case Operator.Multiply:
2987 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2988 opcode = OpCodes.Mul_Ovf;
2989 else if (isUnsigned)
2990 opcode = OpCodes.Mul_Ovf_Un;
2992 opcode = OpCodes.Mul;
2994 opcode = OpCodes.Mul;
2998 case Operator.Division:
3000 opcode = OpCodes.Div_Un;
3002 opcode = OpCodes.Div;
3005 case Operator.Modulus:
3007 opcode = OpCodes.Rem_Un;
3009 opcode = OpCodes.Rem;
3012 case Operator.Addition:
3014 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3015 opcode = OpCodes.Add_Ovf;
3016 else if (isUnsigned)
3017 opcode = OpCodes.Add_Ovf_Un;
3019 opcode = OpCodes.Add;
3021 opcode = OpCodes.Add;
3024 case Operator.Subtraction:
3026 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3027 opcode = OpCodes.Sub_Ovf;
3028 else if (isUnsigned)
3029 opcode = OpCodes.Sub_Ovf_Un;
3031 opcode = OpCodes.Sub;
3033 opcode = OpCodes.Sub;
3036 case Operator.RightShift:
3038 opcode = OpCodes.Shr_Un;
3040 opcode = OpCodes.Shr;
3043 case Operator.LeftShift:
3044 opcode = OpCodes.Shl;
3047 case Operator.Equality:
3048 opcode = OpCodes.Ceq;
3051 case Operator.Inequality:
3052 ig.Emit (OpCodes.Ceq);
3053 ig.Emit (OpCodes.Ldc_I4_0);
3055 opcode = OpCodes.Ceq;
3058 case Operator.LessThan:
3060 opcode = OpCodes.Clt_Un;
3062 opcode = OpCodes.Clt;
3065 case Operator.GreaterThan:
3067 opcode = OpCodes.Cgt_Un;
3069 opcode = OpCodes.Cgt;
3072 case Operator.LessThanOrEqual:
3073 Type lt = left.Type;
3075 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
3076 ig.Emit (OpCodes.Cgt_Un);
3078 ig.Emit (OpCodes.Cgt);
3079 ig.Emit (OpCodes.Ldc_I4_0);
3081 opcode = OpCodes.Ceq;
3084 case Operator.GreaterThanOrEqual:
3085 Type le = left.Type;
3087 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3088 ig.Emit (OpCodes.Clt_Un);
3090 ig.Emit (OpCodes.Clt);
3092 ig.Emit (OpCodes.Ldc_I4_0);
3094 opcode = OpCodes.Ceq;
3097 case Operator.BitwiseOr:
3098 opcode = OpCodes.Or;
3101 case Operator.BitwiseAnd:
3102 opcode = OpCodes.And;
3105 case Operator.ExclusiveOr:
3106 opcode = OpCodes.Xor;
3110 throw new Exception ("This should not happen: Operator = "
3111 + oper.ToString ());
3119 // Object created by Binary when the binary operator uses an method instead of being
3120 // a binary operation that maps to a CIL binary operation.
3122 public class BinaryMethod : Expression {
3123 public MethodBase method;
3124 public ArrayList Arguments;
3126 public BinaryMethod (Type t, MethodBase m, ArrayList args)
3131 eclass = ExprClass.Value;
3134 public override Expression DoResolve (EmitContext ec)
3139 public override void Emit (EmitContext ec)
3141 ILGenerator ig = ec.ig;
3143 if (Arguments != null)
3144 Invocation.EmitArguments (ec, method, Arguments);
3146 if (method is MethodInfo)
3147 ig.Emit (OpCodes.Call, (MethodInfo) method);
3149 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3154 // Object created with +/= on delegates
3156 public class BinaryDelegate : Expression {
3160 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3165 eclass = ExprClass.Value;
3168 public override Expression DoResolve (EmitContext ec)
3173 public override void Emit (EmitContext ec)
3175 ILGenerator ig = ec.ig;
3177 Invocation.EmitArguments (ec, method, args);
3179 ig.Emit (OpCodes.Call, (MethodInfo) method);
3180 ig.Emit (OpCodes.Castclass, type);
3183 public Expression Right {
3185 Argument arg = (Argument) args [1];
3190 public bool IsAddition {
3192 return method == TypeManager.delegate_combine_delegate_delegate;
3198 // User-defined conditional logical operator
3199 public class ConditionalLogicalOperator : Expression {
3200 Expression left, right;
3203 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3206 eclass = ExprClass.Value;
3210 this.is_and = is_and;
3213 protected void Error19 ()
3215 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3218 protected void Error218 ()
3220 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3221 "declarations of operator true and operator false");
3224 Expression op_true, op_false, op;
3226 public override Expression DoResolve (EmitContext ec)
3229 Expression operator_group;
3231 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3232 if (operator_group == null) {
3237 ArrayList arguments = new ArrayList ();
3238 arguments.Add (new Argument (left, Argument.AType.Expression));
3239 arguments.Add (new Argument (right, Argument.AType.Expression));
3240 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) operator_group, arguments, loc) as MethodInfo;
3241 if ((method == null) || (method.ReturnType != type)) {
3246 op = new StaticCallExpr (method, arguments, loc);
3248 op_true = GetOperatorTrue (ec, left, loc);
3249 op_false = GetOperatorFalse (ec, left, loc);
3250 if ((op_true == null) || (op_false == null)) {
3258 public override void Emit (EmitContext ec)
3260 ILGenerator ig = ec.ig;
3261 Label false_target = ig.DefineLabel ();
3262 Label end_target = ig.DefineLabel ();
3264 ig.Emit (OpCodes.Nop);
3266 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
3268 ig.Emit (OpCodes.Br, end_target);
3269 ig.MarkLabel (false_target);
3271 ig.MarkLabel (end_target);
3273 ig.Emit (OpCodes.Nop);
3277 public class PointerArithmetic : Expression {
3278 Expression left, right;
3282 // We assume that `l' is always a pointer
3284 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3287 eclass = ExprClass.Variable;
3291 is_add = is_addition;
3294 public override Expression DoResolve (EmitContext ec)
3297 // We are born fully resolved
3302 public override void Emit (EmitContext ec)
3304 Type op_type = left.Type;
3305 ILGenerator ig = ec.ig;
3306 int size = GetTypeSize (TypeManager.GetElementType (op_type));
3307 Type rtype = right.Type;
3309 if (rtype.IsPointer){
3311 // handle (pointer - pointer)
3315 ig.Emit (OpCodes.Sub);
3319 ig.Emit (OpCodes.Sizeof, op_type);
3321 IntLiteral.EmitInt (ig, size);
3322 ig.Emit (OpCodes.Div);
3324 ig.Emit (OpCodes.Conv_I8);
3327 // handle + and - on (pointer op int)
3330 ig.Emit (OpCodes.Conv_I);
3334 ig.Emit (OpCodes.Sizeof, op_type);
3336 IntLiteral.EmitInt (ig, size);
3337 if (rtype == TypeManager.int64_type)
3338 ig.Emit (OpCodes.Conv_I8);
3339 else if (rtype == TypeManager.uint64_type)
3340 ig.Emit (OpCodes.Conv_U8);
3341 ig.Emit (OpCodes.Mul);
3342 ig.Emit (OpCodes.Conv_I);
3345 ig.Emit (OpCodes.Add);
3347 ig.Emit (OpCodes.Sub);
3353 /// Implements the ternary conditional operator (?:)
3355 public class Conditional : Expression {
3356 Expression expr, trueExpr, falseExpr;
3358 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3361 this.trueExpr = trueExpr;
3362 this.falseExpr = falseExpr;
3366 public Expression Expr {
3372 public Expression TrueExpr {
3378 public Expression FalseExpr {
3384 public override Expression DoResolve (EmitContext ec)
3386 expr = expr.Resolve (ec);
3391 if (expr.Type != TypeManager.bool_type){
3392 expr = Expression.ResolveBoolean (
3399 trueExpr = trueExpr.Resolve (ec);
3400 falseExpr = falseExpr.Resolve (ec);
3402 if (trueExpr == null || falseExpr == null)
3405 eclass = ExprClass.Value;
3406 if (trueExpr.Type == falseExpr.Type)
3407 type = trueExpr.Type;
3410 Type true_type = trueExpr.Type;
3411 Type false_type = falseExpr.Type;
3413 if (trueExpr is NullLiteral){
3416 } else if (falseExpr is NullLiteral){
3422 // First, if an implicit conversion exists from trueExpr
3423 // to falseExpr, then the result type is of type falseExpr.Type
3425 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3428 // Check if both can convert implicitl to each other's type
3430 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3432 "Can not compute type of conditional expression " +
3433 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3434 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3435 "' convert implicitly to each other");
3440 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3444 Error (173, "The type of the conditional expression can " +
3445 "not be computed because there is no implicit conversion" +
3446 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3447 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3452 if (expr is BoolConstant){
3453 BoolConstant bc = (BoolConstant) expr;
3464 public override void Emit (EmitContext ec)
3466 ILGenerator ig = ec.ig;
3467 Label false_target = ig.DefineLabel ();
3468 Label end_target = ig.DefineLabel ();
3470 expr.EmitBranchable (ec, false_target, false);
3472 ig.Emit (OpCodes.Br, end_target);
3473 ig.MarkLabel (false_target);
3474 falseExpr.Emit (ec);
3475 ig.MarkLabel (end_target);
3483 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3484 public readonly string Name;
3485 public readonly Block Block;
3486 LocalInfo local_info;
3489 public LocalVariableReference (Block block, string name, Location l)
3494 eclass = ExprClass.Variable;
3497 // Setting `is_readonly' to false will allow you to create a writable
3498 // reference to a read-only variable. This is used by foreach and using.
3499 public LocalVariableReference (Block block, string name, Location l,
3500 LocalInfo local_info, bool is_readonly)
3501 : this (block, name, l)
3503 this.local_info = local_info;
3504 this.is_readonly = is_readonly;
3507 public VariableInfo VariableInfo {
3508 get { return local_info.VariableInfo; }
3511 public bool IsReadOnly {
3517 protected void DoResolveBase (EmitContext ec)
3519 if (local_info == null) {
3520 local_info = Block.GetLocalInfo (Name);
3521 is_readonly = local_info.ReadOnly;
3524 type = local_info.VariableType;
3526 if (ec.InAnonymousMethod)
3527 Block.LiftVariable (local_info);
3531 protected Expression DoResolve (EmitContext ec, bool is_lvalue)
3533 Expression e = Block.GetConstantExpression (Name);
3535 local_info.Used = true;
3536 eclass = ExprClass.Value;
3540 VariableInfo variable_info = local_info.VariableInfo;
3541 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3545 local_info.Used = true;
3547 if (local_info.LocalBuilder == null)
3548 return ec.RemapLocal (local_info);
3553 public override Expression DoResolve (EmitContext ec)
3557 return DoResolve (ec, false);
3560 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3564 VariableInfo variable_info = local_info.VariableInfo;
3565 if (variable_info != null)
3566 variable_info.SetAssigned (ec);
3568 Expression e = DoResolve (ec, true);
3574 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3578 if (local_info.LocalBuilder == null)
3579 return ec.RemapLocalLValue (local_info, right_side);
3584 public bool VerifyFixed (bool is_expression)
3586 return !is_expression || local_info.IsFixed;
3589 public override void Emit (EmitContext ec)
3591 ILGenerator ig = ec.ig;
3593 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3596 public void EmitAssign (EmitContext ec, Expression source)
3598 ILGenerator ig = ec.ig;
3601 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3604 public void AddressOf (EmitContext ec, AddressOp mode)
3606 ILGenerator ig = ec.ig;
3608 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3611 public override string ToString ()
3613 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3618 /// This represents a reference to a parameter in the intermediate
3621 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3627 public Parameter.Modifier mod;
3628 public bool is_ref, is_out;
3630 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3637 eclass = ExprClass.Variable;
3640 public VariableInfo VariableInfo {
3644 public bool VerifyFixed (bool is_expression)
3646 return !is_expression || TypeManager.IsValueType (type);
3649 public bool IsAssigned (EmitContext ec, Location loc)
3651 if (!ec.DoFlowAnalysis || !is_out ||
3652 ec.CurrentBranching.IsAssigned (vi))
3655 Report.Error (165, loc,
3656 "Use of unassigned parameter `" + name + "'");
3660 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3662 if (!ec.DoFlowAnalysis || !is_out ||
3663 ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3666 Report.Error (170, loc,
3667 "Use of possibly unassigned field `" + field_name + "'");
3671 public void SetAssigned (EmitContext ec)
3673 if (is_out && ec.DoFlowAnalysis)
3674 ec.CurrentBranching.SetAssigned (vi);
3677 public void SetFieldAssigned (EmitContext ec, string field_name)
3679 if (is_out && ec.DoFlowAnalysis)
3680 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3683 protected void DoResolveBase (EmitContext ec)
3685 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
3686 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3687 is_out = (mod & Parameter.Modifier.OUT) != 0;
3688 eclass = ExprClass.Variable;
3691 vi = block.ParameterMap [idx];
3695 // Notice that for ref/out parameters, the type exposed is not the
3696 // same type exposed externally.
3699 // externally we expose "int&"
3700 // here we expose "int".
3702 // We record this in "is_ref". This means that the type system can treat
3703 // the type as it is expected, but when we generate the code, we generate
3704 // the alternate kind of code.
3706 public override Expression DoResolve (EmitContext ec)
3710 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3713 if (ec.RemapToProxy)
3714 return ec.RemapParameter (idx);
3719 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3725 if (ec.RemapToProxy)
3726 return ec.RemapParameterLValue (idx, right_side);
3731 static public void EmitLdArg (ILGenerator ig, int x)
3735 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3736 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3737 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3738 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3739 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3742 ig.Emit (OpCodes.Ldarg, x);
3746 // This method is used by parameters that are references, that are
3747 // being passed as references: we only want to pass the pointer (that
3748 // is already stored in the parameter, not the address of the pointer,
3749 // and not the value of the variable).
3751 public void EmitLoad (EmitContext ec)
3753 ILGenerator ig = ec.ig;
3759 EmitLdArg (ig, arg_idx);
3762 public override void Emit (EmitContext ec)
3764 ILGenerator ig = ec.ig;
3771 EmitLdArg (ig, arg_idx);
3777 // If we are a reference, we loaded on the stack a pointer
3778 // Now lets load the real value
3780 LoadFromPtr (ig, type);
3783 public void EmitAssign (EmitContext ec, Expression source)
3785 ILGenerator ig = ec.ig;
3793 EmitLdArg (ig, arg_idx);
3798 StoreFromPtr (ig, type);
3801 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
3803 ig.Emit (OpCodes.Starg, arg_idx);
3807 public void AddressOf (EmitContext ec, AddressOp mode)
3816 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
3818 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
3821 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
3823 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
3830 /// Used for arguments to New(), Invocation()
3832 public class Argument {
3833 public enum AType : byte {
3839 public readonly AType ArgType;
3840 public Expression Expr;
3842 public Argument (Expression expr, AType type)
3845 this.ArgType = type;
3850 if (ArgType == AType.Ref || ArgType == AType.Out)
3851 return TypeManager.GetReferenceType (Expr.Type);
3857 public Parameter.Modifier GetParameterModifier ()
3861 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
3864 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
3867 return Parameter.Modifier.NONE;
3871 public static string FullDesc (Argument a)
3873 return (a.ArgType == AType.Ref ? "ref " :
3874 (a.ArgType == AType.Out ? "out " : "")) +
3875 TypeManager.CSharpName (a.Expr.Type);
3878 public bool ResolveMethodGroup (EmitContext ec, Location loc)
3880 // FIXME: csc doesn't report any error if you try to use `ref' or
3881 // `out' in a delegate creation expression.
3882 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
3889 public bool Resolve (EmitContext ec, Location loc)
3891 if (ArgType == AType.Ref) {
3892 Expr = Expr.Resolve (ec);
3896 Expr = Expr.ResolveLValue (ec, Expr);
3897 } else if (ArgType == AType.Out)
3898 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
3900 Expr = Expr.Resolve (ec);
3905 if (ArgType == AType.Expression)
3908 if (Expr.eclass != ExprClass.Variable){
3910 // We just probe to match the CSC output
3912 if (Expr.eclass == ExprClass.PropertyAccess ||
3913 Expr.eclass == ExprClass.IndexerAccess){
3916 "A property or indexer can not be passed as an out or ref " +
3921 "An lvalue is required as an argument to out or ref");
3929 public void Emit (EmitContext ec)
3932 // Ref and Out parameters need to have their addresses taken.
3934 // ParameterReferences might already be references, so we want
3935 // to pass just the value
3937 if (ArgType == AType.Ref || ArgType == AType.Out){
3938 AddressOp mode = AddressOp.Store;
3940 if (ArgType == AType.Ref)
3941 mode |= AddressOp.Load;
3943 if (Expr is ParameterReference){
3944 ParameterReference pr = (ParameterReference) Expr;
3950 pr.AddressOf (ec, mode);
3953 ((IMemoryLocation)Expr).AddressOf (ec, mode);
3960 /// Invocation of methods or delegates.
3962 public class Invocation : ExpressionStatement {
3963 public readonly ArrayList Arguments;
3966 MethodBase method = null;
3969 static Hashtable method_parameter_cache;
3971 static Invocation ()
3973 method_parameter_cache = new PtrHashtable ();
3977 // arguments is an ArrayList, but we do not want to typecast,
3978 // as it might be null.
3980 // FIXME: only allow expr to be a method invocation or a
3981 // delegate invocation (7.5.5)
3983 public Invocation (Expression expr, ArrayList arguments, Location l)
3986 Arguments = arguments;
3990 public Expression Expr {
3997 /// Returns the Parameters (a ParameterData interface) for the
4000 public static ParameterData GetParameterData (MethodBase mb)
4002 object pd = method_parameter_cache [mb];
4006 return (ParameterData) pd;
4009 ip = TypeManager.LookupParametersByBuilder (mb);
4011 method_parameter_cache [mb] = ip;
4013 return (ParameterData) ip;
4015 ParameterInfo [] pi = mb.GetParameters ();
4016 ReflectionParameters rp = new ReflectionParameters (pi);
4017 method_parameter_cache [mb] = rp;
4019 return (ParameterData) rp;
4024 /// Determines "better conversion" as specified in 7.4.2.3
4026 /// Returns : 1 if a->p is better
4027 /// 0 if a->q or neither is better
4029 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
4031 Type argument_type = a.Type;
4032 Expression argument_expr = a.Expr;
4034 if (argument_type == null)
4035 throw new Exception ("Expression of type " + a.Expr +
4036 " does not resolve its type");
4039 // This is a special case since csc behaves this way. I can't find
4040 // it anywhere in the spec but oh well ...
4042 if (argument_expr is NullLiteral &&
4043 p == TypeManager.string_type &&
4044 q == TypeManager.object_type)
4046 else if (argument_expr is NullLiteral &&
4047 p == TypeManager.object_type &&
4048 q == TypeManager.string_type)
4054 if (argument_type == p)
4057 if (argument_type == q)
4061 // Now probe whether an implicit constant expression conversion
4064 // An implicit constant expression conversion permits the following
4067 // * A constant-expression of type `int' can be converted to type
4068 // sbyte, byute, short, ushort, uint, ulong provided the value of
4069 // of the expression is withing the range of the destination type.
4071 // * A constant-expression of type long can be converted to type
4072 // ulong, provided the value of the constant expression is not negative
4074 // FIXME: Note that this assumes that constant folding has
4075 // taken place. We dont do constant folding yet.
4078 if (argument_expr is IntConstant){
4079 IntConstant ei = (IntConstant) argument_expr;
4080 int value = ei.Value;
4082 if (p == TypeManager.sbyte_type){
4083 if (value >= SByte.MinValue && value <= SByte.MaxValue)
4085 } else if (p == TypeManager.byte_type){
4086 if (q == TypeManager.sbyte_type &&
4087 value >= SByte.MinValue && value <= SByte.MaxValue)
4089 else if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
4091 } else if (p == TypeManager.short_type){
4092 if (value >= Int16.MinValue && value <= Int16.MaxValue)
4094 } else if (p == TypeManager.ushort_type){
4095 if (q == TypeManager.short_type &&
4096 value >= Int16.MinValue && value <= Int16.MaxValue)
4098 else if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
4100 } else if (p == TypeManager.int32_type){
4101 if (value >= Int32.MinValue && value <= Int32.MaxValue)
4103 } else if (p == TypeManager.uint32_type){
4105 // we can optimize this case: a positive int32
4106 // always fits on a uint32
4110 } else if (p == TypeManager.uint64_type){
4112 // we can optimize this case: a positive int32
4113 // always fits on a uint64
4117 // This special case is needed because csc behaves like this.
4118 // int -> uint is better than int -> ulong!
4120 if (q == TypeManager.uint32_type)
4123 if (q == TypeManager.int64_type)
4125 else if (value >= 0)
4127 } else if (p == TypeManager.int64_type){
4130 } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
4131 LongConstant lc = (LongConstant) argument_expr;
4133 if (p == TypeManager.uint64_type){
4140 Expression tmp = Convert.ImplicitConversion (ec, argument_expr, p, loc);
4148 Expression p_tmp = new EmptyExpression (p);
4149 Expression q_tmp = new EmptyExpression (q);
4151 if (Convert.ImplicitConversionExists (ec, p_tmp, q) == true &&
4152 Convert.ImplicitConversionExists (ec, q_tmp, p) == false)
4155 if (p == TypeManager.sbyte_type)
4156 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4157 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4160 if (p == TypeManager.short_type)
4161 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4162 q == TypeManager.uint64_type)
4165 if (p == TypeManager.int32_type)
4166 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4169 if (p == TypeManager.int64_type)
4170 if (q == TypeManager.uint64_type)
4177 /// Determines "Better function" between candidate
4178 /// and the current best match
4181 /// Returns an integer indicating :
4182 /// 0 if candidate ain't better
4183 /// 1 if candidate is better than the current best match
4185 static int BetterFunction (EmitContext ec, ArrayList args,
4186 MethodBase candidate, bool candidate_params,
4187 MethodBase best, bool best_params,
4190 ParameterData candidate_pd = GetParameterData (candidate);
4191 ParameterData best_pd;
4197 argument_count = args.Count;
4199 int cand_count = candidate_pd.Count;
4202 // If there is no best method, than this one
4203 // is better, however, if we already found a
4204 // best method, we cant tell. This happens
4216 // interface IFooBar : IFoo, IBar {}
4218 // We cant tell if IFoo.DoIt is better than IBar.DoIt
4220 // However, we have to consider that
4221 // Trim (); is better than Trim (params char[] chars);
4222 if (cand_count == 0 && argument_count == 0)
4223 return best == null || best_params ? 1 : 0;
4225 if (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS)
4226 if (cand_count != argument_count)
4232 if (argument_count == 0 && cand_count == 1 &&
4233 candidate_pd.ParameterModifier (cand_count - 1) == Parameter.Modifier.PARAMS)
4236 for (int j = 0; j < argument_count; ++j) {
4238 Argument a = (Argument) args [j];
4239 Type t = candidate_pd.ParameterType (j);
4241 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4242 if (candidate_params)
4243 t = TypeManager.GetElementType (t);
4245 x = BetterConversion (ec, a, t, null, loc);
4257 best_pd = GetParameterData (best);
4259 int rating1 = 0, rating2 = 0;
4261 for (int j = 0; j < argument_count; ++j) {
4264 Argument a = (Argument) args [j];
4266 Type ct = candidate_pd.ParameterType (j);
4267 Type bt = best_pd.ParameterType (j);
4269 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4270 if (candidate_params)
4271 ct = TypeManager.GetElementType (ct);
4273 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4275 bt = TypeManager.GetElementType (bt);
4277 x = BetterConversion (ec, a, ct, bt, loc);
4278 y = BetterConversion (ec, a, bt, ct, loc);
4288 // If a method (in the normal form) with the
4289 // same signature as the expanded form of the
4290 // current best params method already exists,
4291 // the expanded form is not applicable so we
4292 // force it to select the candidate
4294 if (!candidate_params && best_params && cand_count == argument_count)
4297 if (rating1 > rating2)
4303 public static string FullMethodDesc (MethodBase mb)
4305 string ret_type = "";
4307 if (mb is MethodInfo)
4308 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
4310 StringBuilder sb = new StringBuilder (ret_type);
4312 sb.Append (mb.ReflectedType.ToString ());
4314 sb.Append (mb.Name);
4316 ParameterData pd = GetParameterData (mb);
4318 int count = pd.Count;
4321 for (int i = count; i > 0; ) {
4324 sb.Append (pd.ParameterDesc (count - i - 1));
4330 return sb.ToString ();
4333 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4335 MemberInfo [] miset;
4336 MethodGroupExpr union;
4341 return (MethodGroupExpr) mg2;
4344 return (MethodGroupExpr) mg1;
4347 MethodGroupExpr left_set = null, right_set = null;
4348 int length1 = 0, length2 = 0;
4350 left_set = (MethodGroupExpr) mg1;
4351 length1 = left_set.Methods.Length;
4353 right_set = (MethodGroupExpr) mg2;
4354 length2 = right_set.Methods.Length;
4356 ArrayList common = new ArrayList ();
4358 foreach (MethodBase r in right_set.Methods){
4359 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
4363 miset = new MemberInfo [length1 + length2 - common.Count];
4364 left_set.Methods.CopyTo (miset, 0);
4368 foreach (MethodBase r in right_set.Methods) {
4369 if (!common.Contains (r))
4373 union = new MethodGroupExpr (miset, loc);
4379 /// Determines if the candidate method, if a params method, is applicable
4380 /// in its expanded form to the given set of arguments
4382 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
4386 if (arguments == null)
4389 arg_count = arguments.Count;
4391 ParameterData pd = GetParameterData (candidate);
4393 int pd_count = pd.Count;
4398 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
4401 if (pd_count - 1 > arg_count)
4404 if (pd_count == 1 && arg_count == 0)
4408 // If we have come this far, the case which
4409 // remains is when the number of parameters is
4410 // less than or equal to the argument count.
4412 for (int i = 0; i < pd_count - 1; ++i) {
4414 Argument a = (Argument) arguments [i];
4416 Parameter.Modifier a_mod = a.GetParameterModifier () &
4417 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4418 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4419 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4421 if (a_mod == p_mod) {
4423 if (a_mod == Parameter.Modifier.NONE)
4424 if (!Convert.ImplicitConversionExists (ec,
4426 pd.ParameterType (i)))
4429 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4430 Type pt = pd.ParameterType (i);
4433 pt = TypeManager.GetReferenceType (pt);
4443 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4445 for (int i = pd_count - 1; i < arg_count; i++) {
4446 Argument a = (Argument) arguments [i];
4448 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4456 /// Determines if the candidate method is applicable (section 14.4.2.1)
4457 /// to the given set of arguments
4459 static bool IsApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
4463 if (arguments == null)
4466 arg_count = arguments.Count;
4469 ParameterData pd = GetParameterData (candidate);
4471 if (arg_count != pd.Count)
4474 for (int i = arg_count; i > 0; ) {
4477 Argument a = (Argument) arguments [i];
4479 Parameter.Modifier a_mod = a.GetParameterModifier () &
4480 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4481 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4482 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4485 if (a_mod == p_mod ||
4486 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4487 if (a_mod == Parameter.Modifier.NONE) {
4488 if (!Convert.ImplicitConversionExists (ec,
4490 pd.ParameterType (i)))
4494 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4495 Type pt = pd.ParameterType (i);
4498 pt = TypeManager.GetReferenceType (pt);
4513 /// Find the Applicable Function Members (7.4.2.1)
4515 /// me: Method Group expression with the members to select.
4516 /// it might contain constructors or methods (or anything
4517 /// that maps to a method).
4519 /// Arguments: ArrayList containing resolved Argument objects.
4521 /// loc: The location if we want an error to be reported, or a Null
4522 /// location for "probing" purposes.
4524 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4525 /// that is the best match of me on Arguments.
4528 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4529 ArrayList Arguments, Location loc)
4531 MethodBase method = null;
4532 Type applicable_type = null;
4534 ArrayList candidates = new ArrayList ();
4537 // Used to keep a map between the candidate
4538 // and whether it is being considered in its
4539 // normal or expanded form
4541 Hashtable candidate_to_form = new PtrHashtable ();
4545 // First we construct the set of applicable methods
4547 // We start at the top of the type hierarchy and
4548 // go down to find applicable methods
4550 applicable_type = me.DeclaringType;
4552 if (me.Name == "Invoke" && TypeManager.IsDelegateType (applicable_type)) {
4553 Error_InvokeOnDelegate (loc);
4557 bool found_applicable = false;
4559 foreach (MethodBase candidate in me.Methods){
4560 Type decl_type = candidate.DeclaringType;
4563 // If we have already found an applicable method
4564 // we eliminate all base types (Section 14.5.5.1)
4566 if (decl_type != applicable_type &&
4567 (applicable_type.IsSubclassOf (decl_type) ||
4568 TypeManager.ImplementsInterface (applicable_type, decl_type)) &&
4573 // Check if candidate is applicable (section 14.4.2.1)
4574 if (IsApplicable (ec, Arguments, candidate)) {
4575 // Candidate is applicable in normal form
4576 candidates.Add (candidate);
4577 applicable_type = candidate.DeclaringType;
4578 found_applicable = true;
4579 candidate_to_form [candidate] = false;
4581 if (IsParamsMethodApplicable (ec, Arguments, candidate)) {
4582 // Candidate is applicable in expanded form
4583 candidates.Add (candidate);
4584 applicable_type = candidate.DeclaringType;
4585 found_applicable = true;
4586 candidate_to_form [candidate] = true;
4593 // Now we actually find the best method
4595 int candidate_top = candidates.Count;
4596 for (int ix = 0; ix < candidate_top; ix++){
4597 MethodBase candidate = (MethodBase) candidates [ix];
4599 bool cand_params = (bool) candidate_to_form [candidate];
4600 bool method_params = false;
4603 method_params = (bool) candidate_to_form [method];
4605 int x = BetterFunction (ec, Arguments,
4606 candidate, cand_params,
4607 method, method_params,
4616 if (Arguments == null)
4619 argument_count = Arguments.Count;
4622 if (method == null) {
4624 // Okay so we have failed to find anything so we
4625 // return by providing info about the closest match
4627 for (int i = 0; i < me.Methods.Length; ++i) {
4629 MethodBase c = (MethodBase) me.Methods [i];
4630 ParameterData pd = GetParameterData (c);
4632 if (pd.Count != argument_count)
4635 VerifyArgumentsCompat (ec, Arguments, argument_count, c, false,
4640 if (!Location.IsNull (loc)) {
4641 string report_name = me.Name;
4642 if (report_name == ".ctor")
4643 report_name = me.DeclaringType.ToString ();
4645 Error_WrongNumArguments (loc, report_name, argument_count);
4652 // Now check that there are no ambiguities i.e the selected method
4653 // should be better than all the others
4655 bool best_params = (bool) candidate_to_form [method];
4657 for (int ix = 0; ix < candidate_top; ix++){
4658 MethodBase candidate = (MethodBase) candidates [ix];
4660 if (candidate == method)
4664 // If a normal method is applicable in
4665 // the sense that it has the same
4666 // number of arguments, then the
4667 // expanded params method is never
4668 // applicable so we debar the params
4671 if ((IsParamsMethodApplicable (ec, Arguments, candidate) &&
4672 IsApplicable (ec, Arguments, method)))
4675 bool cand_params = (bool) candidate_to_form [candidate];
4676 int x = BetterFunction (ec, Arguments,
4677 method, best_params,
4678 candidate, cand_params,
4684 "Ambiguous call when selecting function due to implicit casts");
4690 // And now check if the arguments are all
4691 // compatible, perform conversions if
4692 // necessary etc. and return if everything is
4695 if (!VerifyArgumentsCompat (ec, Arguments, argument_count, method,
4696 best_params, null, loc))
4702 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
4704 Report.Error (1501, loc,
4705 "No overload for method `" + name + "' takes `" +
4706 arg_count + "' arguments");
4709 static void Error_InvokeOnDelegate (Location loc)
4711 Report.Error (1533, loc,
4712 "Invoke cannot be called directly on a delegate");
4715 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
4716 Type delegate_type, string arg_sig, string par_desc)
4718 if (delegate_type == null)
4719 Report.Error (1502, loc,
4720 "The best overloaded match for method '" +
4721 FullMethodDesc (method) +
4722 "' has some invalid arguments");
4724 Report.Error (1594, loc,
4725 "Delegate '" + delegate_type.ToString () +
4726 "' has some invalid arguments.");
4727 Report.Error (1503, loc,
4728 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
4729 idx, arg_sig, par_desc));
4732 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
4735 bool chose_params_expanded,
4739 ParameterData pd = GetParameterData (method);
4740 int pd_count = pd.Count;
4742 for (int j = 0; j < argument_count; j++) {
4743 Argument a = (Argument) Arguments [j];
4744 Expression a_expr = a.Expr;
4745 Type parameter_type = pd.ParameterType (j);
4746 Parameter.Modifier pm = pd.ParameterModifier (j);
4748 if (pm == Parameter.Modifier.PARAMS){
4749 if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
4750 if (!Location.IsNull (loc))
4751 Error_InvalidArguments (
4752 loc, j, method, delegate_type,
4753 Argument.FullDesc (a), pd.ParameterDesc (j));
4757 if (chose_params_expanded)
4758 parameter_type = TypeManager.GetElementType (parameter_type);
4763 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
4764 if (!Location.IsNull (loc))
4765 Error_InvalidArguments (
4766 loc, j, method, delegate_type,
4767 Argument.FullDesc (a), pd.ParameterDesc (j));
4775 if (a.Type != parameter_type){
4778 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
4781 if (!Location.IsNull (loc))
4782 Error_InvalidArguments (
4783 loc, j, method, delegate_type,
4784 Argument.FullDesc (a), pd.ParameterDesc (j));
4789 // Update the argument with the implicit conversion
4795 Parameter.Modifier a_mod = a.GetParameterModifier () &
4796 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4797 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
4798 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4800 if (a_mod != p_mod &&
4801 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
4802 if (!Location.IsNull (loc)) {
4803 Report.Error (1502, loc,
4804 "The best overloaded match for method '" + FullMethodDesc (method)+
4805 "' has some invalid arguments");
4806 Report.Error (1503, loc,
4807 "Argument " + (j+1) +
4808 ": Cannot convert from '" + Argument.FullDesc (a)
4809 + "' to '" + pd.ParameterDesc (j) + "'");
4819 public override Expression DoResolve (EmitContext ec)
4822 // First, resolve the expression that is used to
4823 // trigger the invocation
4825 if (expr is BaseAccess)
4828 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4832 if (!(expr is MethodGroupExpr)) {
4833 Type expr_type = expr.Type;
4835 if (expr_type != null){
4836 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
4838 return (new DelegateInvocation (
4839 this.expr, Arguments, loc)).Resolve (ec);
4843 if (!(expr is MethodGroupExpr)){
4844 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup);
4849 // Next, evaluate all the expressions in the argument list
4851 if (Arguments != null){
4852 foreach (Argument a in Arguments){
4853 if (!a.Resolve (ec, loc))
4858 MethodGroupExpr mg = (MethodGroupExpr) expr;
4859 method = OverloadResolve (ec, mg, Arguments, loc);
4861 if (method == null){
4863 "Could not find any applicable function for this argument list");
4867 MethodInfo mi = method as MethodInfo;
4869 type = TypeManager.TypeToCoreType (mi.ReturnType);
4870 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null))
4871 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
4874 if (type.IsPointer){
4882 // Only base will allow this invocation to happen.
4884 if (is_base && method.IsAbstract){
4885 Report.Error (205, loc, "Cannot call an abstract base member: " +
4886 FullMethodDesc (method));
4890 if ((method.Attributes & MethodAttributes.SpecialName) != 0){
4891 if (TypeManager.IsSpecialMethod (method))
4892 Report.Error (571, loc, method.Name + ": can not call operator or accessor");
4895 eclass = ExprClass.Value;
4900 // Emits the list of arguments as an array
4902 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
4904 ILGenerator ig = ec.ig;
4905 int count = arguments.Count - idx;
4906 Argument a = (Argument) arguments [idx];
4907 Type t = a.Expr.Type;
4908 string array_type = t.FullName + "[]";
4911 array = ig.DeclareLocal (TypeManager.LookupType (array_type));
4912 IntConstant.EmitInt (ig, count);
4913 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
4914 ig.Emit (OpCodes.Stloc, array);
4916 int top = arguments.Count;
4917 for (int j = idx; j < top; j++){
4918 a = (Argument) arguments [j];
4920 ig.Emit (OpCodes.Ldloc, array);
4921 IntConstant.EmitInt (ig, j - idx);
4924 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj);
4926 ig.Emit (OpCodes.Ldelema, t);
4931 ig.Emit (OpCodes.Stobj, t);
4935 ig.Emit (OpCodes.Ldloc, array);
4939 /// Emits a list of resolved Arguments that are in the arguments
4942 /// The MethodBase argument might be null if the
4943 /// emission of the arguments is known not to contain
4944 /// a `params' field (for example in constructors or other routines
4945 /// that keep their arguments in this structure)
4947 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
4951 pd = GetParameterData (mb);
4956 // If we are calling a params method with no arguments, special case it
4958 if (arguments == null){
4959 if (pd != null && pd.Count > 0 &&
4960 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
4961 ILGenerator ig = ec.ig;
4963 IntConstant.EmitInt (ig, 0);
4964 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
4970 int top = arguments.Count;
4972 for (int i = 0; i < top; i++){
4973 Argument a = (Argument) arguments [i];
4976 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
4978 // Special case if we are passing the same data as the
4979 // params argument, do not put it in an array.
4981 if (pd.ParameterType (i) == a.Type)
4984 EmitParams (ec, i, arguments);
4992 if (pd != null && pd.Count > top &&
4993 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
4994 ILGenerator ig = ec.ig;
4996 IntConstant.EmitInt (ig, 0);
4997 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
5002 /// is_base tells whether we want to force the use of the `call'
5003 /// opcode instead of using callvirt. Call is required to call
5004 /// a specific method, while callvirt will always use the most
5005 /// recent method in the vtable.
5007 /// is_static tells whether this is an invocation on a static method
5009 /// instance_expr is an expression that represents the instance
5010 /// it must be non-null if is_static is false.
5012 /// method is the method to invoke.
5014 /// Arguments is the list of arguments to pass to the method or constructor.
5016 public static void EmitCall (EmitContext ec, bool is_base,
5017 bool is_static, Expression instance_expr,
5018 MethodBase method, ArrayList Arguments, Location loc)
5020 ILGenerator ig = ec.ig;
5021 bool struct_call = false;
5023 Type decl_type = method.DeclaringType;
5025 if (!RootContext.StdLib) {
5026 // Replace any calls to the system's System.Array type with calls to
5027 // the newly created one.
5028 if (method == TypeManager.system_int_array_get_length)
5029 method = TypeManager.int_array_get_length;
5030 else if (method == TypeManager.system_int_array_get_rank)
5031 method = TypeManager.int_array_get_rank;
5032 else if (method == TypeManager.system_object_array_clone)
5033 method = TypeManager.object_array_clone;
5034 else if (method == TypeManager.system_int_array_get_length_int)
5035 method = TypeManager.int_array_get_length_int;
5036 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5037 method = TypeManager.int_array_get_lower_bound_int;
5038 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5039 method = TypeManager.int_array_get_upper_bound_int;
5040 else if (method == TypeManager.system_void_array_copyto_array_int)
5041 method = TypeManager.void_array_copyto_array_int;
5045 // This checks the `ConditionalAttribute' on the method, and the
5046 // ObsoleteAttribute
5048 TypeManager.MethodFlags flags = TypeManager.GetMethodFlags (method, loc);
5049 if ((flags & TypeManager.MethodFlags.IsObsoleteError) != 0)
5051 if ((flags & TypeManager.MethodFlags.ShouldIgnore) != 0)
5055 if (decl_type.IsValueType)
5058 // If this is ourselves, push "this"
5060 if (instance_expr == null){
5061 ig.Emit (OpCodes.Ldarg_0);
5064 // Push the instance expression
5066 if (instance_expr.Type.IsValueType){
5068 // Special case: calls to a function declared in a
5069 // reference-type with a value-type argument need
5070 // to have their value boxed.
5073 if (decl_type.IsValueType){
5075 // If the expression implements IMemoryLocation, then
5076 // we can optimize and use AddressOf on the
5079 // If not we have to use some temporary storage for
5081 if (instance_expr is IMemoryLocation){
5082 ((IMemoryLocation)instance_expr).
5083 AddressOf (ec, AddressOp.LoadStore);
5086 Type t = instance_expr.Type;
5088 instance_expr.Emit (ec);
5089 LocalBuilder temp = ig.DeclareLocal (t);
5090 ig.Emit (OpCodes.Stloc, temp);
5091 ig.Emit (OpCodes.Ldloca, temp);
5094 instance_expr.Emit (ec);
5095 ig.Emit (OpCodes.Box, instance_expr.Type);
5098 instance_expr.Emit (ec);
5102 EmitArguments (ec, method, Arguments);
5104 if (is_static || struct_call || is_base){
5105 if (method is MethodInfo) {
5106 ig.Emit (OpCodes.Call, (MethodInfo) method);
5108 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5110 if (method is MethodInfo)
5111 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
5113 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
5117 public override void Emit (EmitContext ec)
5119 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5121 EmitCall (ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5124 public override void EmitStatement (EmitContext ec)
5129 // Pop the return value if there is one
5131 if (method is MethodInfo){
5132 Type ret = ((MethodInfo)method).ReturnType;
5133 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5134 ec.ig.Emit (OpCodes.Pop);
5139 public class InvocationOrCast : ExpressionStatement
5142 Expression argument;
5144 public InvocationOrCast (Expression expr, Expression argument, Location loc)
5147 this.argument = argument;
5151 public override Expression DoResolve (EmitContext ec)
5154 // First try to resolve it as a cast.
5156 type = ec.DeclSpace.ResolveType (expr, true, loc);
5158 Cast cast = new Cast (new TypeExpression (type, loc), argument, loc);
5159 return cast.Resolve (ec);
5163 // This can either be a type or a delegate invocation.
5164 // Let's just resolve it and see what we'll get.
5166 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5171 // Ok, so it's a Cast.
5173 if (expr.eclass == ExprClass.Type) {
5174 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
5175 return cast.Resolve (ec);
5179 // It's a delegate invocation.
5181 if (!TypeManager.IsDelegateType (expr.Type)) {
5182 Error (149, "Method name expected");
5186 ArrayList args = new ArrayList ();
5187 args.Add (new Argument (argument, Argument.AType.Expression));
5188 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5189 return invocation.Resolve (ec);
5194 Error (201, "Only assignment, call, increment, decrement and new object " +
5195 "expressions can be used as a statement");
5198 public override ExpressionStatement ResolveStatement (EmitContext ec)
5201 // First try to resolve it as a cast.
5203 type = ec.DeclSpace.ResolveType (expr, true, loc);
5210 // This can either be a type or a delegate invocation.
5211 // Let's just resolve it and see what we'll get.
5213 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5214 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5220 // It's a delegate invocation.
5222 if (!TypeManager.IsDelegateType (expr.Type)) {
5223 Error (149, "Method name expected");
5227 ArrayList args = new ArrayList ();
5228 args.Add (new Argument (argument, Argument.AType.Expression));
5229 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5230 return invocation.ResolveStatement (ec);
5233 public override void Emit (EmitContext ec)
5235 throw new Exception ("Cannot happen");
5238 public override void EmitStatement (EmitContext ec)
5240 throw new Exception ("Cannot happen");
5245 // This class is used to "disable" the code generation for the
5246 // temporary variable when initializing value types.
5248 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5249 public void AddressOf (EmitContext ec, AddressOp Mode)
5256 /// Implements the new expression
5258 public class New : ExpressionStatement, IMemoryLocation {
5259 public readonly ArrayList Arguments;
5262 // During bootstrap, it contains the RequestedType,
5263 // but if `type' is not null, it *might* contain a NewDelegate
5264 // (because of field multi-initialization)
5266 public Expression RequestedType;
5268 MethodBase method = null;
5271 // If set, the new expression is for a value_target, and
5272 // we will not leave anything on the stack.
5274 Expression value_target;
5275 bool value_target_set = false;
5277 public New (Expression requested_type, ArrayList arguments, Location l)
5279 RequestedType = requested_type;
5280 Arguments = arguments;
5284 public bool SetValueTypeVariable (Expression value)
5286 value_target = value;
5287 value_target_set = true;
5288 if (!(value_target is IMemoryLocation)){
5289 Error_UnexpectedKind ("variable");
5296 // This function is used to disable the following code sequence for
5297 // value type initialization:
5299 // AddressOf (temporary)
5303 // Instead the provide will have provided us with the address on the
5304 // stack to store the results.
5306 static Expression MyEmptyExpression;
5308 public void DisableTemporaryValueType ()
5310 if (MyEmptyExpression == null)
5311 MyEmptyExpression = new EmptyAddressOf ();
5314 // To enable this, look into:
5315 // test-34 and test-89 and self bootstrapping.
5317 // For instance, we can avoid a copy by using `newobj'
5318 // instead of Call + Push-temp on value types.
5319 // value_target = MyEmptyExpression;
5322 public override Expression DoResolve (EmitContext ec)
5325 // The New DoResolve might be called twice when initializing field
5326 // expressions (see EmitFieldInitializers, the call to
5327 // GetInitializerExpression will perform a resolve on the expression,
5328 // and later the assign will trigger another resolution
5330 // This leads to bugs (#37014)
5333 if (RequestedType is NewDelegate)
5334 return RequestedType;
5338 type = ec.DeclSpace.ResolveType (RequestedType, false, loc);
5343 bool IsDelegate = TypeManager.IsDelegateType (type);
5346 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5347 if (RequestedType != null)
5348 if (!(RequestedType is NewDelegate))
5349 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
5350 return RequestedType;
5353 if (type.IsInterface || type.IsAbstract){
5354 Error (144, "It is not possible to create instances of interfaces or abstract classes");
5358 bool is_struct = type.IsValueType;
5359 eclass = ExprClass.Value;
5362 // SRE returns a match for .ctor () on structs (the object constructor),
5363 // so we have to manually ignore it.
5365 if (is_struct && Arguments == null)
5369 ml = MemberLookupFinal (ec, null, type, ".ctor",
5370 MemberTypes.Constructor,
5371 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5376 if (! (ml is MethodGroupExpr)){
5378 ml.Error_UnexpectedKind ("method group");
5384 if (Arguments != null){
5385 foreach (Argument a in Arguments){
5386 if (!a.Resolve (ec, loc))
5391 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
5395 if (method == null) {
5396 if (!is_struct || Arguments.Count > 0) {
5397 Error (1501, String.Format (
5398 "New invocation: Can not find a constructor in `{0}' for this argument list",
5399 TypeManager.CSharpName (type)));
5408 // This DoEmit can be invoked in two contexts:
5409 // * As a mechanism that will leave a value on the stack (new object)
5410 // * As one that wont (init struct)
5412 // You can control whether a value is required on the stack by passing
5413 // need_value_on_stack. The code *might* leave a value on the stack
5414 // so it must be popped manually
5416 // If we are dealing with a ValueType, we have a few
5417 // situations to deal with:
5419 // * The target is a ValueType, and we have been provided
5420 // the instance (this is easy, we are being assigned).
5422 // * The target of New is being passed as an argument,
5423 // to a boxing operation or a function that takes a
5426 // In this case, we need to create a temporary variable
5427 // that is the argument of New.
5429 // Returns whether a value is left on the stack
5431 bool DoEmit (EmitContext ec, bool need_value_on_stack)
5433 bool is_value_type = type.IsValueType;
5434 ILGenerator ig = ec.ig;
5439 // Allow DoEmit() to be called multiple times.
5440 // We need to create a new LocalTemporary each time since
5441 // you can't share LocalBuilders among ILGeneators.
5442 if (!value_target_set)
5443 value_target = new LocalTemporary (ec, type);
5445 ml = (IMemoryLocation) value_target;
5446 ml.AddressOf (ec, AddressOp.Store);
5450 Invocation.EmitArguments (ec, method, Arguments);
5454 ig.Emit (OpCodes.Initobj, type);
5456 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5457 if (need_value_on_stack){
5458 value_target.Emit (ec);
5463 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
5468 public override void Emit (EmitContext ec)
5473 public override void EmitStatement (EmitContext ec)
5475 if (DoEmit (ec, false))
5476 ec.ig.Emit (OpCodes.Pop);
5479 public void AddressOf (EmitContext ec, AddressOp Mode)
5481 if (!type.IsValueType){
5483 // We throw an exception. So far, I believe we only need to support
5485 // foreach (int j in new StructType ())
5488 throw new Exception ("AddressOf should not be used for classes");
5491 if (!value_target_set)
5492 value_target = new LocalTemporary (ec, type);
5494 IMemoryLocation ml = (IMemoryLocation) value_target;
5495 ml.AddressOf (ec, AddressOp.Store);
5497 Invocation.EmitArguments (ec, method, Arguments);
5500 ec.ig.Emit (OpCodes.Initobj, type);
5502 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5504 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
5509 /// 14.5.10.2: Represents an array creation expression.
5513 /// There are two possible scenarios here: one is an array creation
5514 /// expression that specifies the dimensions and optionally the
5515 /// initialization data and the other which does not need dimensions
5516 /// specified but where initialization data is mandatory.
5518 public class ArrayCreation : ExpressionStatement {
5519 Expression requested_base_type;
5520 ArrayList initializers;
5523 // The list of Argument types.
5524 // This is used to construct the `newarray' or constructor signature
5526 ArrayList arguments;
5529 // Method used to create the array object.
5531 MethodBase new_method = null;
5533 Type array_element_type;
5534 Type underlying_type;
5535 bool is_one_dimensional = false;
5536 bool is_builtin_type = false;
5537 bool expect_initializers = false;
5538 int num_arguments = 0;
5542 ArrayList array_data;
5547 // The number of array initializers that we can handle
5548 // via the InitializeArray method - through EmitStaticInitializers
5550 int num_automatic_initializers;
5552 const int max_automatic_initializers = 6;
5554 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
5556 this.requested_base_type = requested_base_type;
5557 this.initializers = initializers;
5561 arguments = new ArrayList ();
5563 foreach (Expression e in exprs) {
5564 arguments.Add (new Argument (e, Argument.AType.Expression));
5569 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
5571 this.requested_base_type = requested_base_type;
5572 this.initializers = initializers;
5576 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
5578 //string tmp = rank.Substring (rank.LastIndexOf ('['));
5580 //dimensions = tmp.Length - 1;
5581 expect_initializers = true;
5584 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
5586 StringBuilder sb = new StringBuilder (rank);
5589 for (int i = 1; i < idx_count; i++)
5594 return new ComposedCast (base_type, sb.ToString (), loc);
5597 void Error_IncorrectArrayInitializer ()
5599 Error (178, "Incorrectly structured array initializer");
5602 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
5604 if (specified_dims) {
5605 Argument a = (Argument) arguments [idx];
5607 if (!a.Resolve (ec, loc))
5610 if (!(a.Expr is Constant)) {
5611 Error (150, "A constant value is expected");
5615 int value = (int) ((Constant) a.Expr).GetValue ();
5617 if (value != probe.Count) {
5618 Error_IncorrectArrayInitializer ();
5622 bounds [idx] = value;
5625 int child_bounds = -1;
5626 foreach (object o in probe) {
5627 if (o is ArrayList) {
5628 int current_bounds = ((ArrayList) o).Count;
5630 if (child_bounds == -1)
5631 child_bounds = current_bounds;
5633 else if (child_bounds != current_bounds){
5634 Error_IncorrectArrayInitializer ();
5637 if (specified_dims && (idx + 1 >= arguments.Count)){
5638 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
5642 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
5646 if (child_bounds != -1){
5647 Error_IncorrectArrayInitializer ();
5651 Expression tmp = (Expression) o;
5652 tmp = tmp.Resolve (ec);
5656 // Console.WriteLine ("I got: " + tmp);
5657 // Handle initialization from vars, fields etc.
5659 Expression conv = Convert.ImplicitConversionRequired (
5660 ec, tmp, underlying_type, loc);
5665 if (conv is StringConstant)
5666 array_data.Add (conv);
5667 else if (conv is Constant) {
5668 array_data.Add (conv);
5669 num_automatic_initializers++;
5671 array_data.Add (conv);
5678 public void UpdateIndices (EmitContext ec)
5681 for (ArrayList probe = initializers; probe != null;) {
5682 if (probe.Count > 0 && probe [0] is ArrayList) {
5683 Expression e = new IntConstant (probe.Count);
5684 arguments.Add (new Argument (e, Argument.AType.Expression));
5686 bounds [i++] = probe.Count;
5688 probe = (ArrayList) probe [0];
5691 Expression e = new IntConstant (probe.Count);
5692 arguments.Add (new Argument (e, Argument.AType.Expression));
5694 bounds [i++] = probe.Count;
5701 public bool ValidateInitializers (EmitContext ec, Type array_type)
5703 if (initializers == null) {
5704 if (expect_initializers)
5710 if (underlying_type == null)
5714 // We use this to store all the date values in the order in which we
5715 // will need to store them in the byte blob later
5717 array_data = new ArrayList ();
5718 bounds = new Hashtable ();
5722 if (arguments != null) {
5723 ret = CheckIndices (ec, initializers, 0, true);
5726 arguments = new ArrayList ();
5728 ret = CheckIndices (ec, initializers, 0, false);
5735 if (arguments.Count != dimensions) {
5736 Error_IncorrectArrayInitializer ();
5744 void Error_NegativeArrayIndex ()
5746 Error (284, "Can not create array with a negative size");
5750 // Converts `source' to an int, uint, long or ulong.
5752 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
5756 bool old_checked = ec.CheckState;
5757 ec.CheckState = true;
5759 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
5760 if (target == null){
5761 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
5762 if (target == null){
5763 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
5764 if (target == null){
5765 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
5767 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
5771 ec.CheckState = old_checked;
5774 // Only positive constants are allowed at compile time
5776 if (target is Constant){
5777 if (target is IntConstant){
5778 if (((IntConstant) target).Value < 0){
5779 Error_NegativeArrayIndex ();
5784 if (target is LongConstant){
5785 if (((LongConstant) target).Value < 0){
5786 Error_NegativeArrayIndex ();
5797 // Creates the type of the array
5799 bool LookupType (EmitContext ec)
5801 StringBuilder array_qualifier = new StringBuilder (rank);
5804 // `In the first form allocates an array instace of the type that results
5805 // from deleting each of the individual expression from the expression list'
5807 if (num_arguments > 0) {
5808 array_qualifier.Append ("[");
5809 for (int i = num_arguments-1; i > 0; i--)
5810 array_qualifier.Append (",");
5811 array_qualifier.Append ("]");
5817 Expression array_type_expr;
5818 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
5819 type = ec.DeclSpace.ResolveType (array_type_expr, false, loc);
5824 underlying_type = type;
5825 if (underlying_type.IsArray)
5826 underlying_type = TypeManager.GetElementType (underlying_type);
5827 dimensions = type.GetArrayRank ();
5832 public override Expression DoResolve (EmitContext ec)
5836 if (!LookupType (ec))
5840 // First step is to validate the initializers and fill
5841 // in any missing bits
5843 if (!ValidateInitializers (ec, type))
5846 if (arguments == null)
5849 arg_count = arguments.Count;
5850 foreach (Argument a in arguments){
5851 if (!a.Resolve (ec, loc))
5854 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
5855 if (real_arg == null)
5862 array_element_type = TypeManager.GetElementType (type);
5864 if (arg_count == 1) {
5865 is_one_dimensional = true;
5866 eclass = ExprClass.Value;
5870 is_builtin_type = TypeManager.IsBuiltinType (type);
5872 if (is_builtin_type) {
5875 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
5876 AllBindingFlags, loc);
5878 if (!(ml is MethodGroupExpr)) {
5879 ml.Error_UnexpectedKind ("method group");
5884 Error (-6, "New invocation: Can not find a constructor for " +
5885 "this argument list");
5889 new_method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, arguments, loc);
5891 if (new_method == null) {
5892 Error (-6, "New invocation: Can not find a constructor for " +
5893 "this argument list");
5897 eclass = ExprClass.Value;
5900 ModuleBuilder mb = CodeGen.ModuleBuilder;
5901 ArrayList args = new ArrayList ();
5903 if (arguments != null) {
5904 for (int i = 0; i < arg_count; i++)
5905 args.Add (TypeManager.int32_type);
5908 Type [] arg_types = null;
5911 arg_types = new Type [args.Count];
5913 args.CopyTo (arg_types, 0);
5915 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
5918 if (new_method == null) {
5919 Error (-6, "New invocation: Can not find a constructor for " +
5920 "this argument list");
5924 eclass = ExprClass.Value;
5929 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
5934 int count = array_data.Count;
5936 if (underlying_type.IsEnum)
5937 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
5939 factor = GetTypeSize (underlying_type);
5941 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
5943 data = new byte [(count * factor + 4) & ~3];
5946 for (int i = 0; i < count; ++i) {
5947 object v = array_data [i];
5949 if (v is EnumConstant)
5950 v = ((EnumConstant) v).Child;
5952 if (v is Constant && !(v is StringConstant))
5953 v = ((Constant) v).GetValue ();
5959 if (underlying_type == TypeManager.int64_type){
5960 if (!(v is Expression)){
5961 long val = (long) v;
5963 for (int j = 0; j < factor; ++j) {
5964 data [idx + j] = (byte) (val & 0xFF);
5968 } else if (underlying_type == TypeManager.uint64_type){
5969 if (!(v is Expression)){
5970 ulong val = (ulong) v;
5972 for (int j = 0; j < factor; ++j) {
5973 data [idx + j] = (byte) (val & 0xFF);
5977 } else if (underlying_type == TypeManager.float_type) {
5978 if (!(v is Expression)){
5979 element = BitConverter.GetBytes ((float) v);
5981 for (int j = 0; j < factor; ++j)
5982 data [idx + j] = element [j];
5984 } else if (underlying_type == TypeManager.double_type) {
5985 if (!(v is Expression)){
5986 element = BitConverter.GetBytes ((double) v);
5988 for (int j = 0; j < factor; ++j)
5989 data [idx + j] = element [j];
5991 } else if (underlying_type == TypeManager.char_type){
5992 if (!(v is Expression)){
5993 int val = (int) ((char) v);
5995 data [idx] = (byte) (val & 0xff);
5996 data [idx+1] = (byte) (val >> 8);
5998 } else if (underlying_type == TypeManager.short_type){
5999 if (!(v is Expression)){
6000 int val = (int) ((short) v);
6002 data [idx] = (byte) (val & 0xff);
6003 data [idx+1] = (byte) (val >> 8);
6005 } else if (underlying_type == TypeManager.ushort_type){
6006 if (!(v is Expression)){
6007 int val = (int) ((ushort) v);
6009 data [idx] = (byte) (val & 0xff);
6010 data [idx+1] = (byte) (val >> 8);
6012 } else if (underlying_type == TypeManager.int32_type) {
6013 if (!(v is Expression)){
6016 data [idx] = (byte) (val & 0xff);
6017 data [idx+1] = (byte) ((val >> 8) & 0xff);
6018 data [idx+2] = (byte) ((val >> 16) & 0xff);
6019 data [idx+3] = (byte) (val >> 24);
6021 } else if (underlying_type == TypeManager.uint32_type) {
6022 if (!(v is Expression)){
6023 uint val = (uint) v;
6025 data [idx] = (byte) (val & 0xff);
6026 data [idx+1] = (byte) ((val >> 8) & 0xff);
6027 data [idx+2] = (byte) ((val >> 16) & 0xff);
6028 data [idx+3] = (byte) (val >> 24);
6030 } else if (underlying_type == TypeManager.sbyte_type) {
6031 if (!(v is Expression)){
6032 sbyte val = (sbyte) v;
6033 data [idx] = (byte) val;
6035 } else if (underlying_type == TypeManager.byte_type) {
6036 if (!(v is Expression)){
6037 byte val = (byte) v;
6038 data [idx] = (byte) val;
6040 } else if (underlying_type == TypeManager.bool_type) {
6041 if (!(v is Expression)){
6042 bool val = (bool) v;
6043 data [idx] = (byte) (val ? 1 : 0);
6045 } else if (underlying_type == TypeManager.decimal_type){
6046 if (!(v is Expression)){
6047 int [] bits = Decimal.GetBits ((decimal) v);
6050 // FIXME: For some reason, this doesn't work on the MS runtime.
6051 int [] nbits = new int [4];
6052 nbits [0] = bits [3];
6053 nbits [1] = bits [2];
6054 nbits [2] = bits [0];
6055 nbits [3] = bits [1];
6057 for (int j = 0; j < 4; j++){
6058 data [p++] = (byte) (nbits [j] & 0xff);
6059 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6060 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6061 data [p++] = (byte) (nbits [j] >> 24);
6065 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6074 // Emits the initializers for the array
6076 void EmitStaticInitializers (EmitContext ec, bool is_expression)
6079 // First, the static data
6082 ILGenerator ig = ec.ig;
6084 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6086 fb = RootContext.MakeStaticData (data);
6089 ig.Emit (OpCodes.Dup);
6090 ig.Emit (OpCodes.Ldtoken, fb);
6091 ig.Emit (OpCodes.Call,
6092 TypeManager.void_initializearray_array_fieldhandle);
6096 // Emits pieces of the array that can not be computed at compile
6097 // time (variables and string locations).
6099 // This always expect the top value on the stack to be the array
6101 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
6103 ILGenerator ig = ec.ig;
6104 int dims = bounds.Count;
6105 int [] current_pos = new int [dims];
6106 int top = array_data.Count;
6107 LocalBuilder temp = ig.DeclareLocal (type);
6109 ig.Emit (OpCodes.Stloc, temp);
6111 MethodInfo set = null;
6115 ModuleBuilder mb = null;
6116 mb = CodeGen.ModuleBuilder;
6117 args = new Type [dims + 1];
6120 for (j = 0; j < dims; j++)
6121 args [j] = TypeManager.int32_type;
6123 args [j] = array_element_type;
6125 set = mb.GetArrayMethod (
6127 CallingConventions.HasThis | CallingConventions.Standard,
6128 TypeManager.void_type, args);
6131 for (int i = 0; i < top; i++){
6133 Expression e = null;
6135 if (array_data [i] is Expression)
6136 e = (Expression) array_data [i];
6140 // Basically we do this for string literals and
6141 // other non-literal expressions
6143 if (e is EnumConstant){
6144 e = ((EnumConstant) e).Child;
6147 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6148 num_automatic_initializers <= max_automatic_initializers) {
6149 Type etype = e.Type;
6151 ig.Emit (OpCodes.Ldloc, temp);
6153 for (int idx = 0; idx < dims; idx++)
6154 IntConstant.EmitInt (ig, current_pos [idx]);
6157 // If we are dealing with a struct, get the
6158 // address of it, so we can store it.
6161 etype.IsSubclassOf (TypeManager.value_type) &&
6162 (!TypeManager.IsBuiltinOrEnum (etype) ||
6163 etype == TypeManager.decimal_type)) {
6168 // Let new know that we are providing
6169 // the address where to store the results
6171 n.DisableTemporaryValueType ();
6174 ig.Emit (OpCodes.Ldelema, etype);
6180 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
6182 ig.Emit (OpCodes.Call, set);
6190 for (int j = dims - 1; j >= 0; j--){
6192 if (current_pos [j] < (int) bounds [j])
6194 current_pos [j] = 0;
6199 ig.Emit (OpCodes.Ldloc, temp);
6202 void EmitArrayArguments (EmitContext ec)
6204 ILGenerator ig = ec.ig;
6206 foreach (Argument a in arguments) {
6207 Type atype = a.Type;
6210 if (atype == TypeManager.uint64_type)
6211 ig.Emit (OpCodes.Conv_Ovf_U4);
6212 else if (atype == TypeManager.int64_type)
6213 ig.Emit (OpCodes.Conv_Ovf_I4);
6217 void DoEmit (EmitContext ec, bool is_statement)
6219 ILGenerator ig = ec.ig;
6221 EmitArrayArguments (ec);
6222 if (is_one_dimensional)
6223 ig.Emit (OpCodes.Newarr, array_element_type);
6225 if (is_builtin_type)
6226 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6228 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6231 if (initializers != null){
6233 // FIXME: Set this variable correctly.
6235 bool dynamic_initializers = true;
6237 if (underlying_type != TypeManager.string_type &&
6238 underlying_type != TypeManager.decimal_type &&
6239 underlying_type != TypeManager.object_type) {
6240 if (num_automatic_initializers > max_automatic_initializers)
6241 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
6244 if (dynamic_initializers)
6245 EmitDynamicInitializers (ec, !is_statement);
6249 public override void Emit (EmitContext ec)
6254 public override void EmitStatement (EmitContext ec)
6259 public object EncodeAsAttribute ()
6261 if (!is_one_dimensional){
6262 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6266 if (array_data == null){
6267 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6271 object [] ret = new object [array_data.Count];
6273 foreach (Expression e in array_data){
6276 if (e is NullLiteral)
6279 if (!Attribute.GetAttributeArgumentExpression (e, Location, out v))
6289 /// Represents the `this' construct
6291 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6294 VariableInfo variable_info;
6296 public This (Block block, Location loc)
6302 public This (Location loc)
6307 public VariableInfo VariableInfo {
6308 get { return variable_info; }
6311 public bool VerifyFixed (bool is_expression)
6313 if ((variable_info == null) || (variable_info.LocalInfo == null))
6316 return variable_info.LocalInfo.IsFixed;
6319 public bool ResolveBase (EmitContext ec)
6321 eclass = ExprClass.Variable;
6322 type = ec.ContainerType;
6325 Error (26, "Keyword this not valid in static code");
6329 if ((block != null) && (block.ThisVariable != null))
6330 variable_info = block.ThisVariable.VariableInfo;
6335 public override Expression DoResolve (EmitContext ec)
6337 if (!ResolveBase (ec))
6340 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
6341 Error (188, "The this object cannot be used before all " +
6342 "of its fields are assigned to");
6343 variable_info.SetAssigned (ec);
6347 if (ec.IsFieldInitializer) {
6348 Error (27, "Keyword `this' can't be used outside a constructor, " +
6349 "a method or a property.");
6356 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6358 if (!ResolveBase (ec))
6361 if (variable_info != null)
6362 variable_info.SetAssigned (ec);
6364 if (ec.TypeContainer is Class){
6365 Error (1604, "Cannot assign to `this'");
6372 public override void Emit (EmitContext ec)
6374 ILGenerator ig = ec.ig;
6376 ig.Emit (OpCodes.Ldarg_0);
6377 if (ec.TypeContainer is Struct)
6378 ig.Emit (OpCodes.Ldobj, type);
6381 public void EmitAssign (EmitContext ec, Expression source)
6383 ILGenerator ig = ec.ig;
6385 if (ec.TypeContainer is Struct){
6386 ig.Emit (OpCodes.Ldarg_0);
6388 ig.Emit (OpCodes.Stobj, type);
6391 ig.Emit (OpCodes.Starg, 0);
6395 public void AddressOf (EmitContext ec, AddressOp mode)
6397 ec.ig.Emit (OpCodes.Ldarg_0);
6400 // FIGURE OUT WHY LDARG_S does not work
6402 // consider: struct X { int val; int P { set { val = value; }}}
6404 // Yes, this looks very bad. Look at `NOTAS' for
6406 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
6411 // This produces the value that renders an instance, used by the iterators code
6413 public class ProxyInstance : Expression, IMemoryLocation {
6414 public override Expression DoResolve (EmitContext ec)
6416 eclass = ExprClass.Variable;
6417 type = ec.ContainerType;
6421 public override void Emit (EmitContext ec)
6423 ec.ig.Emit (OpCodes.Ldarg_0);
6427 public void AddressOf (EmitContext ec, AddressOp mode)
6429 ec.ig.Emit (OpCodes.Ldarg_0);
6434 /// Implements the typeof operator
6436 public class TypeOf : Expression {
6437 public readonly Expression QueriedType;
6438 protected Type typearg;
6440 public TypeOf (Expression queried_type, Location l)
6442 QueriedType = queried_type;
6446 public override Expression DoResolve (EmitContext ec)
6448 typearg = ec.DeclSpace.ResolveType (QueriedType, false, loc);
6450 if (typearg == null)
6453 if (typearg == TypeManager.void_type) {
6454 Error (673, "System.Void cannot be used from C# - " +
6455 "use typeof (void) to get the void type object");
6459 type = TypeManager.type_type;
6460 eclass = ExprClass.Type;
6464 public override void Emit (EmitContext ec)
6466 ec.ig.Emit (OpCodes.Ldtoken, typearg);
6467 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6470 public Type TypeArg {
6471 get { return typearg; }
6476 /// Implements the `typeof (void)' operator
6478 public class TypeOfVoid : TypeOf {
6479 public TypeOfVoid (Location l) : base (null, l)
6484 public override Expression DoResolve (EmitContext ec)
6486 type = TypeManager.type_type;
6487 typearg = TypeManager.void_type;
6488 eclass = ExprClass.Type;
6494 /// Implements the sizeof expression
6496 public class SizeOf : Expression {
6497 public readonly Expression QueriedType;
6500 public SizeOf (Expression queried_type, Location l)
6502 this.QueriedType = queried_type;
6506 public override Expression DoResolve (EmitContext ec)
6510 233, loc, "Sizeof may only be used in an unsafe context " +
6511 "(consider using System.Runtime.InteropServices.Marshal.Sizeof");
6515 type_queried = ec.DeclSpace.ResolveType (QueriedType, false, loc);
6516 if (type_queried == null)
6519 if (!TypeManager.IsUnmanagedType (type_queried)){
6520 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
6524 type = TypeManager.int32_type;
6525 eclass = ExprClass.Value;
6529 public override void Emit (EmitContext ec)
6531 int size = GetTypeSize (type_queried);
6534 ec.ig.Emit (OpCodes.Sizeof, type_queried);
6536 IntConstant.EmitInt (ec.ig, size);
6541 /// Implements the member access expression
6543 public class MemberAccess : Expression {
6544 public readonly string Identifier;
6547 public MemberAccess (Expression expr, string id, Location l)
6554 public Expression Expr {
6560 static void error176 (Location loc, string name)
6562 Report.Error (176, loc, "Static member `" +
6563 name + "' cannot be accessed " +
6564 "with an instance reference, qualify with a " +
6565 "type name instead");
6568 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
6570 if (left_original == null)
6573 if (!(left_original is SimpleName))
6576 SimpleName sn = (SimpleName) left_original;
6578 Type t = RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc);
6585 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
6586 Expression left, Location loc,
6587 Expression left_original)
6589 bool left_is_type, left_is_explicit;
6591 // If `left' is null, then we're called from SimpleNameResolve and this is
6592 // a member in the currently defining class.
6594 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
6595 left_is_explicit = false;
6597 // Implicitly default to `this' unless we're static.
6598 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
6599 left = ec.GetThis (loc);
6601 left_is_type = left is TypeExpr;
6602 left_is_explicit = true;
6605 if (member_lookup is FieldExpr){
6606 FieldExpr fe = (FieldExpr) member_lookup;
6607 FieldInfo fi = fe.FieldInfo;
6608 Type decl_type = fi.DeclaringType;
6610 if (fi is FieldBuilder) {
6611 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
6614 object o = c.LookupConstantValue ();
6618 object real_value = ((Constant) c.Expr).GetValue ();
6620 return Constantify (real_value, fi.FieldType);
6625 Type t = fi.FieldType;
6629 if (fi is FieldBuilder)
6630 o = TypeManager.GetValue ((FieldBuilder) fi);
6632 o = fi.GetValue (fi);
6634 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
6635 if (left_is_explicit && !left_is_type &&
6636 !IdenticalNameAndTypeName (ec, left_original, loc)) {
6637 error176 (loc, fe.FieldInfo.Name);
6641 Expression enum_member = MemberLookup (
6642 ec, decl_type, "value__", MemberTypes.Field,
6643 AllBindingFlags, loc);
6645 Enum en = TypeManager.LookupEnum (decl_type);
6649 c = Constantify (o, en.UnderlyingType);
6651 c = Constantify (o, enum_member.Type);
6653 return new EnumConstant (c, decl_type);
6656 Expression exp = Constantify (o, t);
6658 if (left_is_explicit && !left_is_type) {
6659 error176 (loc, fe.FieldInfo.Name);
6666 if (fi.FieldType.IsPointer && !ec.InUnsafe){
6672 if (member_lookup is EventExpr) {
6673 EventExpr ee = (EventExpr) member_lookup;
6676 // If the event is local to this class, we transform ourselves into
6680 if (ee.EventInfo.DeclaringType == ec.ContainerType ||
6681 TypeManager.IsNestedChildOf(ec.ContainerType, ee.EventInfo.DeclaringType)) {
6682 MemberInfo mi = GetFieldFromEvent (ee);
6686 // If this happens, then we have an event with its own
6687 // accessors and private field etc so there's no need
6688 // to transform ourselves.
6693 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
6696 Report.Error (-200, loc, "Internal error!!");
6700 if (!left_is_explicit)
6703 return ResolveMemberAccess (ec, ml, left, loc, left_original);
6707 if (member_lookup is IMemberExpr) {
6708 IMemberExpr me = (IMemberExpr) member_lookup;
6711 MethodGroupExpr mg = me as MethodGroupExpr;
6712 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
6713 mg.IsExplicitImpl = left_is_explicit;
6716 if ((ec.IsFieldInitializer || ec.IsStatic) &&
6717 IdenticalNameAndTypeName (ec, left_original, loc))
6718 return member_lookup;
6720 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
6725 if (!me.IsInstance){
6726 if (IdenticalNameAndTypeName (ec, left_original, loc))
6727 return member_lookup;
6729 if (left_is_explicit) {
6730 error176 (loc, me.Name);
6736 // Since we can not check for instance objects in SimpleName,
6737 // becaue of the rule that allows types and variables to share
6738 // the name (as long as they can be de-ambiguated later, see
6739 // IdenticalNameAndTypeName), we have to check whether left
6740 // is an instance variable in a static context
6742 // However, if the left-hand value is explicitly given, then
6743 // it is already our instance expression, so we aren't in
6747 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
6748 IMemberExpr mexp = (IMemberExpr) left;
6750 if (!mexp.IsStatic){
6751 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
6756 me.InstanceExpression = left;
6759 return member_lookup;
6762 Console.WriteLine ("Left is: " + left);
6763 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
6764 Environment.Exit (0);
6768 public Expression DoResolve (EmitContext ec, Expression right_side, ResolveFlags flags)
6771 throw new Exception ();
6774 // Resolve the expression with flow analysis turned off, we'll do the definite
6775 // assignment checks later. This is because we don't know yet what the expression
6776 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
6777 // definite assignment check on the actual field and not on the whole struct.
6780 Expression original = expr;
6781 expr = expr.Resolve (ec, flags | ResolveFlags.DisableFlowAnalysis);
6785 if (expr is SimpleName){
6786 SimpleName child_expr = (SimpleName) expr;
6788 Expression new_expr = new SimpleName (child_expr.Name, Identifier, loc);
6790 return new_expr.Resolve (ec, flags);
6794 // TODO: I mailed Ravi about this, and apparently we can get rid
6795 // of this and put it in the right place.
6797 // Handle enums here when they are in transit.
6798 // Note that we cannot afford to hit MemberLookup in this case because
6799 // it will fail to find any members at all
6802 Type expr_type = expr.Type;
6803 if (expr is TypeExpr){
6804 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
6805 Error (122, "`" + expr_type + "' " +
6806 "is inaccessible because of its protection level");
6810 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
6811 Enum en = TypeManager.LookupEnum (expr_type);
6814 object value = en.LookupEnumValue (ec, Identifier, loc);
6817 Constant c = Constantify (value, en.UnderlyingType);
6818 return new EnumConstant (c, expr_type);
6824 if (expr_type.IsPointer){
6825 Error (23, "The `.' operator can not be applied to pointer operands (" +
6826 TypeManager.CSharpName (expr_type) + ")");
6830 Expression member_lookup;
6831 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
6832 if (member_lookup == null)
6835 if (member_lookup is TypeExpr) {
6836 if (!(expr is TypeExpr) && !(expr is SimpleName)) {
6837 Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
6838 member_lookup.Type + "' instead");
6842 return member_lookup;
6845 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
6846 if (member_lookup == null)
6849 // The following DoResolve/DoResolveLValue will do the definite assignment
6852 if (right_side != null)
6853 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
6855 member_lookup = member_lookup.DoResolve (ec);
6857 return member_lookup;
6860 public override Expression DoResolve (EmitContext ec)
6862 return DoResolve (ec, null, ResolveFlags.VariableOrValue |
6863 ResolveFlags.SimpleName | ResolveFlags.Type);
6866 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
6868 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
6869 ResolveFlags.SimpleName | ResolveFlags.Type);
6872 public override Expression ResolveAsTypeStep (EmitContext ec)
6874 string fname = null;
6875 MemberAccess full_expr = this;
6876 while (full_expr != null) {
6878 fname = String.Concat (full_expr.Identifier, ".", fname);
6880 fname = full_expr.Identifier;
6882 if (full_expr.Expr is SimpleName) {
6883 string full_name = String.Concat (((SimpleName) full_expr.Expr).Name, ".", fname);
6884 Type fully_qualified = ec.DeclSpace.FindType (loc, full_name);
6885 if (fully_qualified != null)
6886 return new TypeExpression (fully_qualified, loc);
6889 full_expr = full_expr.Expr as MemberAccess;
6892 Expression new_expr = expr.ResolveAsTypeStep (ec);
6894 if (new_expr == null)
6897 if (new_expr is SimpleName){
6898 SimpleName child_expr = (SimpleName) new_expr;
6900 new_expr = new SimpleName (child_expr.Name, Identifier, loc);
6902 return new_expr.ResolveAsTypeStep (ec);
6905 Type expr_type = new_expr.Type;
6907 if (expr_type.IsPointer){
6908 Error (23, "The `.' operator can not be applied to pointer operands (" +
6909 TypeManager.CSharpName (expr_type) + ")");
6913 Expression member_lookup;
6914 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
6915 if (member_lookup == null)
6918 if (member_lookup is TypeExpr){
6919 member_lookup.Resolve (ec, ResolveFlags.Type);
6920 return member_lookup;
6926 public override void Emit (EmitContext ec)
6928 throw new Exception ("Should not happen");
6931 public override string ToString ()
6933 return expr + "." + Identifier;
6938 /// Implements checked expressions
6940 public class CheckedExpr : Expression {
6942 public Expression Expr;
6944 public CheckedExpr (Expression e, Location l)
6950 public override Expression DoResolve (EmitContext ec)
6952 bool last_check = ec.CheckState;
6953 bool last_const_check = ec.ConstantCheckState;
6955 ec.CheckState = true;
6956 ec.ConstantCheckState = true;
6957 Expr = Expr.Resolve (ec);
6958 ec.CheckState = last_check;
6959 ec.ConstantCheckState = last_const_check;
6964 if (Expr is Constant)
6967 eclass = Expr.eclass;
6972 public override void Emit (EmitContext ec)
6974 bool last_check = ec.CheckState;
6975 bool last_const_check = ec.ConstantCheckState;
6977 ec.CheckState = true;
6978 ec.ConstantCheckState = true;
6980 ec.CheckState = last_check;
6981 ec.ConstantCheckState = last_const_check;
6987 /// Implements the unchecked expression
6989 public class UnCheckedExpr : Expression {
6991 public Expression Expr;
6993 public UnCheckedExpr (Expression e, Location l)
6999 public override Expression DoResolve (EmitContext ec)
7001 bool last_check = ec.CheckState;
7002 bool last_const_check = ec.ConstantCheckState;
7004 ec.CheckState = false;
7005 ec.ConstantCheckState = false;
7006 Expr = Expr.Resolve (ec);
7007 ec.CheckState = last_check;
7008 ec.ConstantCheckState = last_const_check;
7013 if (Expr is Constant)
7016 eclass = Expr.eclass;
7021 public override void Emit (EmitContext ec)
7023 bool last_check = ec.CheckState;
7024 bool last_const_check = ec.ConstantCheckState;
7026 ec.CheckState = false;
7027 ec.ConstantCheckState = false;
7029 ec.CheckState = last_check;
7030 ec.ConstantCheckState = last_const_check;
7036 /// An Element Access expression.
7038 /// During semantic analysis these are transformed into
7039 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7041 public class ElementAccess : Expression {
7042 public ArrayList Arguments;
7043 public Expression Expr;
7045 public ElementAccess (Expression e, ArrayList e_list, Location l)
7054 Arguments = new ArrayList ();
7055 foreach (Expression tmp in e_list)
7056 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7060 bool CommonResolve (EmitContext ec)
7062 Expr = Expr.Resolve (ec);
7067 if (Arguments == null)
7070 foreach (Argument a in Arguments){
7071 if (!a.Resolve (ec, loc))
7078 Expression MakePointerAccess ()
7082 if (t == TypeManager.void_ptr_type){
7083 Error (242, "The array index operation is not valid for void pointers");
7086 if (Arguments.Count != 1){
7087 Error (196, "A pointer must be indexed by a single value");
7092 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc);
7093 return new Indirection (p, loc);
7096 public override Expression DoResolve (EmitContext ec)
7098 if (!CommonResolve (ec))
7102 // We perform some simple tests, and then to "split" the emit and store
7103 // code we create an instance of a different class, and return that.
7105 // I am experimenting with this pattern.
7109 if (t == TypeManager.array_type){
7110 Report.Error (21, loc, "Cannot use indexer on System.Array");
7115 return (new ArrayAccess (this, loc)).Resolve (ec);
7116 else if (t.IsPointer)
7117 return MakePointerAccess ();
7119 return (new IndexerAccess (this, loc)).Resolve (ec);
7122 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7124 if (!CommonResolve (ec))
7129 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
7130 else if (t.IsPointer)
7131 return MakePointerAccess ();
7133 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
7136 public override void Emit (EmitContext ec)
7138 throw new Exception ("Should never be reached");
7143 /// Implements array access
7145 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7147 // Points to our "data" repository
7151 LocalTemporary [] cached_locations;
7153 public ArrayAccess (ElementAccess ea_data, Location l)
7156 eclass = ExprClass.Variable;
7160 public override Expression DoResolve (EmitContext ec)
7163 ExprClass eclass = ea.Expr.eclass;
7165 // As long as the type is valid
7166 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7167 eclass == ExprClass.Value)) {
7168 ea.Expr.Error_UnexpectedKind ("variable or value");
7173 Type t = ea.Expr.Type;
7174 if (t.GetArrayRank () != ea.Arguments.Count){
7176 "Incorrect number of indexes for array " +
7177 " expected: " + t.GetArrayRank () + " got: " +
7178 ea.Arguments.Count);
7182 type = TypeManager.GetElementType (t);
7183 if (type.IsPointer && !ec.InUnsafe){
7184 UnsafeError (ea.Location);
7188 foreach (Argument a in ea.Arguments){
7189 Type argtype = a.Type;
7191 if (argtype == TypeManager.int32_type ||
7192 argtype == TypeManager.uint32_type ||
7193 argtype == TypeManager.int64_type ||
7194 argtype == TypeManager.uint64_type)
7198 // Mhm. This is strage, because the Argument.Type is not the same as
7199 // Argument.Expr.Type: the value changes depending on the ref/out setting.
7201 // Wonder if I will run into trouble for this.
7203 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
7208 eclass = ExprClass.Variable;
7214 /// Emits the right opcode to load an object of Type `t'
7215 /// from an array of T
7217 static public void EmitLoadOpcode (ILGenerator ig, Type type)
7219 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7220 ig.Emit (OpCodes.Ldelem_U1);
7221 else if (type == TypeManager.sbyte_type)
7222 ig.Emit (OpCodes.Ldelem_I1);
7223 else if (type == TypeManager.short_type)
7224 ig.Emit (OpCodes.Ldelem_I2);
7225 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7226 ig.Emit (OpCodes.Ldelem_U2);
7227 else if (type == TypeManager.int32_type)
7228 ig.Emit (OpCodes.Ldelem_I4);
7229 else if (type == TypeManager.uint32_type)
7230 ig.Emit (OpCodes.Ldelem_U4);
7231 else if (type == TypeManager.uint64_type)
7232 ig.Emit (OpCodes.Ldelem_I8);
7233 else if (type == TypeManager.int64_type)
7234 ig.Emit (OpCodes.Ldelem_I8);
7235 else if (type == TypeManager.float_type)
7236 ig.Emit (OpCodes.Ldelem_R4);
7237 else if (type == TypeManager.double_type)
7238 ig.Emit (OpCodes.Ldelem_R8);
7239 else if (type == TypeManager.intptr_type)
7240 ig.Emit (OpCodes.Ldelem_I);
7241 else if (type.IsValueType){
7242 ig.Emit (OpCodes.Ldelema, type);
7243 ig.Emit (OpCodes.Ldobj, type);
7245 ig.Emit (OpCodes.Ldelem_Ref);
7249 /// Emits the right opcode to store an object of Type `t'
7250 /// from an array of T.
7252 static public void EmitStoreOpcode (ILGenerator ig, Type t)
7255 OpCode op = GetStoreOpcode (t, out is_stobj);
7257 ig.Emit (OpCodes.Stobj, t);
7263 /// Returns the right opcode to store an object of Type `t'
7264 /// from an array of T.
7266 static public OpCode GetStoreOpcode (Type t, out bool is_stobj)
7268 //Console.WriteLine (new System.Diagnostics.StackTrace ());
7270 t = TypeManager.TypeToCoreType (t);
7271 if (TypeManager.IsEnumType (t) && t != TypeManager.enum_type)
7272 t = TypeManager.EnumToUnderlying (t);
7273 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
7274 t == TypeManager.bool_type)
7275 return OpCodes.Stelem_I1;
7276 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
7277 t == TypeManager.char_type)
7278 return OpCodes.Stelem_I2;
7279 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
7280 return OpCodes.Stelem_I4;
7281 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
7282 return OpCodes.Stelem_I8;
7283 else if (t == TypeManager.float_type)
7284 return OpCodes.Stelem_R4;
7285 else if (t == TypeManager.double_type)
7286 return OpCodes.Stelem_R8;
7287 else if (t == TypeManager.intptr_type) {
7289 return OpCodes.Stobj;
7290 } else if (t.IsValueType) {
7292 return OpCodes.Stobj;
7294 return OpCodes.Stelem_Ref;
7297 MethodInfo FetchGetMethod ()
7299 ModuleBuilder mb = CodeGen.ModuleBuilder;
7300 int arg_count = ea.Arguments.Count;
7301 Type [] args = new Type [arg_count];
7304 for (int i = 0; i < arg_count; i++){
7305 //args [i++] = a.Type;
7306 args [i] = TypeManager.int32_type;
7309 get = mb.GetArrayMethod (
7310 ea.Expr.Type, "Get",
7311 CallingConventions.HasThis |
7312 CallingConventions.Standard,
7318 MethodInfo FetchAddressMethod ()
7320 ModuleBuilder mb = CodeGen.ModuleBuilder;
7321 int arg_count = ea.Arguments.Count;
7322 Type [] args = new Type [arg_count];
7326 ret_type = TypeManager.GetReferenceType (type);
7328 for (int i = 0; i < arg_count; i++){
7329 //args [i++] = a.Type;
7330 args [i] = TypeManager.int32_type;
7333 address = mb.GetArrayMethod (
7334 ea.Expr.Type, "Address",
7335 CallingConventions.HasThis |
7336 CallingConventions.Standard,
7343 // Load the array arguments into the stack.
7345 // If we have been requested to cache the values (cached_locations array
7346 // initialized), then load the arguments the first time and store them
7347 // in locals. otherwise load from local variables.
7349 void LoadArrayAndArguments (EmitContext ec)
7351 ILGenerator ig = ec.ig;
7353 if (cached_locations == null){
7355 foreach (Argument a in ea.Arguments){
7356 Type argtype = a.Expr.Type;
7360 if (argtype == TypeManager.int64_type)
7361 ig.Emit (OpCodes.Conv_Ovf_I);
7362 else if (argtype == TypeManager.uint64_type)
7363 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7368 if (cached_locations [0] == null){
7369 cached_locations [0] = new LocalTemporary (ec, ea.Expr.Type);
7371 ig.Emit (OpCodes.Dup);
7372 cached_locations [0].Store (ec);
7376 foreach (Argument a in ea.Arguments){
7377 Type argtype = a.Expr.Type;
7379 cached_locations [j] = new LocalTemporary (ec, TypeManager.intptr_type /* a.Expr.Type */);
7381 if (argtype == TypeManager.int64_type)
7382 ig.Emit (OpCodes.Conv_Ovf_I);
7383 else if (argtype == TypeManager.uint64_type)
7384 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7386 ig.Emit (OpCodes.Dup);
7387 cached_locations [j].Store (ec);
7393 foreach (LocalTemporary lt in cached_locations)
7397 public new void CacheTemporaries (EmitContext ec)
7399 cached_locations = new LocalTemporary [ea.Arguments.Count + 1];
7402 public override void Emit (EmitContext ec)
7404 int rank = ea.Expr.Type.GetArrayRank ();
7405 ILGenerator ig = ec.ig;
7407 LoadArrayAndArguments (ec);
7410 EmitLoadOpcode (ig, type);
7414 method = FetchGetMethod ();
7415 ig.Emit (OpCodes.Call, method);
7419 public void EmitAssign (EmitContext ec, Expression source)
7421 int rank = ea.Expr.Type.GetArrayRank ();
7422 ILGenerator ig = ec.ig;
7423 Type t = source.Type;
7425 LoadArrayAndArguments (ec);
7428 // The stobj opcode used by value types will need
7429 // an address on the stack, not really an array/array
7433 if (t == TypeManager.enum_type || t == TypeManager.decimal_type ||
7434 (t.IsSubclassOf (TypeManager.value_type) && !TypeManager.IsEnumType (t) && !TypeManager.IsBuiltinType (t)))
7435 ig.Emit (OpCodes.Ldelema, t);
7441 EmitStoreOpcode (ig, t);
7443 ModuleBuilder mb = CodeGen.ModuleBuilder;
7444 int arg_count = ea.Arguments.Count;
7445 Type [] args = new Type [arg_count + 1];
7448 for (int i = 0; i < arg_count; i++){
7449 //args [i++] = a.Type;
7450 args [i] = TypeManager.int32_type;
7453 args [arg_count] = type;
7455 set = mb.GetArrayMethod (
7456 ea.Expr.Type, "Set",
7457 CallingConventions.HasThis |
7458 CallingConventions.Standard,
7459 TypeManager.void_type, args);
7461 ig.Emit (OpCodes.Call, set);
7465 public void AddressOf (EmitContext ec, AddressOp mode)
7467 int rank = ea.Expr.Type.GetArrayRank ();
7468 ILGenerator ig = ec.ig;
7470 LoadArrayAndArguments (ec);
7473 ig.Emit (OpCodes.Ldelema, type);
7475 MethodInfo address = FetchAddressMethod ();
7476 ig.Emit (OpCodes.Call, address);
7483 public ArrayList Properties;
7484 static Hashtable map;
7486 public struct Indexer {
7487 public readonly Type Type;
7488 public readonly MethodInfo Getter, Setter;
7490 public Indexer (Type type, MethodInfo get, MethodInfo set)
7500 map = new Hashtable ();
7505 Properties = new ArrayList ();
7508 void Append (MemberInfo [] mi)
7510 foreach (PropertyInfo property in mi){
7511 MethodInfo get, set;
7513 get = property.GetGetMethod (true);
7514 set = property.GetSetMethod (true);
7515 Properties.Add (new Indexer (property.PropertyType, get, set));
7519 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
7521 string p_name = TypeManager.IndexerPropertyName (lookup_type);
7523 MemberInfo [] mi = TypeManager.MemberLookup (
7524 caller_type, caller_type, lookup_type, MemberTypes.Property,
7525 BindingFlags.Public | BindingFlags.Instance |
7526 BindingFlags.DeclaredOnly, p_name);
7528 if (mi == null || mi.Length == 0)
7534 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
7536 Indexers ix = (Indexers) map [lookup_type];
7541 Type copy = lookup_type;
7542 while (copy != TypeManager.object_type && copy != null){
7543 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
7547 ix = new Indexers ();
7552 copy = copy.BaseType;
7555 if (!lookup_type.IsInterface)
7558 TypeExpr [] ifaces = TypeManager.GetInterfaces (lookup_type);
7559 if (ifaces != null) {
7560 foreach (TypeExpr iface in ifaces) {
7561 Type itype = iface.Type;
7562 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
7565 ix = new Indexers ();
7577 /// Expressions that represent an indexer call.
7579 public class IndexerAccess : Expression, IAssignMethod {
7581 // Points to our "data" repository
7583 MethodInfo get, set;
7584 ArrayList set_arguments;
7585 bool is_base_indexer;
7587 protected Type indexer_type;
7588 protected Type current_type;
7589 protected Expression instance_expr;
7590 protected ArrayList arguments;
7592 public IndexerAccess (ElementAccess ea, Location loc)
7593 : this (ea.Expr, false, loc)
7595 this.arguments = ea.Arguments;
7598 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
7601 this.instance_expr = instance_expr;
7602 this.is_base_indexer = is_base_indexer;
7603 this.eclass = ExprClass.Value;
7607 protected virtual bool CommonResolve (EmitContext ec)
7609 indexer_type = instance_expr.Type;
7610 current_type = ec.ContainerType;
7615 public override Expression DoResolve (EmitContext ec)
7617 ArrayList AllGetters = new ArrayList();
7618 if (!CommonResolve (ec))
7622 // Step 1: Query for all `Item' *properties*. Notice
7623 // that the actual methods are pointed from here.
7625 // This is a group of properties, piles of them.
7627 bool found_any = false, found_any_getters = false;
7628 Type lookup_type = indexer_type;
7631 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
7632 if (ilist != null) {
7634 if (ilist.Properties != null) {
7635 foreach (Indexers.Indexer ix in ilist.Properties) {
7636 if (ix.Getter != null)
7637 AllGetters.Add(ix.Getter);
7642 if (AllGetters.Count > 0) {
7643 found_any_getters = true;
7644 get = (MethodInfo) Invocation.OverloadResolve (
7645 ec, new MethodGroupExpr (AllGetters, loc), arguments, loc);
7649 Report.Error (21, loc,
7650 "Type `" + TypeManager.CSharpName (indexer_type) +
7651 "' does not have any indexers defined");
7655 if (!found_any_getters) {
7656 Error (154, "indexer can not be used in this context, because " +
7657 "it lacks a `get' accessor");
7662 Error (1501, "No Overload for method `this' takes `" +
7663 arguments.Count + "' arguments");
7668 // Only base will allow this invocation to happen.
7670 if (get.IsAbstract && this is BaseIndexerAccess){
7671 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
7675 type = get.ReturnType;
7676 if (type.IsPointer && !ec.InUnsafe){
7681 eclass = ExprClass.IndexerAccess;
7685 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7687 ArrayList AllSetters = new ArrayList();
7688 if (!CommonResolve (ec))
7691 bool found_any = false, found_any_setters = false;
7693 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
7694 if (ilist != null) {
7696 if (ilist.Properties != null) {
7697 foreach (Indexers.Indexer ix in ilist.Properties) {
7698 if (ix.Setter != null)
7699 AllSetters.Add(ix.Setter);
7703 if (AllSetters.Count > 0) {
7704 found_any_setters = true;
7705 set_arguments = (ArrayList) arguments.Clone ();
7706 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
7707 set = (MethodInfo) Invocation.OverloadResolve (
7708 ec, new MethodGroupExpr (AllSetters, loc),
7709 set_arguments, loc);
7713 Report.Error (21, loc,
7714 "Type `" + TypeManager.CSharpName (indexer_type) +
7715 "' does not have any indexers defined");
7719 if (!found_any_setters) {
7720 Error (154, "indexer can not be used in this context, because " +
7721 "it lacks a `set' accessor");
7726 Error (1501, "No Overload for method `this' takes `" +
7727 arguments.Count + "' arguments");
7732 // Only base will allow this invocation to happen.
7734 if (set.IsAbstract && this is BaseIndexerAccess){
7735 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
7740 // Now look for the actual match in the list of indexers to set our "return" type
7742 type = TypeManager.void_type; // default value
7743 foreach (Indexers.Indexer ix in ilist.Properties){
7744 if (ix.Setter == set){
7750 eclass = ExprClass.IndexerAccess;
7754 public override void Emit (EmitContext ec)
7756 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc);
7760 // source is ignored, because we already have a copy of it from the
7761 // LValue resolution and we have already constructed a pre-cached
7762 // version of the arguments (ea.set_arguments);
7764 public void EmitAssign (EmitContext ec, Expression source)
7766 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc);
7771 /// The base operator for method names
7773 public class BaseAccess : Expression {
7776 public BaseAccess (string member, Location l)
7778 this.member = member;
7782 public override Expression DoResolve (EmitContext ec)
7784 Expression c = CommonResolve (ec);
7790 // MethodGroups use this opportunity to flag an error on lacking ()
7792 if (!(c is MethodGroupExpr))
7793 return c.Resolve (ec);
7797 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7799 Expression c = CommonResolve (ec);
7805 // MethodGroups use this opportunity to flag an error on lacking ()
7807 if (! (c is MethodGroupExpr))
7808 return c.DoResolveLValue (ec, right_side);
7813 Expression CommonResolve (EmitContext ec)
7815 Expression member_lookup;
7816 Type current_type = ec.ContainerType;
7817 Type base_type = current_type.BaseType;
7821 Error (1511, "Keyword base is not allowed in static method");
7825 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type, member,
7826 AllMemberTypes, AllBindingFlags, loc);
7827 if (member_lookup == null) {
7828 MemberLookupFailed (ec, base_type, base_type, member, null, loc);
7835 left = new TypeExpression (base_type, loc);
7837 left = ec.GetThis (loc);
7839 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
7841 if (e is PropertyExpr){
7842 PropertyExpr pe = (PropertyExpr) e;
7850 public override void Emit (EmitContext ec)
7852 throw new Exception ("Should never be called");
7857 /// The base indexer operator
7859 public class BaseIndexerAccess : IndexerAccess {
7860 public BaseIndexerAccess (ArrayList args, Location loc)
7861 : base (null, true, loc)
7863 arguments = new ArrayList ();
7864 foreach (Expression tmp in args)
7865 arguments.Add (new Argument (tmp, Argument.AType.Expression));
7868 protected override bool CommonResolve (EmitContext ec)
7870 instance_expr = ec.GetThis (loc);
7872 current_type = ec.ContainerType.BaseType;
7873 indexer_type = current_type;
7875 foreach (Argument a in arguments){
7876 if (!a.Resolve (ec, loc))
7885 /// This class exists solely to pass the Type around and to be a dummy
7886 /// that can be passed to the conversion functions (this is used by
7887 /// foreach implementation to typecast the object return value from
7888 /// get_Current into the proper type. All code has been generated and
7889 /// we only care about the side effect conversions to be performed
7891 /// This is also now used as a placeholder where a no-action expression
7892 /// is needed (the `New' class).
7894 public class EmptyExpression : Expression {
7895 public EmptyExpression ()
7897 type = TypeManager.object_type;
7898 eclass = ExprClass.Value;
7899 loc = Location.Null;
7902 public EmptyExpression (Type t)
7905 eclass = ExprClass.Value;
7906 loc = Location.Null;
7909 public override Expression DoResolve (EmitContext ec)
7914 public override void Emit (EmitContext ec)
7916 // nothing, as we only exist to not do anything.
7920 // This is just because we might want to reuse this bad boy
7921 // instead of creating gazillions of EmptyExpressions.
7922 // (CanImplicitConversion uses it)
7924 public void SetType (Type t)
7930 public class UserCast : Expression {
7934 public UserCast (MethodInfo method, Expression source, Location l)
7936 this.method = method;
7937 this.source = source;
7938 type = method.ReturnType;
7939 eclass = ExprClass.Value;
7943 public override Expression DoResolve (EmitContext ec)
7946 // We are born fully resolved
7951 public override void Emit (EmitContext ec)
7953 ILGenerator ig = ec.ig;
7957 if (method is MethodInfo)
7958 ig.Emit (OpCodes.Call, (MethodInfo) method);
7960 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
7966 // This class is used to "construct" the type during a typecast
7967 // operation. Since the Type.GetType class in .NET can parse
7968 // the type specification, we just use this to construct the type
7969 // one bit at a time.
7971 public class ComposedCast : TypeExpr {
7975 public ComposedCast (Expression left, string dim, Location l)
7982 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
7984 Type ltype = ec.DeclSpace.ResolveType (left, false, loc);
7989 // ltype.Fullname is already fully qualified, so we can skip
7990 // a lot of probes, and go directly to TypeManager.LookupType
7992 string cname = ltype.FullName + dim;
7993 type = TypeManager.LookupTypeDirect (cname);
7996 // For arrays of enumerations we are having a problem
7997 // with the direct lookup. Need to investigate.
7999 // For now, fall back to the full lookup in that case.
8001 type = RootContext.LookupType (
8002 ec.DeclSpace, cname, false, loc);
8008 if (!ec.ResolvingTypeTree){
8010 // If the above flag is set, this is being invoked from the ResolveType function.
8011 // Upper layers take care of the type validity in this context.
8013 if (!ec.InUnsafe && type.IsPointer){
8019 eclass = ExprClass.Type;
8023 public override string Name {
8031 // This class is used to represent the address of an array, used
8032 // only by the Fixed statement, this is like the C "&a [0]" construct.
8034 public class ArrayPtr : Expression {
8037 public ArrayPtr (Expression array, Location l)
8039 Type array_type = TypeManager.GetElementType (array.Type);
8043 type = TypeManager.GetPointerType (array_type);
8044 eclass = ExprClass.Value;
8048 public override void Emit (EmitContext ec)
8050 ILGenerator ig = ec.ig;
8053 IntLiteral.EmitInt (ig, 0);
8054 ig.Emit (OpCodes.Ldelema, TypeManager.GetElementType (array.Type));
8057 public override Expression DoResolve (EmitContext ec)
8060 // We are born fully resolved
8067 // Used by the fixed statement
8069 public class StringPtr : Expression {
8072 public StringPtr (LocalBuilder b, Location l)
8075 eclass = ExprClass.Value;
8076 type = TypeManager.char_ptr_type;
8080 public override Expression DoResolve (EmitContext ec)
8082 // This should never be invoked, we are born in fully
8083 // initialized state.
8088 public override void Emit (EmitContext ec)
8090 ILGenerator ig = ec.ig;
8092 ig.Emit (OpCodes.Ldloc, b);
8093 ig.Emit (OpCodes.Conv_I);
8094 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
8095 ig.Emit (OpCodes.Add);
8100 // Implements the `stackalloc' keyword
8102 public class StackAlloc : Expression {
8107 public StackAlloc (Expression type, Expression count, Location l)
8114 public override Expression DoResolve (EmitContext ec)
8116 count = count.Resolve (ec);
8120 if (count.Type != TypeManager.int32_type){
8121 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8126 if (ec.InCatch || ec.InFinally){
8128 "stackalloc can not be used in a catch or finally block");
8132 otype = ec.DeclSpace.ResolveType (t, false, loc);
8137 if (!TypeManager.VerifyUnManaged (otype, loc))
8140 type = TypeManager.GetPointerType (otype);
8141 eclass = ExprClass.Value;
8146 public override void Emit (EmitContext ec)
8148 int size = GetTypeSize (otype);
8149 ILGenerator ig = ec.ig;
8152 ig.Emit (OpCodes.Sizeof, otype);
8154 IntConstant.EmitInt (ig, size);
8156 ig.Emit (OpCodes.Mul);
8157 ig.Emit (OpCodes.Localloc);