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;
4584 // Now we actually find the best method
4586 foreach (MethodBase candidate in candidates) {
4587 bool cand_params = (bool) candidate_to_form [candidate];
4588 bool method_params = false;
4591 method_params = (bool) candidate_to_form [method];
4593 int x = BetterFunction (ec, Arguments,
4594 candidate, cand_params,
4595 method, method_params,
4603 if (Arguments == null)
4606 argument_count = Arguments.Count;
4609 if (method == null) {
4611 // Okay so we have failed to find anything so we
4612 // return by providing info about the closest match
4614 for (int i = 0; i < me.Methods.Length; ++i) {
4616 MethodBase c = (MethodBase) me.Methods [i];
4617 ParameterData pd = GetParameterData (c);
4619 if (pd.Count != argument_count)
4622 VerifyArgumentsCompat (ec, Arguments, argument_count, c, false,
4627 if (!Location.IsNull (loc)) {
4628 string report_name = me.Name;
4629 if (report_name == ".ctor")
4630 report_name = me.DeclaringType.ToString ();
4632 Error_WrongNumArguments (loc, report_name, argument_count);
4639 // Now check that there are no ambiguities i.e the selected method
4640 // should be better than all the others
4642 bool best_params = (bool) candidate_to_form [method];
4644 foreach (MethodBase candidate in candidates){
4646 if (candidate == method)
4650 // If a normal method is applicable in
4651 // the sense that it has the same
4652 // number of arguments, then the
4653 // expanded params method is never
4654 // applicable so we debar the params
4657 if ((IsParamsMethodApplicable (ec, Arguments, candidate) &&
4658 IsApplicable (ec, Arguments, method)))
4661 bool cand_params = (bool) candidate_to_form [candidate];
4662 int x = BetterFunction (ec, Arguments,
4663 method, best_params,
4664 candidate, cand_params,
4670 "Ambiguous call when selecting function due to implicit casts");
4676 // And now check if the arguments are all
4677 // compatible, perform conversions if
4678 // necessary etc. and return if everything is
4681 if (!VerifyArgumentsCompat (ec, Arguments, argument_count, method,
4682 best_params, null, loc))
4688 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
4690 Report.Error (1501, loc,
4691 "No overload for method `" + name + "' takes `" +
4692 arg_count + "' arguments");
4695 static void Error_InvokeOnDelegate (Location loc)
4697 Report.Error (1533, loc,
4698 "Invoke cannot be called directly on a delegate");
4701 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
4702 Type delegate_type, string arg_sig, string par_desc)
4704 if (delegate_type == null)
4705 Report.Error (1502, loc,
4706 "The best overloaded match for method '" +
4707 FullMethodDesc (method) +
4708 "' has some invalid arguments");
4710 Report.Error (1594, loc,
4711 "Delegate '" + delegate_type.ToString () +
4712 "' has some invalid arguments.");
4713 Report.Error (1503, loc,
4714 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
4715 idx, arg_sig, par_desc));
4718 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
4721 bool chose_params_expanded,
4725 ParameterData pd = GetParameterData (method);
4726 int pd_count = pd.Count;
4728 for (int j = 0; j < argument_count; j++) {
4729 Argument a = (Argument) Arguments [j];
4730 Expression a_expr = a.Expr;
4731 Type parameter_type = pd.ParameterType (j);
4732 Parameter.Modifier pm = pd.ParameterModifier (j);
4734 if (pm == Parameter.Modifier.PARAMS){
4735 Parameter.Modifier am = a.GetParameterModifier ();
4737 if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
4738 if (!Location.IsNull (loc))
4739 Error_InvalidArguments (
4740 loc, j, method, delegate_type,
4741 Argument.FullDesc (a), pd.ParameterDesc (j));
4745 if (chose_params_expanded)
4746 parameter_type = TypeManager.GetElementType (parameter_type);
4751 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
4752 if (!Location.IsNull (loc))
4753 Error_InvalidArguments (
4754 loc, j, method, delegate_type,
4755 Argument.FullDesc (a), pd.ParameterDesc (j));
4763 if (a.Type != parameter_type){
4766 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
4769 Console.WriteLine ("GAA: {0} {1} {2}",
4770 pd.ParameterType (j),
4771 pd.ParameterType (j).Assembly == CodeGen.AssemblyBuilder,
4772 method.DeclaringType.Assembly == CodeGen.AssemblyBuilder);
4774 if (!Location.IsNull (loc))
4775 Error_InvalidArguments (
4776 loc, j, method, delegate_type,
4777 Argument.FullDesc (a), pd.ParameterDesc (j));
4782 // Update the argument with the implicit conversion
4788 Parameter.Modifier a_mod = a.GetParameterModifier () &
4789 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4790 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
4791 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4793 if (a_mod != p_mod &&
4794 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
4795 if (!Location.IsNull (loc)) {
4796 Report.Error (1502, loc,
4797 "The best overloaded match for method '" + FullMethodDesc (method)+
4798 "' has some invalid arguments");
4799 Report.Error (1503, loc,
4800 "Argument " + (j+1) +
4801 ": Cannot convert from '" + Argument.FullDesc (a)
4802 + "' to '" + pd.ParameterDesc (j) + "'");
4812 public override Expression DoResolve (EmitContext ec)
4815 // First, resolve the expression that is used to
4816 // trigger the invocation
4818 if (expr is BaseAccess)
4821 Expression old = expr;
4823 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4827 if (!(expr is MethodGroupExpr)) {
4828 Type expr_type = expr.Type;
4830 if (expr_type != null){
4831 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
4833 return (new DelegateInvocation (
4834 this.expr, Arguments, loc)).Resolve (ec);
4838 if (!(expr is MethodGroupExpr)){
4839 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup);
4844 // Next, evaluate all the expressions in the argument list
4846 if (Arguments != null){
4847 foreach (Argument a in Arguments){
4848 if (!a.Resolve (ec, loc))
4853 MethodGroupExpr mg = (MethodGroupExpr) expr;
4854 method = OverloadResolve (ec, mg, Arguments, loc);
4856 if (method == null){
4858 "Could not find any applicable function for this argument list");
4862 MethodInfo mi = method as MethodInfo;
4864 type = TypeManager.TypeToCoreType (mi.ReturnType);
4865 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null))
4866 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
4869 if (type.IsPointer){
4877 // Only base will allow this invocation to happen.
4879 if (is_base && method.IsAbstract){
4880 Report.Error (205, loc, "Cannot call an abstract base member: " +
4881 FullMethodDesc (method));
4885 if ((method.Attributes & MethodAttributes.SpecialName) != 0){
4886 if (TypeManager.IsSpecialMethod (method))
4887 Report.Error (571, loc, method.Name + ": can not call operator or accessor");
4890 eclass = ExprClass.Value;
4895 // Emits the list of arguments as an array
4897 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
4899 ILGenerator ig = ec.ig;
4900 int count = arguments.Count - idx;
4901 Argument a = (Argument) arguments [idx];
4902 Type t = a.Expr.Type;
4903 string array_type = t.FullName + "[]";
4906 array = ig.DeclareLocal (TypeManager.LookupType (array_type));
4907 IntConstant.EmitInt (ig, count);
4908 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
4909 ig.Emit (OpCodes.Stloc, array);
4911 int top = arguments.Count;
4912 for (int j = idx; j < top; j++){
4913 a = (Argument) arguments [j];
4915 ig.Emit (OpCodes.Ldloc, array);
4916 IntConstant.EmitInt (ig, j - idx);
4919 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj);
4921 ig.Emit (OpCodes.Ldelema, t);
4926 ig.Emit (OpCodes.Stobj, t);
4930 ig.Emit (OpCodes.Ldloc, array);
4934 /// Emits a list of resolved Arguments that are in the arguments
4937 /// The MethodBase argument might be null if the
4938 /// emission of the arguments is known not to contain
4939 /// a `params' field (for example in constructors or other routines
4940 /// that keep their arguments in this structure)
4942 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
4946 pd = GetParameterData (mb);
4951 // If we are calling a params method with no arguments, special case it
4953 if (arguments == null){
4954 if (pd != null && pd.Count > 0 &&
4955 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
4956 ILGenerator ig = ec.ig;
4958 IntConstant.EmitInt (ig, 0);
4959 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
4965 int top = arguments.Count;
4967 for (int i = 0; i < top; i++){
4968 Argument a = (Argument) arguments [i];
4971 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
4973 // Special case if we are passing the same data as the
4974 // params argument, do not put it in an array.
4976 if (pd.ParameterType (i) == a.Type)
4979 EmitParams (ec, i, arguments);
4987 if (pd != null && pd.Count > top &&
4988 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
4989 ILGenerator ig = ec.ig;
4991 IntConstant.EmitInt (ig, 0);
4992 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
4997 /// is_base tells whether we want to force the use of the `call'
4998 /// opcode instead of using callvirt. Call is required to call
4999 /// a specific method, while callvirt will always use the most
5000 /// recent method in the vtable.
5002 /// is_static tells whether this is an invocation on a static method
5004 /// instance_expr is an expression that represents the instance
5005 /// it must be non-null if is_static is false.
5007 /// method is the method to invoke.
5009 /// Arguments is the list of arguments to pass to the method or constructor.
5011 public static void EmitCall (EmitContext ec, bool is_base,
5012 bool is_static, Expression instance_expr,
5013 MethodBase method, ArrayList Arguments, Location loc)
5015 ILGenerator ig = ec.ig;
5016 bool struct_call = false;
5018 Type decl_type = method.DeclaringType;
5020 if (!RootContext.StdLib) {
5021 // Replace any calls to the system's System.Array type with calls to
5022 // the newly created one.
5023 if (method == TypeManager.system_int_array_get_length)
5024 method = TypeManager.int_array_get_length;
5025 else if (method == TypeManager.system_int_array_get_rank)
5026 method = TypeManager.int_array_get_rank;
5027 else if (method == TypeManager.system_object_array_clone)
5028 method = TypeManager.object_array_clone;
5029 else if (method == TypeManager.system_int_array_get_length_int)
5030 method = TypeManager.int_array_get_length_int;
5031 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5032 method = TypeManager.int_array_get_lower_bound_int;
5033 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5034 method = TypeManager.int_array_get_upper_bound_int;
5035 else if (method == TypeManager.system_void_array_copyto_array_int)
5036 method = TypeManager.void_array_copyto_array_int;
5040 // This checks the `ConditionalAttribute' on the method, and the
5041 // ObsoleteAttribute
5043 TypeManager.MethodFlags flags = TypeManager.GetMethodFlags (method, loc);
5044 if ((flags & TypeManager.MethodFlags.IsObsoleteError) != 0)
5046 if ((flags & TypeManager.MethodFlags.ShouldIgnore) != 0)
5050 if (decl_type.IsValueType)
5053 // If this is ourselves, push "this"
5055 if (instance_expr == null){
5056 ig.Emit (OpCodes.Ldarg_0);
5059 // Push the instance expression
5061 if (instance_expr.Type.IsValueType){
5063 // Special case: calls to a function declared in a
5064 // reference-type with a value-type argument need
5065 // to have their value boxed.
5068 if (decl_type.IsValueType){
5070 // If the expression implements IMemoryLocation, then
5071 // we can optimize and use AddressOf on the
5074 // If not we have to use some temporary storage for
5076 if (instance_expr is IMemoryLocation){
5077 ((IMemoryLocation)instance_expr).
5078 AddressOf (ec, AddressOp.LoadStore);
5081 Type t = instance_expr.Type;
5083 instance_expr.Emit (ec);
5084 LocalBuilder temp = ig.DeclareLocal (t);
5085 ig.Emit (OpCodes.Stloc, temp);
5086 ig.Emit (OpCodes.Ldloca, temp);
5089 instance_expr.Emit (ec);
5090 ig.Emit (OpCodes.Box, instance_expr.Type);
5093 instance_expr.Emit (ec);
5097 EmitArguments (ec, method, Arguments);
5099 if (is_static || struct_call || is_base){
5100 if (method is MethodInfo) {
5101 ig.Emit (OpCodes.Call, (MethodInfo) method);
5103 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5105 if (method is MethodInfo)
5106 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
5108 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
5112 public override void Emit (EmitContext ec)
5114 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5116 EmitCall (ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5119 public override void EmitStatement (EmitContext ec)
5124 // Pop the return value if there is one
5126 if (method is MethodInfo){
5127 Type ret = ((MethodInfo)method).ReturnType;
5128 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5129 ec.ig.Emit (OpCodes.Pop);
5134 public class InvocationOrCast : ExpressionStatement
5137 Expression argument;
5139 public InvocationOrCast (Expression expr, Expression argument, Location loc)
5142 this.argument = argument;
5146 public override Expression DoResolve (EmitContext ec)
5149 // First try to resolve it as a cast.
5151 type = ec.DeclSpace.ResolveType (expr, true, loc);
5153 Cast cast = new Cast (new TypeExpr (type, loc), argument, loc);
5154 return cast.Resolve (ec);
5158 // This can either be a type or a delegate invocation.
5159 // Let's just resolve it and see what we'll get.
5161 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5166 // Ok, so it's a Cast.
5168 if (expr.eclass == ExprClass.Type) {
5169 Cast cast = new Cast (new TypeExpr (expr.Type, loc), argument, loc);
5170 return cast.Resolve (ec);
5174 // It's a delegate invocation.
5176 if (!TypeManager.IsDelegateType (expr.Type)) {
5177 Error (149, "Method name expected");
5181 ArrayList args = new ArrayList ();
5182 args.Add (new Argument (argument, Argument.AType.Expression));
5183 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5184 return invocation.Resolve (ec);
5189 Error (201, "Only assignment, call, increment, decrement and new object " +
5190 "expressions can be used as a statement");
5193 public override ExpressionStatement ResolveStatement (EmitContext ec)
5196 // First try to resolve it as a cast.
5198 type = ec.DeclSpace.ResolveType (expr, true, loc);
5205 // This can either be a type or a delegate invocation.
5206 // Let's just resolve it and see what we'll get.
5208 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5209 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5215 // It's a delegate invocation.
5217 if (!TypeManager.IsDelegateType (expr.Type)) {
5218 Error (149, "Method name expected");
5222 ArrayList args = new ArrayList ();
5223 args.Add (new Argument (argument, Argument.AType.Expression));
5224 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5225 return invocation.ResolveStatement (ec);
5228 public override void Emit (EmitContext ec)
5230 throw new Exception ("Cannot happen");
5233 public override void EmitStatement (EmitContext ec)
5235 throw new Exception ("Cannot happen");
5240 // This class is used to "disable" the code generation for the
5241 // temporary variable when initializing value types.
5243 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5244 public void AddressOf (EmitContext ec, AddressOp Mode)
5251 /// Implements the new expression
5253 public class New : ExpressionStatement, IMemoryLocation {
5254 public readonly ArrayList Arguments;
5255 public readonly Expression RequestedType;
5257 MethodBase method = null;
5260 // If set, the new expression is for a value_target, and
5261 // we will not leave anything on the stack.
5263 Expression value_target;
5264 bool value_target_set = false;
5266 public New (Expression requested_type, ArrayList arguments, Location l)
5268 RequestedType = requested_type;
5269 Arguments = arguments;
5273 public bool SetValueTypeVariable (Expression value)
5275 value_target = value;
5276 value_target_set = true;
5277 if (!(value_target is IMemoryLocation)){
5278 Error_UnexpectedKind ("variable");
5285 // This function is used to disable the following code sequence for
5286 // value type initialization:
5288 // AddressOf (temporary)
5292 // Instead the provide will have provided us with the address on the
5293 // stack to store the results.
5295 static Expression MyEmptyExpression;
5297 public void DisableTemporaryValueType ()
5299 if (MyEmptyExpression == null)
5300 MyEmptyExpression = new EmptyAddressOf ();
5303 // To enable this, look into:
5304 // test-34 and test-89 and self bootstrapping.
5306 // For instance, we can avoid a copy by using `newobj'
5307 // instead of Call + Push-temp on value types.
5308 // value_target = MyEmptyExpression;
5311 public override Expression DoResolve (EmitContext ec)
5314 // The New DoResolve might be called twice when initializing field
5315 // expressions (see EmitFieldInitializers, the call to
5316 // GetInitializerExpression will perform a resolve on the expression,
5317 // and later the assign will trigger another resolution
5319 // This leads to bugs (#37014)
5324 type = ec.DeclSpace.ResolveType (RequestedType, false, loc);
5329 bool IsDelegate = TypeManager.IsDelegateType (type);
5332 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5334 if (type.IsInterface || type.IsAbstract){
5335 Error (144, "It is not possible to create instances of interfaces or abstract classes");
5339 bool is_struct = type.IsValueType;
5340 eclass = ExprClass.Value;
5343 // SRE returns a match for .ctor () on structs (the object constructor),
5344 // so we have to manually ignore it.
5346 if (is_struct && Arguments == null)
5350 ml = MemberLookupFinal (ec, null, type, ".ctor",
5351 MemberTypes.Constructor,
5352 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5357 if (! (ml is MethodGroupExpr)){
5359 ml.Error_UnexpectedKind ("method group");
5365 if (Arguments != null){
5366 foreach (Argument a in Arguments){
5367 if (!a.Resolve (ec, loc))
5372 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
5376 if (method == null) {
5377 if (!is_struct || Arguments.Count > 0) {
5378 Error (1501, String.Format (
5379 "New invocation: Can not find a constructor in `{0}' for this argument list",
5380 TypeManager.CSharpName (type)));
5389 // This DoEmit can be invoked in two contexts:
5390 // * As a mechanism that will leave a value on the stack (new object)
5391 // * As one that wont (init struct)
5393 // You can control whether a value is required on the stack by passing
5394 // need_value_on_stack. The code *might* leave a value on the stack
5395 // so it must be popped manually
5397 // If we are dealing with a ValueType, we have a few
5398 // situations to deal with:
5400 // * The target is a ValueType, and we have been provided
5401 // the instance (this is easy, we are being assigned).
5403 // * The target of New is being passed as an argument,
5404 // to a boxing operation or a function that takes a
5407 // In this case, we need to create a temporary variable
5408 // that is the argument of New.
5410 // Returns whether a value is left on the stack
5412 bool DoEmit (EmitContext ec, bool need_value_on_stack)
5414 bool is_value_type = type.IsValueType;
5415 ILGenerator ig = ec.ig;
5420 // Allow DoEmit() to be called multiple times.
5421 // We need to create a new LocalTemporary each time since
5422 // you can't share LocalBuilders among ILGeneators.
5423 if (!value_target_set)
5424 value_target = new LocalTemporary (ec, type);
5426 ml = (IMemoryLocation) value_target;
5427 ml.AddressOf (ec, AddressOp.Store);
5431 Invocation.EmitArguments (ec, method, Arguments);
5435 ig.Emit (OpCodes.Initobj, type);
5437 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5438 if (need_value_on_stack){
5439 value_target.Emit (ec);
5444 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
5449 public override void Emit (EmitContext ec)
5454 public override void EmitStatement (EmitContext ec)
5456 if (DoEmit (ec, false))
5457 ec.ig.Emit (OpCodes.Pop);
5460 public void AddressOf (EmitContext ec, AddressOp Mode)
5462 if (!type.IsValueType){
5464 // We throw an exception. So far, I believe we only need to support
5466 // foreach (int j in new StructType ())
5469 throw new Exception ("AddressOf should not be used for classes");
5472 if (!value_target_set)
5473 value_target = new LocalTemporary (ec, type);
5475 IMemoryLocation ml = (IMemoryLocation) value_target;
5476 ml.AddressOf (ec, AddressOp.Store);
5478 Invocation.EmitArguments (ec, method, Arguments);
5481 ec.ig.Emit (OpCodes.Initobj, type);
5483 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5485 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
5490 /// 14.5.10.2: Represents an array creation expression.
5494 /// There are two possible scenarios here: one is an array creation
5495 /// expression that specifies the dimensions and optionally the
5496 /// initialization data and the other which does not need dimensions
5497 /// specified but where initialization data is mandatory.
5499 public class ArrayCreation : ExpressionStatement {
5500 Expression requested_base_type;
5501 ArrayList initializers;
5504 // The list of Argument types.
5505 // This is used to construct the `newarray' or constructor signature
5507 ArrayList arguments;
5510 // Method used to create the array object.
5512 MethodBase new_method = null;
5514 Type array_element_type;
5515 Type underlying_type;
5516 bool is_one_dimensional = false;
5517 bool is_builtin_type = false;
5518 bool expect_initializers = false;
5519 int num_arguments = 0;
5523 ArrayList array_data;
5528 // The number of array initializers that we can handle
5529 // via the InitializeArray method - through EmitStaticInitializers
5531 int num_automatic_initializers;
5533 const int max_automatic_initializers = 6;
5535 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
5537 this.requested_base_type = requested_base_type;
5538 this.initializers = initializers;
5542 arguments = new ArrayList ();
5544 foreach (Expression e in exprs) {
5545 arguments.Add (new Argument (e, Argument.AType.Expression));
5550 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
5552 this.requested_base_type = requested_base_type;
5553 this.initializers = initializers;
5557 //this.rank = rank.Substring (0, rank.LastIndexOf ("["));
5559 //string tmp = rank.Substring (rank.LastIndexOf ("["));
5561 //dimensions = tmp.Length - 1;
5562 expect_initializers = true;
5565 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
5567 StringBuilder sb = new StringBuilder (rank);
5570 for (int i = 1; i < idx_count; i++)
5575 return new ComposedCast (base_type, sb.ToString (), loc);
5578 void Error_IncorrectArrayInitializer ()
5580 Error (178, "Incorrectly structured array initializer");
5583 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
5585 if (specified_dims) {
5586 Argument a = (Argument) arguments [idx];
5588 if (!a.Resolve (ec, loc))
5591 if (!(a.Expr is Constant)) {
5592 Error (150, "A constant value is expected");
5596 int value = (int) ((Constant) a.Expr).GetValue ();
5598 if (value != probe.Count) {
5599 Error_IncorrectArrayInitializer ();
5603 bounds [idx] = value;
5606 int child_bounds = -1;
5607 foreach (object o in probe) {
5608 if (o is ArrayList) {
5609 int current_bounds = ((ArrayList) o).Count;
5611 if (child_bounds == -1)
5612 child_bounds = current_bounds;
5614 else if (child_bounds != current_bounds){
5615 Error_IncorrectArrayInitializer ();
5618 if (specified_dims && (idx + 1 >= arguments.Count)){
5619 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
5623 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
5627 if (child_bounds != -1){
5628 Error_IncorrectArrayInitializer ();
5632 Expression tmp = (Expression) o;
5633 tmp = tmp.Resolve (ec);
5637 // Console.WriteLine ("I got: " + tmp);
5638 // Handle initialization from vars, fields etc.
5640 Expression conv = Convert.ImplicitConversionRequired (
5641 ec, tmp, underlying_type, loc);
5646 if (conv is StringConstant)
5647 array_data.Add (conv);
5648 else if (conv is Constant) {
5649 array_data.Add (conv);
5650 num_automatic_initializers++;
5652 array_data.Add (conv);
5659 public void UpdateIndices (EmitContext ec)
5662 for (ArrayList probe = initializers; probe != null;) {
5663 if (probe.Count > 0 && probe [0] is ArrayList) {
5664 Expression e = new IntConstant (probe.Count);
5665 arguments.Add (new Argument (e, Argument.AType.Expression));
5667 bounds [i++] = probe.Count;
5669 probe = (ArrayList) probe [0];
5672 Expression e = new IntConstant (probe.Count);
5673 arguments.Add (new Argument (e, Argument.AType.Expression));
5675 bounds [i++] = probe.Count;
5682 public bool ValidateInitializers (EmitContext ec, Type array_type)
5684 if (initializers == null) {
5685 if (expect_initializers)
5691 if (underlying_type == null)
5695 // We use this to store all the date values in the order in which we
5696 // will need to store them in the byte blob later
5698 array_data = new ArrayList ();
5699 bounds = new Hashtable ();
5703 if (arguments != null) {
5704 ret = CheckIndices (ec, initializers, 0, true);
5707 arguments = new ArrayList ();
5709 ret = CheckIndices (ec, initializers, 0, false);
5716 if (arguments.Count != dimensions) {
5717 Error_IncorrectArrayInitializer ();
5725 void Error_NegativeArrayIndex ()
5727 Error (284, "Can not create array with a negative size");
5731 // Converts `source' to an int, uint, long or ulong.
5733 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
5737 bool old_checked = ec.CheckState;
5738 ec.CheckState = true;
5740 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
5741 if (target == null){
5742 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
5743 if (target == null){
5744 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
5745 if (target == null){
5746 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
5748 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
5752 ec.CheckState = old_checked;
5755 // Only positive constants are allowed at compile time
5757 if (target is Constant){
5758 if (target is IntConstant){
5759 if (((IntConstant) target).Value < 0){
5760 Error_NegativeArrayIndex ();
5765 if (target is LongConstant){
5766 if (((LongConstant) target).Value < 0){
5767 Error_NegativeArrayIndex ();
5778 // Creates the type of the array
5780 bool LookupType (EmitContext ec)
5782 StringBuilder array_qualifier = new StringBuilder (rank);
5785 // `In the first form allocates an array instace of the type that results
5786 // from deleting each of the individual expression from the expression list'
5788 if (num_arguments > 0) {
5789 array_qualifier.Append ("[");
5790 for (int i = num_arguments-1; i > 0; i--)
5791 array_qualifier.Append (",");
5792 array_qualifier.Append ("]");
5798 Expression array_type_expr;
5799 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
5800 type = ec.DeclSpace.ResolveType (array_type_expr, false, loc);
5805 underlying_type = type;
5806 if (underlying_type.IsArray)
5807 underlying_type = TypeManager.GetElementType (underlying_type);
5808 dimensions = type.GetArrayRank ();
5813 public override Expression DoResolve (EmitContext ec)
5817 if (!LookupType (ec))
5821 // First step is to validate the initializers and fill
5822 // in any missing bits
5824 if (!ValidateInitializers (ec, type))
5827 if (arguments == null)
5830 arg_count = arguments.Count;
5831 foreach (Argument a in arguments){
5832 if (!a.Resolve (ec, loc))
5835 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
5836 if (real_arg == null)
5843 array_element_type = TypeManager.GetElementType (type);
5845 if (arg_count == 1) {
5846 is_one_dimensional = true;
5847 eclass = ExprClass.Value;
5851 is_builtin_type = TypeManager.IsBuiltinType (type);
5853 if (is_builtin_type) {
5856 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
5857 AllBindingFlags, loc);
5859 if (!(ml is MethodGroupExpr)) {
5860 ml.Error_UnexpectedKind ("method group");
5865 Error (-6, "New invocation: Can not find a constructor for " +
5866 "this argument list");
5870 new_method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, arguments, loc);
5872 if (new_method == null) {
5873 Error (-6, "New invocation: Can not find a constructor for " +
5874 "this argument list");
5878 eclass = ExprClass.Value;
5881 ModuleBuilder mb = CodeGen.ModuleBuilder;
5882 ArrayList args = new ArrayList ();
5884 if (arguments != null) {
5885 for (int i = 0; i < arg_count; i++)
5886 args.Add (TypeManager.int32_type);
5889 Type [] arg_types = null;
5892 arg_types = new Type [args.Count];
5894 args.CopyTo (arg_types, 0);
5896 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
5899 if (new_method == null) {
5900 Error (-6, "New invocation: Can not find a constructor for " +
5901 "this argument list");
5905 eclass = ExprClass.Value;
5910 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
5915 int count = array_data.Count;
5917 if (underlying_type.IsEnum)
5918 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
5920 factor = GetTypeSize (underlying_type);
5922 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
5924 data = new byte [(count * factor + 4) & ~3];
5927 for (int i = 0; i < count; ++i) {
5928 object v = array_data [i];
5930 if (v is EnumConstant)
5931 v = ((EnumConstant) v).Child;
5933 if (v is Constant && !(v is StringConstant))
5934 v = ((Constant) v).GetValue ();
5940 if (underlying_type == TypeManager.int64_type){
5941 if (!(v is Expression)){
5942 long val = (long) v;
5944 for (int j = 0; j < factor; ++j) {
5945 data [idx + j] = (byte) (val & 0xFF);
5949 } else if (underlying_type == TypeManager.uint64_type){
5950 if (!(v is Expression)){
5951 ulong val = (ulong) v;
5953 for (int j = 0; j < factor; ++j) {
5954 data [idx + j] = (byte) (val & 0xFF);
5958 } else if (underlying_type == TypeManager.float_type) {
5959 if (!(v is Expression)){
5960 element = BitConverter.GetBytes ((float) v);
5962 for (int j = 0; j < factor; ++j)
5963 data [idx + j] = element [j];
5965 } else if (underlying_type == TypeManager.double_type) {
5966 if (!(v is Expression)){
5967 element = BitConverter.GetBytes ((double) v);
5969 for (int j = 0; j < factor; ++j)
5970 data [idx + j] = element [j];
5972 } else if (underlying_type == TypeManager.char_type){
5973 if (!(v is Expression)){
5974 int val = (int) ((char) v);
5976 data [idx] = (byte) (val & 0xff);
5977 data [idx+1] = (byte) (val >> 8);
5979 } else if (underlying_type == TypeManager.short_type){
5980 if (!(v is Expression)){
5981 int val = (int) ((short) v);
5983 data [idx] = (byte) (val & 0xff);
5984 data [idx+1] = (byte) (val >> 8);
5986 } else if (underlying_type == TypeManager.ushort_type){
5987 if (!(v is Expression)){
5988 int val = (int) ((ushort) v);
5990 data [idx] = (byte) (val & 0xff);
5991 data [idx+1] = (byte) (val >> 8);
5993 } else if (underlying_type == TypeManager.int32_type) {
5994 if (!(v is Expression)){
5997 data [idx] = (byte) (val & 0xff);
5998 data [idx+1] = (byte) ((val >> 8) & 0xff);
5999 data [idx+2] = (byte) ((val >> 16) & 0xff);
6000 data [idx+3] = (byte) (val >> 24);
6002 } else if (underlying_type == TypeManager.uint32_type) {
6003 if (!(v is Expression)){
6004 uint val = (uint) v;
6006 data [idx] = (byte) (val & 0xff);
6007 data [idx+1] = (byte) ((val >> 8) & 0xff);
6008 data [idx+2] = (byte) ((val >> 16) & 0xff);
6009 data [idx+3] = (byte) (val >> 24);
6011 } else if (underlying_type == TypeManager.sbyte_type) {
6012 if (!(v is Expression)){
6013 sbyte val = (sbyte) v;
6014 data [idx] = (byte) val;
6016 } else if (underlying_type == TypeManager.byte_type) {
6017 if (!(v is Expression)){
6018 byte val = (byte) v;
6019 data [idx] = (byte) val;
6021 } else if (underlying_type == TypeManager.bool_type) {
6022 if (!(v is Expression)){
6023 bool val = (bool) v;
6024 data [idx] = (byte) (val ? 1 : 0);
6026 } else if (underlying_type == TypeManager.decimal_type){
6027 if (!(v is Expression)){
6028 int [] bits = Decimal.GetBits ((decimal) v);
6031 // FIXME: For some reason, this doesn't work on the MS runtime.
6032 int [] nbits = new int [4];
6033 nbits [0] = bits [3];
6034 nbits [1] = bits [2];
6035 nbits [2] = bits [0];
6036 nbits [3] = bits [1];
6038 for (int j = 0; j < 4; j++){
6039 data [p++] = (byte) (nbits [j] & 0xff);
6040 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6041 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6042 data [p++] = (byte) (nbits [j] >> 24);
6046 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6055 // Emits the initializers for the array
6057 void EmitStaticInitializers (EmitContext ec, bool is_expression)
6060 // First, the static data
6063 ILGenerator ig = ec.ig;
6065 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6067 fb = RootContext.MakeStaticData (data);
6070 ig.Emit (OpCodes.Dup);
6071 ig.Emit (OpCodes.Ldtoken, fb);
6072 ig.Emit (OpCodes.Call,
6073 TypeManager.void_initializearray_array_fieldhandle);
6077 // Emits pieces of the array that can not be computed at compile
6078 // time (variables and string locations).
6080 // This always expect the top value on the stack to be the array
6082 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
6084 ILGenerator ig = ec.ig;
6085 int dims = bounds.Count;
6086 int [] current_pos = new int [dims];
6087 int top = array_data.Count;
6088 LocalBuilder temp = ig.DeclareLocal (type);
6090 ig.Emit (OpCodes.Stloc, temp);
6092 MethodInfo set = null;
6096 ModuleBuilder mb = null;
6097 mb = CodeGen.ModuleBuilder;
6098 args = new Type [dims + 1];
6101 for (j = 0; j < dims; j++)
6102 args [j] = TypeManager.int32_type;
6104 args [j] = array_element_type;
6106 set = mb.GetArrayMethod (
6108 CallingConventions.HasThis | CallingConventions.Standard,
6109 TypeManager.void_type, args);
6112 for (int i = 0; i < top; i++){
6114 Expression e = null;
6116 if (array_data [i] is Expression)
6117 e = (Expression) array_data [i];
6121 // Basically we do this for string literals and
6122 // other non-literal expressions
6124 if (e is EnumConstant){
6125 e = ((EnumConstant) e).Child;
6128 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6129 num_automatic_initializers <= max_automatic_initializers) {
6130 Type etype = e.Type;
6132 ig.Emit (OpCodes.Ldloc, temp);
6134 for (int idx = 0; idx < dims; idx++)
6135 IntConstant.EmitInt (ig, current_pos [idx]);
6138 // If we are dealing with a struct, get the
6139 // address of it, so we can store it.
6142 etype.IsSubclassOf (TypeManager.value_type) &&
6143 (!TypeManager.IsBuiltinOrEnum (etype) ||
6144 etype == TypeManager.decimal_type)) {
6149 // Let new know that we are providing
6150 // the address where to store the results
6152 n.DisableTemporaryValueType ();
6155 ig.Emit (OpCodes.Ldelema, etype);
6158 ig.Emit (OpCodes.Nop);
6160 ig.Emit (OpCodes.Nop);
6161 ig.Emit (OpCodes.Nop);
6164 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
6166 ig.Emit (OpCodes.Call, set);
6174 for (int j = dims - 1; j >= 0; j--){
6176 if (current_pos [j] < (int) bounds [j])
6178 current_pos [j] = 0;
6183 ig.Emit (OpCodes.Ldloc, temp);
6186 void EmitArrayArguments (EmitContext ec)
6188 ILGenerator ig = ec.ig;
6190 foreach (Argument a in arguments) {
6191 Type atype = a.Type;
6194 if (atype == TypeManager.uint64_type)
6195 ig.Emit (OpCodes.Conv_Ovf_U4);
6196 else if (atype == TypeManager.int64_type)
6197 ig.Emit (OpCodes.Conv_Ovf_I4);
6201 void DoEmit (EmitContext ec, bool is_statement)
6203 ILGenerator ig = ec.ig;
6205 EmitArrayArguments (ec);
6206 if (is_one_dimensional)
6207 ig.Emit (OpCodes.Newarr, array_element_type);
6209 if (is_builtin_type)
6210 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6212 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6215 if (initializers != null){
6217 // FIXME: Set this variable correctly.
6219 bool dynamic_initializers = true;
6221 if (underlying_type != TypeManager.string_type &&
6222 underlying_type != TypeManager.decimal_type &&
6223 underlying_type != TypeManager.object_type) {
6224 if (num_automatic_initializers > max_automatic_initializers)
6225 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
6228 if (dynamic_initializers)
6229 EmitDynamicInitializers (ec, !is_statement);
6233 public override void Emit (EmitContext ec)
6238 public override void EmitStatement (EmitContext ec)
6243 public object EncodeAsAttribute ()
6245 if (!is_one_dimensional){
6246 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6250 if (array_data == null){
6251 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6255 object [] ret = new object [array_data.Count];
6257 foreach (Expression e in array_data){
6260 if (e is NullLiteral)
6263 if (!Attribute.GetAttributeArgumentExpression (e, Location, out v))
6273 /// Represents the `this' construct
6275 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6278 VariableInfo variable_info;
6280 public This (Block block, Location loc)
6286 public This (Location loc)
6291 public VariableInfo VariableInfo {
6292 get { return variable_info; }
6295 public bool VerifyFixed (bool is_expression)
6297 if ((variable_info == null) || (variable_info.LocalInfo == null))
6300 return variable_info.LocalInfo.IsFixed;
6303 public bool ResolveBase (EmitContext ec)
6305 eclass = ExprClass.Variable;
6306 type = ec.ContainerType;
6309 Error (26, "Keyword this not valid in static code");
6313 if ((block != null) && (block.ThisVariable != null))
6314 variable_info = block.ThisVariable.VariableInfo;
6319 public override Expression DoResolve (EmitContext ec)
6321 if (!ResolveBase (ec))
6324 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
6325 Error (188, "The this object cannot be used before all " +
6326 "of its fields are assigned to");
6327 variable_info.SetAssigned (ec);
6331 if (ec.IsFieldInitializer) {
6332 Error (27, "Keyword `this' can't be used outside a constructor, " +
6333 "a method or a property.");
6340 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6342 if (!ResolveBase (ec))
6345 if (variable_info != null)
6346 variable_info.SetAssigned (ec);
6348 if (ec.TypeContainer is Class){
6349 Error (1604, "Cannot assign to `this'");
6356 public override void Emit (EmitContext ec)
6358 ILGenerator ig = ec.ig;
6360 ig.Emit (OpCodes.Ldarg_0);
6361 if (ec.TypeContainer is Struct)
6362 ig.Emit (OpCodes.Ldobj, type);
6365 public void EmitAssign (EmitContext ec, Expression source)
6367 ILGenerator ig = ec.ig;
6369 if (ec.TypeContainer is Struct){
6370 ig.Emit (OpCodes.Ldarg_0);
6372 ig.Emit (OpCodes.Stobj, type);
6375 ig.Emit (OpCodes.Starg, 0);
6379 public void AddressOf (EmitContext ec, AddressOp mode)
6381 ec.ig.Emit (OpCodes.Ldarg_0);
6384 // FIGURE OUT WHY LDARG_S does not work
6386 // consider: struct X { int val; int P { set { val = value; }}}
6388 // Yes, this looks very bad. Look at `NOTAS' for
6390 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
6395 // This produces the value that renders an instance, used by the iterators code
6397 public class ProxyInstance : Expression, IMemoryLocation {
6398 public override Expression DoResolve (EmitContext ec)
6400 eclass = ExprClass.Variable;
6401 type = ec.ContainerType;
6405 public override void Emit (EmitContext ec)
6407 ec.ig.Emit (OpCodes.Ldarg_0);
6411 public void AddressOf (EmitContext ec, AddressOp mode)
6413 ec.ig.Emit (OpCodes.Ldarg_0);
6418 /// Implements the typeof operator
6420 public class TypeOf : Expression {
6421 public readonly Expression QueriedType;
6424 public TypeOf (Expression queried_type, Location l)
6426 QueriedType = queried_type;
6430 public override Expression DoResolve (EmitContext ec)
6432 typearg = ec.DeclSpace.ResolveType (QueriedType, false, loc);
6434 if (typearg == null)
6437 if (typearg == TypeManager.void_type) {
6438 Error (673, "System.Void cannot be used from C# - " +
6439 "use typeof (void) to get the void type object");
6443 type = TypeManager.type_type;
6444 eclass = ExprClass.Type;
6448 public override void Emit (EmitContext ec)
6450 ec.ig.Emit (OpCodes.Ldtoken, typearg);
6451 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6454 public Type TypeArg {
6455 get { return typearg; }
6460 /// Implements the `typeof (void)' operator
6462 public class TypeOfVoid : Expression {
6463 public TypeOfVoid (Location l)
6468 public override Expression DoResolve (EmitContext ec)
6470 type = TypeManager.type_type;
6471 eclass = ExprClass.Type;
6475 public override void Emit (EmitContext ec)
6477 ec.ig.Emit (OpCodes.Ldtoken, TypeManager.void_type);
6478 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6481 public Type TypeArg {
6482 get { return TypeManager.void_type; }
6487 /// Implements the sizeof expression
6489 public class SizeOf : Expression {
6490 public Expression QueriedType;
6493 public SizeOf (Expression queried_type, Location l)
6495 this.QueriedType = queried_type;
6499 public override Expression DoResolve (EmitContext ec)
6503 233, loc, "Sizeof may only be used in an unsafe context " +
6504 "(consider using System.Runtime.InteropServices.Marshal.Sizeof");
6508 QueriedType = ec.DeclSpace.ResolveTypeExpr (QueriedType, false, loc);
6509 if (QueriedType == null || QueriedType.Type == null)
6512 if (QueriedType is TypeParameterExpr){
6513 ((TypeParameterExpr)QueriedType).Error_CannotUseAsUnmanagedType (loc);
6517 if (!TypeManager.IsUnmanagedType (type_queried)){
6518 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
6522 type = TypeManager.int32_type;
6523 eclass = ExprClass.Value;
6527 public override void Emit (EmitContext ec)
6529 int size = GetTypeSize (type_queried);
6532 ec.ig.Emit (OpCodes.Sizeof, type_queried);
6534 IntConstant.EmitInt (ec.ig, size);
6539 /// Implements the member access expression
6541 public class MemberAccess : Expression {
6542 public readonly string Identifier;
6545 public MemberAccess (Expression expr, string id, Location l)
6552 public Expression Expr {
6558 static void error176 (Location loc, string name)
6560 Report.Error (176, loc, "Static member `" +
6561 name + "' cannot be accessed " +
6562 "with an instance reference, qualify with a " +
6563 "type name instead");
6566 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
6568 if (left_original == null)
6571 if (!(left_original is SimpleName))
6574 SimpleName sn = (SimpleName) left_original;
6576 Type t = RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc);
6583 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
6584 Expression left, Location loc,
6585 Expression left_original)
6587 bool left_is_type, left_is_explicit;
6589 // If `left' is null, then we're called from SimpleNameResolve and this is
6590 // a member in the currently defining class.
6592 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
6593 left_is_explicit = false;
6595 // Implicitly default to `this' unless we're static.
6596 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
6597 left = ec.GetThis (loc);
6599 left_is_type = left is TypeExpr;
6600 left_is_explicit = true;
6603 if (member_lookup is FieldExpr){
6604 FieldExpr fe = (FieldExpr) member_lookup;
6605 FieldInfo fi = fe.FieldInfo;
6606 Type decl_type = fi.DeclaringType;
6608 if (fi is FieldBuilder) {
6609 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
6612 object o = c.LookupConstantValue ();
6616 object real_value = ((Constant) c.Expr).GetValue ();
6618 return Constantify (real_value, fi.FieldType);
6623 Type t = fi.FieldType;
6627 if (fi is FieldBuilder)
6628 o = TypeManager.GetValue ((FieldBuilder) fi);
6630 o = fi.GetValue (fi);
6632 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
6633 if (left_is_explicit && !left_is_type &&
6634 !IdenticalNameAndTypeName (ec, left_original, loc)) {
6635 error176 (loc, fe.FieldInfo.Name);
6639 Expression enum_member = MemberLookup (
6640 ec, decl_type, "value__", MemberTypes.Field,
6641 AllBindingFlags, loc);
6643 Enum en = TypeManager.LookupEnum (decl_type);
6647 c = Constantify (o, en.UnderlyingType);
6649 c = Constantify (o, enum_member.Type);
6651 return new EnumConstant (c, decl_type);
6654 Expression exp = Constantify (o, t);
6656 if (left_is_explicit && !left_is_type) {
6657 error176 (loc, fe.FieldInfo.Name);
6664 if (fi.FieldType.IsPointer && !ec.InUnsafe){
6670 if (member_lookup is EventExpr) {
6671 EventExpr ee = (EventExpr) member_lookup;
6674 // If the event is local to this class, we transform ourselves into
6678 if (ee.EventInfo.DeclaringType == ec.ContainerType ||
6679 TypeManager.IsNestedChildOf(ec.ContainerType, ee.EventInfo.DeclaringType)) {
6680 MemberInfo mi = GetFieldFromEvent (ee);
6684 // If this happens, then we have an event with its own
6685 // accessors and private field etc so there's no need
6686 // to transform ourselves.
6691 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
6694 Report.Error (-200, loc, "Internal error!!");
6698 if (!left_is_explicit)
6701 return ResolveMemberAccess (ec, ml, left, loc, left_original);
6705 if (member_lookup is IMemberExpr) {
6706 IMemberExpr me = (IMemberExpr) member_lookup;
6709 MethodGroupExpr mg = me as MethodGroupExpr;
6710 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
6711 mg.IsExplicitImpl = left_is_explicit;
6714 if ((ec.IsFieldInitializer || ec.IsStatic) &&
6715 IdenticalNameAndTypeName (ec, left_original, loc))
6716 return member_lookup;
6718 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
6723 if (!me.IsInstance){
6724 if (IdenticalNameAndTypeName (ec, left_original, loc))
6725 return member_lookup;
6727 if (left_is_explicit) {
6728 error176 (loc, me.Name);
6734 // Since we can not check for instance objects in SimpleName,
6735 // becaue of the rule that allows types and variables to share
6736 // the name (as long as they can be de-ambiguated later, see
6737 // IdenticalNameAndTypeName), we have to check whether left
6738 // is an instance variable in a static context
6740 // However, if the left-hand value is explicitly given, then
6741 // it is already our instance expression, so we aren't in
6745 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
6746 IMemberExpr mexp = (IMemberExpr) left;
6748 if (!mexp.IsStatic){
6749 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
6754 me.InstanceExpression = left;
6757 return member_lookup;
6760 Console.WriteLine ("Left is: " + left);
6761 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
6762 Environment.Exit (0);
6766 public virtual Expression DoResolve (EmitContext ec, Expression right_side,
6770 throw new Exception ();
6773 // Resolve the expression with flow analysis turned off, we'll do the definite
6774 // assignment checks later. This is because we don't know yet what the expression
6775 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
6776 // definite assignment check on the actual field and not on the whole struct.
6779 Expression original = expr;
6780 expr = expr.Resolve (ec, flags | ResolveFlags.DisableFlowAnalysis);
6784 if (expr is SimpleName){
6785 SimpleName child_expr = (SimpleName) expr;
6787 Expression new_expr = new SimpleName (child_expr.Name, Identifier, loc);
6789 return new_expr.Resolve (ec, flags);
6793 // TODO: I mailed Ravi about this, and apparently we can get rid
6794 // of this and put it in the right place.
6796 // Handle enums here when they are in transit.
6797 // Note that we cannot afford to hit MemberLookup in this case because
6798 // it will fail to find any members at all
6801 int errors = Report.Errors;
6803 Type expr_type = expr.Type;
6804 if (expr is TypeExpr){
6805 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
6806 Error (122, "`" + expr_type + "' " +
6807 "is inaccessible because of its protection level");
6811 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
6812 Enum en = TypeManager.LookupEnum (expr_type);
6815 object value = en.LookupEnumValue (ec, Identifier, loc);
6818 Constant c = Constantify (value, en.UnderlyingType);
6819 return new EnumConstant (c, expr_type);
6825 if (expr_type.IsPointer){
6826 Error (23, "The `.' operator can not be applied to pointer operands (" +
6827 TypeManager.CSharpName (expr_type) + ")");
6831 Expression member_lookup;
6832 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
6833 if (member_lookup == null)
6836 if (member_lookup is TypeExpr) {
6837 if (!(expr is TypeExpr) && !(expr is SimpleName)) {
6838 Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
6839 member_lookup.Type + "' instead");
6843 return member_lookup;
6846 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
6847 if (member_lookup == null)
6850 // The following DoResolve/DoResolveLValue will do the definite assignment
6853 if (right_side != null)
6854 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
6856 member_lookup = member_lookup.DoResolve (ec);
6858 return member_lookup;
6861 public override Expression DoResolve (EmitContext ec)
6863 return DoResolve (ec, null, ResolveFlags.VariableOrValue |
6864 ResolveFlags.SimpleName | ResolveFlags.Type);
6867 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
6869 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
6870 ResolveFlags.SimpleName | ResolveFlags.Type);
6873 public override Expression ResolveAsTypeStep (EmitContext ec)
6875 string fname = null;
6876 MemberAccess full_expr = this;
6877 while (full_expr != null) {
6879 fname = String.Concat (full_expr.Identifier, ".", fname);
6881 fname = full_expr.Identifier;
6883 if (full_expr.Expr is SimpleName) {
6884 string full_name = String.Concat (((SimpleName) full_expr.Expr).Name, ".", fname);
6885 Type fully_qualified = ec.DeclSpace.FindType (loc, full_name);
6886 if (fully_qualified != null)
6887 return new TypeExpr (fully_qualified, loc);
6890 full_expr = full_expr.Expr as MemberAccess;
6893 Expression new_expr = expr.ResolveAsTypeStep (ec);
6895 if (new_expr == null)
6898 if (new_expr is SimpleName){
6899 SimpleName child_expr = (SimpleName) new_expr;
6901 new_expr = new SimpleName (child_expr.Name, Identifier, loc);
6903 return new_expr.ResolveAsTypeStep (ec);
6906 Type expr_type = new_expr.Type;
6908 if (expr_type.IsPointer){
6909 Error (23, "The `.' operator can not be applied to pointer operands (" +
6910 TypeManager.CSharpName (expr_type) + ")");
6914 Expression member_lookup;
6915 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
6916 if (member_lookup == null)
6919 if (member_lookup is TypeExpr){
6920 member_lookup.Resolve (ec, ResolveFlags.Type);
6921 return member_lookup;
6927 public override void Emit (EmitContext ec)
6929 throw new Exception ("Should not happen");
6932 public override string ToString ()
6934 return expr + "." + Identifier;
6939 /// Implements checked expressions
6941 public class CheckedExpr : Expression {
6943 public Expression Expr;
6945 public CheckedExpr (Expression e, Location l)
6951 public override Expression DoResolve (EmitContext ec)
6953 bool last_check = ec.CheckState;
6954 bool last_const_check = ec.ConstantCheckState;
6956 ec.CheckState = true;
6957 ec.ConstantCheckState = true;
6958 Expr = Expr.Resolve (ec);
6959 ec.CheckState = last_check;
6960 ec.ConstantCheckState = last_const_check;
6965 if (Expr is Constant)
6968 eclass = Expr.eclass;
6973 public override void Emit (EmitContext ec)
6975 bool last_check = ec.CheckState;
6976 bool last_const_check = ec.ConstantCheckState;
6978 ec.CheckState = true;
6979 ec.ConstantCheckState = true;
6981 ec.CheckState = last_check;
6982 ec.ConstantCheckState = last_const_check;
6988 /// Implements the unchecked expression
6990 public class UnCheckedExpr : Expression {
6992 public Expression Expr;
6994 public UnCheckedExpr (Expression e, Location l)
7000 public override Expression DoResolve (EmitContext ec)
7002 bool last_check = ec.CheckState;
7003 bool last_const_check = ec.ConstantCheckState;
7005 ec.CheckState = false;
7006 ec.ConstantCheckState = false;
7007 Expr = Expr.Resolve (ec);
7008 ec.CheckState = last_check;
7009 ec.ConstantCheckState = last_const_check;
7014 if (Expr is Constant)
7017 eclass = Expr.eclass;
7022 public override void Emit (EmitContext ec)
7024 bool last_check = ec.CheckState;
7025 bool last_const_check = ec.ConstantCheckState;
7027 ec.CheckState = false;
7028 ec.ConstantCheckState = false;
7030 ec.CheckState = last_check;
7031 ec.ConstantCheckState = last_const_check;
7037 /// An Element Access expression.
7039 /// During semantic analysis these are transformed into
7040 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7042 public class ElementAccess : Expression {
7043 public ArrayList Arguments;
7044 public Expression Expr;
7046 public ElementAccess (Expression e, ArrayList e_list, Location l)
7055 Arguments = new ArrayList ();
7056 foreach (Expression tmp in e_list)
7057 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7061 bool CommonResolve (EmitContext ec)
7063 Expr = Expr.Resolve (ec);
7068 if (Arguments == null)
7071 foreach (Argument a in Arguments){
7072 if (!a.Resolve (ec, loc))
7079 Expression MakePointerAccess ()
7083 if (t == TypeManager.void_ptr_type){
7084 Error (242, "The array index operation is not valid for void pointers");
7087 if (Arguments.Count != 1){
7088 Error (196, "A pointer must be indexed by a single value");
7093 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc);
7094 return new Indirection (p, loc);
7097 public override Expression DoResolve (EmitContext ec)
7099 if (!CommonResolve (ec))
7103 // We perform some simple tests, and then to "split" the emit and store
7104 // code we create an instance of a different class, and return that.
7106 // I am experimenting with this pattern.
7110 if (t == TypeManager.array_type){
7111 Report.Error (21, loc, "Cannot use indexer on System.Array");
7116 return (new ArrayAccess (this, loc)).Resolve (ec);
7117 else if (t.IsPointer)
7118 return MakePointerAccess ();
7120 return (new IndexerAccess (this, loc)).Resolve (ec);
7123 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7125 if (!CommonResolve (ec))
7130 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
7131 else if (t.IsPointer)
7132 return MakePointerAccess ();
7134 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
7137 public override void Emit (EmitContext ec)
7139 throw new Exception ("Should never be reached");
7144 /// Implements array access
7146 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7148 // Points to our "data" repository
7152 LocalTemporary [] cached_locations;
7154 public ArrayAccess (ElementAccess ea_data, Location l)
7157 eclass = ExprClass.Variable;
7161 public override Expression DoResolve (EmitContext ec)
7163 ExprClass eclass = ea.Expr.eclass;
7166 // As long as the type is valid
7167 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7168 eclass == ExprClass.Value)) {
7169 ea.Expr.Error_UnexpectedKind ("variable or value");
7174 Type t = ea.Expr.Type;
7175 if (t.GetArrayRank () != ea.Arguments.Count){
7177 "Incorrect number of indexes for array " +
7178 " expected: " + t.GetArrayRank () + " got: " +
7179 ea.Arguments.Count);
7183 type = TypeManager.GetElementType (t);
7184 if (type.IsPointer && !ec.InUnsafe){
7185 UnsafeError (ea.Location);
7189 foreach (Argument a in ea.Arguments){
7190 Type argtype = a.Type;
7192 if (argtype == TypeManager.int32_type ||
7193 argtype == TypeManager.uint32_type ||
7194 argtype == TypeManager.int64_type ||
7195 argtype == TypeManager.uint64_type)
7199 // Mhm. This is strage, because the Argument.Type is not the same as
7200 // Argument.Expr.Type: the value changes depending on the ref/out setting.
7202 // Wonder if I will run into trouble for this.
7204 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
7209 eclass = ExprClass.Variable;
7215 /// Emits the right opcode to load an object of Type `t'
7216 /// from an array of T
7218 static public void EmitLoadOpcode (ILGenerator ig, Type type)
7220 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7221 ig.Emit (OpCodes.Ldelem_U1);
7222 else if (type == TypeManager.sbyte_type)
7223 ig.Emit (OpCodes.Ldelem_I1);
7224 else if (type == TypeManager.short_type)
7225 ig.Emit (OpCodes.Ldelem_I2);
7226 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7227 ig.Emit (OpCodes.Ldelem_U2);
7228 else if (type == TypeManager.int32_type)
7229 ig.Emit (OpCodes.Ldelem_I4);
7230 else if (type == TypeManager.uint32_type)
7231 ig.Emit (OpCodes.Ldelem_U4);
7232 else if (type == TypeManager.uint64_type)
7233 ig.Emit (OpCodes.Ldelem_I8);
7234 else if (type == TypeManager.int64_type)
7235 ig.Emit (OpCodes.Ldelem_I8);
7236 else if (type == TypeManager.float_type)
7237 ig.Emit (OpCodes.Ldelem_R4);
7238 else if (type == TypeManager.double_type)
7239 ig.Emit (OpCodes.Ldelem_R8);
7240 else if (type == TypeManager.intptr_type)
7241 ig.Emit (OpCodes.Ldelem_I);
7242 else if (type.IsValueType){
7243 ig.Emit (OpCodes.Ldelema, type);
7244 ig.Emit (OpCodes.Ldobj, type);
7246 ig.Emit (OpCodes.Ldelem_Ref);
7250 /// Emits the right opcode to store an object of Type `t'
7251 /// from an array of T.
7253 static public void EmitStoreOpcode (ILGenerator ig, Type t)
7256 OpCode op = GetStoreOpcode (t, out is_stobj);
7258 ig.Emit (OpCodes.Stobj, t);
7264 /// Returns the right opcode to store an object of Type `t'
7265 /// from an array of T.
7267 static public OpCode GetStoreOpcode (Type t, out bool is_stobj)
7269 //Console.WriteLine (new System.Diagnostics.StackTrace ());
7271 t = TypeManager.TypeToCoreType (t);
7272 if (TypeManager.IsEnumType (t) && t != TypeManager.enum_type)
7273 t = TypeManager.EnumToUnderlying (t);
7274 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
7275 t == TypeManager.bool_type)
7276 return OpCodes.Stelem_I1;
7277 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
7278 t == TypeManager.char_type)
7279 return OpCodes.Stelem_I2;
7280 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
7281 return OpCodes.Stelem_I4;
7282 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
7283 return OpCodes.Stelem_I8;
7284 else if (t == TypeManager.float_type)
7285 return OpCodes.Stelem_R4;
7286 else if (t == TypeManager.double_type)
7287 return OpCodes.Stelem_R8;
7288 else if (t == TypeManager.intptr_type) {
7290 return OpCodes.Stobj;
7291 } else if (t.IsValueType) {
7293 return OpCodes.Stobj;
7295 return OpCodes.Stelem_Ref;
7298 MethodInfo FetchGetMethod ()
7300 ModuleBuilder mb = CodeGen.ModuleBuilder;
7301 int arg_count = ea.Arguments.Count;
7302 Type [] args = new Type [arg_count];
7305 for (int i = 0; i < arg_count; i++){
7306 //args [i++] = a.Type;
7307 args [i] = TypeManager.int32_type;
7310 get = mb.GetArrayMethod (
7311 ea.Expr.Type, "Get",
7312 CallingConventions.HasThis |
7313 CallingConventions.Standard,
7319 MethodInfo FetchAddressMethod ()
7321 ModuleBuilder mb = CodeGen.ModuleBuilder;
7322 int arg_count = ea.Arguments.Count;
7323 Type [] args = new Type [arg_count];
7327 ret_type = TypeManager.GetReferenceType (type);
7329 for (int i = 0; i < arg_count; i++){
7330 //args [i++] = a.Type;
7331 args [i] = TypeManager.int32_type;
7334 address = mb.GetArrayMethod (
7335 ea.Expr.Type, "Address",
7336 CallingConventions.HasThis |
7337 CallingConventions.Standard,
7344 // Load the array arguments into the stack.
7346 // If we have been requested to cache the values (cached_locations array
7347 // initialized), then load the arguments the first time and store them
7348 // in locals. otherwise load from local variables.
7350 void LoadArrayAndArguments (EmitContext ec)
7352 ILGenerator ig = ec.ig;
7354 if (cached_locations == null){
7356 foreach (Argument a in ea.Arguments){
7357 Type argtype = a.Expr.Type;
7361 if (argtype == TypeManager.int64_type)
7362 ig.Emit (OpCodes.Conv_Ovf_I);
7363 else if (argtype == TypeManager.uint64_type)
7364 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7369 if (cached_locations [0] == null){
7370 cached_locations [0] = new LocalTemporary (ec, ea.Expr.Type);
7372 ig.Emit (OpCodes.Dup);
7373 cached_locations [0].Store (ec);
7377 foreach (Argument a in ea.Arguments){
7378 Type argtype = a.Expr.Type;
7380 cached_locations [j] = new LocalTemporary (ec, TypeManager.intptr_type /* a.Expr.Type */);
7382 if (argtype == TypeManager.int64_type)
7383 ig.Emit (OpCodes.Conv_Ovf_I);
7384 else if (argtype == TypeManager.uint64_type)
7385 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7387 ig.Emit (OpCodes.Dup);
7388 cached_locations [j].Store (ec);
7394 foreach (LocalTemporary lt in cached_locations)
7398 public new void CacheTemporaries (EmitContext ec)
7400 cached_locations = new LocalTemporary [ea.Arguments.Count + 1];
7403 public override void Emit (EmitContext ec)
7405 int rank = ea.Expr.Type.GetArrayRank ();
7406 ILGenerator ig = ec.ig;
7408 LoadArrayAndArguments (ec);
7411 EmitLoadOpcode (ig, type);
7415 method = FetchGetMethod ();
7416 ig.Emit (OpCodes.Call, method);
7420 public void EmitAssign (EmitContext ec, Expression source)
7422 int rank = ea.Expr.Type.GetArrayRank ();
7423 ILGenerator ig = ec.ig;
7424 Type t = source.Type;
7426 LoadArrayAndArguments (ec);
7429 // The stobj opcode used by value types will need
7430 // an address on the stack, not really an array/array
7434 if (t == TypeManager.enum_type || t == TypeManager.decimal_type ||
7435 (t.IsSubclassOf (TypeManager.value_type) && !TypeManager.IsEnumType (t) && !TypeManager.IsBuiltinType (t)))
7436 ig.Emit (OpCodes.Ldelema, t);
7442 EmitStoreOpcode (ig, t);
7444 ModuleBuilder mb = CodeGen.ModuleBuilder;
7445 int arg_count = ea.Arguments.Count;
7446 Type [] args = new Type [arg_count + 1];
7449 for (int i = 0; i < arg_count; i++){
7450 //args [i++] = a.Type;
7451 args [i] = TypeManager.int32_type;
7454 args [arg_count] = type;
7456 set = mb.GetArrayMethod (
7457 ea.Expr.Type, "Set",
7458 CallingConventions.HasThis |
7459 CallingConventions.Standard,
7460 TypeManager.void_type, args);
7462 ig.Emit (OpCodes.Call, set);
7466 public void AddressOf (EmitContext ec, AddressOp mode)
7468 int rank = ea.Expr.Type.GetArrayRank ();
7469 ILGenerator ig = ec.ig;
7471 LoadArrayAndArguments (ec);
7474 ig.Emit (OpCodes.Ldelema, type);
7476 MethodInfo address = FetchAddressMethod ();
7477 ig.Emit (OpCodes.Call, address);
7484 public ArrayList Properties;
7485 static Hashtable map;
7487 public struct Indexer {
7488 public readonly Type Type;
7489 public readonly MethodInfo Getter, Setter;
7491 public Indexer (Type type, MethodInfo get, MethodInfo set)
7501 map = new Hashtable ();
7506 Properties = new ArrayList ();
7509 void Append (MemberInfo [] mi)
7511 foreach (PropertyInfo property in mi){
7512 MethodInfo get, set;
7514 get = property.GetGetMethod (true);
7515 set = property.GetSetMethod (true);
7516 Properties.Add (new Indexer (property.PropertyType, get, set));
7520 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
7522 string p_name = TypeManager.IndexerPropertyName (lookup_type);
7524 MemberInfo [] mi = TypeManager.MemberLookup (
7525 caller_type, caller_type, lookup_type, MemberTypes.Property,
7526 BindingFlags.Public | BindingFlags.Instance |
7527 BindingFlags.DeclaredOnly, p_name);
7529 if (mi == null || mi.Length == 0)
7535 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
7537 Indexers ix = (Indexers) map [lookup_type];
7542 Type copy = lookup_type;
7543 while (copy != TypeManager.object_type && copy != null){
7544 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
7548 ix = new Indexers ();
7553 copy = copy.BaseType;
7556 if (!lookup_type.IsInterface)
7559 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
7560 if (ifaces != null) {
7561 foreach (Type itype in ifaces) {
7562 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
7565 ix = new Indexers ();
7577 /// Expressions that represent an indexer call.
7579 public class IndexerAccess : Expression, IAssignMethod {
7581 // Points to our "data" repository
7583 MethodInfo get, set;
7584 ArrayList set_arguments;
7585 bool is_base_indexer;
7587 protected Type indexer_type;
7588 protected Type current_type;
7589 protected Expression instance_expr;
7590 protected ArrayList arguments;
7592 public IndexerAccess (ElementAccess ea, Location loc)
7593 : this (ea.Expr, false, loc)
7595 this.arguments = ea.Arguments;
7598 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
7601 this.instance_expr = instance_expr;
7602 this.is_base_indexer = is_base_indexer;
7603 this.eclass = ExprClass.Value;
7607 protected virtual bool CommonResolve (EmitContext ec)
7609 indexer_type = instance_expr.Type;
7610 current_type = ec.ContainerType;
7615 public override Expression DoResolve (EmitContext ec)
7617 ArrayList AllGetters = new ArrayList();
7618 if (!CommonResolve (ec))
7622 // Step 1: Query for all `Item' *properties*. Notice
7623 // that the actual methods are pointed from here.
7625 // This is a group of properties, piles of them.
7627 bool found_any = false, found_any_getters = false;
7628 Type lookup_type = indexer_type;
7631 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
7632 if (ilist != null) {
7634 if (ilist.Properties != null) {
7635 foreach (Indexers.Indexer ix in ilist.Properties) {
7636 if (ix.Getter != null)
7637 AllGetters.Add(ix.Getter);
7642 if (AllGetters.Count > 0) {
7643 found_any_getters = true;
7644 get = (MethodInfo) Invocation.OverloadResolve (
7645 ec, new MethodGroupExpr (AllGetters, loc), arguments, loc);
7649 Report.Error (21, loc,
7650 "Type `" + TypeManager.CSharpName (indexer_type) +
7651 "' does not have any indexers defined");
7655 if (!found_any_getters) {
7656 Error (154, "indexer can not be used in this context, because " +
7657 "it lacks a `get' accessor");
7662 Error (1501, "No Overload for method `this' takes `" +
7663 arguments.Count + "' arguments");
7668 // Only base will allow this invocation to happen.
7670 if (get.IsAbstract && this is BaseIndexerAccess){
7671 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
7675 type = get.ReturnType;
7676 if (type.IsPointer && !ec.InUnsafe){
7681 eclass = ExprClass.IndexerAccess;
7685 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7687 ArrayList AllSetters = new ArrayList();
7688 if (!CommonResolve (ec))
7691 Type right_type = right_side.Type;
7693 bool found_any = false, found_any_setters = false;
7695 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
7696 if (ilist != null) {
7698 if (ilist.Properties != null) {
7699 foreach (Indexers.Indexer ix in ilist.Properties) {
7700 if (ix.Setter != null)
7701 AllSetters.Add(ix.Setter);
7705 if (AllSetters.Count > 0) {
7706 found_any_setters = true;
7707 set_arguments = (ArrayList) arguments.Clone ();
7708 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
7709 set = (MethodInfo) Invocation.OverloadResolve (
7710 ec, new MethodGroupExpr (AllSetters, loc),
7711 set_arguments, loc);
7715 Report.Error (21, loc,
7716 "Type `" + TypeManager.CSharpName (indexer_type) +
7717 "' does not have any indexers defined");
7721 if (!found_any_setters) {
7722 Error (154, "indexer can not be used in this context, because " +
7723 "it lacks a `set' accessor");
7728 Error (1501, "No Overload for method `this' takes `" +
7729 arguments.Count + "' arguments");
7734 // Only base will allow this invocation to happen.
7736 if (set.IsAbstract && this is BaseIndexerAccess){
7737 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
7742 // Now look for the actual match in the list of indexers to set our "return" type
7744 type = TypeManager.void_type; // default value
7745 foreach (Indexers.Indexer ix in ilist.Properties){
7746 if (ix.Setter == set){
7752 eclass = ExprClass.IndexerAccess;
7756 public override void Emit (EmitContext ec)
7758 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc);
7762 // source is ignored, because we already have a copy of it from the
7763 // LValue resolution and we have already constructed a pre-cached
7764 // version of the arguments (ea.set_arguments);
7766 public void EmitAssign (EmitContext ec, Expression source)
7768 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc);
7773 /// The base operator for method names
7775 public class BaseAccess : Expression {
7778 public BaseAccess (string member, Location l)
7780 this.member = member;
7784 public override Expression DoResolve (EmitContext ec)
7786 Expression c = CommonResolve (ec);
7792 // MethodGroups use this opportunity to flag an error on lacking ()
7794 if (!(c is MethodGroupExpr))
7795 return c.Resolve (ec);
7799 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7801 Expression c = CommonResolve (ec);
7807 // MethodGroups use this opportunity to flag an error on lacking ()
7809 if (! (c is MethodGroupExpr))
7810 return c.DoResolveLValue (ec, right_side);
7815 Expression CommonResolve (EmitContext ec)
7817 Expression member_lookup;
7818 Type current_type = ec.ContainerType;
7819 Type base_type = current_type.BaseType;
7823 Error (1511, "Keyword base is not allowed in static method");
7827 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type, member,
7828 AllMemberTypes, AllBindingFlags, loc);
7829 if (member_lookup == null) {
7830 MemberLookupFailed (ec, base_type, base_type, member, null, loc);
7837 left = new TypeExpr (base_type, loc);
7839 left = ec.GetThis (loc);
7841 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
7843 if (e is PropertyExpr){
7844 PropertyExpr pe = (PropertyExpr) e;
7852 public override void Emit (EmitContext ec)
7854 throw new Exception ("Should never be called");
7859 /// The base indexer operator
7861 public class BaseIndexerAccess : IndexerAccess {
7862 public BaseIndexerAccess (ArrayList args, Location loc)
7863 : base (null, true, loc)
7865 arguments = new ArrayList ();
7866 foreach (Expression tmp in args)
7867 arguments.Add (new Argument (tmp, Argument.AType.Expression));
7870 protected override bool CommonResolve (EmitContext ec)
7872 instance_expr = ec.GetThis (loc);
7874 current_type = ec.ContainerType.BaseType;
7875 indexer_type = current_type;
7877 foreach (Argument a in arguments){
7878 if (!a.Resolve (ec, loc))
7887 /// This class exists solely to pass the Type around and to be a dummy
7888 /// that can be passed to the conversion functions (this is used by
7889 /// foreach implementation to typecast the object return value from
7890 /// get_Current into the proper type. All code has been generated and
7891 /// we only care about the side effect conversions to be performed
7893 /// This is also now used as a placeholder where a no-action expression
7894 /// is needed (the `New' class).
7896 public class EmptyExpression : Expression {
7897 public EmptyExpression ()
7899 type = TypeManager.object_type;
7900 eclass = ExprClass.Value;
7901 loc = Location.Null;
7904 public EmptyExpression (Type t)
7907 eclass = ExprClass.Value;
7908 loc = Location.Null;
7911 public override Expression DoResolve (EmitContext ec)
7916 public override void Emit (EmitContext ec)
7918 // nothing, as we only exist to not do anything.
7922 // This is just because we might want to reuse this bad boy
7923 // instead of creating gazillions of EmptyExpressions.
7924 // (CanImplicitConversion uses it)
7926 public void SetType (Type t)
7932 public class UserCast : Expression {
7936 public UserCast (MethodInfo method, Expression source, Location l)
7938 this.method = method;
7939 this.source = source;
7940 type = method.ReturnType;
7941 eclass = ExprClass.Value;
7945 public override Expression DoResolve (EmitContext ec)
7948 // We are born fully resolved
7953 public override void Emit (EmitContext ec)
7955 ILGenerator ig = ec.ig;
7959 if (method is MethodInfo)
7960 ig.Emit (OpCodes.Call, (MethodInfo) method);
7962 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
7968 // This class is used to "construct" the type during a typecast
7969 // operation. Since the Type.GetType class in .NET can parse
7970 // the type specification, we just use this to construct the type
7971 // one bit at a time.
7973 public class ComposedCast : Expression {
7977 public ComposedCast (Expression left, string dim, Location l)
7984 public override Expression ResolveAsTypeStep (EmitContext ec)
7986 Type ltype = ec.DeclSpace.ResolveType (left, false, loc);
7990 if (ltype.IsGenericParameter) {
7991 int rank = dim.Length-2;
7992 if ((rank < 0) || (dim [0] != '[') || (dim [rank+1] != ']'))
7994 for (int i = 0; i < rank; i++)
7995 if (dim [i+1] != ',')
7998 type = Array.CreateInstance (ltype, rank).GetType ();
8000 eclass = ExprClass.Type;
8005 // ltype.Fullname is already fully qualified, so we can skip
8006 // a lot of probes, and go directly to TypeManager.LookupType
8008 string cname = ltype.FullName + dim;
8009 type = TypeManager.LookupTypeDirect (cname);
8012 // For arrays of enumerations we are having a problem
8013 // with the direct lookup. Need to investigate.
8015 // For now, fall back to the full lookup in that case.
8017 type = RootContext.LookupType (
8018 ec.DeclSpace, cname, false, loc);
8024 if (!ec.ResolvingTypeTree){
8026 // If the above flag is set, this is being invoked from the ResolveType function.
8027 // Upper layers take care of the type validity in this context.
8029 if (!ec.InUnsafe && type.IsPointer){
8035 eclass = ExprClass.Type;
8039 public override Expression DoResolve (EmitContext ec)
8041 return ResolveAsTypeStep (ec);
8044 public override void Emit (EmitContext ec)
8046 throw new Exception ("This should never be called");
8049 public override string ToString ()
8056 // This class is used to represent the address of an array, used
8057 // only by the Fixed statement, this is like the C "&a [0]" construct.
8059 public class ArrayPtr : Expression {
8062 public ArrayPtr (Expression array, Location l)
8064 Type array_type = TypeManager.GetElementType (array.Type);
8068 type = TypeManager.GetPointerType (array_type);
8069 eclass = ExprClass.Value;
8073 public override void Emit (EmitContext ec)
8075 ILGenerator ig = ec.ig;
8078 IntLiteral.EmitInt (ig, 0);
8079 ig.Emit (OpCodes.Ldelema, TypeManager.GetElementType (array.Type));
8082 public override Expression DoResolve (EmitContext ec)
8085 // We are born fully resolved
8092 // Used by the fixed statement
8094 public class StringPtr : Expression {
8097 public StringPtr (LocalBuilder b, Location l)
8100 eclass = ExprClass.Value;
8101 type = TypeManager.char_ptr_type;
8105 public override Expression DoResolve (EmitContext ec)
8107 // This should never be invoked, we are born in fully
8108 // initialized state.
8113 public override void Emit (EmitContext ec)
8115 ILGenerator ig = ec.ig;
8117 ig.Emit (OpCodes.Ldloc, b);
8118 ig.Emit (OpCodes.Conv_I);
8119 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
8120 ig.Emit (OpCodes.Add);
8125 // Implements the `stackalloc' keyword
8127 public class StackAlloc : Expression {
8132 public StackAlloc (Expression type, Expression count, Location l)
8139 public override Expression DoResolve (EmitContext ec)
8141 count = count.Resolve (ec);
8145 if (count.Type != TypeManager.int32_type){
8146 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8151 if (ec.InCatch || ec.InFinally){
8153 "stackalloc can not be used in a catch or finally block");
8157 otype = ec.DeclSpace.ResolveType (t, false, loc);
8162 if (!TypeManager.VerifyUnManaged (otype, loc))
8165 type = TypeManager.GetPointerType (otype);
8166 eclass = ExprClass.Value;
8171 public override void Emit (EmitContext ec)
8173 int size = GetTypeSize (otype);
8174 ILGenerator ig = ec.ig;
8177 ig.Emit (OpCodes.Sizeof, otype);
8179 IntConstant.EmitInt (ig, size);
8181 ig.Emit (OpCodes.Mul);
8182 ig.Emit (OpCodes.Localloc);