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 TypeExpr (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 TypeExpr (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 TypeExpr (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 TypeExpr (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;
568 Type expr_type = Expr.Type;
571 case Operator.UnaryPlus:
572 throw new Exception ("This should be caught by Resolve");
574 case Operator.UnaryNegation:
576 ig.Emit (OpCodes.Neg);
579 case Operator.LogicalNot:
581 ig.Emit (OpCodes.Ldc_I4_0);
582 ig.Emit (OpCodes.Ceq);
585 case Operator.OnesComplement:
587 ig.Emit (OpCodes.Not);
590 case Operator.AddressOf:
591 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
595 throw new Exception ("This should not happen: Operator = "
601 /// This will emit the child expression for `ec' avoiding the logical
602 /// not. The parent will take care of changing brfalse/brtrue
604 public void EmitLogicalNot (EmitContext ec)
606 if (Oper != Operator.LogicalNot)
607 throw new Exception ("EmitLogicalNot can only be called with !expr");
612 public override string ToString ()
614 return "Unary (" + Oper + ", " + Expr + ")";
620 // Unary operators are turned into Indirection expressions
621 // after semantic analysis (this is so we can take the address
622 // of an indirection).
624 public class Indirection : Expression, IMemoryLocation, IAssignMethod {
626 LocalTemporary temporary;
629 public Indirection (Expression expr, Location l)
632 this.type = TypeManager.GetElementType (expr.Type);
633 eclass = ExprClass.Variable;
637 void LoadExprValue (EmitContext ec)
641 public override void Emit (EmitContext ec)
643 ILGenerator ig = ec.ig;
645 if (temporary != null){
651 ec.ig.Emit (OpCodes.Dup);
652 temporary.Store (ec);
653 have_temporary = true;
657 LoadFromPtr (ig, Type);
660 public void EmitAssign (EmitContext ec, Expression source)
662 if (temporary != null){
667 ec.ig.Emit (OpCodes.Dup);
668 temporary.Store (ec);
669 have_temporary = true;
675 StoreFromPtr (ec.ig, type);
678 public void AddressOf (EmitContext ec, AddressOp Mode)
680 if (temporary != null){
686 ec.ig.Emit (OpCodes.Dup);
687 temporary.Store (ec);
688 have_temporary = true;
693 public override Expression DoResolve (EmitContext ec)
696 // Born fully resolved
701 public new void CacheTemporaries (EmitContext ec)
703 temporary = new LocalTemporary (ec, expr.Type);
706 public override string ToString ()
708 return "*(" + expr + ")";
713 /// Unary Mutator expressions (pre and post ++ and --)
717 /// UnaryMutator implements ++ and -- expressions. It derives from
718 /// ExpressionStatement becuase the pre/post increment/decrement
719 /// operators can be used in a statement context.
721 /// FIXME: Idea, we could split this up in two classes, one simpler
722 /// for the common case, and one with the extra fields for more complex
723 /// classes (indexers require temporary access; overloaded require method)
726 public class UnaryMutator : ExpressionStatement {
728 public enum Mode : byte {
735 PreDecrement = IsDecrement,
736 PostIncrement = IsPost,
737 PostDecrement = IsPost | IsDecrement
742 LocalTemporary temp_storage;
745 // This is expensive for the simplest case.
749 public UnaryMutator (Mode m, Expression e, Location l)
756 static string OperName (Mode mode)
758 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
762 void Error23 (Type t)
765 23, "Operator " + OperName (mode) +
766 " cannot be applied to operand of type `" +
767 TypeManager.CSharpName (t) + "'");
771 /// Returns whether an object of type `t' can be incremented
772 /// or decremented with add/sub (ie, basically whether we can
773 /// use pre-post incr-decr operations on it, but it is not a
774 /// System.Decimal, which we require operator overloading to catch)
776 static bool IsIncrementableNumber (Type t)
778 return (t == TypeManager.sbyte_type) ||
779 (t == TypeManager.byte_type) ||
780 (t == TypeManager.short_type) ||
781 (t == TypeManager.ushort_type) ||
782 (t == TypeManager.int32_type) ||
783 (t == TypeManager.uint32_type) ||
784 (t == TypeManager.int64_type) ||
785 (t == TypeManager.uint64_type) ||
786 (t == TypeManager.char_type) ||
787 (t.IsSubclassOf (TypeManager.enum_type)) ||
788 (t == TypeManager.float_type) ||
789 (t == TypeManager.double_type) ||
790 (t.IsPointer && t != TypeManager.void_ptr_type);
793 Expression ResolveOperator (EmitContext ec)
795 Type expr_type = expr.Type;
798 // Step 1: Perform Operator Overload location
803 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
804 op_name = "op_Increment";
806 op_name = "op_Decrement";
808 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
810 if (mg == null && expr_type.BaseType != null)
811 mg = MemberLookup (ec, expr_type.BaseType, op_name,
812 MemberTypes.Method, AllBindingFlags, loc);
815 method = StaticCallExpr.MakeSimpleCall (
816 ec, (MethodGroupExpr) mg, expr, loc);
823 // The operand of the prefix/postfix increment decrement operators
824 // should be an expression that is classified as a variable,
825 // a property access or an indexer access
828 if (expr.eclass == ExprClass.Variable){
829 LocalVariableReference var = expr as LocalVariableReference;
830 if ((var != null) && var.IsReadOnly)
831 Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
832 if (IsIncrementableNumber (expr_type) ||
833 expr_type == TypeManager.decimal_type){
836 } else if (expr.eclass == ExprClass.IndexerAccess){
837 IndexerAccess ia = (IndexerAccess) expr;
839 temp_storage = new LocalTemporary (ec, expr.Type);
841 expr = ia.ResolveLValue (ec, temp_storage);
846 } else if (expr.eclass == ExprClass.PropertyAccess){
847 PropertyExpr pe = (PropertyExpr) expr;
849 if (pe.VerifyAssignable ())
854 expr.Error_UnexpectedKind ("variable, indexer or property access");
858 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
859 TypeManager.CSharpName (expr_type) + "'");
863 public override Expression DoResolve (EmitContext ec)
865 expr = expr.Resolve (ec);
870 eclass = ExprClass.Value;
871 return ResolveOperator (ec);
874 static int PtrTypeSize (Type t)
876 return GetTypeSize (TypeManager.GetElementType (t));
880 // Loads the proper "1" into the stack based on the type, then it emits the
881 // opcode for the operation requested
883 void LoadOneAndEmitOp (EmitContext ec, Type t)
886 // Measure if getting the typecode and using that is more/less efficient
887 // that comparing types. t.GetTypeCode() is an internal call.
889 ILGenerator ig = ec.ig;
891 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
892 LongConstant.EmitLong (ig, 1);
893 else if (t == TypeManager.double_type)
894 ig.Emit (OpCodes.Ldc_R8, 1.0);
895 else if (t == TypeManager.float_type)
896 ig.Emit (OpCodes.Ldc_R4, 1.0F);
897 else if (t.IsPointer){
898 int n = PtrTypeSize (t);
901 ig.Emit (OpCodes.Sizeof, t);
903 IntConstant.EmitInt (ig, n);
905 ig.Emit (OpCodes.Ldc_I4_1);
908 // Now emit the operation
911 if (t == TypeManager.int32_type ||
912 t == TypeManager.int64_type){
913 if ((mode & Mode.IsDecrement) != 0)
914 ig.Emit (OpCodes.Sub_Ovf);
916 ig.Emit (OpCodes.Add_Ovf);
917 } else if (t == TypeManager.uint32_type ||
918 t == TypeManager.uint64_type){
919 if ((mode & Mode.IsDecrement) != 0)
920 ig.Emit (OpCodes.Sub_Ovf_Un);
922 ig.Emit (OpCodes.Add_Ovf_Un);
924 if ((mode & Mode.IsDecrement) != 0)
925 ig.Emit (OpCodes.Sub_Ovf);
927 ig.Emit (OpCodes.Add_Ovf);
930 if ((mode & Mode.IsDecrement) != 0)
931 ig.Emit (OpCodes.Sub);
933 ig.Emit (OpCodes.Add);
936 if (t == TypeManager.sbyte_type){
938 ig.Emit (OpCodes.Conv_Ovf_I1);
940 ig.Emit (OpCodes.Conv_I1);
941 } else if (t == TypeManager.byte_type){
943 ig.Emit (OpCodes.Conv_Ovf_U1);
945 ig.Emit (OpCodes.Conv_U1);
946 } else if (t == TypeManager.short_type){
948 ig.Emit (OpCodes.Conv_Ovf_I2);
950 ig.Emit (OpCodes.Conv_I2);
951 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
953 ig.Emit (OpCodes.Conv_Ovf_U2);
955 ig.Emit (OpCodes.Conv_U2);
960 static EmptyExpression empty_expr;
962 void EmitCode (EmitContext ec, bool is_expr)
964 ILGenerator ig = ec.ig;
965 IAssignMethod ia = (IAssignMethod) expr;
966 Type expr_type = expr.Type;
968 ia.CacheTemporaries (ec);
970 if (temp_storage == null){
972 // Temporary improvement: if we are dealing with something that does
973 // not require complicated instance setup, avoid using a temporary
975 // For now: only localvariables when not remapped
978 if (method == null && (expr is FieldExpr && ((FieldExpr) expr).FieldInfo.IsStatic)){
979 if (empty_expr == null)
980 empty_expr = new EmptyExpression ();
983 case Mode.PreIncrement:
984 case Mode.PreDecrement:
987 LoadOneAndEmitOp (ec, expr_type);
989 ig.Emit (OpCodes.Dup);
990 ia.EmitAssign (ec, empty_expr);
993 case Mode.PostIncrement:
994 case Mode.PostDecrement:
997 ig.Emit (OpCodes.Dup);
999 LoadOneAndEmitOp (ec, expr_type);
1000 ia.EmitAssign (ec, empty_expr);
1005 temp_storage = new LocalTemporary (ec, expr_type);
1009 case Mode.PreIncrement:
1010 case Mode.PreDecrement:
1011 if (method == null){
1014 LoadOneAndEmitOp (ec, expr_type);
1018 temp_storage.Store (ec);
1019 ia.EmitAssign (ec, temp_storage);
1021 temp_storage.Emit (ec);
1024 case Mode.PostIncrement:
1025 case Mode.PostDecrement:
1029 if (method == null){
1033 ig.Emit (OpCodes.Dup);
1035 LoadOneAndEmitOp (ec, expr_type);
1040 temp_storage.Store (ec);
1041 ia.EmitAssign (ec, temp_storage);
1046 public override void Emit (EmitContext ec)
1048 EmitCode (ec, true);
1052 public override void EmitStatement (EmitContext ec)
1054 EmitCode (ec, false);
1060 /// Base class for the `Is' and `As' classes.
1064 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1067 public abstract class Probe : Expression {
1068 public readonly Expression ProbeType;
1069 protected Expression expr;
1070 protected Type probe_type;
1072 public Probe (Expression expr, Expression probe_type, Location l)
1074 ProbeType = probe_type;
1079 public Expression Expr {
1085 public override Expression DoResolve (EmitContext ec)
1087 probe_type = ec.DeclSpace.ResolveType (ProbeType, false, loc);
1089 if (probe_type == null)
1092 expr = expr.Resolve (ec);
1101 /// Implementation of the `is' operator.
1103 public class Is : Probe {
1104 public Is (Expression expr, Expression probe_type, Location l)
1105 : base (expr, probe_type, l)
1110 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1115 public override void Emit (EmitContext ec)
1117 ILGenerator ig = ec.ig;
1122 case Action.AlwaysFalse:
1123 ig.Emit (OpCodes.Pop);
1124 IntConstant.EmitInt (ig, 0);
1126 case Action.AlwaysTrue:
1127 ig.Emit (OpCodes.Pop);
1128 IntConstant.EmitInt (ig, 1);
1130 case Action.LeaveOnStack:
1131 // the `e != null' rule.
1132 ig.Emit (OpCodes.Ldnull);
1133 ig.Emit (OpCodes.Ceq);
1134 ig.Emit (OpCodes.Ldc_I4_0);
1135 ig.Emit (OpCodes.Ceq);
1138 ig.Emit (OpCodes.Isinst, probe_type);
1139 ig.Emit (OpCodes.Ldnull);
1140 ig.Emit (OpCodes.Cgt_Un);
1143 throw new Exception ("never reached");
1146 public override Expression DoResolve (EmitContext ec)
1148 Expression e = base.DoResolve (ec);
1150 if ((e == null) || (expr == null))
1153 Type etype = expr.Type;
1154 bool warning_always_matches = false;
1155 bool warning_never_matches = false;
1157 type = TypeManager.bool_type;
1158 eclass = ExprClass.Value;
1161 // First case, if at compile time, there is an implicit conversion
1162 // then e != null (objects) or true (value types)
1164 e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1167 if (etype.IsValueType)
1168 action = Action.AlwaysTrue;
1170 action = Action.LeaveOnStack;
1172 warning_always_matches = true;
1173 } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1175 // Second case: explicit reference convresion
1177 if (expr is NullLiteral)
1178 action = Action.AlwaysFalse;
1180 action = Action.Probe;
1182 action = Action.AlwaysFalse;
1183 warning_never_matches = true;
1186 if (RootContext.WarningLevel >= 1){
1187 if (warning_always_matches)
1188 Warning (183, "The expression is always of type `" +
1189 TypeManager.CSharpName (probe_type) + "'");
1190 else if (warning_never_matches){
1191 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1193 "The expression is never of type `" +
1194 TypeManager.CSharpName (probe_type) + "'");
1203 /// Implementation of the `as' operator.
1205 public class As : Probe {
1206 public As (Expression expr, Expression probe_type, Location l)
1207 : base (expr, probe_type, l)
1211 bool do_isinst = false;
1213 public override void Emit (EmitContext ec)
1215 ILGenerator ig = ec.ig;
1220 ig.Emit (OpCodes.Isinst, probe_type);
1223 static void Error_CannotConvertType (Type source, Type target, Location loc)
1226 39, loc, "as operator can not convert from `" +
1227 TypeManager.CSharpName (source) + "' to `" +
1228 TypeManager.CSharpName (target) + "'");
1231 public override Expression DoResolve (EmitContext ec)
1233 Expression e = base.DoResolve (ec);
1239 eclass = ExprClass.Value;
1240 Type etype = expr.Type;
1242 if (TypeManager.IsValueType (probe_type)){
1243 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1244 TypeManager.CSharpName (probe_type) + " is a value type");
1249 e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1256 if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1261 Error_CannotConvertType (etype, probe_type, loc);
1267 /// This represents a typecast in the source language.
1269 /// FIXME: Cast expressions have an unusual set of parsing
1270 /// rules, we need to figure those out.
1272 public class Cast : Expression {
1273 Expression target_type;
1276 public Cast (Expression cast_type, Expression expr, Location loc)
1278 this.target_type = cast_type;
1283 public Expression TargetType {
1289 public Expression Expr {
1298 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1300 if (!ec.ConstantCheckState)
1303 if ((value < min) || (value > max)) {
1304 Error (221, "Constant value `" + value + "' cannot be converted " +
1305 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1306 "syntax to override)");
1313 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1315 if (!ec.ConstantCheckState)
1319 Error (221, "Constant value `" + value + "' cannot be converted " +
1320 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1321 "syntax to override)");
1328 bool CheckUnsigned (EmitContext ec, long value, Type type)
1330 if (!ec.ConstantCheckState)
1334 Error (221, "Constant value `" + value + "' cannot be converted " +
1335 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1336 "syntax to override)");
1344 /// Attempts to do a compile-time folding of a constant cast.
1346 Expression TryReduce (EmitContext ec, Type target_type)
1348 Expression real_expr = expr;
1349 if (real_expr is EnumConstant)
1350 real_expr = ((EnumConstant) real_expr).Child;
1352 if (real_expr is ByteConstant){
1353 byte v = ((ByteConstant) real_expr).Value;
1355 if (target_type == TypeManager.sbyte_type) {
1356 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1358 return new SByteConstant ((sbyte) v);
1360 if (target_type == TypeManager.short_type)
1361 return new ShortConstant ((short) v);
1362 if (target_type == TypeManager.ushort_type)
1363 return new UShortConstant ((ushort) v);
1364 if (target_type == TypeManager.int32_type)
1365 return new IntConstant ((int) v);
1366 if (target_type == TypeManager.uint32_type)
1367 return new UIntConstant ((uint) v);
1368 if (target_type == TypeManager.int64_type)
1369 return new LongConstant ((long) v);
1370 if (target_type == TypeManager.uint64_type)
1371 return new ULongConstant ((ulong) v);
1372 if (target_type == TypeManager.float_type)
1373 return new FloatConstant ((float) v);
1374 if (target_type == TypeManager.double_type)
1375 return new DoubleConstant ((double) v);
1376 if (target_type == TypeManager.char_type)
1377 return new CharConstant ((char) v);
1378 if (target_type == TypeManager.decimal_type)
1379 return new DecimalConstant ((decimal) v);
1381 if (real_expr is SByteConstant){
1382 sbyte v = ((SByteConstant) real_expr).Value;
1384 if (target_type == TypeManager.byte_type) {
1385 if (!CheckUnsigned (ec, v, target_type))
1387 return new ByteConstant ((byte) v);
1389 if (target_type == TypeManager.short_type)
1390 return new ShortConstant ((short) v);
1391 if (target_type == TypeManager.ushort_type) {
1392 if (!CheckUnsigned (ec, v, target_type))
1394 return new UShortConstant ((ushort) v);
1395 } if (target_type == TypeManager.int32_type)
1396 return new IntConstant ((int) v);
1397 if (target_type == TypeManager.uint32_type) {
1398 if (!CheckUnsigned (ec, v, target_type))
1400 return new UIntConstant ((uint) v);
1401 } if (target_type == TypeManager.int64_type)
1402 return new LongConstant ((long) v);
1403 if (target_type == TypeManager.uint64_type) {
1404 if (!CheckUnsigned (ec, v, target_type))
1406 return new ULongConstant ((ulong) v);
1408 if (target_type == TypeManager.float_type)
1409 return new FloatConstant ((float) v);
1410 if (target_type == TypeManager.double_type)
1411 return new DoubleConstant ((double) v);
1412 if (target_type == TypeManager.char_type) {
1413 if (!CheckUnsigned (ec, v, target_type))
1415 return new CharConstant ((char) v);
1417 if (target_type == TypeManager.decimal_type)
1418 return new DecimalConstant ((decimal) v);
1420 if (real_expr is ShortConstant){
1421 short v = ((ShortConstant) real_expr).Value;
1423 if (target_type == TypeManager.byte_type) {
1424 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1426 return new ByteConstant ((byte) v);
1428 if (target_type == TypeManager.sbyte_type) {
1429 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1431 return new SByteConstant ((sbyte) v);
1433 if (target_type == TypeManager.ushort_type) {
1434 if (!CheckUnsigned (ec, v, target_type))
1436 return new UShortConstant ((ushort) v);
1438 if (target_type == TypeManager.int32_type)
1439 return new IntConstant ((int) v);
1440 if (target_type == TypeManager.uint32_type) {
1441 if (!CheckUnsigned (ec, v, target_type))
1443 return new UIntConstant ((uint) v);
1445 if (target_type == TypeManager.int64_type)
1446 return new LongConstant ((long) v);
1447 if (target_type == TypeManager.uint64_type) {
1448 if (!CheckUnsigned (ec, v, target_type))
1450 return new ULongConstant ((ulong) v);
1452 if (target_type == TypeManager.float_type)
1453 return new FloatConstant ((float) v);
1454 if (target_type == TypeManager.double_type)
1455 return new DoubleConstant ((double) v);
1456 if (target_type == TypeManager.char_type) {
1457 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1459 return new CharConstant ((char) v);
1461 if (target_type == TypeManager.decimal_type)
1462 return new DecimalConstant ((decimal) v);
1464 if (real_expr is UShortConstant){
1465 ushort v = ((UShortConstant) real_expr).Value;
1467 if (target_type == TypeManager.byte_type) {
1468 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1470 return new ByteConstant ((byte) v);
1472 if (target_type == TypeManager.sbyte_type) {
1473 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1475 return new SByteConstant ((sbyte) v);
1477 if (target_type == TypeManager.short_type) {
1478 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1480 return new ShortConstant ((short) v);
1482 if (target_type == TypeManager.int32_type)
1483 return new IntConstant ((int) v);
1484 if (target_type == TypeManager.uint32_type)
1485 return new UIntConstant ((uint) v);
1486 if (target_type == TypeManager.int64_type)
1487 return new LongConstant ((long) v);
1488 if (target_type == TypeManager.uint64_type)
1489 return new ULongConstant ((ulong) v);
1490 if (target_type == TypeManager.float_type)
1491 return new FloatConstant ((float) v);
1492 if (target_type == TypeManager.double_type)
1493 return new DoubleConstant ((double) v);
1494 if (target_type == TypeManager.char_type) {
1495 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1497 return new CharConstant ((char) v);
1499 if (target_type == TypeManager.decimal_type)
1500 return new DecimalConstant ((decimal) v);
1502 if (real_expr is IntConstant){
1503 int v = ((IntConstant) real_expr).Value;
1505 if (target_type == TypeManager.byte_type) {
1506 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1508 return new ByteConstant ((byte) v);
1510 if (target_type == TypeManager.sbyte_type) {
1511 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1513 return new SByteConstant ((sbyte) v);
1515 if (target_type == TypeManager.short_type) {
1516 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1518 return new ShortConstant ((short) v);
1520 if (target_type == TypeManager.ushort_type) {
1521 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1523 return new UShortConstant ((ushort) v);
1525 if (target_type == TypeManager.uint32_type) {
1526 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1528 return new UIntConstant ((uint) v);
1530 if (target_type == TypeManager.int64_type)
1531 return new LongConstant ((long) v);
1532 if (target_type == TypeManager.uint64_type) {
1533 if (!CheckUnsigned (ec, v, target_type))
1535 return new ULongConstant ((ulong) v);
1537 if (target_type == TypeManager.float_type)
1538 return new FloatConstant ((float) v);
1539 if (target_type == TypeManager.double_type)
1540 return new DoubleConstant ((double) v);
1541 if (target_type == TypeManager.char_type) {
1542 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1544 return new CharConstant ((char) v);
1546 if (target_type == TypeManager.decimal_type)
1547 return new DecimalConstant ((decimal) v);
1549 if (real_expr is UIntConstant){
1550 uint v = ((UIntConstant) real_expr).Value;
1552 if (target_type == TypeManager.byte_type) {
1553 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1555 return new ByteConstant ((byte) v);
1557 if (target_type == TypeManager.sbyte_type) {
1558 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1560 return new SByteConstant ((sbyte) v);
1562 if (target_type == TypeManager.short_type) {
1563 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1565 return new ShortConstant ((short) v);
1567 if (target_type == TypeManager.ushort_type) {
1568 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1570 return new UShortConstant ((ushort) v);
1572 if (target_type == TypeManager.int32_type) {
1573 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1575 return new IntConstant ((int) v);
1577 if (target_type == TypeManager.int64_type)
1578 return new LongConstant ((long) v);
1579 if (target_type == TypeManager.uint64_type)
1580 return new ULongConstant ((ulong) v);
1581 if (target_type == TypeManager.float_type)
1582 return new FloatConstant ((float) v);
1583 if (target_type == TypeManager.double_type)
1584 return new DoubleConstant ((double) v);
1585 if (target_type == TypeManager.char_type) {
1586 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1588 return new CharConstant ((char) v);
1590 if (target_type == TypeManager.decimal_type)
1591 return new DecimalConstant ((decimal) v);
1593 if (real_expr is LongConstant){
1594 long v = ((LongConstant) real_expr).Value;
1596 if (target_type == TypeManager.byte_type) {
1597 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1599 return new ByteConstant ((byte) v);
1601 if (target_type == TypeManager.sbyte_type) {
1602 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1604 return new SByteConstant ((sbyte) v);
1606 if (target_type == TypeManager.short_type) {
1607 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1609 return new ShortConstant ((short) v);
1611 if (target_type == TypeManager.ushort_type) {
1612 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1614 return new UShortConstant ((ushort) v);
1616 if (target_type == TypeManager.int32_type) {
1617 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1619 return new IntConstant ((int) v);
1621 if (target_type == TypeManager.uint32_type) {
1622 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1624 return new UIntConstant ((uint) v);
1626 if (target_type == TypeManager.uint64_type) {
1627 if (!CheckUnsigned (ec, v, target_type))
1629 return new ULongConstant ((ulong) v);
1631 if (target_type == TypeManager.float_type)
1632 return new FloatConstant ((float) v);
1633 if (target_type == TypeManager.double_type)
1634 return new DoubleConstant ((double) v);
1635 if (target_type == TypeManager.char_type) {
1636 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1638 return new CharConstant ((char) v);
1640 if (target_type == TypeManager.decimal_type)
1641 return new DecimalConstant ((decimal) v);
1643 if (real_expr is ULongConstant){
1644 ulong v = ((ULongConstant) real_expr).Value;
1646 if (target_type == TypeManager.byte_type) {
1647 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1649 return new ByteConstant ((byte) v);
1651 if (target_type == TypeManager.sbyte_type) {
1652 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1654 return new SByteConstant ((sbyte) v);
1656 if (target_type == TypeManager.short_type) {
1657 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1659 return new ShortConstant ((short) v);
1661 if (target_type == TypeManager.ushort_type) {
1662 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1664 return new UShortConstant ((ushort) v);
1666 if (target_type == TypeManager.int32_type) {
1667 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1669 return new IntConstant ((int) v);
1671 if (target_type == TypeManager.uint32_type) {
1672 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1674 return new UIntConstant ((uint) v);
1676 if (target_type == TypeManager.int64_type) {
1677 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1679 return new LongConstant ((long) v);
1681 if (target_type == TypeManager.float_type)
1682 return new FloatConstant ((float) v);
1683 if (target_type == TypeManager.double_type)
1684 return new DoubleConstant ((double) v);
1685 if (target_type == TypeManager.char_type) {
1686 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1688 return new CharConstant ((char) v);
1690 if (target_type == TypeManager.decimal_type)
1691 return new DecimalConstant ((decimal) v);
1693 if (real_expr is FloatConstant){
1694 float v = ((FloatConstant) real_expr).Value;
1696 if (target_type == TypeManager.byte_type)
1697 return new ByteConstant ((byte) v);
1698 if (target_type == TypeManager.sbyte_type)
1699 return new SByteConstant ((sbyte) v);
1700 if (target_type == TypeManager.short_type)
1701 return new ShortConstant ((short) v);
1702 if (target_type == TypeManager.ushort_type)
1703 return new UShortConstant ((ushort) v);
1704 if (target_type == TypeManager.int32_type)
1705 return new IntConstant ((int) v);
1706 if (target_type == TypeManager.uint32_type)
1707 return new UIntConstant ((uint) v);
1708 if (target_type == TypeManager.int64_type)
1709 return new LongConstant ((long) v);
1710 if (target_type == TypeManager.uint64_type)
1711 return new ULongConstant ((ulong) v);
1712 if (target_type == TypeManager.double_type)
1713 return new DoubleConstant ((double) v);
1714 if (target_type == TypeManager.char_type)
1715 return new CharConstant ((char) v);
1716 if (target_type == TypeManager.decimal_type)
1717 return new DecimalConstant ((decimal) v);
1719 if (real_expr is DoubleConstant){
1720 double v = ((DoubleConstant) real_expr).Value;
1722 if (target_type == TypeManager.byte_type)
1723 return new ByteConstant ((byte) v);
1724 if (target_type == TypeManager.sbyte_type)
1725 return new SByteConstant ((sbyte) v);
1726 if (target_type == TypeManager.short_type)
1727 return new ShortConstant ((short) v);
1728 if (target_type == TypeManager.ushort_type)
1729 return new UShortConstant ((ushort) v);
1730 if (target_type == TypeManager.int32_type)
1731 return new IntConstant ((int) v);
1732 if (target_type == TypeManager.uint32_type)
1733 return new UIntConstant ((uint) v);
1734 if (target_type == TypeManager.int64_type)
1735 return new LongConstant ((long) v);
1736 if (target_type == TypeManager.uint64_type)
1737 return new ULongConstant ((ulong) v);
1738 if (target_type == TypeManager.float_type)
1739 return new FloatConstant ((float) v);
1740 if (target_type == TypeManager.char_type)
1741 return new CharConstant ((char) v);
1742 if (target_type == TypeManager.decimal_type)
1743 return new DecimalConstant ((decimal) v);
1746 if (real_expr is CharConstant){
1747 char v = ((CharConstant) real_expr).Value;
1749 if (target_type == TypeManager.byte_type) {
1750 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1752 return new ByteConstant ((byte) v);
1754 if (target_type == TypeManager.sbyte_type) {
1755 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1757 return new SByteConstant ((sbyte) v);
1759 if (target_type == TypeManager.short_type) {
1760 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1762 return new ShortConstant ((short) 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.double_type)
1775 return new DoubleConstant ((double) v);
1776 if (target_type == TypeManager.char_type) {
1777 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1779 return new CharConstant ((char) v);
1781 if (target_type == TypeManager.decimal_type)
1782 return new DecimalConstant ((decimal) v);
1788 public override Expression DoResolve (EmitContext ec)
1790 expr = expr.Resolve (ec);
1794 int errors = Report.Errors;
1796 type = ec.DeclSpace.ResolveType (target_type, false, Location);
1801 eclass = ExprClass.Value;
1803 if (expr is Constant){
1804 Expression e = TryReduce (ec, type);
1810 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1814 public override void Emit (EmitContext ec)
1817 // This one will never happen
1819 throw new Exception ("Should not happen");
1824 /// Binary operators
1826 public class Binary : Expression {
1827 public enum Operator : byte {
1828 Multiply, Division, Modulus,
1829 Addition, Subtraction,
1830 LeftShift, RightShift,
1831 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1832 Equality, Inequality,
1842 Expression left, right;
1844 // This must be kept in sync with Operator!!!
1845 public static readonly string [] oper_names;
1849 oper_names = new string [(int) Operator.TOP];
1851 oper_names [(int) Operator.Multiply] = "op_Multiply";
1852 oper_names [(int) Operator.Division] = "op_Division";
1853 oper_names [(int) Operator.Modulus] = "op_Modulus";
1854 oper_names [(int) Operator.Addition] = "op_Addition";
1855 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1856 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1857 oper_names [(int) Operator.RightShift] = "op_RightShift";
1858 oper_names [(int) Operator.LessThan] = "op_LessThan";
1859 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1860 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1861 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1862 oper_names [(int) Operator.Equality] = "op_Equality";
1863 oper_names [(int) Operator.Inequality] = "op_Inequality";
1864 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1865 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1866 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1867 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1868 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1871 public Binary (Operator oper, Expression left, Expression right, Location loc)
1879 public Operator Oper {
1888 public Expression Left {
1897 public Expression Right {
1908 /// Returns a stringified representation of the Operator
1910 static string OperName (Operator oper)
1913 case Operator.Multiply:
1915 case Operator.Division:
1917 case Operator.Modulus:
1919 case Operator.Addition:
1921 case Operator.Subtraction:
1923 case Operator.LeftShift:
1925 case Operator.RightShift:
1927 case Operator.LessThan:
1929 case Operator.GreaterThan:
1931 case Operator.LessThanOrEqual:
1933 case Operator.GreaterThanOrEqual:
1935 case Operator.Equality:
1937 case Operator.Inequality:
1939 case Operator.BitwiseAnd:
1941 case Operator.BitwiseOr:
1943 case Operator.ExclusiveOr:
1945 case Operator.LogicalOr:
1947 case Operator.LogicalAnd:
1951 return oper.ToString ();
1954 public override string ToString ()
1956 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1957 right.ToString () + ")";
1960 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1962 if (expr.Type == target_type)
1965 return Convert.ImplicitConversion (ec, expr, target_type, loc);
1968 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1971 34, loc, "Operator `" + OperName (oper)
1972 + "' is ambiguous on operands of type `"
1973 + TypeManager.CSharpName (l) + "' "
1974 + "and `" + TypeManager.CSharpName (r)
1978 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
1980 if ((l == t) || (r == t))
1983 if (!check_user_conversions)
1986 if (Convert.ImplicitUserConversionExists (ec, l, t))
1988 else if (Convert.ImplicitUserConversionExists (ec, r, t))
1995 // Note that handling the case l == Decimal || r == Decimal
1996 // is taken care of by the Step 1 Operator Overload resolution.
1998 // If `check_user_conv' is true, we also check whether a user-defined conversion
1999 // exists. Note that we only need to do this if both arguments are of a user-defined
2000 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
2001 // so we don't explicitly check for performance reasons.
2003 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
2005 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
2007 // If either operand is of type double, the other operand is
2008 // conveted to type double.
2010 if (r != TypeManager.double_type)
2011 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
2012 if (l != TypeManager.double_type)
2013 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
2015 type = TypeManager.double_type;
2016 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
2018 // if either operand is of type float, the other operand is
2019 // converted to type float.
2021 if (r != TypeManager.double_type)
2022 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
2023 if (l != TypeManager.double_type)
2024 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
2025 type = TypeManager.float_type;
2026 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2030 // If either operand is of type ulong, the other operand is
2031 // converted to type ulong. or an error ocurrs if the other
2032 // operand is of type sbyte, short, int or long
2034 if (l == TypeManager.uint64_type){
2035 if (r != TypeManager.uint64_type){
2036 if (right is IntConstant){
2037 IntConstant ic = (IntConstant) right;
2039 e = Convert.TryImplicitIntConversion (l, ic);
2042 } else if (right is LongConstant){
2043 long ll = ((LongConstant) right).Value;
2046 right = new ULongConstant ((ulong) ll);
2048 e = Convert.ImplicitNumericConversion (ec, right, l, loc);
2055 if (left is IntConstant){
2056 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
2059 } else if (left is LongConstant){
2060 long ll = ((LongConstant) left).Value;
2063 left = new ULongConstant ((ulong) ll);
2065 e = Convert.ImplicitNumericConversion (ec, left, r, loc);
2072 if ((other == TypeManager.sbyte_type) ||
2073 (other == TypeManager.short_type) ||
2074 (other == TypeManager.int32_type) ||
2075 (other == TypeManager.int64_type))
2076 Error_OperatorAmbiguous (loc, oper, l, r);
2077 type = TypeManager.uint64_type;
2078 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2080 // If either operand is of type long, the other operand is converted
2083 if (l != TypeManager.int64_type)
2084 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
2085 if (r != TypeManager.int64_type)
2086 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
2088 type = TypeManager.int64_type;
2089 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2091 // If either operand is of type uint, and the other
2092 // operand is of type sbyte, short or int, othe operands are
2093 // converted to type long.
2097 if (l == TypeManager.uint32_type){
2098 if (right is IntConstant){
2099 IntConstant ic = (IntConstant) right;
2103 right = new UIntConstant ((uint) val);
2110 } else if (r == TypeManager.uint32_type){
2111 if (left is IntConstant){
2112 IntConstant ic = (IntConstant) left;
2116 left = new UIntConstant ((uint) val);
2125 if ((other == TypeManager.sbyte_type) ||
2126 (other == TypeManager.short_type) ||
2127 (other == TypeManager.int32_type)){
2128 left = ForceConversion (ec, left, TypeManager.int64_type);
2129 right = ForceConversion (ec, right, TypeManager.int64_type);
2130 type = TypeManager.int64_type;
2133 // if either operand is of type uint, the other
2134 // operand is converd to type uint
2136 left = ForceConversion (ec, left, TypeManager.uint32_type);
2137 right = ForceConversion (ec, right, TypeManager.uint32_type);
2138 type = TypeManager.uint32_type;
2140 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2141 if (l != TypeManager.decimal_type)
2142 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
2144 if (r != TypeManager.decimal_type)
2145 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
2146 type = TypeManager.decimal_type;
2148 left = ForceConversion (ec, left, TypeManager.int32_type);
2149 right = ForceConversion (ec, right, TypeManager.int32_type);
2151 type = TypeManager.int32_type;
2154 return (left != null) && (right != null);
2157 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2159 Report.Error (19, loc,
2160 "Operator " + name + " cannot be applied to operands of type `" +
2161 TypeManager.CSharpName (l) + "' and `" +
2162 TypeManager.CSharpName (r) + "'");
2165 void Error_OperatorCannotBeApplied ()
2167 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2170 static bool is_32_or_64 (Type t)
2172 return (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2173 t == TypeManager.int64_type || t == TypeManager.uint64_type);
2176 static bool is_unsigned (Type t)
2178 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2179 t == TypeManager.short_type || t == TypeManager.byte_type);
2182 static bool is_user_defined (Type t)
2184 if (t.IsSubclassOf (TypeManager.value_type) &&
2185 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2191 Expression CheckShiftArguments (EmitContext ec)
2195 Type r = right.Type;
2197 e = ForceConversion (ec, right, TypeManager.int32_type);
2199 Error_OperatorCannotBeApplied ();
2204 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
2205 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
2206 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
2207 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
2213 Error_OperatorCannotBeApplied ();
2217 Expression ResolveOperator (EmitContext ec)
2220 Type r = right.Type;
2222 bool overload_failed = false;
2225 // Special cases: string comapred to null
2227 if (oper == Operator.Equality || oper == Operator.Inequality){
2228 if ((l == TypeManager.string_type && (right is NullLiteral)) ||
2229 (r == TypeManager.string_type && (left is NullLiteral))){
2230 Type = TypeManager.bool_type;
2237 // Do not perform operator overload resolution when both sides are
2240 if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
2242 // Step 1: Perform Operator Overload location
2244 Expression left_expr, right_expr;
2246 string op = oper_names [(int) oper];
2248 MethodGroupExpr union;
2249 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2251 right_expr = MemberLookup (
2252 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2253 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2255 union = (MethodGroupExpr) left_expr;
2257 if (union != null) {
2258 ArrayList args = new ArrayList (2);
2259 args.Add (new Argument (left, Argument.AType.Expression));
2260 args.Add (new Argument (right, Argument.AType.Expression));
2262 MethodBase method = Invocation.OverloadResolve (ec, union, args, Location.Null);
2263 if (method != null) {
2264 MethodInfo mi = (MethodInfo) method;
2266 return new BinaryMethod (mi.ReturnType, method, args);
2268 overload_failed = true;
2274 // Step 2: Default operations on CLI native types.
2278 // Step 0: String concatenation (because overloading will get this wrong)
2280 if (oper == Operator.Addition){
2282 // If any of the arguments is a string, cast to string
2285 if (l == TypeManager.string_type){
2288 if (r == TypeManager.void_type) {
2289 Error_OperatorCannotBeApplied ();
2293 if (r == TypeManager.string_type){
2294 if (left is Constant && right is Constant){
2295 StringConstant ls = (StringConstant) left;
2296 StringConstant rs = (StringConstant) right;
2298 return new StringConstant (
2299 ls.Value + rs.Value);
2302 if (left is BinaryMethod){
2303 BinaryMethod b = (BinaryMethod) left;
2306 // Call String.Concat (string, string, string) or
2307 // String.Concat (string, string, string, string)
2310 if (b.method == TypeManager.string_concat_string_string ||
2311 b.method == TypeManager.string_concat_string_string_string){
2312 ArrayList bargs = b.Arguments;
2313 int count = bargs.Count;
2316 bargs.Add (new Argument (right, Argument.AType.Expression));
2317 return new BinaryMethod (
2318 TypeManager.string_type,
2319 TypeManager.string_concat_string_string_string, bargs);
2320 } else if (count == 3){
2321 bargs.Add (new Argument (right, Argument.AType.Expression));
2322 return new BinaryMethod (
2323 TypeManager.string_type,
2324 TypeManager.string_concat_string_string_string_string, bargs);
2330 method = TypeManager.string_concat_string_string;
2333 method = TypeManager.string_concat_object_object;
2334 right = Convert.ImplicitConversion (
2335 ec, right, TypeManager.object_type, loc);
2337 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2343 // Cascading concats will hold up to 4 arguments
2345 ArrayList args = new ArrayList (4);
2346 args.Add (new Argument (left, Argument.AType.Expression));
2347 args.Add (new Argument (right, Argument.AType.Expression));
2349 return new BinaryMethod (TypeManager.string_type, method, args);
2350 } else if (r == TypeManager.string_type){
2353 if (l == TypeManager.void_type) {
2354 Error_OperatorCannotBeApplied ();
2358 left = Convert.ImplicitConversion (ec, left, TypeManager.object_type, loc);
2360 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2363 ArrayList args = new ArrayList (2);
2364 args.Add (new Argument (left, Argument.AType.Expression));
2365 args.Add (new Argument (right, Argument.AType.Expression));
2367 return new BinaryMethod (TypeManager.string_type, TypeManager.string_concat_object_object, args);
2371 // Transform a + ( - b) into a - b
2373 if (right is Unary){
2374 Unary right_unary = (Unary) right;
2376 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2377 oper = Operator.Subtraction;
2378 right = right_unary.Expr;
2384 if (oper == Operator.Equality || oper == Operator.Inequality){
2385 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2386 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2387 Error_OperatorCannotBeApplied ();
2391 type = TypeManager.bool_type;
2396 // operator != (object a, object b)
2397 // operator == (object a, object b)
2399 // For this to be used, both arguments have to be reference-types.
2400 // Read the rationale on the spec (14.9.6)
2402 // Also, if at compile time we know that the classes do not inherit
2403 // one from the other, then we catch the error there.
2405 if (!(l.IsValueType || r.IsValueType)){
2406 type = TypeManager.bool_type;
2411 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2415 // Also, a standard conversion must exist from either one
2417 if (!(Convert.ImplicitStandardConversionExists (left, r) ||
2418 Convert.ImplicitStandardConversionExists (right, l))){
2419 Error_OperatorCannotBeApplied ();
2423 // We are going to have to convert to an object to compare
2425 if (l != TypeManager.object_type)
2426 left = new EmptyCast (left, TypeManager.object_type);
2427 if (r != TypeManager.object_type)
2428 right = new EmptyCast (right, TypeManager.object_type);
2431 // FIXME: CSC here catches errors cs254 and cs252
2437 // One of them is a valuetype, but the other one is not.
2439 if (!l.IsValueType || !r.IsValueType) {
2440 Error_OperatorCannotBeApplied ();
2445 // Only perform numeric promotions on:
2446 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2448 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2449 if (l.IsSubclassOf (TypeManager.delegate_type) &&
2450 r.IsSubclassOf (TypeManager.delegate_type)) {
2452 ArrayList args = new ArrayList (2);
2454 args = new ArrayList (2);
2455 args.Add (new Argument (left, Argument.AType.Expression));
2456 args.Add (new Argument (right, Argument.AType.Expression));
2458 if (oper == Operator.Addition)
2459 method = TypeManager.delegate_combine_delegate_delegate;
2461 method = TypeManager.delegate_remove_delegate_delegate;
2464 Error_OperatorCannotBeApplied ();
2468 return new BinaryDelegate (l, method, args);
2472 // Pointer arithmetic:
2474 // T* operator + (T* x, int y);
2475 // T* operator + (T* x, uint y);
2476 // T* operator + (T* x, long y);
2477 // T* operator + (T* x, ulong y);
2479 // T* operator + (int y, T* x);
2480 // T* operator + (uint y, T *x);
2481 // T* operator + (long y, T *x);
2482 // T* operator + (ulong y, T *x);
2484 // T* operator - (T* x, int y);
2485 // T* operator - (T* x, uint y);
2486 // T* operator - (T* x, long y);
2487 // T* operator - (T* x, ulong y);
2489 // long operator - (T* x, T *y)
2492 if (r.IsPointer && oper == Operator.Subtraction){
2494 return new PointerArithmetic (
2495 false, left, right, TypeManager.int64_type,
2497 } else if (is_32_or_64 (r))
2498 return new PointerArithmetic (
2499 oper == Operator.Addition, left, right, l, loc);
2500 } else if (r.IsPointer && is_32_or_64 (l) && oper == Operator.Addition)
2501 return new PointerArithmetic (
2502 true, right, left, r, loc);
2506 // Enumeration operators
2508 bool lie = TypeManager.IsEnumType (l);
2509 bool rie = TypeManager.IsEnumType (r);
2513 // U operator - (E e, E f)
2514 if (lie && rie && oper == Operator.Subtraction){
2516 type = TypeManager.EnumToUnderlying (l);
2519 Error_OperatorCannotBeApplied ();
2524 // operator + (E e, U x)
2525 // operator - (E e, U x)
2527 if (oper == Operator.Addition || oper == Operator.Subtraction){
2528 Type enum_type = lie ? l : r;
2529 Type other_type = lie ? r : l;
2530 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2533 if (underlying_type != other_type){
2534 Error_OperatorCannotBeApplied ();
2543 temp = Convert.ImplicitConversion (ec, right, l, loc);
2547 Error_OperatorCannotBeApplied ();
2551 temp = Convert.ImplicitConversion (ec, left, r, loc);
2556 Error_OperatorCannotBeApplied ();
2561 if (oper == Operator.Equality || oper == Operator.Inequality ||
2562 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2563 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2564 if (left.Type != right.Type){
2565 Error_OperatorCannotBeApplied ();
2568 type = TypeManager.bool_type;
2572 if (oper == Operator.BitwiseAnd ||
2573 oper == Operator.BitwiseOr ||
2574 oper == Operator.ExclusiveOr){
2578 Error_OperatorCannotBeApplied ();
2582 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2583 return CheckShiftArguments (ec);
2585 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2586 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2587 type = TypeManager.bool_type;
2592 Error_OperatorCannotBeApplied ();
2596 Expression e = new ConditionalLogicalOperator (
2597 oper == Operator.LogicalAnd, left, right, l, loc);
2598 return e.Resolve (ec);
2602 // operator & (bool x, bool y)
2603 // operator | (bool x, bool y)
2604 // operator ^ (bool x, bool y)
2606 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2607 if (oper == Operator.BitwiseAnd ||
2608 oper == Operator.BitwiseOr ||
2609 oper == Operator.ExclusiveOr){
2616 // Pointer comparison
2618 if (l.IsPointer && r.IsPointer){
2619 if (oper == Operator.Equality || oper == Operator.Inequality ||
2620 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2621 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2622 type = TypeManager.bool_type;
2628 // We are dealing with numbers
2630 if (overload_failed){
2631 Error_OperatorCannotBeApplied ();
2636 // This will leave left or right set to null if there is an error
2638 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2639 DoNumericPromotions (ec, l, r, check_user_conv);
2640 if (left == null || right == null){
2641 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2646 // reload our cached types if required
2651 if (oper == Operator.BitwiseAnd ||
2652 oper == Operator.BitwiseOr ||
2653 oper == Operator.ExclusiveOr){
2655 if (!((l == TypeManager.int32_type) ||
2656 (l == TypeManager.uint32_type) ||
2657 (l == TypeManager.short_type) ||
2658 (l == TypeManager.ushort_type) ||
2659 (l == TypeManager.int64_type) ||
2660 (l == TypeManager.uint64_type)))
2663 Error_OperatorCannotBeApplied ();
2668 if (oper == Operator.Equality ||
2669 oper == Operator.Inequality ||
2670 oper == Operator.LessThanOrEqual ||
2671 oper == Operator.LessThan ||
2672 oper == Operator.GreaterThanOrEqual ||
2673 oper == Operator.GreaterThan){
2674 type = TypeManager.bool_type;
2680 public override Expression DoResolve (EmitContext ec)
2682 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2683 left = ((ParenthesizedExpression) left).Expr;
2684 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2688 if (left.eclass == ExprClass.Type) {
2689 Error (75, "Casting a negative value needs to have the value in parentheses.");
2693 left = left.Resolve (ec);
2694 right = right.Resolve (ec);
2696 if (left == null || right == null)
2699 eclass = ExprClass.Value;
2701 Constant rc = right as Constant;
2702 Constant lc = left as Constant;
2704 if (rc != null & lc != null){
2705 Expression e = ConstantFold.BinaryFold (
2706 ec, oper, lc, rc, loc);
2711 return ResolveOperator (ec);
2715 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2716 /// context of a conditional bool expression. This function will return
2717 /// false if it is was possible to use EmitBranchable, or true if it was.
2719 /// The expression's code is generated, and we will generate a branch to `target'
2720 /// if the resulting expression value is equal to isTrue
2722 public bool EmitBranchable (EmitContext ec, Label target, bool onTrue)
2724 ILGenerator ig = ec.ig;
2727 // This is more complicated than it looks, but its just to avoid
2728 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2729 // but on top of that we want for == and != to use a special path
2730 // if we are comparing against null
2732 if (oper == Operator.Equality || oper == Operator.Inequality){
2733 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2735 if (left is NullLiteral){
2738 ig.Emit (OpCodes.Brtrue, target);
2740 ig.Emit (OpCodes.Brfalse, target);
2742 } else if (right is NullLiteral){
2745 ig.Emit (OpCodes.Brtrue, target);
2747 ig.Emit (OpCodes.Brfalse, target);
2749 } else if (left is BoolConstant){
2751 if (my_on_true != ((BoolConstant) left).Value)
2752 ig.Emit (OpCodes.Brtrue, target);
2754 ig.Emit (OpCodes.Brfalse, target);
2756 } else if (right is BoolConstant){
2758 if (my_on_true != ((BoolConstant) right).Value)
2759 ig.Emit (OpCodes.Brtrue, target);
2761 ig.Emit (OpCodes.Brfalse, target);
2765 } else if (oper == Operator.LogicalAnd){
2766 if (left is Binary){
2767 Binary left_binary = (Binary) left;
2770 Label tests_end = ig.DefineLabel ();
2772 if (left_binary.EmitBranchable (ec, tests_end, false)){
2773 if (right is Binary){
2774 Binary right_binary = (Binary) right;
2776 if (right_binary.EmitBranchable (ec, target, true)){
2777 ig.MarkLabel (tests_end);
2782 ig.Emit (OpCodes.Brtrue, target);
2783 ig.MarkLabel (tests_end);
2787 if (left_binary.EmitBranchable (ec, target, false)){
2788 if (right is Binary){
2789 Binary right_binary = (Binary) right;
2791 if (right_binary.EmitBranchable (ec, target, false))
2796 ig.Emit (OpCodes.Brtrue, target);
2798 ig.Emit (OpCodes.Brfalse, target);
2803 // Give up, and let the regular Emit work, but we could
2804 // also optimize the left-non-Branchable, but-right-Branchable
2808 } else if (oper == Operator.LogicalOr){
2809 if (left is Binary){
2810 Binary left_binary = (Binary) left;
2813 if (left_binary.EmitBranchable (ec, target, true)){
2814 if (right is Binary){
2815 Binary right_binary = (Binary) right;
2817 if (right_binary.EmitBranchable (ec, target, true))
2821 ig.Emit (OpCodes.Brtrue, target);
2826 // Give up, and let the regular Emit work, but we could
2827 // also optimize the left-non-Branchable, but-right-Branchable
2830 Label tests_end = ig.DefineLabel ();
2832 if (left_binary.EmitBranchable (ec, tests_end, true)){
2833 if (right is Binary){
2834 Binary right_binary = (Binary) right;
2836 if (right_binary.EmitBranchable (ec, target, false)){
2837 ig.MarkLabel (tests_end);
2842 ig.Emit (OpCodes.Brfalse, target);
2843 ig.MarkLabel (tests_end);
2850 } else if (!(oper == Operator.LessThan ||
2851 oper == Operator.GreaterThan ||
2852 oper == Operator.LessThanOrEqual ||
2853 oper == Operator.GreaterThanOrEqual))
2860 bool isUnsigned = is_unsigned (t);
2863 case Operator.Equality:
2865 ig.Emit (OpCodes.Beq, target);
2867 ig.Emit (OpCodes.Bne_Un, target);
2870 case Operator.Inequality:
2872 ig.Emit (OpCodes.Bne_Un, target);
2874 ig.Emit (OpCodes.Beq, target);
2877 case Operator.LessThan:
2880 ig.Emit (OpCodes.Blt_Un, target);
2882 ig.Emit (OpCodes.Blt, target);
2885 ig.Emit (OpCodes.Bge_Un, target);
2887 ig.Emit (OpCodes.Bge, target);
2890 case Operator.GreaterThan:
2893 ig.Emit (OpCodes.Bgt_Un, target);
2895 ig.Emit (OpCodes.Bgt, target);
2898 ig.Emit (OpCodes.Ble_Un, target);
2900 ig.Emit (OpCodes.Ble, target);
2903 case Operator.LessThanOrEqual:
2904 if (t == TypeManager.double_type || t == TypeManager.float_type)
2909 ig.Emit (OpCodes.Ble_Un, target);
2911 ig.Emit (OpCodes.Ble, target);
2914 ig.Emit (OpCodes.Bgt_Un, target);
2916 ig.Emit (OpCodes.Bgt, target);
2920 case Operator.GreaterThanOrEqual:
2921 if (t == TypeManager.double_type || t == TypeManager.float_type)
2925 ig.Emit (OpCodes.Bge_Un, target);
2927 ig.Emit (OpCodes.Bge, target);
2930 ig.Emit (OpCodes.Blt_Un, target);
2932 ig.Emit (OpCodes.Blt, target);
2942 public override void Emit (EmitContext ec)
2944 ILGenerator ig = ec.ig;
2946 Type r = right.Type;
2950 // Handle short-circuit operators differently
2953 if (oper == Operator.LogicalAnd){
2954 Label load_zero = ig.DefineLabel ();
2955 Label end = ig.DefineLabel ();
2956 bool process = true;
2958 if (left is Binary){
2959 Binary left_binary = (Binary) left;
2961 if (left_binary.EmitBranchable (ec, load_zero, false)){
2963 ig.Emit (OpCodes.Br, end);
2970 ig.Emit (OpCodes.Brfalse, load_zero);
2972 ig.Emit (OpCodes.Br, end);
2974 ig.MarkLabel (load_zero);
2975 ig.Emit (OpCodes.Ldc_I4_0);
2978 } else if (oper == Operator.LogicalOr){
2979 Label load_one = ig.DefineLabel ();
2980 Label end = ig.DefineLabel ();
2981 bool process = true;
2983 if (left is Binary){
2984 Binary left_binary = (Binary) left;
2986 if (left_binary.EmitBranchable (ec, load_one, true)){
2988 ig.Emit (OpCodes.Br, end);
2995 ig.Emit (OpCodes.Brtrue, load_one);
2997 ig.Emit (OpCodes.Br, end);
2999 ig.MarkLabel (load_one);
3000 ig.Emit (OpCodes.Ldc_I4_1);
3008 bool isUnsigned = is_unsigned (left.Type);
3011 case Operator.Multiply:
3013 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3014 opcode = OpCodes.Mul_Ovf;
3015 else if (isUnsigned)
3016 opcode = OpCodes.Mul_Ovf_Un;
3018 opcode = OpCodes.Mul;
3020 opcode = OpCodes.Mul;
3024 case Operator.Division:
3026 opcode = OpCodes.Div_Un;
3028 opcode = OpCodes.Div;
3031 case Operator.Modulus:
3033 opcode = OpCodes.Rem_Un;
3035 opcode = OpCodes.Rem;
3038 case Operator.Addition:
3040 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3041 opcode = OpCodes.Add_Ovf;
3042 else if (isUnsigned)
3043 opcode = OpCodes.Add_Ovf_Un;
3045 opcode = OpCodes.Add;
3047 opcode = OpCodes.Add;
3050 case Operator.Subtraction:
3052 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3053 opcode = OpCodes.Sub_Ovf;
3054 else if (isUnsigned)
3055 opcode = OpCodes.Sub_Ovf_Un;
3057 opcode = OpCodes.Sub;
3059 opcode = OpCodes.Sub;
3062 case Operator.RightShift:
3064 opcode = OpCodes.Shr_Un;
3066 opcode = OpCodes.Shr;
3069 case Operator.LeftShift:
3070 opcode = OpCodes.Shl;
3073 case Operator.Equality:
3074 opcode = OpCodes.Ceq;
3077 case Operator.Inequality:
3078 ig.Emit (OpCodes.Ceq);
3079 ig.Emit (OpCodes.Ldc_I4_0);
3081 opcode = OpCodes.Ceq;
3084 case Operator.LessThan:
3086 opcode = OpCodes.Clt_Un;
3088 opcode = OpCodes.Clt;
3091 case Operator.GreaterThan:
3093 opcode = OpCodes.Cgt_Un;
3095 opcode = OpCodes.Cgt;
3098 case Operator.LessThanOrEqual:
3099 Type lt = left.Type;
3101 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
3102 ig.Emit (OpCodes.Cgt_Un);
3104 ig.Emit (OpCodes.Cgt);
3105 ig.Emit (OpCodes.Ldc_I4_0);
3107 opcode = OpCodes.Ceq;
3110 case Operator.GreaterThanOrEqual:
3111 Type le = left.Type;
3113 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3114 ig.Emit (OpCodes.Clt_Un);
3116 ig.Emit (OpCodes.Clt);
3118 ig.Emit (OpCodes.Ldc_I4_0);
3120 opcode = OpCodes.Ceq;
3123 case Operator.BitwiseOr:
3124 opcode = OpCodes.Or;
3127 case Operator.BitwiseAnd:
3128 opcode = OpCodes.And;
3131 case Operator.ExclusiveOr:
3132 opcode = OpCodes.Xor;
3136 throw new Exception ("This should not happen: Operator = "
3137 + oper.ToString ());
3145 // Object created by Binary when the binary operator uses an method instead of being
3146 // a binary operation that maps to a CIL binary operation.
3148 public class BinaryMethod : Expression {
3149 public MethodBase method;
3150 public ArrayList Arguments;
3152 public BinaryMethod (Type t, MethodBase m, ArrayList args)
3157 eclass = ExprClass.Value;
3160 public override Expression DoResolve (EmitContext ec)
3165 public override void Emit (EmitContext ec)
3167 ILGenerator ig = ec.ig;
3169 if (Arguments != null)
3170 Invocation.EmitArguments (ec, method, Arguments);
3172 if (method is MethodInfo)
3173 ig.Emit (OpCodes.Call, (MethodInfo) method);
3175 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3180 // Object created with +/= on delegates
3182 public class BinaryDelegate : Expression {
3186 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3191 eclass = ExprClass.Value;
3194 public override Expression DoResolve (EmitContext ec)
3199 public override void Emit (EmitContext ec)
3201 ILGenerator ig = ec.ig;
3203 Invocation.EmitArguments (ec, method, args);
3205 ig.Emit (OpCodes.Call, (MethodInfo) method);
3206 ig.Emit (OpCodes.Castclass, type);
3209 public Expression Right {
3211 Argument arg = (Argument) args [1];
3216 public bool IsAddition {
3218 return method == TypeManager.delegate_combine_delegate_delegate;
3224 // User-defined conditional logical operator
3225 public class ConditionalLogicalOperator : Expression {
3226 Expression left, right;
3229 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3232 eclass = ExprClass.Value;
3236 this.is_and = is_and;
3239 protected void Error19 ()
3241 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3244 protected void Error218 ()
3246 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3247 "declarations of operator true and operator false");
3250 Expression op_true, op_false, op;
3252 public override Expression DoResolve (EmitContext ec)
3255 Expression operator_group;
3257 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3258 if (operator_group == null) {
3263 ArrayList arguments = new ArrayList ();
3264 arguments.Add (new Argument (left, Argument.AType.Expression));
3265 arguments.Add (new Argument (right, Argument.AType.Expression));
3266 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) operator_group, arguments, loc) as MethodInfo;
3267 if ((method == null) || (method.ReturnType != type)) {
3272 op = new StaticCallExpr (method, arguments, loc);
3274 op_true = GetOperatorTrue (ec, left, loc);
3275 op_false = GetOperatorFalse (ec, left, loc);
3276 if ((op_true == null) || (op_false == null)) {
3284 public override void Emit (EmitContext ec)
3286 ILGenerator ig = ec.ig;
3287 Label false_target = ig.DefineLabel ();
3288 Label end_target = ig.DefineLabel ();
3290 ig.Emit (OpCodes.Nop);
3292 Statement.EmitBoolExpression (ec, is_and ? op_false : op_true, false_target, false);
3294 ig.Emit (OpCodes.Br, end_target);
3295 ig.MarkLabel (false_target);
3297 ig.MarkLabel (end_target);
3299 ig.Emit (OpCodes.Nop);
3303 public class PointerArithmetic : Expression {
3304 Expression left, right;
3308 // We assume that `l' is always a pointer
3310 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3313 eclass = ExprClass.Variable;
3317 is_add = is_addition;
3320 public override Expression DoResolve (EmitContext ec)
3323 // We are born fully resolved
3328 public override void Emit (EmitContext ec)
3330 Type op_type = left.Type;
3331 ILGenerator ig = ec.ig;
3332 int size = GetTypeSize (TypeManager.GetElementType (op_type));
3333 Type rtype = right.Type;
3335 if (rtype.IsPointer){
3337 // handle (pointer - pointer)
3341 ig.Emit (OpCodes.Sub);
3345 ig.Emit (OpCodes.Sizeof, op_type);
3347 IntLiteral.EmitInt (ig, size);
3348 ig.Emit (OpCodes.Div);
3350 ig.Emit (OpCodes.Conv_I8);
3353 // handle + and - on (pointer op int)
3356 ig.Emit (OpCodes.Conv_I);
3360 ig.Emit (OpCodes.Sizeof, op_type);
3362 IntLiteral.EmitInt (ig, size);
3363 if (rtype == TypeManager.int64_type)
3364 ig.Emit (OpCodes.Conv_I8);
3365 else if (rtype == TypeManager.uint64_type)
3366 ig.Emit (OpCodes.Conv_U8);
3367 ig.Emit (OpCodes.Mul);
3368 ig.Emit (OpCodes.Conv_I);
3371 ig.Emit (OpCodes.Add);
3373 ig.Emit (OpCodes.Sub);
3379 /// Implements the ternary conditional operator (?:)
3381 public class Conditional : Expression {
3382 Expression expr, trueExpr, falseExpr;
3384 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3387 this.trueExpr = trueExpr;
3388 this.falseExpr = falseExpr;
3392 public Expression Expr {
3398 public Expression TrueExpr {
3404 public Expression FalseExpr {
3410 public override Expression DoResolve (EmitContext ec)
3412 expr = expr.Resolve (ec);
3417 if (expr.Type != TypeManager.bool_type){
3418 expr = Expression.ResolveBoolean (
3425 trueExpr = trueExpr.Resolve (ec);
3426 falseExpr = falseExpr.Resolve (ec);
3428 if (trueExpr == null || falseExpr == null)
3431 eclass = ExprClass.Value;
3432 if (trueExpr.Type == falseExpr.Type)
3433 type = trueExpr.Type;
3436 Type true_type = trueExpr.Type;
3437 Type false_type = falseExpr.Type;
3439 if (trueExpr is NullLiteral){
3442 } else if (falseExpr is NullLiteral){
3448 // First, if an implicit conversion exists from trueExpr
3449 // to falseExpr, then the result type is of type falseExpr.Type
3451 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3454 // Check if both can convert implicitl to each other's type
3456 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3458 "Can not compute type of conditional expression " +
3459 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3460 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3461 "' convert implicitly to each other");
3466 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3470 Error (173, "The type of the conditional expression can " +
3471 "not be computed because there is no implicit conversion" +
3472 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3473 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3478 if (expr is BoolConstant){
3479 BoolConstant bc = (BoolConstant) expr;
3490 public override void Emit (EmitContext ec)
3492 ILGenerator ig = ec.ig;
3493 Label false_target = ig.DefineLabel ();
3494 Label end_target = ig.DefineLabel ();
3496 Statement.EmitBoolExpression (ec, expr, false_target, false);
3498 ig.Emit (OpCodes.Br, end_target);
3499 ig.MarkLabel (false_target);
3500 falseExpr.Emit (ec);
3501 ig.MarkLabel (end_target);
3509 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3510 public readonly string Name;
3511 public readonly Block Block;
3512 LocalInfo local_info;
3515 public LocalVariableReference (Block block, string name, Location l)
3520 eclass = ExprClass.Variable;
3523 // Setting `is_readonly' to false will allow you to create a writable
3524 // reference to a read-only variable. This is used by foreach and using.
3525 public LocalVariableReference (Block block, string name, Location l,
3526 LocalInfo local_info, bool is_readonly)
3527 : this (block, name, l)
3529 this.local_info = local_info;
3530 this.is_readonly = is_readonly;
3533 public VariableInfo VariableInfo {
3534 get { return local_info.VariableInfo; }
3537 public bool IsReadOnly {
3543 protected void DoResolveBase (EmitContext ec)
3545 if (local_info == null) {
3546 local_info = Block.GetLocalInfo (Name);
3547 is_readonly = local_info.ReadOnly;
3550 type = local_info.VariableType;
3552 if (ec.InAnonymousMethod)
3553 Block.LiftVariable (local_info);
3557 public override Expression DoResolve (EmitContext ec)
3561 Expression e = Block.GetConstantExpression (Name);
3563 local_info.Used = true;
3564 eclass = ExprClass.Value;
3568 VariableInfo variable_info = local_info.VariableInfo;
3569 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3572 if (local_info.LocalBuilder == null)
3573 return ec.RemapLocal (local_info);
3578 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3582 VariableInfo variable_info = local_info.VariableInfo;
3583 if (variable_info != null)
3584 variable_info.SetAssigned (ec);
3586 Expression e = DoResolve (ec);
3592 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3596 if (local_info.LocalBuilder == null)
3597 return ec.RemapLocalLValue (local_info, right_side);
3602 public bool VerifyFixed (bool is_expression)
3604 return !is_expression || local_info.IsFixed;
3607 public override void Emit (EmitContext ec)
3609 ILGenerator ig = ec.ig;
3611 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3614 public void EmitAssign (EmitContext ec, Expression source)
3616 ILGenerator ig = ec.ig;
3618 local_info.Assigned = true;
3621 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3624 public void AddressOf (EmitContext ec, AddressOp mode)
3626 ILGenerator ig = ec.ig;
3628 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3631 public override string ToString ()
3633 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3638 /// This represents a reference to a parameter in the intermediate
3641 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3647 public Parameter.Modifier mod;
3648 public bool is_ref, is_out;
3650 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3657 eclass = ExprClass.Variable;
3660 public VariableInfo VariableInfo {
3664 public bool VerifyFixed (bool is_expression)
3666 return !is_expression || TypeManager.IsValueType (type);
3669 public bool IsAssigned (EmitContext ec, Location loc)
3671 if (!ec.DoFlowAnalysis || !is_out ||
3672 ec.CurrentBranching.IsAssigned (vi))
3675 Report.Error (165, loc,
3676 "Use of unassigned parameter `" + name + "'");
3680 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3682 if (!ec.DoFlowAnalysis || !is_out ||
3683 ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3686 Report.Error (170, loc,
3687 "Use of possibly unassigned field `" + field_name + "'");
3691 public void SetAssigned (EmitContext ec)
3693 if (is_out && ec.DoFlowAnalysis)
3694 ec.CurrentBranching.SetAssigned (vi);
3697 public void SetFieldAssigned (EmitContext ec, string field_name)
3699 if (is_out && ec.DoFlowAnalysis)
3700 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3703 protected void DoResolveBase (EmitContext ec)
3705 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
3706 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3707 is_out = (mod & Parameter.Modifier.OUT) != 0;
3708 eclass = ExprClass.Variable;
3711 vi = block.ParameterMap [idx];
3715 // Notice that for ref/out parameters, the type exposed is not the
3716 // same type exposed externally.
3719 // externally we expose "int&"
3720 // here we expose "int".
3722 // We record this in "is_ref". This means that the type system can treat
3723 // the type as it is expected, but when we generate the code, we generate
3724 // the alternate kind of code.
3726 public override Expression DoResolve (EmitContext ec)
3730 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3733 if (ec.RemapToProxy)
3734 return ec.RemapParameter (idx);
3739 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3745 if (ec.RemapToProxy)
3746 return ec.RemapParameterLValue (idx, right_side);
3751 static public void EmitLdArg (ILGenerator ig, int x)
3755 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3756 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3757 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3758 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3759 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3762 ig.Emit (OpCodes.Ldarg, x);
3766 // This method is used by parameters that are references, that are
3767 // being passed as references: we only want to pass the pointer (that
3768 // is already stored in the parameter, not the address of the pointer,
3769 // and not the value of the variable).
3771 public void EmitLoad (EmitContext ec)
3773 ILGenerator ig = ec.ig;
3779 EmitLdArg (ig, arg_idx);
3782 public override void Emit (EmitContext ec)
3784 ILGenerator ig = ec.ig;
3791 EmitLdArg (ig, arg_idx);
3797 // If we are a reference, we loaded on the stack a pointer
3798 // Now lets load the real value
3800 LoadFromPtr (ig, type);
3803 public void EmitAssign (EmitContext ec, Expression source)
3805 ILGenerator ig = ec.ig;
3813 EmitLdArg (ig, arg_idx);
3818 StoreFromPtr (ig, type);
3821 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
3823 ig.Emit (OpCodes.Starg, arg_idx);
3827 public void AddressOf (EmitContext ec, AddressOp mode)
3836 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
3838 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
3841 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
3843 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
3850 /// Used for arguments to New(), Invocation()
3852 public class Argument {
3853 public enum AType : byte {
3859 public readonly AType ArgType;
3860 public Expression Expr;
3862 public Argument (Expression expr, AType type)
3865 this.ArgType = type;
3870 if (ArgType == AType.Ref || ArgType == AType.Out)
3871 return TypeManager.GetReferenceType (Expr.Type);
3877 public Parameter.Modifier GetParameterModifier ()
3881 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
3884 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
3887 return Parameter.Modifier.NONE;
3891 public static string FullDesc (Argument a)
3893 return (a.ArgType == AType.Ref ? "ref " :
3894 (a.ArgType == AType.Out ? "out " : "")) +
3895 TypeManager.CSharpName (a.Expr.Type);
3898 public bool ResolveMethodGroup (EmitContext ec, Location loc)
3900 // FIXME: csc doesn't report any error if you try to use `ref' or
3901 // `out' in a delegate creation expression.
3902 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
3909 public bool Resolve (EmitContext ec, Location loc)
3911 if (ArgType == AType.Ref) {
3912 Expr = Expr.Resolve (ec);
3916 Expr = Expr.ResolveLValue (ec, Expr);
3917 } else if (ArgType == AType.Out)
3918 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
3920 Expr = Expr.Resolve (ec);
3925 if (ArgType == AType.Expression)
3928 if (Expr.eclass != ExprClass.Variable){
3930 // We just probe to match the CSC output
3932 if (Expr.eclass == ExprClass.PropertyAccess ||
3933 Expr.eclass == ExprClass.IndexerAccess){
3936 "A property or indexer can not be passed as an out or ref " +
3941 "An lvalue is required as an argument to out or ref");
3949 public void Emit (EmitContext ec)
3952 // Ref and Out parameters need to have their addresses taken.
3954 // ParameterReferences might already be references, so we want
3955 // to pass just the value
3957 if (ArgType == AType.Ref || ArgType == AType.Out){
3958 AddressOp mode = AddressOp.Store;
3960 if (ArgType == AType.Ref)
3961 mode |= AddressOp.Load;
3963 if (Expr is ParameterReference){
3964 ParameterReference pr = (ParameterReference) Expr;
3970 pr.AddressOf (ec, mode);
3973 ((IMemoryLocation)Expr).AddressOf (ec, mode);
3980 /// Invocation of methods or delegates.
3982 public class Invocation : ExpressionStatement {
3983 public readonly ArrayList Arguments;
3986 MethodBase method = null;
3989 static Hashtable method_parameter_cache;
3991 static Invocation ()
3993 method_parameter_cache = new PtrHashtable ();
3997 // arguments is an ArrayList, but we do not want to typecast,
3998 // as it might be null.
4000 // FIXME: only allow expr to be a method invocation or a
4001 // delegate invocation (7.5.5)
4003 public Invocation (Expression expr, ArrayList arguments, Location l)
4006 Arguments = arguments;
4010 public Expression Expr {
4017 /// Returns the Parameters (a ParameterData interface) for the
4020 public static ParameterData GetParameterData (MethodBase mb)
4022 object pd = method_parameter_cache [mb];
4026 return (ParameterData) pd;
4029 ip = TypeManager.LookupParametersByBuilder (mb);
4031 method_parameter_cache [mb] = ip;
4033 return (ParameterData) ip;
4035 ParameterInfo [] pi = mb.GetParameters ();
4036 ReflectionParameters rp = new ReflectionParameters (pi);
4037 method_parameter_cache [mb] = rp;
4039 return (ParameterData) rp;
4044 /// Determines "better conversion" as specified in 7.4.2.3
4046 /// Returns : 1 if a->p is better
4047 /// 0 if a->q or neither is better
4049 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
4051 Type argument_type = a.Type;
4052 Expression argument_expr = a.Expr;
4054 if (argument_type == null)
4055 throw new Exception ("Expression of type " + a.Expr +
4056 " does not resolve its type");
4059 // This is a special case since csc behaves this way. I can't find
4060 // it anywhere in the spec but oh well ...
4062 if (argument_expr is NullLiteral &&
4063 p == TypeManager.string_type &&
4064 q == TypeManager.object_type)
4066 else if (argument_expr is NullLiteral &&
4067 p == TypeManager.object_type &&
4068 q == TypeManager.string_type)
4074 if (argument_type == p)
4077 if (argument_type == q)
4081 // Now probe whether an implicit constant expression conversion
4084 // An implicit constant expression conversion permits the following
4087 // * A constant-expression of type `int' can be converted to type
4088 // sbyte, byute, short, ushort, uint, ulong provided the value of
4089 // of the expression is withing the range of the destination type.
4091 // * A constant-expression of type long can be converted to type
4092 // ulong, provided the value of the constant expression is not negative
4094 // FIXME: Note that this assumes that constant folding has
4095 // taken place. We dont do constant folding yet.
4098 if (argument_expr is IntConstant){
4099 IntConstant ei = (IntConstant) argument_expr;
4100 int value = ei.Value;
4102 if (p == TypeManager.sbyte_type){
4103 if (value >= SByte.MinValue && value <= SByte.MaxValue)
4105 } else if (p == TypeManager.byte_type){
4106 if (q == TypeManager.sbyte_type &&
4107 value >= SByte.MinValue && value <= SByte.MaxValue)
4109 else if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
4111 } else if (p == TypeManager.short_type){
4112 if (value >= Int16.MinValue && value <= Int16.MaxValue)
4114 } else if (p == TypeManager.ushort_type){
4115 if (q == TypeManager.short_type &&
4116 value >= Int16.MinValue && value <= Int16.MaxValue)
4118 else if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
4120 } else if (p == TypeManager.int32_type){
4121 if (value >= Int32.MinValue && value <= Int32.MaxValue)
4123 } else if (p == TypeManager.uint32_type){
4125 // we can optimize this case: a positive int32
4126 // always fits on a uint32
4130 } else if (p == TypeManager.uint64_type){
4132 // we can optimize this case: a positive int32
4133 // always fits on a uint64
4135 if (q == TypeManager.int64_type)
4137 else if (value >= 0)
4139 } else if (p == TypeManager.int64_type){
4142 } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
4143 LongConstant lc = (LongConstant) argument_expr;
4145 if (p == TypeManager.uint64_type){
4152 Expression tmp = Convert.ImplicitConversion (ec, argument_expr, p, loc);
4160 Expression p_tmp = new EmptyExpression (p);
4161 Expression q_tmp = new EmptyExpression (q);
4163 if (Convert.ImplicitConversionExists (ec, p_tmp, q) == true &&
4164 Convert.ImplicitConversionExists (ec, q_tmp, p) == false)
4167 if (p == TypeManager.sbyte_type)
4168 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4169 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4172 if (p == TypeManager.short_type)
4173 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4174 q == TypeManager.uint64_type)
4177 if (p == TypeManager.int32_type)
4178 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4181 if (p == TypeManager.int64_type)
4182 if (q == TypeManager.uint64_type)
4189 /// Determines "Better function" between candidate
4190 /// and the current best match
4193 /// Returns an integer indicating :
4194 /// 0 if candidate ain't better
4195 /// 1 if candidate is better than the current best match
4197 static int BetterFunction (EmitContext ec, ArrayList args,
4198 MethodBase candidate, bool candidate_params,
4199 MethodBase best, bool best_params,
4202 ParameterData candidate_pd = GetParameterData (candidate);
4203 ParameterData best_pd;
4209 argument_count = args.Count;
4211 int cand_count = candidate_pd.Count;
4213 if (cand_count == 0 && argument_count == 0)
4216 if (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS)
4217 if (cand_count != argument_count)
4223 if (argument_count == 0 && cand_count == 1 &&
4224 candidate_pd.ParameterModifier (cand_count - 1) == Parameter.Modifier.PARAMS)
4227 for (int j = 0; j < argument_count; ++j) {
4229 Argument a = (Argument) args [j];
4230 Type t = candidate_pd.ParameterType (j);
4232 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4233 if (candidate_params)
4234 t = TypeManager.GetElementType (t);
4236 x = BetterConversion (ec, a, t, null, loc);
4248 best_pd = GetParameterData (best);
4250 int rating1 = 0, rating2 = 0;
4252 for (int j = 0; j < argument_count; ++j) {
4255 Argument a = (Argument) args [j];
4257 Type ct = candidate_pd.ParameterType (j);
4258 Type bt = best_pd.ParameterType (j);
4260 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4261 if (candidate_params)
4262 ct = TypeManager.GetElementType (ct);
4264 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4266 bt = TypeManager.GetElementType (bt);
4268 x = BetterConversion (ec, a, ct, bt, loc);
4269 y = BetterConversion (ec, a, bt, ct, loc);
4279 // If a method (in the normal form) with the
4280 // same signature as the expanded form of the
4281 // current best params method already exists,
4282 // the expanded form is not applicable so we
4283 // force it to select the candidate
4285 if (!candidate_params && best_params && cand_count == argument_count)
4288 if (rating1 > rating2)
4294 public static string FullMethodDesc (MethodBase mb)
4296 string ret_type = "";
4298 if (mb is MethodInfo)
4299 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
4301 StringBuilder sb = new StringBuilder (ret_type);
4303 sb.Append (mb.ReflectedType.ToString ());
4305 sb.Append (mb.Name);
4307 ParameterData pd = GetParameterData (mb);
4309 int count = pd.Count;
4312 for (int i = count; i > 0; ) {
4315 sb.Append (pd.ParameterDesc (count - i - 1));
4321 return sb.ToString ();
4324 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4326 MemberInfo [] miset;
4327 MethodGroupExpr union;
4332 return (MethodGroupExpr) mg2;
4335 return (MethodGroupExpr) mg1;
4338 MethodGroupExpr left_set = null, right_set = null;
4339 int length1 = 0, length2 = 0;
4341 left_set = (MethodGroupExpr) mg1;
4342 length1 = left_set.Methods.Length;
4344 right_set = (MethodGroupExpr) mg2;
4345 length2 = right_set.Methods.Length;
4347 ArrayList common = new ArrayList ();
4349 foreach (MethodBase r in right_set.Methods){
4350 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
4354 miset = new MemberInfo [length1 + length2 - common.Count];
4355 left_set.Methods.CopyTo (miset, 0);
4359 foreach (MethodBase r in right_set.Methods) {
4360 if (!common.Contains (r))
4364 union = new MethodGroupExpr (miset, loc);
4370 /// Determines if the candidate method, if a params method, is applicable
4371 /// in its expanded form to the given set of arguments
4373 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
4377 if (arguments == null)
4380 arg_count = arguments.Count;
4382 ParameterData pd = GetParameterData (candidate);
4384 int pd_count = pd.Count;
4389 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
4392 if (pd_count - 1 > arg_count)
4395 if (pd_count == 1 && arg_count == 0)
4399 // If we have come this far, the case which
4400 // remains is when the number of parameters is
4401 // less than or equal to the argument count.
4403 for (int i = 0; i < pd_count - 1; ++i) {
4405 Argument a = (Argument) arguments [i];
4407 Parameter.Modifier a_mod = a.GetParameterModifier () &
4408 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4409 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4410 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4412 if (a_mod == p_mod) {
4414 if (a_mod == Parameter.Modifier.NONE)
4415 if (!Convert.ImplicitConversionExists (ec,
4417 pd.ParameterType (i)))
4420 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4421 Type pt = pd.ParameterType (i);
4424 pt = TypeManager.GetReferenceType (pt);
4434 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4436 for (int i = pd_count - 1; i < arg_count; i++) {
4437 Argument a = (Argument) arguments [i];
4439 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4447 /// Determines if the candidate method is applicable (section 14.4.2.1)
4448 /// to the given set of arguments
4450 static bool IsApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
4454 if (arguments == null)
4457 arg_count = arguments.Count;
4460 ParameterData pd = GetParameterData (candidate);
4462 int pd_count = pd.Count;
4464 if (arg_count != pd.Count)
4467 for (int i = arg_count; i > 0; ) {
4470 Argument a = (Argument) arguments [i];
4472 Parameter.Modifier a_mod = a.GetParameterModifier () &
4473 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4474 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4475 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4478 if (a_mod == p_mod ||
4479 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4480 if (a_mod == Parameter.Modifier.NONE) {
4481 if (!Convert.ImplicitConversionExists (ec,
4483 pd.ParameterType (i)))
4487 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4488 Type pt = pd.ParameterType (i);
4491 pt = TypeManager.GetReferenceType (pt);
4506 /// Find the Applicable Function Members (7.4.2.1)
4508 /// me: Method Group expression with the members to select.
4509 /// it might contain constructors or methods (or anything
4510 /// that maps to a method).
4512 /// Arguments: ArrayList containing resolved Argument objects.
4514 /// loc: The location if we want an error to be reported, or a Null
4515 /// location for "probing" purposes.
4517 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4518 /// that is the best match of me on Arguments.
4521 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4522 ArrayList Arguments, Location loc)
4524 MethodBase method = null;
4525 Type applicable_type = null;
4527 ArrayList candidates = new ArrayList ();
4530 // Used to keep a map between the candidate
4531 // and whether it is being considered in its
4532 // normal or expanded form
4534 Hashtable candidate_to_form = new PtrHashtable ();
4538 // First we construct the set of applicable methods
4540 // We start at the top of the type hierarchy and
4541 // go down to find applicable methods
4543 applicable_type = me.DeclaringType;
4545 if (me.Name == "Invoke" && TypeManager.IsDelegateType (applicable_type)) {
4546 Error_InvokeOnDelegate (loc);
4550 bool found_applicable = false;
4551 foreach (MethodBase candidate in me.Methods) {
4552 Type decl_type = candidate.DeclaringType;
4555 // If we have already found an applicable method
4556 // we eliminate all base types (Section 14.5.5.1)
4558 if (decl_type != applicable_type &&
4559 (applicable_type.IsSubclassOf (decl_type) ||
4560 TypeManager.ImplementsInterface (applicable_type, decl_type)) &&
4565 // Check if candidate is applicable (section 14.4.2.1)
4566 if (IsApplicable (ec, Arguments, candidate)) {
4567 // Candidate is applicable in normal form
4568 candidates.Add (candidate);
4569 applicable_type = candidate.DeclaringType;
4570 found_applicable = true;
4571 candidate_to_form [candidate] = false;
4573 if (IsParamsMethodApplicable (ec, Arguments, candidate)) {
4574 // Candidate is applicable in expanded form
4575 candidates.Add (candidate);
4576 applicable_type = candidate.DeclaringType;
4577 found_applicable = true;
4578 candidate_to_form [candidate] = true;
4585 // Now we actually find the best method
4587 foreach (MethodBase candidate in candidates) {
4588 bool cand_params = (bool) candidate_to_form [candidate];
4589 bool method_params = false;
4592 method_params = (bool) candidate_to_form [method];
4594 int x = BetterFunction (ec, Arguments,
4595 candidate, cand_params,
4596 method, method_params,
4605 if (Arguments == null)
4608 argument_count = Arguments.Count;
4611 if (method == null) {
4613 // Okay so we have failed to find anything so we
4614 // return by providing info about the closest match
4616 for (int i = 0; i < me.Methods.Length; ++i) {
4618 MethodBase c = (MethodBase) me.Methods [i];
4619 ParameterData pd = GetParameterData (c);
4621 if (pd.Count != argument_count)
4624 VerifyArgumentsCompat (ec, Arguments, argument_count, c, false,
4629 if (!Location.IsNull (loc)) {
4630 string report_name = me.Name;
4631 if (report_name == ".ctor")
4632 report_name = me.DeclaringType.ToString ();
4634 Error_WrongNumArguments (loc, report_name, argument_count);
4641 // Now check that there are no ambiguities i.e the selected method
4642 // should be better than all the others
4644 bool best_params = (bool) candidate_to_form [method];
4646 foreach (MethodBase candidate in candidates){
4648 if (candidate == method)
4652 // If a normal method is applicable in
4653 // the sense that it has the same
4654 // number of arguments, then the
4655 // expanded params method is never
4656 // applicable so we debar the params
4659 if ((IsParamsMethodApplicable (ec, Arguments, candidate) &&
4660 IsApplicable (ec, Arguments, method)))
4663 bool cand_params = (bool) candidate_to_form [candidate];
4664 int x = BetterFunction (ec, Arguments,
4665 method, best_params,
4666 candidate, cand_params,
4672 "Ambiguous call when selecting function due to implicit casts");
4678 // And now check if the arguments are all
4679 // compatible, perform conversions if
4680 // necessary etc. and return if everything is
4683 if (!VerifyArgumentsCompat (ec, Arguments, argument_count, method,
4684 best_params, null, loc))
4690 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
4692 Report.Error (1501, loc,
4693 "No overload for method `" + name + "' takes `" +
4694 arg_count + "' arguments");
4697 static void Error_InvokeOnDelegate (Location loc)
4699 Report.Error (1533, loc,
4700 "Invoke cannot be called directly on a delegate");
4703 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
4704 Type delegate_type, string arg_sig, string par_desc)
4706 if (delegate_type == null)
4707 Report.Error (1502, loc,
4708 "The best overloaded match for method '" +
4709 FullMethodDesc (method) +
4710 "' has some invalid arguments");
4712 Report.Error (1594, loc,
4713 "Delegate '" + delegate_type.ToString () +
4714 "' has some invalid arguments.");
4715 Report.Error (1503, loc,
4716 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
4717 idx, arg_sig, par_desc));
4720 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
4723 bool chose_params_expanded,
4727 ParameterData pd = GetParameterData (method);
4728 int pd_count = pd.Count;
4730 for (int j = 0; j < argument_count; j++) {
4731 Argument a = (Argument) Arguments [j];
4732 Expression a_expr = a.Expr;
4733 Type parameter_type = pd.ParameterType (j);
4734 Parameter.Modifier pm = pd.ParameterModifier (j);
4736 if (pm == Parameter.Modifier.PARAMS){
4737 Parameter.Modifier am = a.GetParameterModifier ();
4739 if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
4740 if (!Location.IsNull (loc))
4741 Error_InvalidArguments (
4742 loc, j, method, delegate_type,
4743 Argument.FullDesc (a), pd.ParameterDesc (j));
4747 if (chose_params_expanded)
4748 parameter_type = TypeManager.GetElementType (parameter_type);
4753 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
4754 if (!Location.IsNull (loc))
4755 Error_InvalidArguments (
4756 loc, j, method, delegate_type,
4757 Argument.FullDesc (a), pd.ParameterDesc (j));
4765 if (a.Type != parameter_type){
4768 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
4771 if (!Location.IsNull (loc))
4772 Error_InvalidArguments (
4773 loc, j, method, delegate_type,
4774 Argument.FullDesc (a), pd.ParameterDesc (j));
4779 // Update the argument with the implicit conversion
4785 Parameter.Modifier a_mod = a.GetParameterModifier () &
4786 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4787 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
4788 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4790 if (a_mod != p_mod &&
4791 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
4792 if (!Location.IsNull (loc)) {
4793 Report.Error (1502, loc,
4794 "The best overloaded match for method '" + FullMethodDesc (method)+
4795 "' has some invalid arguments");
4796 Report.Error (1503, loc,
4797 "Argument " + (j+1) +
4798 ": Cannot convert from '" + Argument.FullDesc (a)
4799 + "' to '" + pd.ParameterDesc (j) + "'");
4809 public override Expression DoResolve (EmitContext ec)
4812 // First, resolve the expression that is used to
4813 // trigger the invocation
4815 if (expr is BaseAccess)
4818 Expression old = expr;
4820 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4824 if (!(expr is MethodGroupExpr)) {
4825 Type expr_type = expr.Type;
4827 if (expr_type != null){
4828 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
4830 return (new DelegateInvocation (
4831 this.expr, Arguments, loc)).Resolve (ec);
4835 if (!(expr is MethodGroupExpr)){
4836 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup);
4841 // Next, evaluate all the expressions in the argument list
4843 if (Arguments != null){
4844 foreach (Argument a in Arguments){
4845 if (!a.Resolve (ec, loc))
4850 MethodGroupExpr mg = (MethodGroupExpr) expr;
4851 method = OverloadResolve (ec, mg, Arguments, loc);
4853 if (method == null){
4855 "Could not find any applicable function for this argument list");
4859 MethodInfo mi = method as MethodInfo;
4861 type = TypeManager.TypeToCoreType (mi.ReturnType);
4862 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null))
4863 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
4866 if (type.IsPointer){
4874 // Only base will allow this invocation to happen.
4876 if (is_base && method.IsAbstract){
4877 Report.Error (205, loc, "Cannot call an abstract base member: " +
4878 FullMethodDesc (method));
4882 if ((method.Attributes & MethodAttributes.SpecialName) != 0){
4883 if (TypeManager.IsSpecialMethod (method))
4884 Report.Error (571, loc, method.Name + ": can not call operator or accessor");
4887 eclass = ExprClass.Value;
4892 // Emits the list of arguments as an array
4894 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
4896 ILGenerator ig = ec.ig;
4897 int count = arguments.Count - idx;
4898 Argument a = (Argument) arguments [idx];
4899 Type t = a.Expr.Type;
4900 string array_type = t.FullName + "[]";
4903 array = ig.DeclareLocal (TypeManager.LookupType (array_type));
4904 IntConstant.EmitInt (ig, count);
4905 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
4906 ig.Emit (OpCodes.Stloc, array);
4908 int top = arguments.Count;
4909 for (int j = idx; j < top; j++){
4910 a = (Argument) arguments [j];
4912 ig.Emit (OpCodes.Ldloc, array);
4913 IntConstant.EmitInt (ig, j - idx);
4916 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj);
4918 ig.Emit (OpCodes.Ldelema, t);
4923 ig.Emit (OpCodes.Stobj, t);
4927 ig.Emit (OpCodes.Ldloc, array);
4931 /// Emits a list of resolved Arguments that are in the arguments
4934 /// The MethodBase argument might be null if the
4935 /// emission of the arguments is known not to contain
4936 /// a `params' field (for example in constructors or other routines
4937 /// that keep their arguments in this structure)
4939 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
4943 pd = GetParameterData (mb);
4948 // If we are calling a params method with no arguments, special case it
4950 if (arguments == null){
4951 if (pd != null && pd.Count > 0 &&
4952 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
4953 ILGenerator ig = ec.ig;
4955 IntConstant.EmitInt (ig, 0);
4956 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
4962 int top = arguments.Count;
4964 for (int i = 0; i < top; i++){
4965 Argument a = (Argument) arguments [i];
4968 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
4970 // Special case if we are passing the same data as the
4971 // params argument, do not put it in an array.
4973 if (pd.ParameterType (i) == a.Type)
4976 EmitParams (ec, i, arguments);
4984 if (pd != null && pd.Count > top &&
4985 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
4986 ILGenerator ig = ec.ig;
4988 IntConstant.EmitInt (ig, 0);
4989 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
4994 /// is_base tells whether we want to force the use of the `call'
4995 /// opcode instead of using callvirt. Call is required to call
4996 /// a specific method, while callvirt will always use the most
4997 /// recent method in the vtable.
4999 /// is_static tells whether this is an invocation on a static method
5001 /// instance_expr is an expression that represents the instance
5002 /// it must be non-null if is_static is false.
5004 /// method is the method to invoke.
5006 /// Arguments is the list of arguments to pass to the method or constructor.
5008 public static void EmitCall (EmitContext ec, bool is_base,
5009 bool is_static, Expression instance_expr,
5010 MethodBase method, ArrayList Arguments, Location loc)
5012 ILGenerator ig = ec.ig;
5013 bool struct_call = false;
5015 Type decl_type = method.DeclaringType;
5017 if (!RootContext.StdLib) {
5018 // Replace any calls to the system's System.Array type with calls to
5019 // the newly created one.
5020 if (method == TypeManager.system_int_array_get_length)
5021 method = TypeManager.int_array_get_length;
5022 else if (method == TypeManager.system_int_array_get_rank)
5023 method = TypeManager.int_array_get_rank;
5024 else if (method == TypeManager.system_object_array_clone)
5025 method = TypeManager.object_array_clone;
5026 else if (method == TypeManager.system_int_array_get_length_int)
5027 method = TypeManager.int_array_get_length_int;
5028 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5029 method = TypeManager.int_array_get_lower_bound_int;
5030 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5031 method = TypeManager.int_array_get_upper_bound_int;
5032 else if (method == TypeManager.system_void_array_copyto_array_int)
5033 method = TypeManager.void_array_copyto_array_int;
5037 // This checks the `ConditionalAttribute' on the method, and the
5038 // ObsoleteAttribute
5040 TypeManager.MethodFlags flags = TypeManager.GetMethodFlags (method, loc);
5041 if ((flags & TypeManager.MethodFlags.IsObsoleteError) != 0)
5043 if ((flags & TypeManager.MethodFlags.ShouldIgnore) != 0)
5047 if (decl_type.IsValueType)
5050 // If this is ourselves, push "this"
5052 if (instance_expr == null){
5053 ig.Emit (OpCodes.Ldarg_0);
5056 // Push the instance expression
5058 if (instance_expr.Type.IsValueType){
5060 // Special case: calls to a function declared in a
5061 // reference-type with a value-type argument need
5062 // to have their value boxed.
5065 if (decl_type.IsValueType){
5067 // If the expression implements IMemoryLocation, then
5068 // we can optimize and use AddressOf on the
5071 // If not we have to use some temporary storage for
5073 if (instance_expr is IMemoryLocation){
5074 ((IMemoryLocation)instance_expr).
5075 AddressOf (ec, AddressOp.LoadStore);
5078 Type t = instance_expr.Type;
5080 instance_expr.Emit (ec);
5081 LocalBuilder temp = ig.DeclareLocal (t);
5082 ig.Emit (OpCodes.Stloc, temp);
5083 ig.Emit (OpCodes.Ldloca, temp);
5086 instance_expr.Emit (ec);
5087 ig.Emit (OpCodes.Box, instance_expr.Type);
5090 instance_expr.Emit (ec);
5094 EmitArguments (ec, method, Arguments);
5096 if (is_static || struct_call || is_base){
5097 if (method is MethodInfo) {
5098 ig.Emit (OpCodes.Call, (MethodInfo) method);
5100 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5102 if (method is MethodInfo)
5103 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
5105 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
5109 public override void Emit (EmitContext ec)
5111 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5113 EmitCall (ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5116 public override void EmitStatement (EmitContext ec)
5121 // Pop the return value if there is one
5123 if (method is MethodInfo){
5124 Type ret = ((MethodInfo)method).ReturnType;
5125 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5126 ec.ig.Emit (OpCodes.Pop);
5131 public class InvocationOrCast : ExpressionStatement
5134 Expression argument;
5136 public InvocationOrCast (Expression expr, Expression argument, Location loc)
5139 this.argument = argument;
5143 public override Expression DoResolve (EmitContext ec)
5146 // First try to resolve it as a cast.
5148 type = ec.DeclSpace.ResolveType (expr, true, loc);
5150 Cast cast = new Cast (new TypeExpr (type, loc), argument, loc);
5151 return cast.Resolve (ec);
5155 // This can either be a type or a delegate invocation.
5156 // Let's just resolve it and see what we'll get.
5158 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5163 // Ok, so it's a Cast.
5165 if (expr.eclass == ExprClass.Type) {
5166 Cast cast = new Cast (new TypeExpr (expr.Type, loc), argument, loc);
5167 return cast.Resolve (ec);
5171 // It's a delegate invocation.
5173 if (!TypeManager.IsDelegateType (expr.Type)) {
5174 Error (149, "Method name expected");
5178 ArrayList args = new ArrayList ();
5179 args.Add (new Argument (argument, Argument.AType.Expression));
5180 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5181 return invocation.Resolve (ec);
5186 Error (201, "Only assignment, call, increment, decrement and new object " +
5187 "expressions can be used as a statement");
5190 public override ExpressionStatement ResolveStatement (EmitContext ec)
5193 // First try to resolve it as a cast.
5195 type = ec.DeclSpace.ResolveType (expr, true, loc);
5202 // This can either be a type or a delegate invocation.
5203 // Let's just resolve it and see what we'll get.
5205 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5206 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5212 // It's a delegate invocation.
5214 if (!TypeManager.IsDelegateType (expr.Type)) {
5215 Error (149, "Method name expected");
5219 ArrayList args = new ArrayList ();
5220 args.Add (new Argument (argument, Argument.AType.Expression));
5221 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5222 return invocation.ResolveStatement (ec);
5225 public override void Emit (EmitContext ec)
5227 throw new Exception ("Cannot happen");
5230 public override void EmitStatement (EmitContext ec)
5232 throw new Exception ("Cannot happen");
5237 // This class is used to "disable" the code generation for the
5238 // temporary variable when initializing value types.
5240 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5241 public void AddressOf (EmitContext ec, AddressOp Mode)
5248 /// Implements the new expression
5250 public class New : ExpressionStatement, IMemoryLocation {
5251 public readonly ArrayList Arguments;
5254 // During bootstrap, it contains the RequestedType,
5255 // but if `type' is not null, it *might* contain a NewDelegate
5256 // (because of field multi-initialization)
5258 public Expression RequestedType;
5260 MethodBase method = null;
5263 // If set, the new expression is for a value_target, and
5264 // we will not leave anything on the stack.
5266 Expression value_target;
5267 bool value_target_set = false;
5269 public New (Expression requested_type, ArrayList arguments, Location l)
5271 RequestedType = requested_type;
5272 Arguments = arguments;
5276 public bool SetValueTypeVariable (Expression value)
5278 value_target = value;
5279 value_target_set = true;
5280 if (!(value_target is IMemoryLocation)){
5281 Error_UnexpectedKind ("variable");
5288 // This function is used to disable the following code sequence for
5289 // value type initialization:
5291 // AddressOf (temporary)
5295 // Instead the provide will have provided us with the address on the
5296 // stack to store the results.
5298 static Expression MyEmptyExpression;
5300 public void DisableTemporaryValueType ()
5302 if (MyEmptyExpression == null)
5303 MyEmptyExpression = new EmptyAddressOf ();
5306 // To enable this, look into:
5307 // test-34 and test-89 and self bootstrapping.
5309 // For instance, we can avoid a copy by using `newobj'
5310 // instead of Call + Push-temp on value types.
5311 // value_target = MyEmptyExpression;
5314 public override Expression DoResolve (EmitContext ec)
5317 // The New DoResolve might be called twice when initializing field
5318 // expressions (see EmitFieldInitializers, the call to
5319 // GetInitializerExpression will perform a resolve on the expression,
5320 // and later the assign will trigger another resolution
5322 // This leads to bugs (#37014)
5325 if (RequestedType is NewDelegate)
5326 return RequestedType;
5330 type = ec.DeclSpace.ResolveType (RequestedType, false, loc);
5335 bool IsDelegate = TypeManager.IsDelegateType (type);
5338 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5339 if (!(RequestedType is NewDelegate))
5340 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
5341 return RequestedType;
5344 if (type.IsInterface || type.IsAbstract){
5345 Error (144, "It is not possible to create instances of interfaces or abstract classes");
5349 bool is_struct = type.IsValueType;
5350 eclass = ExprClass.Value;
5353 // SRE returns a match for .ctor () on structs (the object constructor),
5354 // so we have to manually ignore it.
5356 if (is_struct && Arguments == null)
5360 ml = MemberLookupFinal (ec, null, type, ".ctor",
5361 MemberTypes.Constructor,
5362 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5367 if (! (ml is MethodGroupExpr)){
5369 ml.Error_UnexpectedKind ("method group");
5375 if (Arguments != null){
5376 foreach (Argument a in Arguments){
5377 if (!a.Resolve (ec, loc))
5382 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
5386 if (method == null) {
5387 if (!is_struct || Arguments.Count > 0) {
5388 Error (1501, String.Format (
5389 "New invocation: Can not find a constructor in `{0}' for this argument list",
5390 TypeManager.CSharpName (type)));
5399 // This DoEmit can be invoked in two contexts:
5400 // * As a mechanism that will leave a value on the stack (new object)
5401 // * As one that wont (init struct)
5403 // You can control whether a value is required on the stack by passing
5404 // need_value_on_stack. The code *might* leave a value on the stack
5405 // so it must be popped manually
5407 // If we are dealing with a ValueType, we have a few
5408 // situations to deal with:
5410 // * The target is a ValueType, and we have been provided
5411 // the instance (this is easy, we are being assigned).
5413 // * The target of New is being passed as an argument,
5414 // to a boxing operation or a function that takes a
5417 // In this case, we need to create a temporary variable
5418 // that is the argument of New.
5420 // Returns whether a value is left on the stack
5422 bool DoEmit (EmitContext ec, bool need_value_on_stack)
5424 bool is_value_type = type.IsValueType;
5425 ILGenerator ig = ec.ig;
5430 // Allow DoEmit() to be called multiple times.
5431 // We need to create a new LocalTemporary each time since
5432 // you can't share LocalBuilders among ILGeneators.
5433 if (!value_target_set)
5434 value_target = new LocalTemporary (ec, type);
5436 ml = (IMemoryLocation) value_target;
5437 ml.AddressOf (ec, AddressOp.Store);
5441 Invocation.EmitArguments (ec, method, Arguments);
5445 ig.Emit (OpCodes.Initobj, type);
5447 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5448 if (need_value_on_stack){
5449 value_target.Emit (ec);
5454 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
5459 public override void Emit (EmitContext ec)
5464 public override void EmitStatement (EmitContext ec)
5466 if (DoEmit (ec, false))
5467 ec.ig.Emit (OpCodes.Pop);
5470 public void AddressOf (EmitContext ec, AddressOp Mode)
5472 if (!type.IsValueType){
5474 // We throw an exception. So far, I believe we only need to support
5476 // foreach (int j in new StructType ())
5479 throw new Exception ("AddressOf should not be used for classes");
5482 if (!value_target_set)
5483 value_target = new LocalTemporary (ec, type);
5485 IMemoryLocation ml = (IMemoryLocation) value_target;
5486 ml.AddressOf (ec, AddressOp.Store);
5488 Invocation.EmitArguments (ec, method, Arguments);
5491 ec.ig.Emit (OpCodes.Initobj, type);
5493 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5495 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
5500 /// 14.5.10.2: Represents an array creation expression.
5504 /// There are two possible scenarios here: one is an array creation
5505 /// expression that specifies the dimensions and optionally the
5506 /// initialization data and the other which does not need dimensions
5507 /// specified but where initialization data is mandatory.
5509 public class ArrayCreation : ExpressionStatement {
5510 Expression requested_base_type;
5511 ArrayList initializers;
5514 // The list of Argument types.
5515 // This is used to construct the `newarray' or constructor signature
5517 ArrayList arguments;
5520 // Method used to create the array object.
5522 MethodBase new_method = null;
5524 Type array_element_type;
5525 Type underlying_type;
5526 bool is_one_dimensional = false;
5527 bool is_builtin_type = false;
5528 bool expect_initializers = false;
5529 int num_arguments = 0;
5533 ArrayList array_data;
5538 // The number of array initializers that we can handle
5539 // via the InitializeArray method - through EmitStaticInitializers
5541 int num_automatic_initializers;
5543 const int max_automatic_initializers = 6;
5545 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
5547 this.requested_base_type = requested_base_type;
5548 this.initializers = initializers;
5552 arguments = new ArrayList ();
5554 foreach (Expression e in exprs) {
5555 arguments.Add (new Argument (e, Argument.AType.Expression));
5560 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
5562 this.requested_base_type = requested_base_type;
5563 this.initializers = initializers;
5567 //this.rank = rank.Substring (0, rank.LastIndexOf ("["));
5569 //string tmp = rank.Substring (rank.LastIndexOf ("["));
5571 //dimensions = tmp.Length - 1;
5572 expect_initializers = true;
5575 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
5577 StringBuilder sb = new StringBuilder (rank);
5580 for (int i = 1; i < idx_count; i++)
5585 return new ComposedCast (base_type, sb.ToString (), loc);
5588 void Error_IncorrectArrayInitializer ()
5590 Error (178, "Incorrectly structured array initializer");
5593 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
5595 if (specified_dims) {
5596 Argument a = (Argument) arguments [idx];
5598 if (!a.Resolve (ec, loc))
5601 if (!(a.Expr is Constant)) {
5602 Error (150, "A constant value is expected");
5606 int value = (int) ((Constant) a.Expr).GetValue ();
5608 if (value != probe.Count) {
5609 Error_IncorrectArrayInitializer ();
5613 bounds [idx] = value;
5616 int child_bounds = -1;
5617 foreach (object o in probe) {
5618 if (o is ArrayList) {
5619 int current_bounds = ((ArrayList) o).Count;
5621 if (child_bounds == -1)
5622 child_bounds = current_bounds;
5624 else if (child_bounds != current_bounds){
5625 Error_IncorrectArrayInitializer ();
5628 if (specified_dims && (idx + 1 >= arguments.Count)){
5629 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
5633 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
5637 if (child_bounds != -1){
5638 Error_IncorrectArrayInitializer ();
5642 Expression tmp = (Expression) o;
5643 tmp = tmp.Resolve (ec);
5647 // Console.WriteLine ("I got: " + tmp);
5648 // Handle initialization from vars, fields etc.
5650 Expression conv = Convert.ImplicitConversionRequired (
5651 ec, tmp, underlying_type, loc);
5656 if (conv is StringConstant)
5657 array_data.Add (conv);
5658 else if (conv is Constant) {
5659 array_data.Add (conv);
5660 num_automatic_initializers++;
5662 array_data.Add (conv);
5669 public void UpdateIndices (EmitContext ec)
5672 for (ArrayList probe = initializers; probe != null;) {
5673 if (probe.Count > 0 && probe [0] is ArrayList) {
5674 Expression e = new IntConstant (probe.Count);
5675 arguments.Add (new Argument (e, Argument.AType.Expression));
5677 bounds [i++] = probe.Count;
5679 probe = (ArrayList) probe [0];
5682 Expression e = new IntConstant (probe.Count);
5683 arguments.Add (new Argument (e, Argument.AType.Expression));
5685 bounds [i++] = probe.Count;
5692 public bool ValidateInitializers (EmitContext ec, Type array_type)
5694 if (initializers == null) {
5695 if (expect_initializers)
5701 if (underlying_type == null)
5705 // We use this to store all the date values in the order in which we
5706 // will need to store them in the byte blob later
5708 array_data = new ArrayList ();
5709 bounds = new Hashtable ();
5713 if (arguments != null) {
5714 ret = CheckIndices (ec, initializers, 0, true);
5717 arguments = new ArrayList ();
5719 ret = CheckIndices (ec, initializers, 0, false);
5726 if (arguments.Count != dimensions) {
5727 Error_IncorrectArrayInitializer ();
5735 void Error_NegativeArrayIndex ()
5737 Error (284, "Can not create array with a negative size");
5741 // Converts `source' to an int, uint, long or ulong.
5743 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
5747 bool old_checked = ec.CheckState;
5748 ec.CheckState = true;
5750 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
5751 if (target == null){
5752 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
5753 if (target == null){
5754 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
5755 if (target == null){
5756 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
5758 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
5762 ec.CheckState = old_checked;
5765 // Only positive constants are allowed at compile time
5767 if (target is Constant){
5768 if (target is IntConstant){
5769 if (((IntConstant) target).Value < 0){
5770 Error_NegativeArrayIndex ();
5775 if (target is LongConstant){
5776 if (((LongConstant) target).Value < 0){
5777 Error_NegativeArrayIndex ();
5788 // Creates the type of the array
5790 bool LookupType (EmitContext ec)
5792 StringBuilder array_qualifier = new StringBuilder (rank);
5795 // `In the first form allocates an array instace of the type that results
5796 // from deleting each of the individual expression from the expression list'
5798 if (num_arguments > 0) {
5799 array_qualifier.Append ("[");
5800 for (int i = num_arguments-1; i > 0; i--)
5801 array_qualifier.Append (",");
5802 array_qualifier.Append ("]");
5808 Expression array_type_expr;
5809 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
5810 type = ec.DeclSpace.ResolveType (array_type_expr, false, loc);
5815 underlying_type = type;
5816 if (underlying_type.IsArray)
5817 underlying_type = TypeManager.GetElementType (underlying_type);
5818 dimensions = type.GetArrayRank ();
5823 public override Expression DoResolve (EmitContext ec)
5827 if (!LookupType (ec))
5831 // First step is to validate the initializers and fill
5832 // in any missing bits
5834 if (!ValidateInitializers (ec, type))
5837 if (arguments == null)
5840 arg_count = arguments.Count;
5841 foreach (Argument a in arguments){
5842 if (!a.Resolve (ec, loc))
5845 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
5846 if (real_arg == null)
5853 array_element_type = TypeManager.GetElementType (type);
5855 if (arg_count == 1) {
5856 is_one_dimensional = true;
5857 eclass = ExprClass.Value;
5861 is_builtin_type = TypeManager.IsBuiltinType (type);
5863 if (is_builtin_type) {
5866 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
5867 AllBindingFlags, loc);
5869 if (!(ml is MethodGroupExpr)) {
5870 ml.Error_UnexpectedKind ("method group");
5875 Error (-6, "New invocation: Can not find a constructor for " +
5876 "this argument list");
5880 new_method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, arguments, loc);
5882 if (new_method == null) {
5883 Error (-6, "New invocation: Can not find a constructor for " +
5884 "this argument list");
5888 eclass = ExprClass.Value;
5891 ModuleBuilder mb = CodeGen.ModuleBuilder;
5892 ArrayList args = new ArrayList ();
5894 if (arguments != null) {
5895 for (int i = 0; i < arg_count; i++)
5896 args.Add (TypeManager.int32_type);
5899 Type [] arg_types = null;
5902 arg_types = new Type [args.Count];
5904 args.CopyTo (arg_types, 0);
5906 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
5909 if (new_method == null) {
5910 Error (-6, "New invocation: Can not find a constructor for " +
5911 "this argument list");
5915 eclass = ExprClass.Value;
5920 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
5925 int count = array_data.Count;
5927 if (underlying_type.IsEnum)
5928 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
5930 factor = GetTypeSize (underlying_type);
5932 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
5934 data = new byte [(count * factor + 4) & ~3];
5937 for (int i = 0; i < count; ++i) {
5938 object v = array_data [i];
5940 if (v is EnumConstant)
5941 v = ((EnumConstant) v).Child;
5943 if (v is Constant && !(v is StringConstant))
5944 v = ((Constant) v).GetValue ();
5950 if (underlying_type == TypeManager.int64_type){
5951 if (!(v is Expression)){
5952 long val = (long) v;
5954 for (int j = 0; j < factor; ++j) {
5955 data [idx + j] = (byte) (val & 0xFF);
5959 } else if (underlying_type == TypeManager.uint64_type){
5960 if (!(v is Expression)){
5961 ulong val = (ulong) v;
5963 for (int j = 0; j < factor; ++j) {
5964 data [idx + j] = (byte) (val & 0xFF);
5968 } else if (underlying_type == TypeManager.float_type) {
5969 if (!(v is Expression)){
5970 element = BitConverter.GetBytes ((float) v);
5972 for (int j = 0; j < factor; ++j)
5973 data [idx + j] = element [j];
5975 } else if (underlying_type == TypeManager.double_type) {
5976 if (!(v is Expression)){
5977 element = BitConverter.GetBytes ((double) v);
5979 for (int j = 0; j < factor; ++j)
5980 data [idx + j] = element [j];
5982 } else if (underlying_type == TypeManager.char_type){
5983 if (!(v is Expression)){
5984 int val = (int) ((char) v);
5986 data [idx] = (byte) (val & 0xff);
5987 data [idx+1] = (byte) (val >> 8);
5989 } else if (underlying_type == TypeManager.short_type){
5990 if (!(v is Expression)){
5991 int val = (int) ((short) v);
5993 data [idx] = (byte) (val & 0xff);
5994 data [idx+1] = (byte) (val >> 8);
5996 } else if (underlying_type == TypeManager.ushort_type){
5997 if (!(v is Expression)){
5998 int val = (int) ((ushort) v);
6000 data [idx] = (byte) (val & 0xff);
6001 data [idx+1] = (byte) (val >> 8);
6003 } else if (underlying_type == TypeManager.int32_type) {
6004 if (!(v is Expression)){
6007 data [idx] = (byte) (val & 0xff);
6008 data [idx+1] = (byte) ((val >> 8) & 0xff);
6009 data [idx+2] = (byte) ((val >> 16) & 0xff);
6010 data [idx+3] = (byte) (val >> 24);
6012 } else if (underlying_type == TypeManager.uint32_type) {
6013 if (!(v is Expression)){
6014 uint val = (uint) v;
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.sbyte_type) {
6022 if (!(v is Expression)){
6023 sbyte val = (sbyte) v;
6024 data [idx] = (byte) val;
6026 } else if (underlying_type == TypeManager.byte_type) {
6027 if (!(v is Expression)){
6028 byte val = (byte) v;
6029 data [idx] = (byte) val;
6031 } else if (underlying_type == TypeManager.bool_type) {
6032 if (!(v is Expression)){
6033 bool val = (bool) v;
6034 data [idx] = (byte) (val ? 1 : 0);
6036 } else if (underlying_type == TypeManager.decimal_type){
6037 if (!(v is Expression)){
6038 int [] bits = Decimal.GetBits ((decimal) v);
6041 // FIXME: For some reason, this doesn't work on the MS runtime.
6042 int [] nbits = new int [4];
6043 nbits [0] = bits [3];
6044 nbits [1] = bits [2];
6045 nbits [2] = bits [0];
6046 nbits [3] = bits [1];
6048 for (int j = 0; j < 4; j++){
6049 data [p++] = (byte) (nbits [j] & 0xff);
6050 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6051 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6052 data [p++] = (byte) (nbits [j] >> 24);
6056 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6065 // Emits the initializers for the array
6067 void EmitStaticInitializers (EmitContext ec, bool is_expression)
6070 // First, the static data
6073 ILGenerator ig = ec.ig;
6075 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6077 fb = RootContext.MakeStaticData (data);
6080 ig.Emit (OpCodes.Dup);
6081 ig.Emit (OpCodes.Ldtoken, fb);
6082 ig.Emit (OpCodes.Call,
6083 TypeManager.void_initializearray_array_fieldhandle);
6087 // Emits pieces of the array that can not be computed at compile
6088 // time (variables and string locations).
6090 // This always expect the top value on the stack to be the array
6092 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
6094 ILGenerator ig = ec.ig;
6095 int dims = bounds.Count;
6096 int [] current_pos = new int [dims];
6097 int top = array_data.Count;
6098 LocalBuilder temp = ig.DeclareLocal (type);
6100 ig.Emit (OpCodes.Stloc, temp);
6102 MethodInfo set = null;
6106 ModuleBuilder mb = null;
6107 mb = CodeGen.ModuleBuilder;
6108 args = new Type [dims + 1];
6111 for (j = 0; j < dims; j++)
6112 args [j] = TypeManager.int32_type;
6114 args [j] = array_element_type;
6116 set = mb.GetArrayMethod (
6118 CallingConventions.HasThis | CallingConventions.Standard,
6119 TypeManager.void_type, args);
6122 for (int i = 0; i < top; i++){
6124 Expression e = null;
6126 if (array_data [i] is Expression)
6127 e = (Expression) array_data [i];
6131 // Basically we do this for string literals and
6132 // other non-literal expressions
6134 if (e is EnumConstant){
6135 e = ((EnumConstant) e).Child;
6138 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6139 num_automatic_initializers <= max_automatic_initializers) {
6140 Type etype = e.Type;
6142 ig.Emit (OpCodes.Ldloc, temp);
6144 for (int idx = 0; idx < dims; idx++)
6145 IntConstant.EmitInt (ig, current_pos [idx]);
6148 // If we are dealing with a struct, get the
6149 // address of it, so we can store it.
6152 etype.IsSubclassOf (TypeManager.value_type) &&
6153 (!TypeManager.IsBuiltinOrEnum (etype) ||
6154 etype == TypeManager.decimal_type)) {
6159 // Let new know that we are providing
6160 // the address where to store the results
6162 n.DisableTemporaryValueType ();
6165 ig.Emit (OpCodes.Ldelema, etype);
6168 ig.Emit (OpCodes.Nop);
6170 ig.Emit (OpCodes.Nop);
6171 ig.Emit (OpCodes.Nop);
6174 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
6176 ig.Emit (OpCodes.Call, set);
6184 for (int j = dims - 1; j >= 0; j--){
6186 if (current_pos [j] < (int) bounds [j])
6188 current_pos [j] = 0;
6193 ig.Emit (OpCodes.Ldloc, temp);
6196 void EmitArrayArguments (EmitContext ec)
6198 ILGenerator ig = ec.ig;
6200 foreach (Argument a in arguments) {
6201 Type atype = a.Type;
6204 if (atype == TypeManager.uint64_type)
6205 ig.Emit (OpCodes.Conv_Ovf_U4);
6206 else if (atype == TypeManager.int64_type)
6207 ig.Emit (OpCodes.Conv_Ovf_I4);
6211 void DoEmit (EmitContext ec, bool is_statement)
6213 ILGenerator ig = ec.ig;
6215 EmitArrayArguments (ec);
6216 if (is_one_dimensional)
6217 ig.Emit (OpCodes.Newarr, array_element_type);
6219 if (is_builtin_type)
6220 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6222 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6225 if (initializers != null){
6227 // FIXME: Set this variable correctly.
6229 bool dynamic_initializers = true;
6231 if (underlying_type != TypeManager.string_type &&
6232 underlying_type != TypeManager.decimal_type &&
6233 underlying_type != TypeManager.object_type) {
6234 if (num_automatic_initializers > max_automatic_initializers)
6235 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
6238 if (dynamic_initializers)
6239 EmitDynamicInitializers (ec, !is_statement);
6243 public override void Emit (EmitContext ec)
6248 public override void EmitStatement (EmitContext ec)
6253 public object EncodeAsAttribute ()
6255 if (!is_one_dimensional){
6256 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6260 if (array_data == null){
6261 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6265 object [] ret = new object [array_data.Count];
6267 foreach (Expression e in array_data){
6270 if (e is NullLiteral)
6273 if (!Attribute.GetAttributeArgumentExpression (e, Location, out v))
6283 /// Represents the `this' construct
6285 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6288 VariableInfo variable_info;
6290 public This (Block block, Location loc)
6296 public This (Location loc)
6301 public VariableInfo VariableInfo {
6302 get { return variable_info; }
6305 public bool VerifyFixed (bool is_expression)
6307 if ((variable_info == null) || (variable_info.LocalInfo == null))
6310 return variable_info.LocalInfo.IsFixed;
6313 public bool ResolveBase (EmitContext ec)
6315 eclass = ExprClass.Variable;
6316 type = ec.ContainerType;
6319 Error (26, "Keyword this not valid in static code");
6323 if ((block != null) && (block.ThisVariable != null))
6324 variable_info = block.ThisVariable.VariableInfo;
6329 public override Expression DoResolve (EmitContext ec)
6331 if (!ResolveBase (ec))
6334 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
6335 Error (188, "The this object cannot be used before all " +
6336 "of its fields are assigned to");
6337 variable_info.SetAssigned (ec);
6341 if (ec.IsFieldInitializer) {
6342 Error (27, "Keyword `this' can't be used outside a constructor, " +
6343 "a method or a property.");
6350 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6352 if (!ResolveBase (ec))
6355 if (variable_info != null)
6356 variable_info.SetAssigned (ec);
6358 if (ec.TypeContainer is Class){
6359 Error (1604, "Cannot assign to `this'");
6366 public override void Emit (EmitContext ec)
6368 ILGenerator ig = ec.ig;
6370 ig.Emit (OpCodes.Ldarg_0);
6371 if (ec.TypeContainer is Struct)
6372 ig.Emit (OpCodes.Ldobj, type);
6375 public void EmitAssign (EmitContext ec, Expression source)
6377 ILGenerator ig = ec.ig;
6379 if (ec.TypeContainer is Struct){
6380 ig.Emit (OpCodes.Ldarg_0);
6382 ig.Emit (OpCodes.Stobj, type);
6385 ig.Emit (OpCodes.Starg, 0);
6389 public void AddressOf (EmitContext ec, AddressOp mode)
6391 ec.ig.Emit (OpCodes.Ldarg_0);
6394 // FIGURE OUT WHY LDARG_S does not work
6396 // consider: struct X { int val; int P { set { val = value; }}}
6398 // Yes, this looks very bad. Look at `NOTAS' for
6400 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
6405 // This produces the value that renders an instance, used by the iterators code
6407 public class ProxyInstance : Expression, IMemoryLocation {
6408 public override Expression DoResolve (EmitContext ec)
6410 eclass = ExprClass.Variable;
6411 type = ec.ContainerType;
6415 public override void Emit (EmitContext ec)
6417 ec.ig.Emit (OpCodes.Ldarg_0);
6421 public void AddressOf (EmitContext ec, AddressOp mode)
6423 ec.ig.Emit (OpCodes.Ldarg_0);
6428 /// Implements the typeof operator
6430 public class TypeOf : Expression {
6431 public readonly Expression QueriedType;
6434 public TypeOf (Expression queried_type, Location l)
6436 QueriedType = queried_type;
6440 public override Expression DoResolve (EmitContext ec)
6442 typearg = ec.DeclSpace.ResolveType (QueriedType, false, loc);
6444 if (typearg == null)
6447 if (typearg == TypeManager.void_type) {
6448 Error (673, "System.Void cannot be used from C# - " +
6449 "use typeof (void) to get the void type object");
6453 type = TypeManager.type_type;
6454 eclass = ExprClass.Type;
6458 public override void Emit (EmitContext ec)
6460 ec.ig.Emit (OpCodes.Ldtoken, typearg);
6461 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6464 public Type TypeArg {
6465 get { return typearg; }
6470 /// Implements the `typeof (void)' operator
6472 public class TypeOfVoid : Expression {
6473 public TypeOfVoid (Location l)
6478 public override Expression DoResolve (EmitContext ec)
6480 type = TypeManager.type_type;
6481 eclass = ExprClass.Type;
6485 public override void Emit (EmitContext ec)
6487 ec.ig.Emit (OpCodes.Ldtoken, TypeManager.void_type);
6488 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6491 public Type TypeArg {
6492 get { return TypeManager.void_type; }
6497 /// Implements the sizeof expression
6499 public class SizeOf : Expression {
6500 public readonly Expression QueriedType;
6503 public SizeOf (Expression queried_type, Location l)
6505 this.QueriedType = queried_type;
6509 public override Expression DoResolve (EmitContext ec)
6513 233, loc, "Sizeof may only be used in an unsafe context " +
6514 "(consider using System.Runtime.InteropServices.Marshal.Sizeof");
6518 type_queried = ec.DeclSpace.ResolveType (QueriedType, false, loc);
6519 if (type_queried == null)
6522 if (!TypeManager.IsUnmanagedType (type_queried)){
6523 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
6527 type = TypeManager.int32_type;
6528 eclass = ExprClass.Value;
6532 public override void Emit (EmitContext ec)
6534 int size = GetTypeSize (type_queried);
6537 ec.ig.Emit (OpCodes.Sizeof, type_queried);
6539 IntConstant.EmitInt (ec.ig, size);
6544 /// Implements the member access expression
6546 public class MemberAccess : Expression {
6547 public readonly string Identifier;
6550 public MemberAccess (Expression expr, string id, Location l)
6557 public Expression Expr {
6563 static void error176 (Location loc, string name)
6565 Report.Error (176, loc, "Static member `" +
6566 name + "' cannot be accessed " +
6567 "with an instance reference, qualify with a " +
6568 "type name instead");
6571 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
6573 if (left_original == null)
6576 if (!(left_original is SimpleName))
6579 SimpleName sn = (SimpleName) left_original;
6581 Type t = RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc);
6588 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
6589 Expression left, Location loc,
6590 Expression left_original)
6592 bool left_is_type, left_is_explicit;
6594 // If `left' is null, then we're called from SimpleNameResolve and this is
6595 // a member in the currently defining class.
6597 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
6598 left_is_explicit = false;
6600 // Implicitly default to `this' unless we're static.
6601 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
6602 left = ec.GetThis (loc);
6604 left_is_type = left is TypeExpr;
6605 left_is_explicit = true;
6608 if (member_lookup is FieldExpr){
6609 FieldExpr fe = (FieldExpr) member_lookup;
6610 FieldInfo fi = fe.FieldInfo;
6611 Type decl_type = fi.DeclaringType;
6613 if (fi is FieldBuilder) {
6614 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
6617 object o = c.LookupConstantValue ();
6621 object real_value = ((Constant) c.Expr).GetValue ();
6623 return Constantify (real_value, fi.FieldType);
6628 Type t = fi.FieldType;
6632 if (fi is FieldBuilder)
6633 o = TypeManager.GetValue ((FieldBuilder) fi);
6635 o = fi.GetValue (fi);
6637 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
6638 if (left_is_explicit && !left_is_type &&
6639 !IdenticalNameAndTypeName (ec, left_original, loc)) {
6640 error176 (loc, fe.FieldInfo.Name);
6644 Expression enum_member = MemberLookup (
6645 ec, decl_type, "value__", MemberTypes.Field,
6646 AllBindingFlags, loc);
6648 Enum en = TypeManager.LookupEnum (decl_type);
6652 c = Constantify (o, en.UnderlyingType);
6654 c = Constantify (o, enum_member.Type);
6656 return new EnumConstant (c, decl_type);
6659 Expression exp = Constantify (o, t);
6661 if (left_is_explicit && !left_is_type) {
6662 error176 (loc, fe.FieldInfo.Name);
6669 if (fi.FieldType.IsPointer && !ec.InUnsafe){
6675 if (member_lookup is EventExpr) {
6676 EventExpr ee = (EventExpr) member_lookup;
6679 // If the event is local to this class, we transform ourselves into
6683 if (ee.EventInfo.DeclaringType == ec.ContainerType ||
6684 TypeManager.IsNestedChildOf(ec.ContainerType, ee.EventInfo.DeclaringType)) {
6685 MemberInfo mi = GetFieldFromEvent (ee);
6689 // If this happens, then we have an event with its own
6690 // accessors and private field etc so there's no need
6691 // to transform ourselves.
6696 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
6699 Report.Error (-200, loc, "Internal error!!");
6703 if (!left_is_explicit)
6706 return ResolveMemberAccess (ec, ml, left, loc, left_original);
6710 if (member_lookup is IMemberExpr) {
6711 IMemberExpr me = (IMemberExpr) member_lookup;
6714 MethodGroupExpr mg = me as MethodGroupExpr;
6715 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
6716 mg.IsExplicitImpl = left_is_explicit;
6719 if ((ec.IsFieldInitializer || ec.IsStatic) &&
6720 IdenticalNameAndTypeName (ec, left_original, loc))
6721 return member_lookup;
6723 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
6728 if (!me.IsInstance){
6729 if (IdenticalNameAndTypeName (ec, left_original, loc))
6730 return member_lookup;
6732 if (left_is_explicit) {
6733 error176 (loc, me.Name);
6739 // Since we can not check for instance objects in SimpleName,
6740 // becaue of the rule that allows types and variables to share
6741 // the name (as long as they can be de-ambiguated later, see
6742 // IdenticalNameAndTypeName), we have to check whether left
6743 // is an instance variable in a static context
6745 // However, if the left-hand value is explicitly given, then
6746 // it is already our instance expression, so we aren't in
6750 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
6751 IMemberExpr mexp = (IMemberExpr) left;
6753 if (!mexp.IsStatic){
6754 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
6759 me.InstanceExpression = left;
6762 return member_lookup;
6765 Console.WriteLine ("Left is: " + left);
6766 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
6767 Environment.Exit (0);
6771 public Expression DoResolve (EmitContext ec, Expression right_side, ResolveFlags flags)
6774 throw new Exception ();
6777 // Resolve the expression with flow analysis turned off, we'll do the definite
6778 // assignment checks later. This is because we don't know yet what the expression
6779 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
6780 // definite assignment check on the actual field and not on the whole struct.
6783 Expression original = expr;
6784 expr = expr.Resolve (ec, flags | ResolveFlags.DisableFlowAnalysis);
6788 if (expr is SimpleName){
6789 SimpleName child_expr = (SimpleName) expr;
6791 Expression new_expr = new SimpleName (child_expr.Name, Identifier, loc);
6793 return new_expr.Resolve (ec, flags);
6797 // TODO: I mailed Ravi about this, and apparently we can get rid
6798 // of this and put it in the right place.
6800 // Handle enums here when they are in transit.
6801 // Note that we cannot afford to hit MemberLookup in this case because
6802 // it will fail to find any members at all
6805 int errors = Report.Errors;
6807 Type expr_type = expr.Type;
6808 if (expr is TypeExpr){
6809 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
6810 Error (122, "`" + expr_type + "' " +
6811 "is inaccessible because of its protection level");
6815 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
6816 Enum en = TypeManager.LookupEnum (expr_type);
6819 object value = en.LookupEnumValue (ec, Identifier, loc);
6822 Constant c = Constantify (value, en.UnderlyingType);
6823 return new EnumConstant (c, expr_type);
6829 if (expr_type.IsPointer){
6830 Error (23, "The `.' operator can not be applied to pointer operands (" +
6831 TypeManager.CSharpName (expr_type) + ")");
6835 Expression member_lookup;
6836 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
6837 if (member_lookup == null)
6840 if (member_lookup is TypeExpr) {
6841 if (!(expr is TypeExpr) && !(expr is SimpleName)) {
6842 Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
6843 member_lookup.Type + "' instead");
6847 return member_lookup;
6850 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
6851 if (member_lookup == null)
6854 // The following DoResolve/DoResolveLValue will do the definite assignment
6857 if (right_side != null)
6858 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
6860 member_lookup = member_lookup.DoResolve (ec);
6862 return member_lookup;
6865 public override Expression DoResolve (EmitContext ec)
6867 return DoResolve (ec, null, ResolveFlags.VariableOrValue |
6868 ResolveFlags.SimpleName | ResolveFlags.Type);
6871 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
6873 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
6874 ResolveFlags.SimpleName | ResolveFlags.Type);
6877 public override Expression ResolveAsTypeStep (EmitContext ec)
6879 string fname = null;
6880 MemberAccess full_expr = this;
6881 while (full_expr != null) {
6883 fname = String.Concat (full_expr.Identifier, ".", fname);
6885 fname = full_expr.Identifier;
6887 if (full_expr.Expr is SimpleName) {
6888 string full_name = String.Concat (((SimpleName) full_expr.Expr).Name, ".", fname);
6889 Type fully_qualified = ec.DeclSpace.FindType (loc, full_name);
6890 if (fully_qualified != null)
6891 return new TypeExpr (fully_qualified, loc);
6894 full_expr = full_expr.Expr as MemberAccess;
6897 Expression new_expr = expr.ResolveAsTypeStep (ec);
6899 if (new_expr == null)
6902 if (new_expr is SimpleName){
6903 SimpleName child_expr = (SimpleName) new_expr;
6905 new_expr = new SimpleName (child_expr.Name, Identifier, loc);
6907 return new_expr.ResolveAsTypeStep (ec);
6910 Type expr_type = new_expr.Type;
6912 if (expr_type.IsPointer){
6913 Error (23, "The `.' operator can not be applied to pointer operands (" +
6914 TypeManager.CSharpName (expr_type) + ")");
6918 Expression member_lookup;
6919 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
6920 if (member_lookup == null)
6923 if (member_lookup is TypeExpr){
6924 member_lookup.Resolve (ec, ResolveFlags.Type);
6925 return member_lookup;
6931 public override void Emit (EmitContext ec)
6933 throw new Exception ("Should not happen");
6936 public override string ToString ()
6938 return expr + "." + Identifier;
6943 /// Implements checked expressions
6945 public class CheckedExpr : Expression {
6947 public Expression Expr;
6949 public CheckedExpr (Expression e, Location l)
6955 public override Expression DoResolve (EmitContext ec)
6957 bool last_check = ec.CheckState;
6958 bool last_const_check = ec.ConstantCheckState;
6960 ec.CheckState = true;
6961 ec.ConstantCheckState = true;
6962 Expr = Expr.Resolve (ec);
6963 ec.CheckState = last_check;
6964 ec.ConstantCheckState = last_const_check;
6969 if (Expr is Constant)
6972 eclass = Expr.eclass;
6977 public override void Emit (EmitContext ec)
6979 bool last_check = ec.CheckState;
6980 bool last_const_check = ec.ConstantCheckState;
6982 ec.CheckState = true;
6983 ec.ConstantCheckState = true;
6985 ec.CheckState = last_check;
6986 ec.ConstantCheckState = last_const_check;
6992 /// Implements the unchecked expression
6994 public class UnCheckedExpr : Expression {
6996 public Expression Expr;
6998 public UnCheckedExpr (Expression e, Location l)
7004 public override Expression DoResolve (EmitContext ec)
7006 bool last_check = ec.CheckState;
7007 bool last_const_check = ec.ConstantCheckState;
7009 ec.CheckState = false;
7010 ec.ConstantCheckState = false;
7011 Expr = Expr.Resolve (ec);
7012 ec.CheckState = last_check;
7013 ec.ConstantCheckState = last_const_check;
7018 if (Expr is Constant)
7021 eclass = Expr.eclass;
7026 public override void Emit (EmitContext ec)
7028 bool last_check = ec.CheckState;
7029 bool last_const_check = ec.ConstantCheckState;
7031 ec.CheckState = false;
7032 ec.ConstantCheckState = false;
7034 ec.CheckState = last_check;
7035 ec.ConstantCheckState = last_const_check;
7041 /// An Element Access expression.
7043 /// During semantic analysis these are transformed into
7044 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7046 public class ElementAccess : Expression {
7047 public ArrayList Arguments;
7048 public Expression Expr;
7050 public ElementAccess (Expression e, ArrayList e_list, Location l)
7059 Arguments = new ArrayList ();
7060 foreach (Expression tmp in e_list)
7061 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7065 bool CommonResolve (EmitContext ec)
7067 Expr = Expr.Resolve (ec);
7072 if (Arguments == null)
7075 foreach (Argument a in Arguments){
7076 if (!a.Resolve (ec, loc))
7083 Expression MakePointerAccess ()
7087 if (t == TypeManager.void_ptr_type){
7088 Error (242, "The array index operation is not valid for void pointers");
7091 if (Arguments.Count != 1){
7092 Error (196, "A pointer must be indexed by a single value");
7097 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc);
7098 return new Indirection (p, loc);
7101 public override Expression DoResolve (EmitContext ec)
7103 if (!CommonResolve (ec))
7107 // We perform some simple tests, and then to "split" the emit and store
7108 // code we create an instance of a different class, and return that.
7110 // I am experimenting with this pattern.
7114 if (t == TypeManager.array_type){
7115 Report.Error (21, loc, "Cannot use indexer on System.Array");
7120 return (new ArrayAccess (this, loc)).Resolve (ec);
7121 else if (t.IsPointer)
7122 return MakePointerAccess ();
7124 return (new IndexerAccess (this, loc)).Resolve (ec);
7127 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7129 if (!CommonResolve (ec))
7134 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
7135 else if (t.IsPointer)
7136 return MakePointerAccess ();
7138 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
7141 public override void Emit (EmitContext ec)
7143 throw new Exception ("Should never be reached");
7148 /// Implements array access
7150 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7152 // Points to our "data" repository
7156 LocalTemporary [] cached_locations;
7158 public ArrayAccess (ElementAccess ea_data, Location l)
7161 eclass = ExprClass.Variable;
7165 public override Expression DoResolve (EmitContext ec)
7167 ExprClass eclass = ea.Expr.eclass;
7170 // As long as the type is valid
7171 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7172 eclass == ExprClass.Value)) {
7173 ea.Expr.Error_UnexpectedKind ("variable or value");
7178 Type t = ea.Expr.Type;
7179 if (t.GetArrayRank () != ea.Arguments.Count){
7181 "Incorrect number of indexes for array " +
7182 " expected: " + t.GetArrayRank () + " got: " +
7183 ea.Arguments.Count);
7187 type = TypeManager.GetElementType (t);
7188 if (type.IsPointer && !ec.InUnsafe){
7189 UnsafeError (ea.Location);
7193 foreach (Argument a in ea.Arguments){
7194 Type argtype = a.Type;
7196 if (argtype == TypeManager.int32_type ||
7197 argtype == TypeManager.uint32_type ||
7198 argtype == TypeManager.int64_type ||
7199 argtype == TypeManager.uint64_type)
7203 // Mhm. This is strage, because the Argument.Type is not the same as
7204 // Argument.Expr.Type: the value changes depending on the ref/out setting.
7206 // Wonder if I will run into trouble for this.
7208 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
7213 eclass = ExprClass.Variable;
7219 /// Emits the right opcode to load an object of Type `t'
7220 /// from an array of T
7222 static public void EmitLoadOpcode (ILGenerator ig, Type type)
7224 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7225 ig.Emit (OpCodes.Ldelem_U1);
7226 else if (type == TypeManager.sbyte_type)
7227 ig.Emit (OpCodes.Ldelem_I1);
7228 else if (type == TypeManager.short_type)
7229 ig.Emit (OpCodes.Ldelem_I2);
7230 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7231 ig.Emit (OpCodes.Ldelem_U2);
7232 else if (type == TypeManager.int32_type)
7233 ig.Emit (OpCodes.Ldelem_I4);
7234 else if (type == TypeManager.uint32_type)
7235 ig.Emit (OpCodes.Ldelem_U4);
7236 else if (type == TypeManager.uint64_type)
7237 ig.Emit (OpCodes.Ldelem_I8);
7238 else if (type == TypeManager.int64_type)
7239 ig.Emit (OpCodes.Ldelem_I8);
7240 else if (type == TypeManager.float_type)
7241 ig.Emit (OpCodes.Ldelem_R4);
7242 else if (type == TypeManager.double_type)
7243 ig.Emit (OpCodes.Ldelem_R8);
7244 else if (type == TypeManager.intptr_type)
7245 ig.Emit (OpCodes.Ldelem_I);
7246 else if (type.IsValueType){
7247 ig.Emit (OpCodes.Ldelema, type);
7248 ig.Emit (OpCodes.Ldobj, type);
7250 ig.Emit (OpCodes.Ldelem_Ref);
7254 /// Emits the right opcode to store an object of Type `t'
7255 /// from an array of T.
7257 static public void EmitStoreOpcode (ILGenerator ig, Type t)
7260 OpCode op = GetStoreOpcode (t, out is_stobj);
7262 ig.Emit (OpCodes.Stobj, t);
7268 /// Returns the right opcode to store an object of Type `t'
7269 /// from an array of T.
7271 static public OpCode GetStoreOpcode (Type t, out bool is_stobj)
7273 //Console.WriteLine (new System.Diagnostics.StackTrace ());
7275 t = TypeManager.TypeToCoreType (t);
7276 if (TypeManager.IsEnumType (t) && t != TypeManager.enum_type)
7277 t = TypeManager.EnumToUnderlying (t);
7278 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
7279 t == TypeManager.bool_type)
7280 return OpCodes.Stelem_I1;
7281 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
7282 t == TypeManager.char_type)
7283 return OpCodes.Stelem_I2;
7284 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
7285 return OpCodes.Stelem_I4;
7286 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
7287 return OpCodes.Stelem_I8;
7288 else if (t == TypeManager.float_type)
7289 return OpCodes.Stelem_R4;
7290 else if (t == TypeManager.double_type)
7291 return OpCodes.Stelem_R8;
7292 else if (t == TypeManager.intptr_type) {
7294 return OpCodes.Stobj;
7295 } else if (t.IsValueType) {
7297 return OpCodes.Stobj;
7299 return OpCodes.Stelem_Ref;
7302 MethodInfo FetchGetMethod ()
7304 ModuleBuilder mb = CodeGen.ModuleBuilder;
7305 int arg_count = ea.Arguments.Count;
7306 Type [] args = new Type [arg_count];
7309 for (int i = 0; i < arg_count; i++){
7310 //args [i++] = a.Type;
7311 args [i] = TypeManager.int32_type;
7314 get = mb.GetArrayMethod (
7315 ea.Expr.Type, "Get",
7316 CallingConventions.HasThis |
7317 CallingConventions.Standard,
7323 MethodInfo FetchAddressMethod ()
7325 ModuleBuilder mb = CodeGen.ModuleBuilder;
7326 int arg_count = ea.Arguments.Count;
7327 Type [] args = new Type [arg_count];
7331 ret_type = TypeManager.GetReferenceType (type);
7333 for (int i = 0; i < arg_count; i++){
7334 //args [i++] = a.Type;
7335 args [i] = TypeManager.int32_type;
7338 address = mb.GetArrayMethod (
7339 ea.Expr.Type, "Address",
7340 CallingConventions.HasThis |
7341 CallingConventions.Standard,
7348 // Load the array arguments into the stack.
7350 // If we have been requested to cache the values (cached_locations array
7351 // initialized), then load the arguments the first time and store them
7352 // in locals. otherwise load from local variables.
7354 void LoadArrayAndArguments (EmitContext ec)
7356 ILGenerator ig = ec.ig;
7358 if (cached_locations == null){
7360 foreach (Argument a in ea.Arguments){
7361 Type argtype = a.Expr.Type;
7365 if (argtype == TypeManager.int64_type)
7366 ig.Emit (OpCodes.Conv_Ovf_I);
7367 else if (argtype == TypeManager.uint64_type)
7368 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7373 if (cached_locations [0] == null){
7374 cached_locations [0] = new LocalTemporary (ec, ea.Expr.Type);
7376 ig.Emit (OpCodes.Dup);
7377 cached_locations [0].Store (ec);
7381 foreach (Argument a in ea.Arguments){
7382 Type argtype = a.Expr.Type;
7384 cached_locations [j] = new LocalTemporary (ec, TypeManager.intptr_type /* a.Expr.Type */);
7386 if (argtype == TypeManager.int64_type)
7387 ig.Emit (OpCodes.Conv_Ovf_I);
7388 else if (argtype == TypeManager.uint64_type)
7389 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7391 ig.Emit (OpCodes.Dup);
7392 cached_locations [j].Store (ec);
7398 foreach (LocalTemporary lt in cached_locations)
7402 public new void CacheTemporaries (EmitContext ec)
7404 cached_locations = new LocalTemporary [ea.Arguments.Count + 1];
7407 public override void Emit (EmitContext ec)
7409 int rank = ea.Expr.Type.GetArrayRank ();
7410 ILGenerator ig = ec.ig;
7412 LoadArrayAndArguments (ec);
7415 EmitLoadOpcode (ig, type);
7419 method = FetchGetMethod ();
7420 ig.Emit (OpCodes.Call, method);
7424 public void EmitAssign (EmitContext ec, Expression source)
7426 int rank = ea.Expr.Type.GetArrayRank ();
7427 ILGenerator ig = ec.ig;
7428 Type t = source.Type;
7430 LoadArrayAndArguments (ec);
7433 // The stobj opcode used by value types will need
7434 // an address on the stack, not really an array/array
7438 if (t == TypeManager.enum_type || t == TypeManager.decimal_type ||
7439 (t.IsSubclassOf (TypeManager.value_type) && !TypeManager.IsEnumType (t) && !TypeManager.IsBuiltinType (t)))
7440 ig.Emit (OpCodes.Ldelema, t);
7446 EmitStoreOpcode (ig, t);
7448 ModuleBuilder mb = CodeGen.ModuleBuilder;
7449 int arg_count = ea.Arguments.Count;
7450 Type [] args = new Type [arg_count + 1];
7453 for (int i = 0; i < arg_count; i++){
7454 //args [i++] = a.Type;
7455 args [i] = TypeManager.int32_type;
7458 args [arg_count] = type;
7460 set = mb.GetArrayMethod (
7461 ea.Expr.Type, "Set",
7462 CallingConventions.HasThis |
7463 CallingConventions.Standard,
7464 TypeManager.void_type, args);
7466 ig.Emit (OpCodes.Call, set);
7470 public void AddressOf (EmitContext ec, AddressOp mode)
7472 int rank = ea.Expr.Type.GetArrayRank ();
7473 ILGenerator ig = ec.ig;
7475 LoadArrayAndArguments (ec);
7478 ig.Emit (OpCodes.Ldelema, type);
7480 MethodInfo address = FetchAddressMethod ();
7481 ig.Emit (OpCodes.Call, address);
7488 public ArrayList Properties;
7489 static Hashtable map;
7491 public struct Indexer {
7492 public readonly Type Type;
7493 public readonly MethodInfo Getter, Setter;
7495 public Indexer (Type type, MethodInfo get, MethodInfo set)
7505 map = new Hashtable ();
7510 Properties = new ArrayList ();
7513 void Append (MemberInfo [] mi)
7515 foreach (PropertyInfo property in mi){
7516 MethodInfo get, set;
7518 get = property.GetGetMethod (true);
7519 set = property.GetSetMethod (true);
7520 Properties.Add (new Indexer (property.PropertyType, get, set));
7524 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
7526 string p_name = TypeManager.IndexerPropertyName (lookup_type);
7528 MemberInfo [] mi = TypeManager.MemberLookup (
7529 caller_type, caller_type, lookup_type, MemberTypes.Property,
7530 BindingFlags.Public | BindingFlags.Instance |
7531 BindingFlags.DeclaredOnly, p_name);
7533 if (mi == null || mi.Length == 0)
7539 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
7541 Indexers ix = (Indexers) map [lookup_type];
7546 Type copy = lookup_type;
7547 while (copy != TypeManager.object_type && copy != null){
7548 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
7552 ix = new Indexers ();
7557 copy = copy.BaseType;
7560 if (!lookup_type.IsInterface)
7563 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
7564 if (ifaces != null) {
7565 foreach (Type itype in ifaces) {
7566 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
7569 ix = new Indexers ();
7581 /// Expressions that represent an indexer call.
7583 public class IndexerAccess : Expression, IAssignMethod {
7585 // Points to our "data" repository
7587 MethodInfo get, set;
7588 ArrayList set_arguments;
7589 bool is_base_indexer;
7591 protected Type indexer_type;
7592 protected Type current_type;
7593 protected Expression instance_expr;
7594 protected ArrayList arguments;
7596 public IndexerAccess (ElementAccess ea, Location loc)
7597 : this (ea.Expr, false, loc)
7599 this.arguments = ea.Arguments;
7602 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
7605 this.instance_expr = instance_expr;
7606 this.is_base_indexer = is_base_indexer;
7607 this.eclass = ExprClass.Value;
7611 protected virtual bool CommonResolve (EmitContext ec)
7613 indexer_type = instance_expr.Type;
7614 current_type = ec.ContainerType;
7619 public override Expression DoResolve (EmitContext ec)
7621 ArrayList AllGetters = new ArrayList();
7622 if (!CommonResolve (ec))
7626 // Step 1: Query for all `Item' *properties*. Notice
7627 // that the actual methods are pointed from here.
7629 // This is a group of properties, piles of them.
7631 bool found_any = false, found_any_getters = false;
7632 Type lookup_type = indexer_type;
7635 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
7636 if (ilist != null) {
7638 if (ilist.Properties != null) {
7639 foreach (Indexers.Indexer ix in ilist.Properties) {
7640 if (ix.Getter != null)
7641 AllGetters.Add(ix.Getter);
7646 if (AllGetters.Count > 0) {
7647 found_any_getters = true;
7648 get = (MethodInfo) Invocation.OverloadResolve (
7649 ec, new MethodGroupExpr (AllGetters, loc), arguments, loc);
7653 Report.Error (21, loc,
7654 "Type `" + TypeManager.CSharpName (indexer_type) +
7655 "' does not have any indexers defined");
7659 if (!found_any_getters) {
7660 Error (154, "indexer can not be used in this context, because " +
7661 "it lacks a `get' accessor");
7666 Error (1501, "No Overload for method `this' takes `" +
7667 arguments.Count + "' arguments");
7672 // Only base will allow this invocation to happen.
7674 if (get.IsAbstract && this is BaseIndexerAccess){
7675 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
7679 type = get.ReturnType;
7680 if (type.IsPointer && !ec.InUnsafe){
7685 eclass = ExprClass.IndexerAccess;
7689 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7691 ArrayList AllSetters = new ArrayList();
7692 if (!CommonResolve (ec))
7695 Type right_type = right_side.Type;
7697 bool found_any = false, found_any_setters = false;
7699 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
7700 if (ilist != null) {
7702 if (ilist.Properties != null) {
7703 foreach (Indexers.Indexer ix in ilist.Properties) {
7704 if (ix.Setter != null)
7705 AllSetters.Add(ix.Setter);
7709 if (AllSetters.Count > 0) {
7710 found_any_setters = true;
7711 set_arguments = (ArrayList) arguments.Clone ();
7712 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
7713 set = (MethodInfo) Invocation.OverloadResolve (
7714 ec, new MethodGroupExpr (AllSetters, loc),
7715 set_arguments, loc);
7719 Report.Error (21, loc,
7720 "Type `" + TypeManager.CSharpName (indexer_type) +
7721 "' does not have any indexers defined");
7725 if (!found_any_setters) {
7726 Error (154, "indexer can not be used in this context, because " +
7727 "it lacks a `set' accessor");
7732 Error (1501, "No Overload for method `this' takes `" +
7733 arguments.Count + "' arguments");
7738 // Only base will allow this invocation to happen.
7740 if (set.IsAbstract && this is BaseIndexerAccess){
7741 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
7746 // Now look for the actual match in the list of indexers to set our "return" type
7748 type = TypeManager.void_type; // default value
7749 foreach (Indexers.Indexer ix in ilist.Properties){
7750 if (ix.Setter == set){
7756 eclass = ExprClass.IndexerAccess;
7760 public override void Emit (EmitContext ec)
7762 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc);
7766 // source is ignored, because we already have a copy of it from the
7767 // LValue resolution and we have already constructed a pre-cached
7768 // version of the arguments (ea.set_arguments);
7770 public void EmitAssign (EmitContext ec, Expression source)
7772 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc);
7777 /// The base operator for method names
7779 public class BaseAccess : Expression {
7782 public BaseAccess (string member, Location l)
7784 this.member = member;
7788 public override Expression DoResolve (EmitContext ec)
7790 Expression c = CommonResolve (ec);
7796 // MethodGroups use this opportunity to flag an error on lacking ()
7798 if (!(c is MethodGroupExpr))
7799 return c.Resolve (ec);
7803 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7805 Expression c = CommonResolve (ec);
7811 // MethodGroups use this opportunity to flag an error on lacking ()
7813 if (! (c is MethodGroupExpr))
7814 return c.DoResolveLValue (ec, right_side);
7819 Expression CommonResolve (EmitContext ec)
7821 Expression member_lookup;
7822 Type current_type = ec.ContainerType;
7823 Type base_type = current_type.BaseType;
7827 Error (1511, "Keyword base is not allowed in static method");
7831 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type, member,
7832 AllMemberTypes, AllBindingFlags, loc);
7833 if (member_lookup == null) {
7834 MemberLookupFailed (ec, base_type, base_type, member, null, loc);
7841 left = new TypeExpr (base_type, loc);
7843 left = ec.GetThis (loc);
7845 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
7847 if (e is PropertyExpr){
7848 PropertyExpr pe = (PropertyExpr) e;
7856 public override void Emit (EmitContext ec)
7858 throw new Exception ("Should never be called");
7863 /// The base indexer operator
7865 public class BaseIndexerAccess : IndexerAccess {
7866 public BaseIndexerAccess (ArrayList args, Location loc)
7867 : base (null, true, loc)
7869 arguments = new ArrayList ();
7870 foreach (Expression tmp in args)
7871 arguments.Add (new Argument (tmp, Argument.AType.Expression));
7874 protected override bool CommonResolve (EmitContext ec)
7876 instance_expr = ec.GetThis (loc);
7878 current_type = ec.ContainerType.BaseType;
7879 indexer_type = current_type;
7881 foreach (Argument a in arguments){
7882 if (!a.Resolve (ec, loc))
7891 /// This class exists solely to pass the Type around and to be a dummy
7892 /// that can be passed to the conversion functions (this is used by
7893 /// foreach implementation to typecast the object return value from
7894 /// get_Current into the proper type. All code has been generated and
7895 /// we only care about the side effect conversions to be performed
7897 /// This is also now used as a placeholder where a no-action expression
7898 /// is needed (the `New' class).
7900 public class EmptyExpression : Expression {
7901 public EmptyExpression ()
7903 type = TypeManager.object_type;
7904 eclass = ExprClass.Value;
7905 loc = Location.Null;
7908 public EmptyExpression (Type t)
7911 eclass = ExprClass.Value;
7912 loc = Location.Null;
7915 public override Expression DoResolve (EmitContext ec)
7920 public override void Emit (EmitContext ec)
7922 // nothing, as we only exist to not do anything.
7926 // This is just because we might want to reuse this bad boy
7927 // instead of creating gazillions of EmptyExpressions.
7928 // (CanImplicitConversion uses it)
7930 public void SetType (Type t)
7936 public class UserCast : Expression {
7940 public UserCast (MethodInfo method, Expression source, Location l)
7942 this.method = method;
7943 this.source = source;
7944 type = method.ReturnType;
7945 eclass = ExprClass.Value;
7949 public override Expression DoResolve (EmitContext ec)
7952 // We are born fully resolved
7957 public override void Emit (EmitContext ec)
7959 ILGenerator ig = ec.ig;
7963 if (method is MethodInfo)
7964 ig.Emit (OpCodes.Call, (MethodInfo) method);
7966 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
7972 // This class is used to "construct" the type during a typecast
7973 // operation. Since the Type.GetType class in .NET can parse
7974 // the type specification, we just use this to construct the type
7975 // one bit at a time.
7977 public class ComposedCast : Expression {
7981 public ComposedCast (Expression left, string dim, Location l)
7988 public override Expression ResolveAsTypeStep (EmitContext ec)
7990 Type ltype = ec.DeclSpace.ResolveType (left, false, loc);
7995 // ltype.Fullname is already fully qualified, so we can skip
7996 // a lot of probes, and go directly to TypeManager.LookupType
7998 string cname = ltype.FullName + dim;
7999 type = TypeManager.LookupTypeDirect (cname);
8002 // For arrays of enumerations we are having a problem
8003 // with the direct lookup. Need to investigate.
8005 // For now, fall back to the full lookup in that case.
8007 type = RootContext.LookupType (
8008 ec.DeclSpace, cname, false, loc);
8014 if (!ec.ResolvingTypeTree){
8016 // If the above flag is set, this is being invoked from the ResolveType function.
8017 // Upper layers take care of the type validity in this context.
8019 if (!ec.InUnsafe && type.IsPointer){
8025 eclass = ExprClass.Type;
8029 public override Expression DoResolve (EmitContext ec)
8031 return ResolveAsTypeStep (ec);
8034 public override void Emit (EmitContext ec)
8036 throw new Exception ("This should never be called");
8039 public override string ToString ()
8046 // This class is used to represent the address of an array, used
8047 // only by the Fixed statement, this is like the C "&a [0]" construct.
8049 public class ArrayPtr : Expression {
8052 public ArrayPtr (Expression array, Location l)
8054 Type array_type = TypeManager.GetElementType (array.Type);
8058 type = TypeManager.GetPointerType (array_type);
8059 eclass = ExprClass.Value;
8063 public override void Emit (EmitContext ec)
8065 ILGenerator ig = ec.ig;
8068 IntLiteral.EmitInt (ig, 0);
8069 ig.Emit (OpCodes.Ldelema, TypeManager.GetElementType (array.Type));
8072 public override Expression DoResolve (EmitContext ec)
8075 // We are born fully resolved
8082 // Used by the fixed statement
8084 public class StringPtr : Expression {
8087 public StringPtr (LocalBuilder b, Location l)
8090 eclass = ExprClass.Value;
8091 type = TypeManager.char_ptr_type;
8095 public override Expression DoResolve (EmitContext ec)
8097 // This should never be invoked, we are born in fully
8098 // initialized state.
8103 public override void Emit (EmitContext ec)
8105 ILGenerator ig = ec.ig;
8107 ig.Emit (OpCodes.Ldloc, b);
8108 ig.Emit (OpCodes.Conv_I);
8109 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
8110 ig.Emit (OpCodes.Add);
8115 // Implements the `stackalloc' keyword
8117 public class StackAlloc : Expression {
8122 public StackAlloc (Expression type, Expression count, Location l)
8129 public override Expression DoResolve (EmitContext ec)
8131 count = count.Resolve (ec);
8135 if (count.Type != TypeManager.int32_type){
8136 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8141 if (ec.InCatch || ec.InFinally){
8143 "stackalloc can not be used in a catch or finally block");
8147 otype = ec.DeclSpace.ResolveType (t, false, loc);
8152 if (!TypeManager.VerifyUnManaged (otype, loc))
8155 type = TypeManager.GetPointerType (otype);
8156 eclass = ExprClass.Value;
8161 public override void Emit (EmitContext ec)
8163 int size = GetTypeSize (otype);
8164 ILGenerator ig = ec.ig;
8167 ig.Emit (OpCodes.Sizeof, otype);
8169 IntConstant.EmitInt (ig, size);
8171 ig.Emit (OpCodes.Mul);
8172 ig.Emit (OpCodes.Localloc);