2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
8 // (C) 2003, 2004 Novell, Inc.
12 namespace Mono.CSharp {
14 using System.Collections;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// This is just a helper class, it is generated by Unary, UnaryMutator
21 /// when an overloaded method has been found. It just emits the code for a
24 public class StaticCallExpr : ExpressionStatement {
28 public StaticCallExpr (MethodInfo m, ArrayList a, Location l)
34 eclass = ExprClass.Value;
38 public override Expression DoResolve (EmitContext ec)
41 // We are born fully resolved
46 public override void Emit (EmitContext ec)
49 Invocation.EmitArguments (ec, mi, args, false, null);
51 ec.ig.Emit (OpCodes.Call, mi);
55 static public StaticCallExpr MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
56 Expression e, Location loc)
61 args = new ArrayList (1);
62 Argument a = new Argument (e, Argument.AType.Expression);
64 // We need to resolve the arguments before sending them in !
65 if (!a.Resolve (ec, loc))
69 method = Invocation.OverloadResolve (
70 ec, (MethodGroupExpr) mg, args, false, loc);
75 return new StaticCallExpr ((MethodInfo) method, args, loc);
78 public override void EmitStatement (EmitContext ec)
81 if (TypeManager.TypeToCoreType (type) != TypeManager.void_type)
82 ec.ig.Emit (OpCodes.Pop);
85 public MethodInfo Method {
90 public class ParenthesizedExpression : Expression
92 public Expression Expr;
94 public ParenthesizedExpression (Expression expr, Location loc)
100 public override Expression DoResolve (EmitContext ec)
102 Expr = Expr.Resolve (ec);
106 public override void Emit (EmitContext ec)
108 throw new Exception ("Should not happen");
113 /// Unary expressions.
117 /// Unary implements unary expressions. It derives from
118 /// ExpressionStatement becuase the pre/post increment/decrement
119 /// operators can be used in a statement context.
121 public class Unary : Expression {
122 public enum Operator : byte {
123 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
124 Indirection, AddressOf, TOP
127 public Operator Oper;
128 public Expression Expr;
130 public Unary (Operator op, Expression expr, Location loc)
138 /// Returns a stringified representation of the Operator
140 static public string OperName (Operator oper)
143 case Operator.UnaryPlus:
145 case Operator.UnaryNegation:
147 case Operator.LogicalNot:
149 case Operator.OnesComplement:
151 case Operator.AddressOf:
153 case Operator.Indirection:
157 return oper.ToString ();
160 public static readonly string [] oper_names;
164 oper_names = new string [(int)Operator.TOP];
166 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
167 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
168 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
169 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
170 oper_names [(int) Operator.Indirection] = "op_Indirection";
171 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
174 void Error23 (Type t)
177 23, "Operator " + OperName (Oper) +
178 " cannot be applied to operand of type `" +
179 TypeManager.CSharpName (t) + "'");
183 /// The result has been already resolved:
185 /// FIXME: a minus constant -128 sbyte cant be turned into a
188 static Expression TryReduceNegative (Constant expr)
192 if (expr is IntConstant)
193 e = new IntConstant (-((IntConstant) expr).Value);
194 else if (expr is UIntConstant){
195 uint value = ((UIntConstant) expr).Value;
197 if (value < 2147483649)
198 return new IntConstant (-(int)value);
200 e = new LongConstant (-value);
202 else if (expr is LongConstant)
203 e = new LongConstant (-((LongConstant) expr).Value);
204 else if (expr is ULongConstant){
205 ulong value = ((ULongConstant) expr).Value;
207 if (value < 9223372036854775809)
208 return new LongConstant(-(long)value);
210 else if (expr is FloatConstant)
211 e = new FloatConstant (-((FloatConstant) expr).Value);
212 else if (expr is DoubleConstant)
213 e = new DoubleConstant (-((DoubleConstant) expr).Value);
214 else if (expr is DecimalConstant)
215 e = new DecimalConstant (-((DecimalConstant) expr).Value);
216 else if (expr is ShortConstant)
217 e = new IntConstant (-((ShortConstant) expr).Value);
218 else if (expr is UShortConstant)
219 e = new IntConstant (-((UShortConstant) expr).Value);
220 else if (expr is SByteConstant)
221 e = new IntConstant (-((SByteConstant) expr).Value);
222 else if (expr is ByteConstant)
223 e = new IntConstant (-((ByteConstant) expr).Value);
228 // This routine will attempt to simplify the unary expression when the
229 // argument is a constant. The result is returned in `result' and the
230 // function returns true or false depending on whether a reduction
231 // was performed or not
233 bool Reduce (EmitContext ec, Constant e, out Expression result)
235 Type expr_type = e.Type;
238 case Operator.UnaryPlus:
242 case Operator.UnaryNegation:
243 result = TryReduceNegative (e);
244 return result != null;
246 case Operator.LogicalNot:
247 if (expr_type != TypeManager.bool_type) {
253 BoolConstant b = (BoolConstant) e;
254 result = new BoolConstant (!(b.Value));
257 case Operator.OnesComplement:
258 if (!((expr_type == TypeManager.int32_type) ||
259 (expr_type == TypeManager.uint32_type) ||
260 (expr_type == TypeManager.int64_type) ||
261 (expr_type == TypeManager.uint64_type) ||
262 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
265 if (Convert.ImplicitConversionExists (ec, e, TypeManager.int32_type)){
266 result = new Cast (new TypeExpression (TypeManager.int32_type, loc), e, loc);
267 result = result.Resolve (ec);
268 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint32_type)){
269 result = new Cast (new TypeExpression (TypeManager.uint32_type, loc), e, loc);
270 result = result.Resolve (ec);
271 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.int64_type)){
272 result = new Cast (new TypeExpression (TypeManager.int64_type, loc), e, loc);
273 result = result.Resolve (ec);
274 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint64_type)){
275 result = new Cast (new TypeExpression (TypeManager.uint64_type, loc), e, loc);
276 result = result.Resolve (ec);
279 if (result == null || !(result is Constant)){
285 expr_type = result.Type;
286 e = (Constant) result;
289 if (e is EnumConstant){
290 EnumConstant enum_constant = (EnumConstant) e;
293 if (Reduce (ec, enum_constant.Child, out reduced)){
294 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
302 if (expr_type == TypeManager.int32_type){
303 result = new IntConstant (~ ((IntConstant) e).Value);
304 } else if (expr_type == TypeManager.uint32_type){
305 result = new UIntConstant (~ ((UIntConstant) e).Value);
306 } else if (expr_type == TypeManager.int64_type){
307 result = new LongConstant (~ ((LongConstant) e).Value);
308 } else if (expr_type == TypeManager.uint64_type){
309 result = new ULongConstant (~ ((ULongConstant) e).Value);
317 case Operator.AddressOf:
321 case Operator.Indirection:
325 throw new Exception ("Can not constant fold: " + Oper.ToString());
328 Expression ResolveOperator (EmitContext ec)
331 // Step 1: Default operations on CLI native types.
334 // Attempt to use a constant folding operation.
335 if (Expr is Constant){
338 if (Reduce (ec, (Constant) Expr, out result))
343 // Step 2: Perform Operator Overload location
345 Type expr_type = Expr.Type;
349 op_name = oper_names [(int) Oper];
351 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
354 Expression e = StaticCallExpr.MakeSimpleCall (
355 ec, (MethodGroupExpr) mg, Expr, loc);
365 // Only perform numeric promotions on:
368 if (expr_type == null)
372 case Operator.LogicalNot:
373 if (expr_type != TypeManager.bool_type) {
374 Expr = ResolveBoolean (ec, Expr, loc);
381 type = TypeManager.bool_type;
384 case Operator.OnesComplement:
385 if (!((expr_type == TypeManager.int32_type) ||
386 (expr_type == TypeManager.uint32_type) ||
387 (expr_type == TypeManager.int64_type) ||
388 (expr_type == TypeManager.uint64_type) ||
389 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
392 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
394 type = TypeManager.int32_type;
397 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint32_type, loc);
399 type = TypeManager.uint32_type;
402 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
404 type = TypeManager.int64_type;
407 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint64_type, loc);
409 type = TypeManager.uint64_type;
418 case Operator.AddressOf:
424 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
428 IVariable variable = Expr as IVariable;
429 bool is_fixed = variable != null && variable.VerifyFixed (false);
431 if (!ec.InFixedInitializer && !is_fixed) {
432 Error (212, "You can only take the address of an unfixed expression inside " +
433 "of a fixed statement initializer");
437 if (ec.InFixedInitializer && is_fixed) {
438 Error (213, "You can not fix an already fixed expression");
442 LocalVariableReference lr = Expr as LocalVariableReference;
444 if (lr.local_info.IsCaptured){
445 AnonymousMethod.Error_AddressOfCapturedVar (lr.Name, loc);
448 lr.local_info.AddressTaken = true;
449 lr.local_info.Used = true;
452 // According to the specs, a variable is considered definitely assigned if you take
454 if ((variable != null) && (variable.VariableInfo != null))
455 variable.VariableInfo.SetAssigned (ec);
457 type = TypeManager.GetPointerType (Expr.Type);
460 case Operator.Indirection:
466 if (!expr_type.IsPointer){
467 Error (193, "The * or -> operator can only be applied to pointers");
472 // We create an Indirection expression, because
473 // it can implement the IMemoryLocation.
475 return new Indirection (Expr, loc);
477 case Operator.UnaryPlus:
479 // A plus in front of something is just a no-op, so return the child.
483 case Operator.UnaryNegation:
485 // Deals with -literals
486 // int operator- (int x)
487 // long operator- (long x)
488 // float operator- (float f)
489 // double operator- (double d)
490 // decimal operator- (decimal d)
492 Expression expr = null;
495 // transform - - expr into expr
498 Unary unary = (Unary) Expr;
500 if (unary.Oper == Operator.UnaryNegation)
505 // perform numeric promotions to int,
509 // The following is inneficient, because we call
510 // ImplicitConversion too many times.
512 // It is also not clear if we should convert to Float
513 // or Double initially.
515 if (expr_type == TypeManager.uint32_type){
517 // FIXME: handle exception to this rule that
518 // permits the int value -2147483648 (-2^31) to
519 // bt wrote as a decimal interger literal
521 type = TypeManager.int64_type;
522 Expr = Convert.ImplicitConversion (ec, Expr, type, loc);
526 if (expr_type == TypeManager.uint64_type){
528 // FIXME: Handle exception of `long value'
529 // -92233720368547758087 (-2^63) to be wrote as
530 // decimal integer literal.
536 if (expr_type == TypeManager.float_type){
541 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
548 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
555 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.double_type, loc);
566 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
567 TypeManager.CSharpName (expr_type) + "'");
571 public override Expression DoResolve (EmitContext ec)
573 if (Oper == Operator.AddressOf) {
574 Expr = Expr.DoResolveLValue (ec, new EmptyExpression ());
576 if (Expr == null || Expr.eclass != ExprClass.Variable){
577 Error (211, "Cannot take the address of non-variables");
582 Expr = Expr.Resolve (ec);
587 if (TypeManager.IsNullableType (Expr.Type))
588 return new Nullable.LiftedUnaryOperator (Oper, Expr, loc).Resolve (ec);
590 eclass = ExprClass.Value;
591 return ResolveOperator (ec);
594 public override Expression DoResolveLValue (EmitContext ec, Expression right)
596 if (Oper == Operator.Indirection)
597 return DoResolve (ec);
602 public override void Emit (EmitContext ec)
604 ILGenerator ig = ec.ig;
607 case Operator.UnaryPlus:
608 throw new Exception ("This should be caught by Resolve");
610 case Operator.UnaryNegation:
612 ig.Emit (OpCodes.Ldc_I4_0);
613 if (type == TypeManager.int64_type)
614 ig.Emit (OpCodes.Conv_U8);
616 ig.Emit (OpCodes.Sub_Ovf);
619 ig.Emit (OpCodes.Neg);
624 case Operator.LogicalNot:
626 ig.Emit (OpCodes.Ldc_I4_0);
627 ig.Emit (OpCodes.Ceq);
630 case Operator.OnesComplement:
632 ig.Emit (OpCodes.Not);
635 case Operator.AddressOf:
636 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
640 throw new Exception ("This should not happen: Operator = "
645 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
647 if (Oper == Operator.LogicalNot)
648 Expr.EmitBranchable (ec, target, !onTrue);
650 base.EmitBranchable (ec, target, onTrue);
653 public override string ToString ()
655 return "Unary (" + Oper + ", " + Expr + ")";
661 // Unary operators are turned into Indirection expressions
662 // after semantic analysis (this is so we can take the address
663 // of an indirection).
665 public class Indirection : Expression, IMemoryLocation, IAssignMethod, IVariable {
667 LocalTemporary temporary;
670 public Indirection (Expression expr, Location l)
673 type = TypeManager.HasElementType (expr.Type) ? TypeManager.GetElementType (expr.Type) : expr.Type;
674 eclass = ExprClass.Variable;
678 public override void Emit (EmitContext ec)
683 LoadFromPtr (ec.ig, Type);
686 public void Emit (EmitContext ec, bool leave_copy)
690 ec.ig.Emit (OpCodes.Dup);
691 temporary = new LocalTemporary (ec, expr.Type);
692 temporary.Store (ec);
696 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
698 prepared = prepare_for_load;
702 if (prepare_for_load)
703 ec.ig.Emit (OpCodes.Dup);
707 ec.ig.Emit (OpCodes.Dup);
708 temporary = new LocalTemporary (ec, expr.Type);
709 temporary.Store (ec);
712 StoreFromPtr (ec.ig, type);
714 if (temporary != null)
718 public void AddressOf (EmitContext ec, AddressOp Mode)
723 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
725 return DoResolve (ec);
728 public override Expression DoResolve (EmitContext ec)
731 // Born fully resolved
736 public override string ToString ()
738 return "*(" + expr + ")";
741 #region IVariable Members
743 public VariableInfo VariableInfo {
749 public bool VerifyFixed (bool is_expression)
758 /// Unary Mutator expressions (pre and post ++ and --)
762 /// UnaryMutator implements ++ and -- expressions. It derives from
763 /// ExpressionStatement becuase the pre/post increment/decrement
764 /// operators can be used in a statement context.
766 /// FIXME: Idea, we could split this up in two classes, one simpler
767 /// for the common case, and one with the extra fields for more complex
768 /// classes (indexers require temporary access; overloaded require method)
771 public class UnaryMutator : ExpressionStatement {
773 public enum Mode : byte {
780 PreDecrement = IsDecrement,
781 PostIncrement = IsPost,
782 PostDecrement = IsPost | IsDecrement
786 bool is_expr = false;
787 bool recurse = false;
792 // This is expensive for the simplest case.
794 StaticCallExpr method;
796 public UnaryMutator (Mode m, Expression e, Location l)
803 static string OperName (Mode mode)
805 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
810 /// Returns whether an object of type `t' can be incremented
811 /// or decremented with add/sub (ie, basically whether we can
812 /// use pre-post incr-decr operations on it, but it is not a
813 /// System.Decimal, which we require operator overloading to catch)
815 static bool IsIncrementableNumber (Type t)
817 return (t == TypeManager.sbyte_type) ||
818 (t == TypeManager.byte_type) ||
819 (t == TypeManager.short_type) ||
820 (t == TypeManager.ushort_type) ||
821 (t == TypeManager.int32_type) ||
822 (t == TypeManager.uint32_type) ||
823 (t == TypeManager.int64_type) ||
824 (t == TypeManager.uint64_type) ||
825 (t == TypeManager.char_type) ||
826 (t.IsSubclassOf (TypeManager.enum_type)) ||
827 (t == TypeManager.float_type) ||
828 (t == TypeManager.double_type) ||
829 (t.IsPointer && t != TypeManager.void_ptr_type);
832 Expression ResolveOperator (EmitContext ec)
834 Type expr_type = expr.Type;
837 // Step 1: Perform Operator Overload location
842 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
843 op_name = "op_Increment";
845 op_name = "op_Decrement";
847 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
850 method = StaticCallExpr.MakeSimpleCall (
851 ec, (MethodGroupExpr) mg, expr, loc);
854 } else if (!IsIncrementableNumber (expr_type)) {
855 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
856 TypeManager.CSharpName (expr_type) + "'");
861 // The operand of the prefix/postfix increment decrement operators
862 // should be an expression that is classified as a variable,
863 // a property access or an indexer access
866 if (expr.eclass == ExprClass.Variable){
867 LocalVariableReference var = expr as LocalVariableReference;
868 if ((var != null) && var.IsReadOnly) {
869 Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
872 } else if (expr.eclass == ExprClass.IndexerAccess || expr.eclass == ExprClass.PropertyAccess){
873 expr = expr.ResolveLValue (ec, this);
877 expr.Error_UnexpectedKind ("variable, indexer or property access", loc);
884 public override Expression DoResolve (EmitContext ec)
886 expr = expr.Resolve (ec);
891 eclass = ExprClass.Value;
893 if (TypeManager.IsNullableType (expr.Type))
894 return new Nullable.LiftedUnaryMutator (mode, expr, loc).Resolve (ec);
896 return ResolveOperator (ec);
899 static int PtrTypeSize (Type t)
901 return GetTypeSize (TypeManager.GetElementType (t));
905 // Loads the proper "1" into the stack based on the type, then it emits the
906 // opcode for the operation requested
908 void LoadOneAndEmitOp (EmitContext ec, Type t)
911 // Measure if getting the typecode and using that is more/less efficient
912 // that comparing types. t.GetTypeCode() is an internal call.
914 ILGenerator ig = ec.ig;
916 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
917 LongConstant.EmitLong (ig, 1);
918 else if (t == TypeManager.double_type)
919 ig.Emit (OpCodes.Ldc_R8, 1.0);
920 else if (t == TypeManager.float_type)
921 ig.Emit (OpCodes.Ldc_R4, 1.0F);
922 else if (t.IsPointer){
923 int n = PtrTypeSize (t);
926 ig.Emit (OpCodes.Sizeof, t);
928 IntConstant.EmitInt (ig, n);
930 ig.Emit (OpCodes.Ldc_I4_1);
933 // Now emit the operation
936 if (t == TypeManager.int32_type ||
937 t == TypeManager.int64_type){
938 if ((mode & Mode.IsDecrement) != 0)
939 ig.Emit (OpCodes.Sub_Ovf);
941 ig.Emit (OpCodes.Add_Ovf);
942 } else if (t == TypeManager.uint32_type ||
943 t == TypeManager.uint64_type){
944 if ((mode & Mode.IsDecrement) != 0)
945 ig.Emit (OpCodes.Sub_Ovf_Un);
947 ig.Emit (OpCodes.Add_Ovf_Un);
949 if ((mode & Mode.IsDecrement) != 0)
950 ig.Emit (OpCodes.Sub_Ovf);
952 ig.Emit (OpCodes.Add_Ovf);
955 if ((mode & Mode.IsDecrement) != 0)
956 ig.Emit (OpCodes.Sub);
958 ig.Emit (OpCodes.Add);
961 if (t == TypeManager.sbyte_type){
963 ig.Emit (OpCodes.Conv_Ovf_I1);
965 ig.Emit (OpCodes.Conv_I1);
966 } else if (t == TypeManager.byte_type){
968 ig.Emit (OpCodes.Conv_Ovf_U1);
970 ig.Emit (OpCodes.Conv_U1);
971 } else if (t == TypeManager.short_type){
973 ig.Emit (OpCodes.Conv_Ovf_I2);
975 ig.Emit (OpCodes.Conv_I2);
976 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
978 ig.Emit (OpCodes.Conv_Ovf_U2);
980 ig.Emit (OpCodes.Conv_U2);
985 void EmitCode (EmitContext ec, bool is_expr)
988 this.is_expr = is_expr;
989 ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
992 public override void Emit (EmitContext ec)
995 // We use recurse to allow ourselfs to be the source
996 // of an assignment. This little hack prevents us from
997 // having to allocate another expression
1000 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
1002 LoadOneAndEmitOp (ec, expr.Type);
1004 ec.ig.Emit (OpCodes.Call, method.Method);
1009 EmitCode (ec, true);
1012 public override void EmitStatement (EmitContext ec)
1014 EmitCode (ec, false);
1019 /// Base class for the `Is' and `As' classes.
1023 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1026 public abstract class Probe : Expression {
1027 public Expression ProbeType;
1028 protected Expression expr;
1029 protected Type probe_type;
1031 public Probe (Expression expr, Expression probe_type, Location l)
1033 ProbeType = probe_type;
1038 public Expression Expr {
1044 public override Expression DoResolve (EmitContext ec)
1046 TypeExpr texpr = ProbeType.ResolveAsTypeTerminal (ec);
1049 probe_type = texpr.Type;
1051 CheckObsoleteAttribute (probe_type);
1053 expr = expr.Resolve (ec);
1057 if (expr.Type.IsPointer) {
1058 Report.Error (244, loc, "\"is\" or \"as\" are not valid on pointer types");
1066 /// Implementation of the `is' operator.
1068 public class Is : Probe {
1069 public Is (Expression expr, Expression probe_type, Location l)
1070 : base (expr, probe_type, l)
1075 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1080 public override void Emit (EmitContext ec)
1082 ILGenerator ig = ec.ig;
1087 case Action.AlwaysFalse:
1088 ig.Emit (OpCodes.Pop);
1089 IntConstant.EmitInt (ig, 0);
1091 case Action.AlwaysTrue:
1092 ig.Emit (OpCodes.Pop);
1093 IntConstant.EmitInt (ig, 1);
1095 case Action.LeaveOnStack:
1096 // the `e != null' rule.
1097 ig.Emit (OpCodes.Ldnull);
1098 ig.Emit (OpCodes.Ceq);
1099 ig.Emit (OpCodes.Ldc_I4_0);
1100 ig.Emit (OpCodes.Ceq);
1103 ig.Emit (OpCodes.Isinst, probe_type);
1104 ig.Emit (OpCodes.Ldnull);
1105 ig.Emit (OpCodes.Cgt_Un);
1108 throw new Exception ("never reached");
1111 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
1113 ILGenerator ig = ec.ig;
1116 case Action.AlwaysFalse:
1118 ig.Emit (OpCodes.Br, target);
1121 case Action.AlwaysTrue:
1123 ig.Emit (OpCodes.Br, target);
1126 case Action.LeaveOnStack:
1127 // the `e != null' rule.
1129 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1133 ig.Emit (OpCodes.Isinst, probe_type);
1134 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1137 throw new Exception ("never reached");
1140 public override Expression DoResolve (EmitContext ec)
1142 Expression e = base.DoResolve (ec);
1144 if ((e == null) || (expr == null))
1147 Type etype = expr.Type;
1148 bool warning_always_matches = false;
1149 bool warning_never_matches = false;
1151 type = TypeManager.bool_type;
1152 eclass = ExprClass.Value;
1155 // First case, if at compile time, there is an implicit conversion
1156 // then e != null (objects) or true (value types)
1158 e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1161 if (etype.IsValueType)
1162 action = Action.AlwaysTrue;
1164 action = Action.LeaveOnStack;
1166 warning_always_matches = true;
1167 } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1168 if (etype.IsGenericParameter)
1169 expr = new BoxedCast (expr, etype);
1172 // Second case: explicit reference convresion
1174 if (expr is NullLiteral)
1175 action = Action.AlwaysFalse;
1177 action = Action.Probe;
1179 action = Action.AlwaysFalse;
1180 warning_never_matches = true;
1183 if (warning_always_matches)
1184 Warning (183, "The given expression is always of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1185 else if (warning_never_matches){
1186 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1187 Warning (184, "The given expression is never of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1195 /// Implementation of the `as' operator.
1197 public class As : Probe {
1198 public As (Expression expr, Expression probe_type, Location l)
1199 : base (expr, probe_type, l)
1203 bool do_isinst = false;
1205 public override void Emit (EmitContext ec)
1207 ILGenerator ig = ec.ig;
1212 ig.Emit (OpCodes.Isinst, probe_type);
1215 static void Error_CannotConvertType (Type source, Type target, Location loc)
1218 39, loc, "as operator can not convert from `" +
1219 TypeManager.CSharpName (source) + "' to `" +
1220 TypeManager.CSharpName (target) + "'");
1223 public override Expression DoResolve (EmitContext ec)
1225 Expression e = base.DoResolve (ec);
1231 eclass = ExprClass.Value;
1232 Type etype = expr.Type;
1234 if (TypeManager.IsValueType (probe_type)){
1235 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1236 TypeManager.CSharpName (probe_type) + " is a value type)");
1241 e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1248 if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1249 if (etype.IsGenericParameter)
1250 expr = new BoxedCast (expr, etype);
1256 Error_CannotConvertType (etype, probe_type, loc);
1262 /// This represents a typecast in the source language.
1264 /// FIXME: Cast expressions have an unusual set of parsing
1265 /// rules, we need to figure those out.
1267 public class Cast : Expression {
1268 Expression target_type;
1271 public Cast (Expression cast_type, Expression expr, Location loc)
1273 this.target_type = cast_type;
1278 public Expression TargetType {
1284 public Expression Expr {
1293 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1295 if (!ec.ConstantCheckState)
1298 if ((value < min) || (value > max)) {
1299 Error (221, "Constant value `" + value + "' cannot be converted " +
1300 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1301 "syntax to override)");
1308 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1310 if (!ec.ConstantCheckState)
1314 Error (221, "Constant value `" + value + "' cannot be converted " +
1315 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1316 "syntax to override)");
1323 bool CheckUnsigned (EmitContext ec, long value, Type type)
1325 if (!ec.ConstantCheckState)
1329 Error (221, "Constant value `" + value + "' cannot be converted " +
1330 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1331 "syntax to override)");
1339 /// Attempts to do a compile-time folding of a constant cast.
1341 Expression TryReduce (EmitContext ec, Type target_type)
1343 Expression real_expr = expr;
1344 if (real_expr is EnumConstant)
1345 real_expr = ((EnumConstant) real_expr).Child;
1347 if (real_expr is ByteConstant){
1348 byte v = ((ByteConstant) real_expr).Value;
1350 if (target_type == TypeManager.sbyte_type) {
1351 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1353 return new SByteConstant ((sbyte) v);
1355 if (target_type == TypeManager.short_type)
1356 return new ShortConstant ((short) v);
1357 if (target_type == TypeManager.ushort_type)
1358 return new UShortConstant ((ushort) v);
1359 if (target_type == TypeManager.int32_type)
1360 return new IntConstant ((int) v);
1361 if (target_type == TypeManager.uint32_type)
1362 return new UIntConstant ((uint) v);
1363 if (target_type == TypeManager.int64_type)
1364 return new LongConstant ((long) v);
1365 if (target_type == TypeManager.uint64_type)
1366 return new ULongConstant ((ulong) v);
1367 if (target_type == TypeManager.float_type)
1368 return new FloatConstant ((float) v);
1369 if (target_type == TypeManager.double_type)
1370 return new DoubleConstant ((double) v);
1371 if (target_type == TypeManager.char_type)
1372 return new CharConstant ((char) v);
1373 if (target_type == TypeManager.decimal_type)
1374 return new DecimalConstant ((decimal) v);
1376 if (real_expr is SByteConstant){
1377 sbyte v = ((SByteConstant) real_expr).Value;
1379 if (target_type == TypeManager.byte_type) {
1380 if (!CheckUnsigned (ec, v, target_type))
1382 return new ByteConstant ((byte) v);
1384 if (target_type == TypeManager.short_type)
1385 return new ShortConstant ((short) v);
1386 if (target_type == TypeManager.ushort_type) {
1387 if (!CheckUnsigned (ec, v, target_type))
1389 return new UShortConstant ((ushort) v);
1390 } if (target_type == TypeManager.int32_type)
1391 return new IntConstant ((int) v);
1392 if (target_type == TypeManager.uint32_type) {
1393 if (!CheckUnsigned (ec, v, target_type))
1395 return new UIntConstant ((uint) v);
1396 } if (target_type == TypeManager.int64_type)
1397 return new LongConstant ((long) v);
1398 if (target_type == TypeManager.uint64_type) {
1399 if (!CheckUnsigned (ec, v, target_type))
1401 return new ULongConstant ((ulong) v);
1403 if (target_type == TypeManager.float_type)
1404 return new FloatConstant ((float) v);
1405 if (target_type == TypeManager.double_type)
1406 return new DoubleConstant ((double) v);
1407 if (target_type == TypeManager.char_type) {
1408 if (!CheckUnsigned (ec, v, target_type))
1410 return new CharConstant ((char) v);
1412 if (target_type == TypeManager.decimal_type)
1413 return new DecimalConstant ((decimal) v);
1415 if (real_expr is ShortConstant){
1416 short v = ((ShortConstant) real_expr).Value;
1418 if (target_type == TypeManager.byte_type) {
1419 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1421 return new ByteConstant ((byte) v);
1423 if (target_type == TypeManager.sbyte_type) {
1424 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1426 return new SByteConstant ((sbyte) v);
1428 if (target_type == TypeManager.ushort_type) {
1429 if (!CheckUnsigned (ec, v, target_type))
1431 return new UShortConstant ((ushort) v);
1433 if (target_type == TypeManager.int32_type)
1434 return new IntConstant ((int) v);
1435 if (target_type == TypeManager.uint32_type) {
1436 if (!CheckUnsigned (ec, v, target_type))
1438 return new UIntConstant ((uint) v);
1440 if (target_type == TypeManager.int64_type)
1441 return new LongConstant ((long) v);
1442 if (target_type == TypeManager.uint64_type) {
1443 if (!CheckUnsigned (ec, v, target_type))
1445 return new ULongConstant ((ulong) v);
1447 if (target_type == TypeManager.float_type)
1448 return new FloatConstant ((float) v);
1449 if (target_type == TypeManager.double_type)
1450 return new DoubleConstant ((double) v);
1451 if (target_type == TypeManager.char_type) {
1452 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1454 return new CharConstant ((char) v);
1456 if (target_type == TypeManager.decimal_type)
1457 return new DecimalConstant ((decimal) v);
1459 if (real_expr is UShortConstant){
1460 ushort v = ((UShortConstant) real_expr).Value;
1462 if (target_type == TypeManager.byte_type) {
1463 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1465 return new ByteConstant ((byte) v);
1467 if (target_type == TypeManager.sbyte_type) {
1468 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1470 return new SByteConstant ((sbyte) v);
1472 if (target_type == TypeManager.short_type) {
1473 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1475 return new ShortConstant ((short) v);
1477 if (target_type == TypeManager.int32_type)
1478 return new IntConstant ((int) v);
1479 if (target_type == TypeManager.uint32_type)
1480 return new UIntConstant ((uint) v);
1481 if (target_type == TypeManager.int64_type)
1482 return new LongConstant ((long) v);
1483 if (target_type == TypeManager.uint64_type)
1484 return new ULongConstant ((ulong) v);
1485 if (target_type == TypeManager.float_type)
1486 return new FloatConstant ((float) v);
1487 if (target_type == TypeManager.double_type)
1488 return new DoubleConstant ((double) v);
1489 if (target_type == TypeManager.char_type) {
1490 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1492 return new CharConstant ((char) v);
1494 if (target_type == TypeManager.decimal_type)
1495 return new DecimalConstant ((decimal) v);
1497 if (real_expr is IntConstant){
1498 int v = ((IntConstant) real_expr).Value;
1500 if (target_type == TypeManager.byte_type) {
1501 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1503 return new ByteConstant ((byte) v);
1505 if (target_type == TypeManager.sbyte_type) {
1506 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1508 return new SByteConstant ((sbyte) v);
1510 if (target_type == TypeManager.short_type) {
1511 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1513 return new ShortConstant ((short) v);
1515 if (target_type == TypeManager.ushort_type) {
1516 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1518 return new UShortConstant ((ushort) v);
1520 if (target_type == TypeManager.uint32_type) {
1521 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1523 return new UIntConstant ((uint) v);
1525 if (target_type == TypeManager.int64_type)
1526 return new LongConstant ((long) v);
1527 if (target_type == TypeManager.uint64_type) {
1528 if (!CheckUnsigned (ec, v, target_type))
1530 return new ULongConstant ((ulong) v);
1532 if (target_type == TypeManager.float_type)
1533 return new FloatConstant ((float) v);
1534 if (target_type == TypeManager.double_type)
1535 return new DoubleConstant ((double) v);
1536 if (target_type == TypeManager.char_type) {
1537 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1539 return new CharConstant ((char) v);
1541 if (target_type == TypeManager.decimal_type)
1542 return new DecimalConstant ((decimal) v);
1544 if (real_expr is UIntConstant){
1545 uint v = ((UIntConstant) real_expr).Value;
1547 if (target_type == TypeManager.byte_type) {
1548 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1550 return new ByteConstant ((byte) v);
1552 if (target_type == TypeManager.sbyte_type) {
1553 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1555 return new SByteConstant ((sbyte) v);
1557 if (target_type == TypeManager.short_type) {
1558 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1560 return new ShortConstant ((short) v);
1562 if (target_type == TypeManager.ushort_type) {
1563 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1565 return new UShortConstant ((ushort) v);
1567 if (target_type == TypeManager.int32_type) {
1568 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1570 return new IntConstant ((int) v);
1572 if (target_type == TypeManager.int64_type)
1573 return new LongConstant ((long) v);
1574 if (target_type == TypeManager.uint64_type)
1575 return new ULongConstant ((ulong) v);
1576 if (target_type == TypeManager.float_type)
1577 return new FloatConstant ((float) v);
1578 if (target_type == TypeManager.double_type)
1579 return new DoubleConstant ((double) v);
1580 if (target_type == TypeManager.char_type) {
1581 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1583 return new CharConstant ((char) v);
1585 if (target_type == TypeManager.decimal_type)
1586 return new DecimalConstant ((decimal) v);
1588 if (real_expr is LongConstant){
1589 long v = ((LongConstant) real_expr).Value;
1591 if (target_type == TypeManager.byte_type) {
1592 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1594 return new ByteConstant ((byte) v);
1596 if (target_type == TypeManager.sbyte_type) {
1597 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1599 return new SByteConstant ((sbyte) v);
1601 if (target_type == TypeManager.short_type) {
1602 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1604 return new ShortConstant ((short) v);
1606 if (target_type == TypeManager.ushort_type) {
1607 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1609 return new UShortConstant ((ushort) v);
1611 if (target_type == TypeManager.int32_type) {
1612 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1614 return new IntConstant ((int) v);
1616 if (target_type == TypeManager.uint32_type) {
1617 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1619 return new UIntConstant ((uint) v);
1621 if (target_type == TypeManager.uint64_type) {
1622 if (!CheckUnsigned (ec, v, target_type))
1624 return new ULongConstant ((ulong) v);
1626 if (target_type == TypeManager.float_type)
1627 return new FloatConstant ((float) v);
1628 if (target_type == TypeManager.double_type)
1629 return new DoubleConstant ((double) v);
1630 if (target_type == TypeManager.char_type) {
1631 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1633 return new CharConstant ((char) v);
1635 if (target_type == TypeManager.decimal_type)
1636 return new DecimalConstant ((decimal) v);
1638 if (real_expr is ULongConstant){
1639 ulong v = ((ULongConstant) real_expr).Value;
1641 if (target_type == TypeManager.byte_type) {
1642 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1644 return new ByteConstant ((byte) v);
1646 if (target_type == TypeManager.sbyte_type) {
1647 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1649 return new SByteConstant ((sbyte) v);
1651 if (target_type == TypeManager.short_type) {
1652 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1654 return new ShortConstant ((short) v);
1656 if (target_type == TypeManager.ushort_type) {
1657 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1659 return new UShortConstant ((ushort) v);
1661 if (target_type == TypeManager.int32_type) {
1662 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1664 return new IntConstant ((int) v);
1666 if (target_type == TypeManager.uint32_type) {
1667 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1669 return new UIntConstant ((uint) v);
1671 if (target_type == TypeManager.int64_type) {
1672 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1674 return new LongConstant ((long) v);
1676 if (target_type == TypeManager.float_type)
1677 return new FloatConstant ((float) v);
1678 if (target_type == TypeManager.double_type)
1679 return new DoubleConstant ((double) v);
1680 if (target_type == TypeManager.char_type) {
1681 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1683 return new CharConstant ((char) v);
1685 if (target_type == TypeManager.decimal_type)
1686 return new DecimalConstant ((decimal) v);
1688 if (real_expr is FloatConstant){
1689 float v = ((FloatConstant) real_expr).Value;
1691 if (target_type == TypeManager.byte_type)
1692 return new ByteConstant ((byte) v);
1693 if (target_type == TypeManager.sbyte_type)
1694 return new SByteConstant ((sbyte) v);
1695 if (target_type == TypeManager.short_type)
1696 return new ShortConstant ((short) v);
1697 if (target_type == TypeManager.ushort_type)
1698 return new UShortConstant ((ushort) v);
1699 if (target_type == TypeManager.int32_type)
1700 return new IntConstant ((int) v);
1701 if (target_type == TypeManager.uint32_type)
1702 return new UIntConstant ((uint) v);
1703 if (target_type == TypeManager.int64_type)
1704 return new LongConstant ((long) v);
1705 if (target_type == TypeManager.uint64_type)
1706 return new ULongConstant ((ulong) v);
1707 if (target_type == TypeManager.double_type)
1708 return new DoubleConstant ((double) v);
1709 if (target_type == TypeManager.char_type)
1710 return new CharConstant ((char) v);
1711 if (target_type == TypeManager.decimal_type)
1712 return new DecimalConstant ((decimal) v);
1714 if (real_expr is DoubleConstant){
1715 double v = ((DoubleConstant) real_expr).Value;
1717 if (target_type == TypeManager.byte_type){
1718 return new ByteConstant ((byte) v);
1719 } if (target_type == TypeManager.sbyte_type)
1720 return new SByteConstant ((sbyte) v);
1721 if (target_type == TypeManager.short_type)
1722 return new ShortConstant ((short) v);
1723 if (target_type == TypeManager.ushort_type)
1724 return new UShortConstant ((ushort) v);
1725 if (target_type == TypeManager.int32_type)
1726 return new IntConstant ((int) v);
1727 if (target_type == TypeManager.uint32_type)
1728 return new UIntConstant ((uint) v);
1729 if (target_type == TypeManager.int64_type)
1730 return new LongConstant ((long) v);
1731 if (target_type == TypeManager.uint64_type)
1732 return new ULongConstant ((ulong) v);
1733 if (target_type == TypeManager.float_type)
1734 return new FloatConstant ((float) v);
1735 if (target_type == TypeManager.char_type)
1736 return new CharConstant ((char) v);
1737 if (target_type == TypeManager.decimal_type)
1738 return new DecimalConstant ((decimal) v);
1741 if (real_expr is CharConstant){
1742 char v = ((CharConstant) real_expr).Value;
1744 if (target_type == TypeManager.byte_type) {
1745 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1747 return new ByteConstant ((byte) v);
1749 if (target_type == TypeManager.sbyte_type) {
1750 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1752 return new SByteConstant ((sbyte) v);
1754 if (target_type == TypeManager.short_type) {
1755 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1757 return new ShortConstant ((short) v);
1759 if (target_type == TypeManager.int32_type)
1760 return new IntConstant ((int) v);
1761 if (target_type == TypeManager.uint32_type)
1762 return new UIntConstant ((uint) v);
1763 if (target_type == TypeManager.int64_type)
1764 return new LongConstant ((long) v);
1765 if (target_type == TypeManager.uint64_type)
1766 return new ULongConstant ((ulong) v);
1767 if (target_type == TypeManager.float_type)
1768 return new FloatConstant ((float) v);
1769 if (target_type == TypeManager.double_type)
1770 return new DoubleConstant ((double) v);
1771 if (target_type == TypeManager.char_type) {
1772 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1774 return new CharConstant ((char) v);
1776 if (target_type == TypeManager.decimal_type)
1777 return new DecimalConstant ((decimal) v);
1783 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1785 expr = expr.DoResolveLValue (ec, right_side);
1789 return ResolveRest (ec);
1792 public override Expression DoResolve (EmitContext ec)
1794 expr = expr.Resolve (ec);
1798 return ResolveRest (ec);
1801 Expression ResolveRest (EmitContext ec)
1803 TypeExpr target = target_type.ResolveAsTypeTerminal (ec);
1809 CheckObsoleteAttribute (type);
1811 if (type.IsAbstract && type.IsSealed) {
1812 Report.Error (716, loc, "Cannot convert to static type '{0}'", TypeManager.CSharpName (type));
1816 eclass = ExprClass.Value;
1818 if (expr is Constant){
1819 Expression e = TryReduce (ec, type);
1825 if (type.IsPointer && !ec.InUnsafe) {
1829 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1833 public override void Emit (EmitContext ec)
1836 // This one will never happen
1838 throw new Exception ("Should not happen");
1843 /// Binary operators
1845 public class Binary : Expression {
1846 public enum Operator : byte {
1847 Multiply, Division, Modulus,
1848 Addition, Subtraction,
1849 LeftShift, RightShift,
1850 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1851 Equality, Inequality,
1861 Expression left, right;
1863 // This must be kept in sync with Operator!!!
1864 public static readonly string [] oper_names;
1868 oper_names = new string [(int) Operator.TOP];
1870 oper_names [(int) Operator.Multiply] = "op_Multiply";
1871 oper_names [(int) Operator.Division] = "op_Division";
1872 oper_names [(int) Operator.Modulus] = "op_Modulus";
1873 oper_names [(int) Operator.Addition] = "op_Addition";
1874 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1875 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1876 oper_names [(int) Operator.RightShift] = "op_RightShift";
1877 oper_names [(int) Operator.LessThan] = "op_LessThan";
1878 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1879 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1880 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1881 oper_names [(int) Operator.Equality] = "op_Equality";
1882 oper_names [(int) Operator.Inequality] = "op_Inequality";
1883 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1884 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1885 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1886 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1887 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1890 public Binary (Operator oper, Expression left, Expression right, Location loc)
1898 public Operator Oper {
1907 public Expression Left {
1916 public Expression Right {
1927 /// Returns a stringified representation of the Operator
1929 static string OperName (Operator oper)
1932 case Operator.Multiply:
1934 case Operator.Division:
1936 case Operator.Modulus:
1938 case Operator.Addition:
1940 case Operator.Subtraction:
1942 case Operator.LeftShift:
1944 case Operator.RightShift:
1946 case Operator.LessThan:
1948 case Operator.GreaterThan:
1950 case Operator.LessThanOrEqual:
1952 case Operator.GreaterThanOrEqual:
1954 case Operator.Equality:
1956 case Operator.Inequality:
1958 case Operator.BitwiseAnd:
1960 case Operator.BitwiseOr:
1962 case Operator.ExclusiveOr:
1964 case Operator.LogicalOr:
1966 case Operator.LogicalAnd:
1970 return oper.ToString ();
1973 public override string ToString ()
1975 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1976 right.ToString () + ")";
1979 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1981 if (expr.Type == target_type)
1984 return Convert.ImplicitConversion (ec, expr, target_type, loc);
1987 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1990 34, loc, "Operator `" + OperName (oper)
1991 + "' is ambiguous on operands of type `"
1992 + TypeManager.CSharpName (l) + "' "
1993 + "and `" + TypeManager.CSharpName (r)
1997 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
1999 if ((l == t) || (r == t))
2002 if (!check_user_conversions)
2005 if (Convert.ImplicitUserConversionExists (ec, l, t))
2007 else if (Convert.ImplicitUserConversionExists (ec, r, t))
2014 // Note that handling the case l == Decimal || r == Decimal
2015 // is taken care of by the Step 1 Operator Overload resolution.
2017 // If `check_user_conv' is true, we also check whether a user-defined conversion
2018 // exists. Note that we only need to do this if both arguments are of a user-defined
2019 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
2020 // so we don't explicitly check for performance reasons.
2022 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
2024 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
2026 // If either operand is of type double, the other operand is
2027 // conveted to type double.
2029 if (r != TypeManager.double_type)
2030 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
2031 if (l != TypeManager.double_type)
2032 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
2034 type = TypeManager.double_type;
2035 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
2037 // if either operand is of type float, the other operand is
2038 // converted to type float.
2040 if (r != TypeManager.double_type)
2041 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
2042 if (l != TypeManager.double_type)
2043 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
2044 type = TypeManager.float_type;
2045 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2049 // If either operand is of type ulong, the other operand is
2050 // converted to type ulong. or an error ocurrs if the other
2051 // operand is of type sbyte, short, int or long
2053 if (l == TypeManager.uint64_type){
2054 if (r != TypeManager.uint64_type){
2055 if (right is IntConstant){
2056 IntConstant ic = (IntConstant) right;
2058 e = Convert.TryImplicitIntConversion (l, ic);
2061 } else if (right is LongConstant){
2062 long ll = ((LongConstant) right).Value;
2065 right = new ULongConstant ((ulong) ll);
2067 e = Convert.ImplicitNumericConversion (ec, right, l, loc);
2074 if (left is IntConstant){
2075 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
2078 } else if (left is LongConstant){
2079 long ll = ((LongConstant) left).Value;
2082 left = new ULongConstant ((ulong) ll);
2084 e = Convert.ImplicitNumericConversion (ec, left, r, loc);
2091 if ((other == TypeManager.sbyte_type) ||
2092 (other == TypeManager.short_type) ||
2093 (other == TypeManager.int32_type) ||
2094 (other == TypeManager.int64_type))
2095 Error_OperatorAmbiguous (loc, oper, l, r);
2097 left = ForceConversion (ec, left, TypeManager.uint64_type);
2098 right = ForceConversion (ec, right, TypeManager.uint64_type);
2100 type = TypeManager.uint64_type;
2101 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2103 // If either operand is of type long, the other operand is converted
2106 if (l != TypeManager.int64_type)
2107 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
2108 if (r != TypeManager.int64_type)
2109 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
2111 type = TypeManager.int64_type;
2112 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2114 // If either operand is of type uint, and the other
2115 // operand is of type sbyte, short or int, othe operands are
2116 // converted to type long (unless we have an int constant).
2120 if (l == TypeManager.uint32_type){
2121 if (right is IntConstant){
2122 IntConstant ic = (IntConstant) right;
2126 right = new UIntConstant ((uint) val);
2133 } else if (r == TypeManager.uint32_type){
2134 if (left is IntConstant){
2135 IntConstant ic = (IntConstant) left;
2139 left = new UIntConstant ((uint) val);
2148 if ((other == TypeManager.sbyte_type) ||
2149 (other == TypeManager.short_type) ||
2150 (other == TypeManager.int32_type)){
2151 left = ForceConversion (ec, left, TypeManager.int64_type);
2152 right = ForceConversion (ec, right, TypeManager.int64_type);
2153 type = TypeManager.int64_type;
2156 // if either operand is of type uint, the other
2157 // operand is converd to type uint
2159 left = ForceConversion (ec, left, TypeManager.uint32_type);
2160 right = ForceConversion (ec, right, TypeManager.uint32_type);
2161 type = TypeManager.uint32_type;
2163 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2164 if (l != TypeManager.decimal_type)
2165 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
2167 if (r != TypeManager.decimal_type)
2168 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
2169 type = TypeManager.decimal_type;
2171 left = ForceConversion (ec, left, TypeManager.int32_type);
2172 right = ForceConversion (ec, right, TypeManager.int32_type);
2174 type = TypeManager.int32_type;
2177 return (left != null) && (right != null);
2180 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2182 Report.Error (19, loc,
2183 "Operator " + name + " cannot be applied to operands of type `" +
2184 TypeManager.CSharpName (l) + "' and `" +
2185 TypeManager.CSharpName (r) + "'");
2188 void Error_OperatorCannotBeApplied ()
2190 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2193 static bool is_unsigned (Type t)
2195 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2196 t == TypeManager.short_type || t == TypeManager.byte_type);
2199 static bool is_user_defined (Type t)
2201 if (t.IsSubclassOf (TypeManager.value_type) &&
2202 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2208 Expression Make32or64 (EmitContext ec, Expression e)
2212 if (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2213 t == TypeManager.int64_type || t == TypeManager.uint64_type)
2215 Expression ee = Convert.ImplicitConversion (ec, e, TypeManager.int32_type, loc);
2218 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint32_type, loc);
2221 ee = Convert.ImplicitConversion (ec, e, TypeManager.int64_type, loc);
2224 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint64_type, loc);
2230 Expression CheckShiftArguments (EmitContext ec)
2234 e = ForceConversion (ec, right, TypeManager.int32_type);
2236 Error_OperatorCannotBeApplied ();
2241 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
2242 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
2243 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
2244 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
2248 if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
2249 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (31), loc);
2250 right = right.DoResolve (ec);
2252 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (63), loc);
2253 right = right.DoResolve (ec);
2258 Error_OperatorCannotBeApplied ();
2262 Expression ResolveOperator (EmitContext ec)
2265 Type r = right.Type;
2268 // Special cases: string or type parameter comapred to null
2270 if (oper == Operator.Equality || oper == Operator.Inequality){
2271 if ((!TypeManager.IsValueType (l) && r == TypeManager.null_type) ||
2272 (!TypeManager.IsValueType (r) && l == TypeManager.null_type)) {
2273 Type = TypeManager.bool_type;
2278 if (l.IsGenericParameter && (right is NullLiteral)) {
2279 if (l.BaseType == TypeManager.value_type) {
2280 Error_OperatorCannotBeApplied ();
2284 left = new BoxedCast (left);
2285 Type = TypeManager.bool_type;
2289 if (r.IsGenericParameter && (left is NullLiteral)) {
2290 if (r.BaseType == TypeManager.value_type) {
2291 Error_OperatorCannotBeApplied ();
2295 right = new BoxedCast (right);
2296 Type = TypeManager.bool_type;
2301 if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
2302 Type = TypeManager.bool_type;
2309 // Do not perform operator overload resolution when both sides are
2312 if (!(TypeManager.IsPrimitiveType (l) && TypeManager.IsPrimitiveType (r))){
2314 // Step 1: Perform Operator Overload location
2316 Expression left_expr, right_expr;
2318 string op = oper_names [(int) oper];
2320 MethodGroupExpr union;
2321 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2323 right_expr = MemberLookup (
2324 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2325 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2327 union = (MethodGroupExpr) left_expr;
2329 if (union != null) {
2330 ArrayList args = new ArrayList (2);
2331 args.Add (new Argument (left, Argument.AType.Expression));
2332 args.Add (new Argument (right, Argument.AType.Expression));
2334 MethodBase method = Invocation.OverloadResolve (
2335 ec, union, args, true, Location.Null);
2337 if (method != null) {
2338 MethodInfo mi = (MethodInfo) method;
2340 return new BinaryMethod (mi.ReturnType, method, args);
2346 // Step 0: String concatenation (because overloading will get this wrong)
2348 if (oper == Operator.Addition){
2350 // If any of the arguments is a string, cast to string
2353 // Simple constant folding
2354 if (left is StringConstant && right is StringConstant)
2355 return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value);
2357 if (l == TypeManager.string_type || r == TypeManager.string_type) {
2359 if (r == TypeManager.void_type || l == TypeManager.void_type) {
2360 Error_OperatorCannotBeApplied ();
2364 // try to fold it in on the left
2365 if (left is StringConcat) {
2368 // We have to test here for not-null, since we can be doubly-resolved
2369 // take care of not appending twice
2372 type = TypeManager.string_type;
2373 ((StringConcat) left).Append (ec, right);
2374 return left.Resolve (ec);
2380 // Otherwise, start a new concat expression
2381 return new StringConcat (ec, loc, left, right).Resolve (ec);
2385 // Transform a + ( - b) into a - b
2387 if (right is Unary){
2388 Unary right_unary = (Unary) right;
2390 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2391 oper = Operator.Subtraction;
2392 right = right_unary.Expr;
2398 if (oper == Operator.Equality || oper == Operator.Inequality){
2399 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2400 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2401 Error_OperatorCannotBeApplied ();
2405 type = TypeManager.bool_type;
2409 bool left_is_null = left is NullLiteral;
2410 bool right_is_null = right is NullLiteral;
2411 if (left_is_null || right_is_null) {
2412 if (oper == Operator.Equality)
2413 return new BoolLiteral (left_is_null == right_is_null);
2415 return new BoolLiteral (left_is_null != right_is_null);
2419 // operator != (object a, object b)
2420 // operator == (object a, object b)
2422 // For this to be used, both arguments have to be reference-types.
2423 // Read the rationale on the spec (14.9.6)
2425 // Also, if at compile time we know that the classes do not inherit
2426 // one from the other, then we catch the error there.
2428 if (!(l.IsValueType || r.IsValueType)){
2429 type = TypeManager.bool_type;
2434 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2438 // Also, a standard conversion must exist from either one
2440 if (!(Convert.ImplicitStandardConversionExists (ec, left, r) ||
2441 Convert.ImplicitStandardConversionExists (ec, right, l))){
2442 Error_OperatorCannotBeApplied ();
2446 // We are going to have to convert to an object to compare
2448 if (l != TypeManager.object_type)
2449 left = new EmptyCast (left, TypeManager.object_type);
2450 if (r != TypeManager.object_type)
2451 right = new EmptyCast (right, TypeManager.object_type);
2454 // FIXME: CSC here catches errors cs254 and cs252
2460 // One of them is a valuetype, but the other one is not.
2462 if (!l.IsValueType || !r.IsValueType) {
2463 Error_OperatorCannotBeApplied ();
2468 // Only perform numeric promotions on:
2469 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2471 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2472 if (TypeManager.IsDelegateType (l)){
2473 if (((right.eclass == ExprClass.MethodGroup) ||
2474 (r == TypeManager.anonymous_method_type))){
2475 if ((RootContext.Version != LanguageVersion.ISO_1)){
2476 Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2484 if (TypeManager.IsDelegateType (r)){
2486 ArrayList args = new ArrayList (2);
2488 args = new ArrayList (2);
2489 args.Add (new Argument (left, Argument.AType.Expression));
2490 args.Add (new Argument (right, Argument.AType.Expression));
2492 if (oper == Operator.Addition)
2493 method = TypeManager.delegate_combine_delegate_delegate;
2495 method = TypeManager.delegate_remove_delegate_delegate;
2497 if (!TypeManager.IsEqual (l, r)) {
2498 Error_OperatorCannotBeApplied ();
2502 return new BinaryDelegate (l, method, args);
2507 // Pointer arithmetic:
2509 // T* operator + (T* x, int y);
2510 // T* operator + (T* x, uint y);
2511 // T* operator + (T* x, long y);
2512 // T* operator + (T* x, ulong y);
2514 // T* operator + (int y, T* x);
2515 // T* operator + (uint y, T *x);
2516 // T* operator + (long y, T *x);
2517 // T* operator + (ulong y, T *x);
2519 // T* operator - (T* x, int y);
2520 // T* operator - (T* x, uint y);
2521 // T* operator - (T* x, long y);
2522 // T* operator - (T* x, ulong y);
2524 // long operator - (T* x, T *y)
2527 if (r.IsPointer && oper == Operator.Subtraction){
2529 return new PointerArithmetic (
2530 false, left, right, TypeManager.int64_type,
2533 Expression t = Make32or64 (ec, right);
2535 return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc).Resolve (ec);
2537 } else if (r.IsPointer && oper == Operator.Addition){
2538 Expression t = Make32or64 (ec, left);
2540 return new PointerArithmetic (true, right, t, r, loc).Resolve (ec);
2545 // Enumeration operators
2547 bool lie = TypeManager.IsEnumType (l);
2548 bool rie = TypeManager.IsEnumType (r);
2552 // U operator - (E e, E f)
2554 if (oper == Operator.Subtraction){
2556 type = TypeManager.EnumToUnderlying (l);
2559 Error_OperatorCannotBeApplied ();
2565 // operator + (E e, U x)
2566 // operator - (E e, U x)
2568 if (oper == Operator.Addition || oper == Operator.Subtraction){
2569 Type enum_type = lie ? l : r;
2570 Type other_type = lie ? r : l;
2571 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2573 if (underlying_type != other_type){
2574 temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
2584 Error_OperatorCannotBeApplied ();
2593 temp = Convert.ImplicitConversion (ec, right, l, loc);
2597 Error_OperatorCannotBeApplied ();
2601 temp = Convert.ImplicitConversion (ec, left, r, loc);
2606 Error_OperatorCannotBeApplied ();
2611 if (oper == Operator.Equality || oper == Operator.Inequality ||
2612 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2613 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2614 if (left.Type != right.Type){
2615 Error_OperatorCannotBeApplied ();
2618 type = TypeManager.bool_type;
2622 if (oper == Operator.BitwiseAnd ||
2623 oper == Operator.BitwiseOr ||
2624 oper == Operator.ExclusiveOr){
2625 if (left.Type != right.Type){
2626 Error_OperatorCannotBeApplied ();
2632 Error_OperatorCannotBeApplied ();
2636 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2637 return CheckShiftArguments (ec);
2639 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2640 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2641 type = TypeManager.bool_type;
2646 Error_OperatorCannotBeApplied ();
2650 Expression e = new ConditionalLogicalOperator (
2651 oper == Operator.LogicalAnd, left, right, l, loc);
2652 return e.Resolve (ec);
2656 // operator & (bool x, bool y)
2657 // operator | (bool x, bool y)
2658 // operator ^ (bool x, bool y)
2660 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2661 if (oper == Operator.BitwiseAnd ||
2662 oper == Operator.BitwiseOr ||
2663 oper == Operator.ExclusiveOr){
2670 // Pointer comparison
2672 if (l.IsPointer && r.IsPointer){
2673 if (oper == Operator.Equality || oper == Operator.Inequality ||
2674 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2675 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2676 type = TypeManager.bool_type;
2682 // This will leave left or right set to null if there is an error
2684 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2685 DoNumericPromotions (ec, l, r, check_user_conv);
2686 if (left == null || right == null){
2687 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2692 // reload our cached types if required
2697 if (oper == Operator.BitwiseAnd ||
2698 oper == Operator.BitwiseOr ||
2699 oper == Operator.ExclusiveOr){
2701 if (((l == TypeManager.int32_type) ||
2702 (l == TypeManager.uint32_type) ||
2703 (l == TypeManager.short_type) ||
2704 (l == TypeManager.ushort_type) ||
2705 (l == TypeManager.int64_type) ||
2706 (l == TypeManager.uint64_type))){
2709 Error_OperatorCannotBeApplied ();
2713 Error_OperatorCannotBeApplied ();
2718 if (oper == Operator.Equality ||
2719 oper == Operator.Inequality ||
2720 oper == Operator.LessThanOrEqual ||
2721 oper == Operator.LessThan ||
2722 oper == Operator.GreaterThanOrEqual ||
2723 oper == Operator.GreaterThan){
2724 type = TypeManager.bool_type;
2730 public override Expression DoResolve (EmitContext ec)
2732 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2733 left = ((ParenthesizedExpression) left).Expr;
2734 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2738 if (left.eclass == ExprClass.Type) {
2739 Error (75, "Casting a negative value needs to have the value in parentheses.");
2743 left = left.Resolve (ec);
2748 Constant lc = left as Constant;
2749 if (lc != null && lc.Type == TypeManager.bool_type &&
2750 ((oper == Operator.LogicalAnd && (bool)lc.GetValue () == false) ||
2751 (oper == Operator.LogicalOr && (bool)lc.GetValue () == true))) {
2753 // TODO: make a sense to resolve unreachable expression as we do for statement
2754 Report.Warning (429, 4, loc, "Unreachable expression code detected");
2758 right = right.Resolve (ec);
2762 eclass = ExprClass.Value;
2764 Constant rc = right as Constant;
2765 if (rc != null & lc != null){
2766 Expression e = ConstantFold.BinaryFold (
2767 ec, oper, lc, rc, loc);
2772 if (TypeManager.IsNullableType (left.Type) || TypeManager.IsNullableType (right.Type))
2773 return new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
2775 return ResolveOperator (ec);
2779 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2780 /// context of a conditional bool expression. This function will return
2781 /// false if it is was possible to use EmitBranchable, or true if it was.
2783 /// The expression's code is generated, and we will generate a branch to `target'
2784 /// if the resulting expression value is equal to isTrue
2786 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2788 ILGenerator ig = ec.ig;
2791 // This is more complicated than it looks, but its just to avoid
2792 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2793 // but on top of that we want for == and != to use a special path
2794 // if we are comparing against null
2796 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
2797 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2800 // put the constant on the rhs, for simplicity
2802 if (left is Constant) {
2803 Expression swap = right;
2808 if (((Constant) right).IsZeroInteger) {
2811 ig.Emit (OpCodes.Brtrue, target);
2813 ig.Emit (OpCodes.Brfalse, target);
2816 } else if (right is BoolConstant){
2818 if (my_on_true != ((BoolConstant) right).Value)
2819 ig.Emit (OpCodes.Brtrue, target);
2821 ig.Emit (OpCodes.Brfalse, target);
2826 } else if (oper == Operator.LogicalAnd) {
2829 Label tests_end = ig.DefineLabel ();
2831 left.EmitBranchable (ec, tests_end, false);
2832 right.EmitBranchable (ec, target, true);
2833 ig.MarkLabel (tests_end);
2835 left.EmitBranchable (ec, target, false);
2836 right.EmitBranchable (ec, target, false);
2841 } else if (oper == Operator.LogicalOr){
2843 left.EmitBranchable (ec, target, true);
2844 right.EmitBranchable (ec, target, true);
2847 Label tests_end = ig.DefineLabel ();
2848 left.EmitBranchable (ec, tests_end, true);
2849 right.EmitBranchable (ec, target, false);
2850 ig.MarkLabel (tests_end);
2855 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2856 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2857 oper == Operator.Equality || oper == Operator.Inequality)) {
2858 base.EmitBranchable (ec, target, onTrue);
2866 bool isUnsigned = is_unsigned (t) || t == TypeManager.double_type || t == TypeManager.float_type;
2869 case Operator.Equality:
2871 ig.Emit (OpCodes.Beq, target);
2873 ig.Emit (OpCodes.Bne_Un, target);
2876 case Operator.Inequality:
2878 ig.Emit (OpCodes.Bne_Un, target);
2880 ig.Emit (OpCodes.Beq, target);
2883 case Operator.LessThan:
2886 ig.Emit (OpCodes.Blt_Un, target);
2888 ig.Emit (OpCodes.Blt, target);
2891 ig.Emit (OpCodes.Bge_Un, target);
2893 ig.Emit (OpCodes.Bge, target);
2896 case Operator.GreaterThan:
2899 ig.Emit (OpCodes.Bgt_Un, target);
2901 ig.Emit (OpCodes.Bgt, target);
2904 ig.Emit (OpCodes.Ble_Un, target);
2906 ig.Emit (OpCodes.Ble, target);
2909 case Operator.LessThanOrEqual:
2912 ig.Emit (OpCodes.Ble_Un, target);
2914 ig.Emit (OpCodes.Ble, target);
2917 ig.Emit (OpCodes.Bgt_Un, target);
2919 ig.Emit (OpCodes.Bgt, target);
2923 case Operator.GreaterThanOrEqual:
2926 ig.Emit (OpCodes.Bge_Un, target);
2928 ig.Emit (OpCodes.Bge, target);
2931 ig.Emit (OpCodes.Blt_Un, target);
2933 ig.Emit (OpCodes.Blt, target);
2936 Console.WriteLine (oper);
2937 throw new Exception ("what is THAT");
2941 public override void Emit (EmitContext ec)
2943 ILGenerator ig = ec.ig;
2948 // Handle short-circuit operators differently
2951 if (oper == Operator.LogicalAnd) {
2952 Label load_zero = ig.DefineLabel ();
2953 Label end = ig.DefineLabel ();
2955 left.EmitBranchable (ec, load_zero, false);
2957 ig.Emit (OpCodes.Br, end);
2959 ig.MarkLabel (load_zero);
2960 ig.Emit (OpCodes.Ldc_I4_0);
2963 } else if (oper == Operator.LogicalOr) {
2964 Label load_one = ig.DefineLabel ();
2965 Label end = ig.DefineLabel ();
2967 left.EmitBranchable (ec, load_one, true);
2969 ig.Emit (OpCodes.Br, end);
2971 ig.MarkLabel (load_one);
2972 ig.Emit (OpCodes.Ldc_I4_1);
2980 bool isUnsigned = is_unsigned (left.Type);
2983 case Operator.Multiply:
2985 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2986 opcode = OpCodes.Mul_Ovf;
2987 else if (isUnsigned)
2988 opcode = OpCodes.Mul_Ovf_Un;
2990 opcode = OpCodes.Mul;
2992 opcode = OpCodes.Mul;
2996 case Operator.Division:
2998 opcode = OpCodes.Div_Un;
3000 opcode = OpCodes.Div;
3003 case Operator.Modulus:
3005 opcode = OpCodes.Rem_Un;
3007 opcode = OpCodes.Rem;
3010 case Operator.Addition:
3012 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3013 opcode = OpCodes.Add_Ovf;
3014 else if (isUnsigned)
3015 opcode = OpCodes.Add_Ovf_Un;
3017 opcode = OpCodes.Add;
3019 opcode = OpCodes.Add;
3022 case Operator.Subtraction:
3024 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3025 opcode = OpCodes.Sub_Ovf;
3026 else if (isUnsigned)
3027 opcode = OpCodes.Sub_Ovf_Un;
3029 opcode = OpCodes.Sub;
3031 opcode = OpCodes.Sub;
3034 case Operator.RightShift:
3036 opcode = OpCodes.Shr_Un;
3038 opcode = OpCodes.Shr;
3041 case Operator.LeftShift:
3042 opcode = OpCodes.Shl;
3045 case Operator.Equality:
3046 opcode = OpCodes.Ceq;
3049 case Operator.Inequality:
3050 ig.Emit (OpCodes.Ceq);
3051 ig.Emit (OpCodes.Ldc_I4_0);
3053 opcode = OpCodes.Ceq;
3056 case Operator.LessThan:
3058 opcode = OpCodes.Clt_Un;
3060 opcode = OpCodes.Clt;
3063 case Operator.GreaterThan:
3065 opcode = OpCodes.Cgt_Un;
3067 opcode = OpCodes.Cgt;
3070 case Operator.LessThanOrEqual:
3071 Type lt = left.Type;
3073 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
3074 ig.Emit (OpCodes.Cgt_Un);
3076 ig.Emit (OpCodes.Cgt);
3077 ig.Emit (OpCodes.Ldc_I4_0);
3079 opcode = OpCodes.Ceq;
3082 case Operator.GreaterThanOrEqual:
3083 Type le = left.Type;
3085 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3086 ig.Emit (OpCodes.Clt_Un);
3088 ig.Emit (OpCodes.Clt);
3090 ig.Emit (OpCodes.Ldc_I4_0);
3092 opcode = OpCodes.Ceq;
3095 case Operator.BitwiseOr:
3096 opcode = OpCodes.Or;
3099 case Operator.BitwiseAnd:
3100 opcode = OpCodes.And;
3103 case Operator.ExclusiveOr:
3104 opcode = OpCodes.Xor;
3108 throw new Exception ("This should not happen: Operator = "
3109 + oper.ToString ());
3117 // Object created by Binary when the binary operator uses an method instead of being
3118 // a binary operation that maps to a CIL binary operation.
3120 public class BinaryMethod : Expression {
3121 public MethodBase method;
3122 public ArrayList Arguments;
3124 public BinaryMethod (Type t, MethodBase m, ArrayList args)
3129 eclass = ExprClass.Value;
3132 public override Expression DoResolve (EmitContext ec)
3137 public override void Emit (EmitContext ec)
3139 ILGenerator ig = ec.ig;
3141 if (Arguments != null)
3142 Invocation.EmitArguments (ec, method, Arguments, false, null);
3144 if (method is MethodInfo)
3145 ig.Emit (OpCodes.Call, (MethodInfo) method);
3147 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3152 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3153 // b, c, d... may be strings or objects.
3155 public class StringConcat : Expression {
3157 bool invalid = false;
3158 bool emit_conv_done = false;
3160 // Are we also concating objects?
3162 bool is_strings_only = true;
3164 public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
3167 type = TypeManager.string_type;
3168 eclass = ExprClass.Value;
3170 operands = new ArrayList (2);
3175 public override Expression DoResolve (EmitContext ec)
3183 public void Append (EmitContext ec, Expression operand)
3188 if (operand is StringConstant && operands.Count != 0) {
3189 StringConstant last_operand = operands [operands.Count - 1] as StringConstant;
3190 if (last_operand != null) {
3191 operands [operands.Count - 1] = new StringConstant (last_operand.Value + ((StringConstant) operand).Value);
3197 // Conversion to object
3199 if (operand.Type != TypeManager.string_type) {
3200 Expression no = Convert.ImplicitConversion (ec, operand, TypeManager.object_type, loc);
3203 Binary.Error_OperatorCannotBeApplied (loc, "+", TypeManager.string_type, operand.Type);
3209 operands.Add (operand);
3212 public override void Emit (EmitContext ec)
3214 MethodInfo concat_method = null;
3217 // Do conversion to arguments; check for strings only
3220 // This can get called multiple times, so we have to deal with that.
3221 if (!emit_conv_done) {
3222 emit_conv_done = true;
3223 for (int i = 0; i < operands.Count; i ++) {
3224 Expression e = (Expression) operands [i];
3225 is_strings_only &= e.Type == TypeManager.string_type;
3228 for (int i = 0; i < operands.Count; i ++) {
3229 Expression e = (Expression) operands [i];
3231 if (! is_strings_only && e.Type == TypeManager.string_type) {
3232 // need to make sure this is an object, because the EmitParams
3233 // method might look at the type of this expression, see it is a
3234 // string and emit a string [] when we want an object [];
3236 e = new EmptyCast (e, TypeManager.object_type);
3238 operands [i] = new Argument (e, Argument.AType.Expression);
3243 // Find the right method
3245 switch (operands.Count) {
3248 // This should not be possible, because simple constant folding
3249 // is taken care of in the Binary code.
3251 throw new Exception ("how did you get here?");
3254 concat_method = is_strings_only ?
3255 TypeManager.string_concat_string_string :
3256 TypeManager.string_concat_object_object ;
3259 concat_method = is_strings_only ?
3260 TypeManager.string_concat_string_string_string :
3261 TypeManager.string_concat_object_object_object ;
3265 // There is not a 4 param overlaod for object (the one that there is
3266 // is actually a varargs methods, and is only in corlib because it was
3267 // introduced there before.).
3269 if (!is_strings_only)
3272 concat_method = TypeManager.string_concat_string_string_string_string;
3275 concat_method = is_strings_only ?
3276 TypeManager.string_concat_string_dot_dot_dot :
3277 TypeManager.string_concat_object_dot_dot_dot ;
3281 Invocation.EmitArguments (ec, concat_method, operands, false, null);
3282 ec.ig.Emit (OpCodes.Call, concat_method);
3287 // Object created with +/= on delegates
3289 public class BinaryDelegate : Expression {
3293 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3298 eclass = ExprClass.Value;
3301 public override Expression DoResolve (EmitContext ec)
3306 public override void Emit (EmitContext ec)
3308 ILGenerator ig = ec.ig;
3310 Invocation.EmitArguments (ec, method, args, false, null);
3312 ig.Emit (OpCodes.Call, (MethodInfo) method);
3313 ig.Emit (OpCodes.Castclass, type);
3316 public Expression Right {
3318 Argument arg = (Argument) args [1];
3323 public bool IsAddition {
3325 return method == TypeManager.delegate_combine_delegate_delegate;
3331 // User-defined conditional logical operator
3332 public class ConditionalLogicalOperator : Expression {
3333 Expression left, right;
3336 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3339 eclass = ExprClass.Value;
3343 this.is_and = is_and;
3346 protected void Error19 ()
3348 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3351 protected void Error218 ()
3353 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3354 "declarations of operator true and operator false");
3357 Expression op_true, op_false, op;
3358 LocalTemporary left_temp;
3360 public override Expression DoResolve (EmitContext ec)
3363 Expression operator_group;
3365 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3366 if (operator_group == null) {
3371 left_temp = new LocalTemporary (ec, type);
3373 ArrayList arguments = new ArrayList ();
3374 arguments.Add (new Argument (left_temp, Argument.AType.Expression));
3375 arguments.Add (new Argument (right, Argument.AType.Expression));
3376 method = Invocation.OverloadResolve (
3377 ec, (MethodGroupExpr) operator_group, arguments, false, loc)
3379 if (method == null) {
3384 if (method.ReturnType != type) {
3385 Report.Error (217, loc, "In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') " +
3386 "must have the same return type as the type of its 2 parameters", TypeManager.CSharpSignature (method));
3390 op = new StaticCallExpr (method, arguments, loc);
3392 op_true = GetOperatorTrue (ec, left_temp, loc);
3393 op_false = GetOperatorFalse (ec, left_temp, loc);
3394 if ((op_true == null) || (op_false == null)) {
3402 public override void Emit (EmitContext ec)
3404 ILGenerator ig = ec.ig;
3405 Label false_target = ig.DefineLabel ();
3406 Label end_target = ig.DefineLabel ();
3409 left_temp.Store (ec);
3411 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
3412 left_temp.Emit (ec);
3413 ig.Emit (OpCodes.Br, end_target);
3414 ig.MarkLabel (false_target);
3416 ig.MarkLabel (end_target);
3420 public class PointerArithmetic : Expression {
3421 Expression left, right;
3425 // We assume that `l' is always a pointer
3427 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3433 is_add = is_addition;
3436 public override Expression DoResolve (EmitContext ec)
3438 eclass = ExprClass.Variable;
3440 if (left.Type == TypeManager.void_ptr_type) {
3441 Error (242, "The operation in question is undefined on void pointers");
3448 public override void Emit (EmitContext ec)
3450 Type op_type = left.Type;
3451 ILGenerator ig = ec.ig;
3453 // It must be either array or fixed buffer
3454 Type element = TypeManager.HasElementType (op_type) ?
3455 element = TypeManager.GetElementType (op_type) :
3456 element = AttributeTester.GetFixedBuffer (((FieldExpr)left).FieldInfo).ElementType;
3458 int size = GetTypeSize (element);
3459 Type rtype = right.Type;
3461 if (rtype.IsPointer){
3463 // handle (pointer - pointer)
3467 ig.Emit (OpCodes.Sub);
3471 ig.Emit (OpCodes.Sizeof, element);
3473 IntLiteral.EmitInt (ig, size);
3474 ig.Emit (OpCodes.Div);
3476 ig.Emit (OpCodes.Conv_I8);
3479 // handle + and - on (pointer op int)
3482 ig.Emit (OpCodes.Conv_I);
3484 Constant right_const = right as Constant;
3485 if (right_const != null && size != 0) {
3486 Expression ex = ConstantFold.BinaryFold (ec, Binary.Operator.Multiply, new IntConstant (size), right_const, loc);
3494 ig.Emit (OpCodes.Sizeof, element);
3496 IntLiteral.EmitInt (ig, size);
3497 if (rtype == TypeManager.int64_type)
3498 ig.Emit (OpCodes.Conv_I8);
3499 else if (rtype == TypeManager.uint64_type)
3500 ig.Emit (OpCodes.Conv_U8);
3501 ig.Emit (OpCodes.Mul);
3505 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
3506 ig.Emit (OpCodes.Conv_I);
3509 ig.Emit (OpCodes.Add);
3511 ig.Emit (OpCodes.Sub);
3517 /// Implements the ternary conditional operator (?:)
3519 public class Conditional : Expression {
3520 Expression expr, trueExpr, falseExpr;
3522 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3525 this.trueExpr = trueExpr;
3526 this.falseExpr = falseExpr;
3530 public Expression Expr {
3536 public Expression TrueExpr {
3542 public Expression FalseExpr {
3548 public override Expression DoResolve (EmitContext ec)
3550 expr = expr.Resolve (ec);
3555 if (TypeManager.IsNullableType (expr.Type))
3556 return new Nullable.LiftedConditional (expr, trueExpr, falseExpr, loc).Resolve (ec);
3558 if (expr.Type != TypeManager.bool_type){
3559 expr = Expression.ResolveBoolean (
3566 trueExpr = trueExpr.Resolve (ec);
3567 falseExpr = falseExpr.Resolve (ec);
3569 if (trueExpr == null || falseExpr == null)
3572 eclass = ExprClass.Value;
3573 if (trueExpr.Type == falseExpr.Type)
3574 type = trueExpr.Type;
3577 Type true_type = trueExpr.Type;
3578 Type false_type = falseExpr.Type;
3581 // First, if an implicit conversion exists from trueExpr
3582 // to falseExpr, then the result type is of type falseExpr.Type
3584 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3587 // Check if both can convert implicitl to each other's type
3589 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3591 "Can not compute type of conditional expression " +
3592 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3593 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3594 "' convert implicitly to each other");
3599 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3603 Error (173, "The type of the conditional expression can " +
3604 "not be computed because there is no implicit conversion" +
3605 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3606 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3611 // Dead code optimalization
3612 if (expr is BoolConstant){
3613 BoolConstant bc = (BoolConstant) expr;
3615 Report.Warning (429, 4, bc.Value ? falseExpr.Location : trueExpr.Location, "Unreachable expression code detected");
3616 return bc.Value ? trueExpr : falseExpr;
3622 public override void Emit (EmitContext ec)
3624 ILGenerator ig = ec.ig;
3625 Label false_target = ig.DefineLabel ();
3626 Label end_target = ig.DefineLabel ();
3628 expr.EmitBranchable (ec, false_target, false);
3630 ig.Emit (OpCodes.Br, end_target);
3631 ig.MarkLabel (false_target);
3632 falseExpr.Emit (ec);
3633 ig.MarkLabel (end_target);
3641 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3642 public readonly string Name;
3643 public readonly Block Block;
3644 public LocalInfo local_info;
3647 LocalTemporary temp;
3649 public LocalVariableReference (Block block, string name, Location l)
3654 eclass = ExprClass.Variable;
3658 // Setting `is_readonly' to false will allow you to create a writable
3659 // reference to a read-only variable. This is used by foreach and using.
3661 public LocalVariableReference (Block block, string name, Location l,
3662 LocalInfo local_info, bool is_readonly)
3663 : this (block, name, l)
3665 this.local_info = local_info;
3666 this.is_readonly = is_readonly;
3669 public VariableInfo VariableInfo {
3671 return local_info.VariableInfo;
3675 public bool IsReadOnly {
3681 protected Expression DoResolveBase (EmitContext ec, Expression lvalue_right_side)
3683 if (local_info == null) {
3684 local_info = Block.GetLocalInfo (Name);
3687 if (lvalue_right_side == EmptyExpression.Null)
3688 local_info.Used = true;
3690 is_readonly = local_info.ReadOnly;
3693 type = local_info.VariableType;
3695 VariableInfo variable_info = local_info.VariableInfo;
3696 if (lvalue_right_side != null){
3698 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3702 if (variable_info != null)
3703 variable_info.SetAssigned (ec);
3706 Expression e = Block.GetConstantExpression (Name);
3708 local_info.Used = true;
3709 eclass = ExprClass.Value;
3710 return e.Resolve (ec);
3713 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3716 if (lvalue_right_side == null)
3717 local_info.Used = true;
3719 if (ec.CurrentAnonymousMethod != null){
3721 // If we are referencing a variable from the external block
3722 // flag it for capturing
3724 if (local_info.Block.Toplevel != ec.CurrentBlock.Toplevel){
3725 if (local_info.AddressTaken){
3726 AnonymousMethod.Error_AddressOfCapturedVar (local_info.Name, loc);
3729 ec.CaptureVariable (local_info);
3736 public override Expression DoResolve (EmitContext ec)
3738 return DoResolveBase (ec, null);
3741 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3743 Expression ret = DoResolveBase (ec, right_side);
3745 CheckObsoleteAttribute (ret.Type);
3750 public bool VerifyFixed (bool is_expression)
3752 return !is_expression || local_info.IsFixed;
3755 public override int GetHashCode()
3757 return Name.GetHashCode ();
3760 public override bool Equals (object obj)
3762 LocalVariableReference lvr = obj as LocalVariableReference;
3766 return Name == lvr.Name && Block == lvr.Block;
3769 public override void Emit (EmitContext ec)
3771 ILGenerator ig = ec.ig;
3773 if (local_info.FieldBuilder == null){
3775 // A local variable on the local CLR stack
3777 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3780 // A local variable captured by anonymous methods.
3783 ec.EmitCapturedVariableInstance (local_info);
3785 ig.Emit (OpCodes.Ldfld, local_info.FieldBuilder);
3789 public void Emit (EmitContext ec, bool leave_copy)
3793 ec.ig.Emit (OpCodes.Dup);
3794 if (local_info.FieldBuilder != null){
3795 temp = new LocalTemporary (ec, Type);
3801 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3803 ILGenerator ig = ec.ig;
3804 prepared = prepare_for_load;
3806 if (local_info.FieldBuilder == null){
3808 // A local variable on the local CLR stack
3810 if (local_info.LocalBuilder == null)
3811 throw new Exception ("This should not happen: both Field and Local are null");
3815 ec.ig.Emit (OpCodes.Dup);
3816 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3819 // A local variable captured by anonymous methods or itereators.
3821 ec.EmitCapturedVariableInstance (local_info);
3823 if (prepare_for_load)
3824 ig.Emit (OpCodes.Dup);
3827 ig.Emit (OpCodes.Dup);
3828 temp = new LocalTemporary (ec, Type);
3831 ig.Emit (OpCodes.Stfld, local_info.FieldBuilder);
3837 public void AddressOf (EmitContext ec, AddressOp mode)
3839 ILGenerator ig = ec.ig;
3841 if (local_info.FieldBuilder == null){
3843 // A local variable on the local CLR stack
3845 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3848 // A local variable captured by anonymous methods or iterators
3850 ec.EmitCapturedVariableInstance (local_info);
3851 ig.Emit (OpCodes.Ldflda, local_info.FieldBuilder);
3855 public override string ToString ()
3857 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3862 /// This represents a reference to a parameter in the intermediate
3865 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3871 public Parameter.Modifier mod;
3872 public bool is_ref, is_out, prepared;
3886 LocalTemporary temp;
3888 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3895 eclass = ExprClass.Variable;
3898 public VariableInfo VariableInfo {
3902 public bool VerifyFixed (bool is_expression)
3904 return !is_expression || TypeManager.IsValueType (type);
3907 public bool IsAssigned (EmitContext ec, Location loc)
3909 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsAssigned (vi))
3912 Report.Error (269, loc,
3913 "Use of unassigned out parameter '{0}'", name);
3917 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3919 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3922 Report.Error (170, loc,
3923 "Use of possibly unassigned field `" + field_name + "'");
3927 public void SetAssigned (EmitContext ec)
3929 if (is_out && ec.DoFlowAnalysis)
3930 ec.CurrentBranching.SetAssigned (vi);
3933 public void SetFieldAssigned (EmitContext ec, string field_name)
3935 if (is_out && ec.DoFlowAnalysis)
3936 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3939 protected void DoResolveBase (EmitContext ec)
3941 type = pars.GetParameterInfo (ec, idx, out mod);
3942 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3943 is_out = (mod & Parameter.Modifier.OUT) != 0;
3944 eclass = ExprClass.Variable;
3947 vi = block.ParameterMap [idx];
3949 if (ec.CurrentAnonymousMethod != null){
3951 Report.Error (1628, Location,
3952 "Can not reference a ref or out parameter in an anonymous method");
3957 // If we are referencing the parameter from the external block
3958 // flag it for capturing
3960 //Console.WriteLine ("Is parameter `{0}' local? {1}", name, block.IsLocalParameter (name));
3961 if (!block.IsLocalParameter (name)){
3962 ec.CaptureParameter (name, type, idx);
3967 public override int GetHashCode()
3969 return name.GetHashCode ();
3972 public override bool Equals (object obj)
3974 ParameterReference pr = obj as ParameterReference;
3978 return name == pr.name && block == pr.block;
3982 // Notice that for ref/out parameters, the type exposed is not the
3983 // same type exposed externally.
3986 // externally we expose "int&"
3987 // here we expose "int".
3989 // We record this in "is_ref". This means that the type system can treat
3990 // the type as it is expected, but when we generate the code, we generate
3991 // the alternate kind of code.
3993 public override Expression DoResolve (EmitContext ec)
3997 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
4000 if (ec.RemapToProxy)
4001 return ec.RemapParameter (idx);
4006 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4012 if (ec.RemapToProxy)
4013 return ec.RemapParameterLValue (idx, right_side);
4018 static public void EmitLdArg (ILGenerator ig, int x)
4022 case 0: ig.Emit (OpCodes.Ldarg_0); break;
4023 case 1: ig.Emit (OpCodes.Ldarg_1); break;
4024 case 2: ig.Emit (OpCodes.Ldarg_2); break;
4025 case 3: ig.Emit (OpCodes.Ldarg_3); break;
4026 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
4029 ig.Emit (OpCodes.Ldarg, x);
4033 // This method is used by parameters that are references, that are
4034 // being passed as references: we only want to pass the pointer (that
4035 // is already stored in the parameter, not the address of the pointer,
4036 // and not the value of the variable).
4038 public void EmitLoad (EmitContext ec)
4040 ILGenerator ig = ec.ig;
4043 if (!ec.MethodIsStatic)
4047 EmitLdArg (ig, arg_idx);
4050 // FIXME: Review for anonymous methods
4054 public override void Emit (EmitContext ec)
4056 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4057 ec.EmitParameter (name);
4064 public void Emit (EmitContext ec, bool leave_copy)
4066 ILGenerator ig = ec.ig;
4069 if (!ec.MethodIsStatic)
4072 EmitLdArg (ig, arg_idx);
4076 ec.ig.Emit (OpCodes.Dup);
4079 // If we are a reference, we loaded on the stack a pointer
4080 // Now lets load the real value
4082 LoadFromPtr (ig, type);
4086 ec.ig.Emit (OpCodes.Dup);
4089 temp = new LocalTemporary (ec, type);
4095 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
4097 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4098 ec.EmitAssignParameter (name, source, leave_copy, prepare_for_load);
4102 ILGenerator ig = ec.ig;
4105 prepared = prepare_for_load;
4107 if (!ec.MethodIsStatic)
4110 if (is_ref && !prepared)
4111 EmitLdArg (ig, arg_idx);
4116 ec.ig.Emit (OpCodes.Dup);
4120 temp = new LocalTemporary (ec, type);
4124 StoreFromPtr (ig, type);
4130 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
4132 ig.Emit (OpCodes.Starg, arg_idx);
4136 public void AddressOf (EmitContext ec, AddressOp mode)
4138 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4139 ec.EmitAddressOfParameter (name);
4145 if (!ec.MethodIsStatic)
4150 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
4152 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
4155 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
4157 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
4164 /// Used for arguments to New(), Invocation()
4166 public class Argument {
4167 public enum AType : byte {
4174 public readonly AType ArgType;
4175 public Expression Expr;
4177 public Argument (Expression expr, AType type)
4180 this.ArgType = type;
4183 public Argument (Expression expr)
4186 this.ArgType = AType.Expression;
4191 if (ArgType == AType.Ref || ArgType == AType.Out)
4192 return TypeManager.GetReferenceType (Expr.Type);
4198 public Parameter.Modifier GetParameterModifier ()
4202 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
4205 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
4208 return Parameter.Modifier.NONE;
4212 public static string FullDesc (Argument a)
4214 if (a.ArgType == AType.ArgList)
4217 return (a.ArgType == AType.Ref ? "ref " :
4218 (a.ArgType == AType.Out ? "out " : "")) +
4219 TypeManager.CSharpName (a.Expr.Type);
4222 public bool ResolveMethodGroup (EmitContext ec, Location loc)
4224 SimpleName sn = Expr as SimpleName;
4226 Expr = sn.GetMethodGroup ();
4228 // FIXME: csc doesn't report any error if you try to use `ref' or
4229 // `out' in a delegate creation expression.
4230 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4237 void Error_LValueRequired (Location loc)
4239 Report.Error (1510, loc, "An lvalue is required as an argument to out or ref");
4242 public bool Resolve (EmitContext ec, Location loc)
4244 if (ArgType == AType.Ref) {
4245 Expr = Expr.Resolve (ec);
4249 if (!ec.IsConstructor) {
4250 FieldExpr fe = Expr as FieldExpr;
4251 if (fe != null && fe.FieldInfo.IsInitOnly) {
4252 if (fe.FieldInfo.IsStatic)
4253 Report.Error (199, loc, "A static readonly field cannot be passed ref or out (except in a static constructor)");
4255 Report.Error (192, loc, "A readonly field cannot be passed ref or out (except in a constructor)");
4259 Expr = Expr.DoResolveLValue (ec, Expr);
4261 Error_LValueRequired (loc);
4262 } else if (ArgType == AType.Out) {
4263 Expr = Expr.DoResolveLValue (ec, EmptyExpression.Null);
4265 Error_LValueRequired (loc);
4268 Expr = Expr.Resolve (ec);
4273 if (ArgType == AType.Expression)
4277 // Catch errors where fields of a MarshalByRefObject are passed as ref or out
4278 // This is only allowed for `this'
4280 FieldExpr fe = Expr as FieldExpr;
4281 if (fe != null && !fe.IsStatic){
4282 Expression instance = fe.InstanceExpression;
4284 if (instance.GetType () != typeof (This)){
4285 if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
4286 Report.SymbolRelatedToPreviousError (fe.InstanceExpression.Type);
4287 Report.Error (197, loc, "Cannot pass '{0}' as ref or out or take its address because it is a member of a marshal-by-reference class",
4295 if (Expr.eclass != ExprClass.Variable){
4297 // We just probe to match the CSC output
4299 if (Expr.eclass == ExprClass.PropertyAccess ||
4300 Expr.eclass == ExprClass.IndexerAccess){
4303 "A property or indexer can not be passed as an out or ref " +
4306 Error_LValueRequired (loc);
4314 public void Emit (EmitContext ec)
4317 // Ref and Out parameters need to have their addresses taken.
4319 // ParameterReferences might already be references, so we want
4320 // to pass just the value
4322 if (ArgType == AType.Ref || ArgType == AType.Out){
4323 AddressOp mode = AddressOp.Store;
4325 if (ArgType == AType.Ref)
4326 mode |= AddressOp.Load;
4328 if (Expr is ParameterReference){
4329 ParameterReference pr = (ParameterReference) Expr;
4335 pr.AddressOf (ec, mode);
4338 if (Expr is IMemoryLocation)
4339 ((IMemoryLocation) Expr).AddressOf (ec, mode);
4342 1510, Expr.Location,
4343 "An lvalue is required as an argument to out or ref");
4353 /// Invocation of methods or delegates.
4355 public class Invocation : ExpressionStatement {
4356 public readonly ArrayList Arguments;
4359 MethodBase method = null;
4362 // arguments is an ArrayList, but we do not want to typecast,
4363 // as it might be null.
4365 // FIXME: only allow expr to be a method invocation or a
4366 // delegate invocation (7.5.5)
4368 public Invocation (Expression expr, ArrayList arguments, Location l)
4371 Arguments = arguments;
4375 public Expression Expr {
4382 /// Determines "better conversion" as specified in 7.4.2.3
4384 /// Returns : p if a->p is better,
4385 /// q if a->q is better,
4386 /// null if neither is better
4388 static Type BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
4390 Type argument_type = TypeManager.TypeToCoreType (a.Type);
4391 Expression argument_expr = a.Expr;
4393 // p = TypeManager.TypeToCoreType (p);
4394 // q = TypeManager.TypeToCoreType (q);
4396 if (argument_type == null)
4397 throw new Exception ("Expression of type " + a.Expr +
4398 " does not resolve its type");
4400 if (p == null || q == null)
4401 throw new InternalErrorException ("BetterConversion Got a null conversion");
4406 if (argument_expr is NullLiteral) {
4408 // If the argument is null and one of the types to compare is 'object' and
4409 // the other is a reference type, we prefer the other.
4411 // This follows from the usual rules:
4412 // * There is an implicit conversion from 'null' to type 'object'
4413 // * There is an implicit conversion from 'null' to any reference type
4414 // * There is an implicit conversion from any reference type to type 'object'
4415 // * There is no implicit conversion from type 'object' to other reference types
4416 // => Conversion of 'null' to a reference type is better than conversion to 'object'
4418 // FIXME: This probably isn't necessary, since the type of a NullLiteral is the
4419 // null type. I think it used to be 'object' and thus needed a special
4420 // case to avoid the immediately following two checks.
4422 if (!p.IsValueType && q == TypeManager.object_type)
4424 if (!q.IsValueType && p == TypeManager.object_type)
4428 if (argument_type == p)
4431 if (argument_type == q)
4434 Expression p_tmp = new EmptyExpression (p);
4435 Expression q_tmp = new EmptyExpression (q);
4437 bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
4438 bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
4440 if (p_to_q && !q_to_p)
4443 if (q_to_p && !p_to_q)
4446 if (p == TypeManager.sbyte_type)
4447 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4448 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4450 if (q == TypeManager.sbyte_type)
4451 if (p == TypeManager.byte_type || p == TypeManager.ushort_type ||
4452 p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4455 if (p == TypeManager.short_type)
4456 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4457 q == TypeManager.uint64_type)
4460 if (q == TypeManager.short_type)
4461 if (p == TypeManager.ushort_type || p == TypeManager.uint32_type ||
4462 p == TypeManager.uint64_type)
4465 if (p == TypeManager.int32_type)
4466 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4469 if (q == TypeManager.int32_type)
4470 if (p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4473 if (p == TypeManager.int64_type)
4474 if (q == TypeManager.uint64_type)
4476 if (q == TypeManager.int64_type)
4477 if (p == TypeManager.uint64_type)
4484 /// Determines "Better function" between candidate
4485 /// and the current best match
4488 /// Returns a boolean indicating :
4489 /// false if candidate ain't better
4490 /// true if candidate is better than the current best match
4492 static bool BetterFunction (EmitContext ec, ArrayList args, int argument_count,
4493 MethodBase candidate, bool candidate_params,
4494 MethodBase best, bool best_params, Location loc)
4496 ParameterData candidate_pd = TypeManager.GetParameterData (candidate);
4497 ParameterData best_pd = TypeManager.GetParameterData (best);
4499 bool better_at_least_one = false;
4501 for (int j = 0; j < argument_count; ++j) {
4502 Argument a = (Argument) args [j];
4504 Type ct = TypeManager.TypeToCoreType (candidate_pd.ParameterType (j));
4505 Type bt = TypeManager.TypeToCoreType (best_pd.ParameterType (j));
4507 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4508 if (candidate_params)
4509 ct = TypeManager.GetElementType (ct);
4511 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4513 bt = TypeManager.GetElementType (bt);
4519 Type better = BetterConversion (ec, a, ct, bt, loc);
4520 // for each argument, the conversion to 'ct' should be no worse than
4521 // the conversion to 'bt'.
4525 // for at least one argument, the conversion to 'ct' should be better than
4526 // the conversion to 'bt'.
4528 better_at_least_one = true;
4531 if (better_at_least_one)
4538 // If two methods have equal parameter types, but
4539 // only one of them is generic, the non-generic one wins.
4541 if (TypeManager.IsGenericMethod (best) && !TypeManager.IsGenericMethod (candidate))
4543 else if (!TypeManager.IsGenericMethod (best) && TypeManager.IsGenericMethod (candidate))
4547 // Note that this is not just an optimization. This handles the case
4548 // This handles the case
4550 // Add (float f1, float f2, float f3);
4551 // Add (params decimal [] foo);
4553 // The call Add (3, 4, 5) should be ambiguous. Without this check, the
4554 // first candidate would've chosen as better.
4557 // This handles the following cases:
4559 // Trim () is better than Trim (params char[] chars)
4560 // Concat (string s1, string s2, string s3) is better than
4561 // Concat (string s1, params string [] srest)
4563 return !candidate_params && best_params;
4566 static bool IsOverride (MethodBase cand_method, MethodBase base_method)
4568 if (!IsAncestralType (base_method.DeclaringType, cand_method.DeclaringType))
4571 ParameterData cand_pd = TypeManager.GetParameterData (cand_method);
4572 ParameterData base_pd = TypeManager.GetParameterData (base_method);
4574 if (cand_pd.Count != base_pd.Count)
4577 for (int j = 0; j < cand_pd.Count; ++j) {
4578 Parameter.Modifier cm = cand_pd.ParameterModifier (j);
4579 Parameter.Modifier bm = base_pd.ParameterModifier (j);
4580 Type ct = TypeManager.TypeToCoreType (cand_pd.ParameterType (j));
4581 Type bt = TypeManager.TypeToCoreType (base_pd.ParameterType (j));
4583 if (cm != bm || ct != bt)
4590 public static string FullMethodDesc (MethodBase mb)
4592 string ret_type = "";
4597 if (mb is MethodInfo)
4598 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
4600 StringBuilder sb = new StringBuilder (ret_type);
4602 sb.Append (mb.ReflectedType.ToString ());
4604 sb.Append (mb.Name);
4606 ParameterData pd = TypeManager.GetParameterData (mb);
4608 int count = pd.Count;
4611 for (int i = count; i > 0; ) {
4614 sb.Append (pd.ParameterDesc (count - i - 1));
4620 return sb.ToString ();
4623 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4625 MemberInfo [] miset;
4626 MethodGroupExpr union;
4631 return (MethodGroupExpr) mg2;
4634 return (MethodGroupExpr) mg1;
4637 MethodGroupExpr left_set = null, right_set = null;
4638 int length1 = 0, length2 = 0;
4640 left_set = (MethodGroupExpr) mg1;
4641 length1 = left_set.Methods.Length;
4643 right_set = (MethodGroupExpr) mg2;
4644 length2 = right_set.Methods.Length;
4646 ArrayList common = new ArrayList ();
4648 foreach (MethodBase r in right_set.Methods){
4649 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
4653 miset = new MemberInfo [length1 + length2 - common.Count];
4654 left_set.Methods.CopyTo (miset, 0);
4658 foreach (MethodBase r in right_set.Methods) {
4659 if (!common.Contains (r))
4663 union = new MethodGroupExpr (miset, loc);
4668 public static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4669 ArrayList arguments, int arg_count,
4670 ref MethodBase candidate)
4672 return IsParamsMethodApplicable (
4673 ec, me, arguments, arg_count, false, ref candidate) ||
4674 IsParamsMethodApplicable (
4675 ec, me, arguments, arg_count, true, ref candidate);
4680 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4681 ArrayList arguments, int arg_count,
4682 bool do_varargs, ref MethodBase candidate)
4684 if (!me.HasTypeArguments &&
4685 !TypeManager.InferParamsTypeArguments (ec, arguments, ref candidate))
4688 return IsParamsMethodApplicable (
4689 ec, arguments, arg_count, candidate, do_varargs);
4693 /// Determines if the candidate method, if a params method, is applicable
4694 /// in its expanded form to the given set of arguments
4696 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
4697 int arg_count, MethodBase candidate,
4700 ParameterData pd = TypeManager.GetParameterData (candidate);
4702 int pd_count = pd.Count;
4707 int count = pd_count - 1;
4709 if (pd.ParameterModifier (count) != Parameter.Modifier.ARGLIST)
4711 if (pd_count != arg_count)
4714 if (pd.ParameterModifier (count) != Parameter.Modifier.PARAMS)
4718 if (count > arg_count)
4721 if (pd_count == 1 && arg_count == 0)
4725 // If we have come this far, the case which
4726 // remains is when the number of parameters is
4727 // less than or equal to the argument count.
4729 for (int i = 0; i < count; ++i) {
4731 Argument a = (Argument) arguments [i];
4733 Parameter.Modifier a_mod = a.GetParameterModifier () &
4734 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4735 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4736 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4738 if (a_mod == p_mod) {
4740 if (a_mod == Parameter.Modifier.NONE)
4741 if (!Convert.ImplicitConversionExists (ec,
4743 pd.ParameterType (i)))
4746 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4747 Type pt = pd.ParameterType (i);
4750 pt = TypeManager.GetReferenceType (pt);
4761 Argument a = (Argument) arguments [count];
4762 if (!(a.Expr is Arglist))
4768 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4770 for (int i = pd_count - 1; i < arg_count; i++) {
4771 Argument a = (Argument) arguments [i];
4773 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4780 public static bool IsApplicable (EmitContext ec, MethodGroupExpr me,
4781 ArrayList arguments, int arg_count,
4782 ref MethodBase candidate)
4784 if (!me.HasTypeArguments &&
4785 !TypeManager.InferTypeArguments (ec, arguments, ref candidate))
4788 return IsApplicable (ec, arguments, arg_count, candidate);
4792 /// Determines if the candidate method is applicable (section 14.4.2.1)
4793 /// to the given set of arguments
4795 static bool IsApplicable (EmitContext ec, ArrayList arguments, int arg_count,
4796 MethodBase candidate)
4798 ParameterData pd = TypeManager.GetParameterData (candidate);
4800 if (arg_count != pd.Count)
4803 for (int i = arg_count; i > 0; ) {
4806 Argument a = (Argument) arguments [i];
4808 Parameter.Modifier a_mod = a.GetParameterModifier () &
4809 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4810 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4811 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4814 if (a_mod == p_mod ||
4815 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4816 if (a_mod == Parameter.Modifier.NONE) {
4817 if (!Convert.ImplicitConversionExists (ec,
4819 pd.ParameterType (i)))
4823 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4824 Type pt = pd.ParameterType (i);
4827 pt = TypeManager.GetReferenceType (pt);
4839 static private bool IsAncestralType (Type first_type, Type second_type)
4841 return first_type != second_type &&
4842 (second_type.IsSubclassOf (first_type) ||
4843 TypeManager.ImplementsInterface (second_type, first_type));
4847 /// Find the Applicable Function Members (7.4.2.1)
4849 /// me: Method Group expression with the members to select.
4850 /// it might contain constructors or methods (or anything
4851 /// that maps to a method).
4853 /// Arguments: ArrayList containing resolved Argument objects.
4855 /// loc: The location if we want an error to be reported, or a Null
4856 /// location for "probing" purposes.
4858 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4859 /// that is the best match of me on Arguments.
4862 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4863 ArrayList Arguments, bool may_fail,
4866 MethodBase method = null;
4867 bool method_params = false;
4868 Type applicable_type = null;
4870 ArrayList candidates = new ArrayList (2);
4871 ArrayList candidate_overrides = null;
4874 // Used to keep a map between the candidate
4875 // and whether it is being considered in its
4876 // normal or expanded form
4878 // false is normal form, true is expanded form
4880 Hashtable candidate_to_form = null;
4882 if (Arguments != null)
4883 arg_count = Arguments.Count;
4885 if ((me.Name == "Invoke") &&
4886 TypeManager.IsDelegateType (me.DeclaringType)) {
4887 Error_InvokeOnDelegate (loc);
4891 MethodBase[] methods = me.Methods;
4894 // First we construct the set of applicable methods
4896 bool is_sorted = true;
4897 for (int i = 0; i < methods.Length; i++){
4898 Type decl_type = methods [i].DeclaringType;
4901 // If we have already found an applicable method
4902 // we eliminate all base types (Section 14.5.5.1)
4904 if ((applicable_type != null) &&
4905 IsAncestralType (decl_type, applicable_type))
4909 // Methods marked 'override' don't take part in 'applicable_type'
4910 // computation, nor in the actual overload resolution.
4911 // However, they still need to be emitted instead of a base virtual method.
4912 // We avoid doing the 'applicable' test here, since it'll anyway be applied
4913 // to the base virtual function, and IsOverride is much faster than IsApplicable.
4916 methods [i].IsVirtual &&
4917 (methods [i].Attributes & MethodAttributes.NewSlot) == 0) {
4918 if (candidate_overrides == null)
4919 candidate_overrides = new ArrayList ();
4920 candidate_overrides.Add (methods [i]);
4925 // Check if candidate is applicable (section 14.4.2.1)
4926 // Is candidate applicable in normal form?
4928 bool is_applicable = IsApplicable (
4929 ec, me, Arguments, arg_count, ref methods [i]);
4931 if (!is_applicable &&
4932 (IsParamsMethodApplicable (
4933 ec, me, Arguments, arg_count, ref methods [i]))) {
4934 MethodBase candidate = methods [i];
4935 if (candidate_to_form == null)
4936 candidate_to_form = new PtrHashtable ();
4937 candidate_to_form [candidate] = candidate;
4938 // Candidate is applicable in expanded form
4939 is_applicable = true;
4945 candidates.Add (methods [i]);
4947 if (applicable_type == null)
4948 applicable_type = decl_type;
4949 else if (applicable_type != decl_type) {
4951 if (IsAncestralType (applicable_type, decl_type))
4952 applicable_type = decl_type;
4956 int candidate_top = candidates.Count;
4958 if (applicable_type == null) {
4960 // Okay so we have failed to find anything so we
4961 // return by providing info about the closest match
4963 for (int i = 0; i < methods.Length; ++i) {
4964 MethodBase c = (MethodBase) methods [i];
4965 ParameterData pd = TypeManager.GetParameterData (c);
4967 if (pd.Count != arg_count)
4970 if (!TypeManager.InferTypeArguments (ec, Arguments, ref c))
4973 VerifyArgumentsCompat (ec, Arguments, arg_count,
4974 c, false, null, may_fail, loc);
4979 string report_name = me.Name;
4980 if (report_name == ".ctor")
4981 report_name = me.DeclaringType.ToString ();
4983 for (int i = 0; i < methods.Length; ++i) {
4984 MethodBase c = methods [i];
4985 ParameterData pd = TypeManager.GetParameterData (c);
4987 if (pd.Count != arg_count)
4990 if (TypeManager.InferTypeArguments (ec, Arguments, ref c))
4994 411, loc, "The type arguments for " +
4995 "method `{0}' cannot be infered from " +
4996 "the usage. Try specifying the type " +
4997 "arguments explicitly.", report_name);
5001 Error_WrongNumArguments (
5002 loc, report_name, arg_count);
5011 // At this point, applicable_type is _one_ of the most derived types
5012 // in the set of types containing the methods in this MethodGroup.
5013 // Filter the candidates so that they only contain methods from the
5014 // most derived types.
5017 int finalized = 0; // Number of finalized candidates
5020 // Invariant: applicable_type is a most derived type
5022 // We'll try to complete Section 14.5.5.1 for 'applicable_type' by
5023 // eliminating all it's base types. At the same time, we'll also move
5024 // every unrelated type to the end of the array, and pick the next
5025 // 'applicable_type'.
5027 Type next_applicable_type = null;
5028 int j = finalized; // where to put the next finalized candidate
5029 int k = finalized; // where to put the next undiscarded candidate
5030 for (int i = finalized; i < candidate_top; ++i) {
5031 MethodBase candidate = (MethodBase) candidates [i];
5032 Type decl_type = candidate.DeclaringType;
5034 if (decl_type == applicable_type) {
5035 candidates [k++] = candidates [j];
5036 candidates [j++] = candidates [i];
5040 if (IsAncestralType (decl_type, applicable_type))
5043 if (next_applicable_type != null &&
5044 IsAncestralType (decl_type, next_applicable_type))
5047 candidates [k++] = candidates [i];
5049 if (next_applicable_type == null ||
5050 IsAncestralType (next_applicable_type, decl_type))
5051 next_applicable_type = decl_type;
5054 applicable_type = next_applicable_type;
5057 } while (applicable_type != null);
5061 // Now we actually find the best method
5064 method = (MethodBase) candidates [0];
5065 method_params = candidate_to_form != null && candidate_to_form.Contains (method);
5066 for (int ix = 1; ix < candidate_top; ix++){
5067 MethodBase candidate = (MethodBase) candidates [ix];
5069 if (candidate == method)
5072 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
5074 if (BetterFunction (ec, Arguments, arg_count,
5075 candidate, cand_params,
5076 method, method_params, loc)) {
5078 method_params = cand_params;
5083 // Now check that there are no ambiguities i.e the selected method
5084 // should be better than all the others
5086 bool ambiguous = false;
5087 for (int ix = 0; ix < candidate_top; ix++){
5088 MethodBase candidate = (MethodBase) candidates [ix];
5090 if (candidate == method)
5093 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
5094 if (!BetterFunction (ec, Arguments, arg_count,
5095 method, method_params,
5096 candidate, cand_params,
5098 Report.SymbolRelatedToPreviousError (candidate);
5104 Report.SymbolRelatedToPreviousError (method);
5105 Report.Error (121, loc, "Ambiguous call when selecting function due to implicit casts");
5110 // If the method is a virtual function, pick an override closer to the LHS type.
5112 if (!me.IsBase && method.IsVirtual) {
5113 if ((method.Attributes & MethodAttributes.NewSlot) != MethodAttributes.NewSlot)
5114 throw new InternalErrorException (
5115 "Should not happen. An 'override' method took part in overload resolution: " + method);
5117 if (candidate_overrides != null)
5118 foreach (MethodBase candidate in candidate_overrides) {
5119 if (IsOverride (candidate, method))
5125 // And now check if the arguments are all
5126 // compatible, perform conversions if
5127 // necessary etc. and return if everything is
5130 if (!VerifyArgumentsCompat (ec, Arguments, arg_count, method,
5131 method_params, null, may_fail, loc))
5134 if (method != null) {
5135 IMethodData data = TypeManager.GetMethod (method);
5137 data.SetMemberIsUsed ();
5142 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
5144 if (name == "Finalize" && arg_count == 0) {
5145 Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
5148 Report.Error (1501, loc,
5149 "No overload for method `" + name + "' takes `" +
5150 arg_count + "' arguments");
5154 static void Error_InvokeOnDelegate (Location loc)
5156 Report.Error (1533, loc,
5157 "Invoke cannot be called directly on a delegate");
5160 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
5161 Type delegate_type, string arg_sig, string par_desc)
5163 if (delegate_type == null)
5164 Report.Error (1502, loc,
5165 "The best overloaded match for method '" +
5166 FullMethodDesc (method) +
5167 "' has some invalid arguments");
5169 Report.Error (1594, loc,
5170 "Delegate '" + delegate_type.ToString () +
5171 "' has some invalid arguments.");
5172 Report.Error (1503, loc,
5173 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
5174 idx, arg_sig, par_desc));
5177 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
5178 int arg_count, MethodBase method,
5179 bool chose_params_expanded,
5180 Type delegate_type, bool may_fail,
5183 ParameterData pd = TypeManager.GetParameterData (method);
5184 int pd_count = pd.Count;
5186 for (int j = 0; j < arg_count; j++) {
5187 Argument a = (Argument) Arguments [j];
5188 Expression a_expr = a.Expr;
5189 Type parameter_type = pd.ParameterType (j);
5190 Parameter.Modifier pm = pd.ParameterModifier (j);
5192 if (pm == Parameter.Modifier.PARAMS){
5193 if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
5195 Error_InvalidArguments (
5196 loc, j, method, delegate_type,
5197 Argument.FullDesc (a), pd.ParameterDesc (j));
5201 if (chose_params_expanded)
5202 parameter_type = TypeManager.GetElementType (parameter_type);
5203 } else if (pm == Parameter.Modifier.ARGLIST){
5209 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
5211 Error_InvalidArguments (
5212 loc, j, method, delegate_type,
5213 Argument.FullDesc (a), pd.ParameterDesc (j));
5221 if (!TypeManager.IsEqual (a.Type, parameter_type)){
5224 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
5228 Error_InvalidArguments (
5229 loc, j, method, delegate_type,
5230 Argument.FullDesc (a), pd.ParameterDesc (j));
5235 // Update the argument with the implicit conversion
5241 if (parameter_type.IsPointer){
5248 Parameter.Modifier a_mod = a.GetParameterModifier () &
5249 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5250 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
5251 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5253 if (a_mod != p_mod &&
5254 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
5256 Report.Error (1502, loc,
5257 "The best overloaded match for method '" + FullMethodDesc (method)+
5258 "' has some invalid arguments");
5259 Report.Error (1503, loc,
5260 "Argument " + (j+1) +
5261 ": Cannot convert from '" + Argument.FullDesc (a)
5262 + "' to '" + pd.ParameterDesc (j) + "'");
5272 public override Expression DoResolve (EmitContext ec)
5275 // First, resolve the expression that is used to
5276 // trigger the invocation
5278 SimpleName sn = expr as SimpleName;
5280 expr = sn.GetMethodGroup ();
5282 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
5286 if (!(expr is MethodGroupExpr)) {
5287 Type expr_type = expr.Type;
5289 if (expr_type != null){
5290 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
5292 return (new DelegateInvocation (
5293 this.expr, Arguments, loc)).Resolve (ec);
5297 if (!(expr is MethodGroupExpr)){
5298 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup, loc);
5303 // Next, evaluate all the expressions in the argument list
5305 if (Arguments != null){
5306 foreach (Argument a in Arguments){
5307 if (!a.Resolve (ec, loc))
5312 MethodGroupExpr mg = (MethodGroupExpr) expr;
5313 method = OverloadResolve (ec, mg, Arguments, false, loc);
5318 MethodInfo mi = method as MethodInfo;
5320 type = TypeManager.TypeToCoreType (mi.ReturnType);
5321 Expression iexpr = mg.InstanceExpression;
5323 if (iexpr == null ||
5324 iexpr is This || iexpr is EmptyExpression ||
5325 mg.IdenticalTypeName) {
5326 mg.InstanceExpression = null;
5328 MemberExpr.error176 (loc, mi.Name);
5332 if (iexpr == null || iexpr is EmptyExpression) {
5333 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
5339 if (type.IsPointer){
5347 // Only base will allow this invocation to happen.
5349 if (mg.IsBase && method.IsAbstract){
5350 Report.Error (205, loc, "Cannot call an abstract base member: " +
5351 FullMethodDesc (method));
5355 if (method.Name == "Finalize" && Arguments == null) {
5356 Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
5360 if ((method.Attributes & MethodAttributes.SpecialName) != 0){
5361 if (TypeManager.LookupDeclSpace (method.DeclaringType) != null || TypeManager.IsSpecialMethod (method)) {
5362 Report.Error (571, loc, TypeManager.CSharpSignature (method) + ": can not call operator or accessor");
5367 if (mg.InstanceExpression != null)
5368 mg.InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
5370 eclass = ExprClass.Value;
5375 // Emits the list of arguments as an array
5377 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
5379 ILGenerator ig = ec.ig;
5380 int count = arguments.Count - idx;
5381 Argument a = (Argument) arguments [idx];
5382 Type t = a.Expr.Type;
5384 IntConstant.EmitInt (ig, count);
5385 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
5387 int top = arguments.Count;
5388 for (int j = idx; j < top; j++){
5389 a = (Argument) arguments [j];
5391 ig.Emit (OpCodes.Dup);
5392 IntConstant.EmitInt (ig, j - idx);
5394 bool is_stobj, has_type_arg;
5395 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj, out has_type_arg);
5397 ig.Emit (OpCodes.Ldelema, t);
5409 /// Emits a list of resolved Arguments that are in the arguments
5412 /// The MethodBase argument might be null if the
5413 /// emission of the arguments is known not to contain
5414 /// a `params' field (for example in constructors or other routines
5415 /// that keep their arguments in this structure)
5417 /// if `dup_args' is true, a copy of the arguments will be left
5418 /// on the stack. If `dup_args' is true, you can specify `this_arg'
5419 /// which will be duplicated before any other args. Only EmitCall
5420 /// should be using this interface.
5422 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments, bool dup_args, LocalTemporary this_arg)
5426 pd = TypeManager.GetParameterData (mb);
5430 LocalTemporary [] temps = null;
5433 temps = new LocalTemporary [arguments.Count];
5436 // If we are calling a params method with no arguments, special case it
5438 if (arguments == null){
5439 if (pd != null && pd.Count > 0 &&
5440 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
5441 ILGenerator ig = ec.ig;
5443 IntConstant.EmitInt (ig, 0);
5444 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
5450 int top = arguments.Count;
5452 for (int i = 0; i < top; i++){
5453 Argument a = (Argument) arguments [i];
5456 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
5458 // Special case if we are passing the same data as the
5459 // params argument, do not put it in an array.
5461 if (pd.ParameterType (i) == a.Type)
5464 EmitParams (ec, i, arguments);
5471 ec.ig.Emit (OpCodes.Dup);
5472 (temps [i] = new LocalTemporary (ec, a.Type)).Store (ec);
5477 if (this_arg != null)
5480 for (int i = 0; i < top; i ++)
5481 temps [i].Emit (ec);
5484 if (pd != null && pd.Count > top &&
5485 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
5486 ILGenerator ig = ec.ig;
5488 IntConstant.EmitInt (ig, 0);
5489 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
5493 static Type[] GetVarargsTypes (EmitContext ec, MethodBase mb,
5494 ArrayList arguments)
5496 ParameterData pd = TypeManager.GetParameterData (mb);
5498 if (arguments == null)
5499 return new Type [0];
5501 Argument a = (Argument) arguments [pd.Count - 1];
5502 Arglist list = (Arglist) a.Expr;
5504 return list.ArgumentTypes;
5508 /// This checks the ConditionalAttribute on the method
5510 static bool IsMethodExcluded (MethodBase method, EmitContext ec)
5512 if (method.IsConstructor)
5515 IMethodData md = TypeManager.GetMethod (method);
5517 return md.IsExcluded (ec);
5519 // For some methods (generated by delegate class) GetMethod returns null
5520 // because they are not included in builder_to_method table
5521 if (method.DeclaringType is TypeBuilder)
5524 return AttributeTester.IsConditionalMethodExcluded (method);
5528 /// is_base tells whether we want to force the use of the `call'
5529 /// opcode instead of using callvirt. Call is required to call
5530 /// a specific method, while callvirt will always use the most
5531 /// recent method in the vtable.
5533 /// is_static tells whether this is an invocation on a static method
5535 /// instance_expr is an expression that represents the instance
5536 /// it must be non-null if is_static is false.
5538 /// method is the method to invoke.
5540 /// Arguments is the list of arguments to pass to the method or constructor.
5542 public static void EmitCall (EmitContext ec, bool is_base,
5543 bool is_static, Expression instance_expr,
5544 MethodBase method, ArrayList Arguments, Location loc)
5546 EmitCall (ec, is_base, is_static, instance_expr, method, Arguments, loc, false, false);
5549 // `dup_args' leaves an extra copy of the arguments on the stack
5550 // `omit_args' does not leave any arguments at all.
5551 // So, basically, you could make one call with `dup_args' set to true,
5552 // and then another with `omit_args' set to true, and the two calls
5553 // would have the same set of arguments. However, each argument would
5554 // only have been evaluated once.
5555 public static void EmitCall (EmitContext ec, bool is_base,
5556 bool is_static, Expression instance_expr,
5557 MethodBase method, ArrayList Arguments, Location loc,
5558 bool dup_args, bool omit_args)
5560 ILGenerator ig = ec.ig;
5561 bool struct_call = false;
5562 bool this_call = false;
5563 LocalTemporary this_arg = null;
5565 Type decl_type = method.DeclaringType;
5567 if (!RootContext.StdLib) {
5568 // Replace any calls to the system's System.Array type with calls to
5569 // the newly created one.
5570 if (method == TypeManager.system_int_array_get_length)
5571 method = TypeManager.int_array_get_length;
5572 else if (method == TypeManager.system_int_array_get_rank)
5573 method = TypeManager.int_array_get_rank;
5574 else if (method == TypeManager.system_object_array_clone)
5575 method = TypeManager.object_array_clone;
5576 else if (method == TypeManager.system_int_array_get_length_int)
5577 method = TypeManager.int_array_get_length_int;
5578 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5579 method = TypeManager.int_array_get_lower_bound_int;
5580 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5581 method = TypeManager.int_array_get_upper_bound_int;
5582 else if (method == TypeManager.system_void_array_copyto_array_int)
5583 method = TypeManager.void_array_copyto_array_int;
5586 if (ec.TestObsoleteMethodUsage) {
5588 // This checks ObsoleteAttribute on the method and on the declaring type
5590 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
5592 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
5594 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
5596 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
5600 if (IsMethodExcluded (method, ec))
5604 this_call = instance_expr == null;
5605 if (decl_type.IsValueType || (!this_call && instance_expr.Type.IsValueType))
5609 // If this is ourselves, push "this"
5614 ig.Emit (OpCodes.Ldarg_0);
5617 Type iexpr_type = instance_expr.Type;
5620 // Push the instance expression
5622 if (TypeManager.IsValueType (iexpr_type)) {
5624 // Special case: calls to a function declared in a
5625 // reference-type with a value-type argument need
5626 // to have their value boxed.
5627 if (decl_type.IsValueType ||
5628 iexpr_type.IsGenericParameter) {
5630 // If the expression implements IMemoryLocation, then
5631 // we can optimize and use AddressOf on the
5634 // If not we have to use some temporary storage for
5636 if (instance_expr is IMemoryLocation) {
5637 ((IMemoryLocation)instance_expr).
5638 AddressOf (ec, AddressOp.LoadStore);
5640 LocalTemporary temp = new LocalTemporary (ec, iexpr_type);
5641 instance_expr.Emit (ec);
5643 temp.AddressOf (ec, AddressOp.Load);
5646 // avoid the overhead of doing this all the time.
5648 t = TypeManager.GetReferenceType (iexpr_type);
5650 instance_expr.Emit (ec);
5651 ig.Emit (OpCodes.Box, instance_expr.Type);
5652 t = TypeManager.object_type;
5655 instance_expr.Emit (ec);
5656 t = instance_expr.Type;
5661 this_arg = new LocalTemporary (ec, t);
5662 ig.Emit (OpCodes.Dup);
5663 this_arg.Store (ec);
5669 EmitArguments (ec, method, Arguments, dup_args, this_arg);
5671 if ((instance_expr != null) && (instance_expr.Type.IsGenericParameter))
5672 ig.Emit (OpCodes.Constrained, instance_expr.Type);
5675 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
5676 call_op = OpCodes.Call;
5678 call_op = OpCodes.Callvirt;
5680 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
5681 Type[] varargs_types = GetVarargsTypes (ec, method, Arguments);
5682 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
5689 // and DoFoo is not virtual, you can omit the callvirt,
5690 // because you don't need the null checking behavior.
5692 if (method is MethodInfo)
5693 ig.Emit (call_op, (MethodInfo) method);
5695 ig.Emit (call_op, (ConstructorInfo) method);
5698 public override void Emit (EmitContext ec)
5700 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5702 EmitCall (ec, mg.IsBase, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5705 public override void EmitStatement (EmitContext ec)
5710 // Pop the return value if there is one
5712 if (method is MethodInfo){
5713 Type ret = ((MethodInfo)method).ReturnType;
5714 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5715 ec.ig.Emit (OpCodes.Pop);
5720 public class InvocationOrCast : ExpressionStatement
5723 Expression argument;
5725 public InvocationOrCast (Expression expr, Expression argument, Location loc)
5728 this.argument = argument;
5732 public override Expression DoResolve (EmitContext ec)
5735 // First try to resolve it as a cast.
5737 TypeExpr te = expr.ResolveAsTypeStep (ec) as TypeExpr;
5738 if ((te != null) && (te.eclass == ExprClass.Type)) {
5739 Cast cast = new Cast (te, argument, loc);
5740 return cast.Resolve (ec);
5744 // This can either be a type or a delegate invocation.
5745 // Let's just resolve it and see what we'll get.
5747 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5752 // Ok, so it's a Cast.
5754 if (expr.eclass == ExprClass.Type) {
5755 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
5756 return cast.Resolve (ec);
5760 // It's a delegate invocation.
5762 if (!TypeManager.IsDelegateType (expr.Type)) {
5763 Error (149, "Method name expected");
5767 ArrayList args = new ArrayList ();
5768 args.Add (new Argument (argument, Argument.AType.Expression));
5769 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5770 return invocation.Resolve (ec);
5775 Error (201, "Only assignment, call, increment, decrement and new object " +
5776 "expressions can be used as a statement");
5779 public override ExpressionStatement ResolveStatement (EmitContext ec)
5782 // First try to resolve it as a cast.
5784 TypeExpr te = expr.ResolveAsTypeStep (ec) as TypeExpr;
5785 if ((te != null) && (te.eclass == ExprClass.Type)) {
5791 // This can either be a type or a delegate invocation.
5792 // Let's just resolve it and see what we'll get.
5794 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5795 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5801 // It's a delegate invocation.
5803 if (!TypeManager.IsDelegateType (expr.Type)) {
5804 Error (149, "Method name expected");
5808 ArrayList args = new ArrayList ();
5809 args.Add (new Argument (argument, Argument.AType.Expression));
5810 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5811 return invocation.ResolveStatement (ec);
5814 public override void Emit (EmitContext ec)
5816 throw new Exception ("Cannot happen");
5819 public override void EmitStatement (EmitContext ec)
5821 throw new Exception ("Cannot happen");
5826 // This class is used to "disable" the code generation for the
5827 // temporary variable when initializing value types.
5829 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5830 public void AddressOf (EmitContext ec, AddressOp Mode)
5837 /// Implements the new expression
5839 public class New : ExpressionStatement, IMemoryLocation {
5840 public readonly ArrayList Arguments;
5843 // During bootstrap, it contains the RequestedType,
5844 // but if `type' is not null, it *might* contain a NewDelegate
5845 // (because of field multi-initialization)
5847 public Expression RequestedType;
5849 MethodBase method = null;
5852 // If set, the new expression is for a value_target, and
5853 // we will not leave anything on the stack.
5855 Expression value_target;
5856 bool value_target_set = false;
5857 bool is_type_parameter = false;
5859 public New (Expression requested_type, ArrayList arguments, Location l)
5861 RequestedType = requested_type;
5862 Arguments = arguments;
5866 public bool SetValueTypeVariable (Expression value)
5868 value_target = value;
5869 value_target_set = true;
5870 if (!(value_target is IMemoryLocation)){
5871 Error_UnexpectedKind ("variable", loc);
5878 // This function is used to disable the following code sequence for
5879 // value type initialization:
5881 // AddressOf (temporary)
5885 // Instead the provide will have provided us with the address on the
5886 // stack to store the results.
5888 static Expression MyEmptyExpression;
5890 public void DisableTemporaryValueType ()
5892 if (MyEmptyExpression == null)
5893 MyEmptyExpression = new EmptyAddressOf ();
5896 // To enable this, look into:
5897 // test-34 and test-89 and self bootstrapping.
5899 // For instance, we can avoid a copy by using `newobj'
5900 // instead of Call + Push-temp on value types.
5901 // value_target = MyEmptyExpression;
5906 /// Converts complex core type syntax like 'new int ()' to simple constant
5908 Expression Constantify (Type t)
5910 if (t == TypeManager.int32_type)
5911 return new IntConstant (0);
5912 if (t == TypeManager.uint32_type)
5913 return new UIntConstant (0);
5914 if (t == TypeManager.int64_type)
5915 return new LongConstant (0);
5916 if (t == TypeManager.uint64_type)
5917 return new ULongConstant (0);
5918 if (t == TypeManager.float_type)
5919 return new FloatConstant (0);
5920 if (t == TypeManager.double_type)
5921 return new DoubleConstant (0);
5922 if (t == TypeManager.short_type)
5923 return new ShortConstant (0);
5924 if (t == TypeManager.ushort_type)
5925 return new UShortConstant (0);
5926 if (t == TypeManager.sbyte_type)
5927 return new SByteConstant (0);
5928 if (t == TypeManager.byte_type)
5929 return new ByteConstant (0);
5930 if (t == TypeManager.char_type)
5931 return new CharConstant ('\0');
5932 if (t == TypeManager.bool_type)
5933 return new BoolConstant (false);
5934 if (t == TypeManager.decimal_type)
5935 return new DecimalConstant (0);
5940 public override Expression DoResolve (EmitContext ec)
5943 // The New DoResolve might be called twice when initializing field
5944 // expressions (see EmitFieldInitializers, the call to
5945 // GetInitializerExpression will perform a resolve on the expression,
5946 // and later the assign will trigger another resolution
5948 // This leads to bugs (#37014)
5951 if (RequestedType is NewDelegate)
5952 return RequestedType;
5956 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec);
5960 if (Arguments == null) {
5961 Expression c = Constantify (type);
5970 CheckObsoleteAttribute (type);
5972 bool IsDelegate = TypeManager.IsDelegateType (type);
5975 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5976 if (RequestedType != null)
5977 if (!(RequestedType is DelegateCreation))
5978 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
5979 return RequestedType;
5982 if (type.IsGenericParameter) {
5983 if (!TypeManager.HasConstructorConstraint (type)) {
5984 Error (304, String.Format (
5985 "Cannot create an instance of the " +
5986 "variable type '{0}' because it " +
5987 "doesn't have the new() constraint",
5992 if ((Arguments != null) && (Arguments.Count != 0)) {
5993 Error (417, String.Format (
5994 "`{0}': cannot provide arguments " +
5995 "when creating an instance of a " +
5996 "variable type.", type));
6000 is_type_parameter = true;
6001 eclass = ExprClass.Value;
6005 if (type.IsInterface || type.IsAbstract){
6006 Error (144, "It is not possible to create instances of interfaces or abstract classes");
6010 if (type.IsAbstract && type.IsSealed) {
6011 Report.Error (712, loc, "Cannot create an instance of the static class '{0}'", TypeManager.CSharpName (type));
6015 bool is_struct = type.IsValueType;
6016 eclass = ExprClass.Value;
6019 // SRE returns a match for .ctor () on structs (the object constructor),
6020 // so we have to manually ignore it.
6022 if (is_struct && Arguments == null)
6026 ml = MemberLookupFinal (ec, type, type, ".ctor",
6027 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
6028 MemberTypes.Constructor,
6029 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
6034 if (! (ml is MethodGroupExpr)){
6036 ml.Error_UnexpectedKind ("method group", loc);
6042 if (Arguments != null){
6043 foreach (Argument a in Arguments){
6044 if (!a.Resolve (ec, loc))
6049 method = Invocation.OverloadResolve (
6050 ec, (MethodGroupExpr) ml, Arguments, true, loc);
6054 if (method == null) {
6055 if (almostMatchedMembers.Count != 0) {
6056 MemberLookupFailed (ec, type, type, ".ctor", null, true, loc);
6060 if (!is_struct || Arguments.Count > 0) {
6061 Error (1501, String.Format (
6062 "New invocation: Can not find a constructor in `{0}' for this argument list",
6063 TypeManager.CSharpName (type)));
6071 bool DoEmitTypeParameter (EmitContext ec)
6073 ILGenerator ig = ec.ig;
6075 ig.Emit (OpCodes.Ldtoken, type);
6076 ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6077 ig.Emit (OpCodes.Call, TypeManager.activator_create_instance);
6078 ig.Emit (OpCodes.Unbox_Any, type);
6084 // This DoEmit can be invoked in two contexts:
6085 // * As a mechanism that will leave a value on the stack (new object)
6086 // * As one that wont (init struct)
6088 // You can control whether a value is required on the stack by passing
6089 // need_value_on_stack. The code *might* leave a value on the stack
6090 // so it must be popped manually
6092 // If we are dealing with a ValueType, we have a few
6093 // situations to deal with:
6095 // * The target is a ValueType, and we have been provided
6096 // the instance (this is easy, we are being assigned).
6098 // * The target of New is being passed as an argument,
6099 // to a boxing operation or a function that takes a
6102 // In this case, we need to create a temporary variable
6103 // that is the argument of New.
6105 // Returns whether a value is left on the stack
6107 bool DoEmit (EmitContext ec, bool need_value_on_stack)
6109 bool is_value_type = TypeManager.IsValueType (type);
6110 ILGenerator ig = ec.ig;
6115 // Allow DoEmit() to be called multiple times.
6116 // We need to create a new LocalTemporary each time since
6117 // you can't share LocalBuilders among ILGeneators.
6118 if (!value_target_set)
6119 value_target = new LocalTemporary (ec, type);
6121 ml = (IMemoryLocation) value_target;
6122 ml.AddressOf (ec, AddressOp.Store);
6126 Invocation.EmitArguments (ec, method, Arguments, false, null);
6130 ig.Emit (OpCodes.Initobj, type);
6132 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6133 if (need_value_on_stack){
6134 value_target.Emit (ec);
6139 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
6144 public override void Emit (EmitContext ec)
6146 if (is_type_parameter)
6147 DoEmitTypeParameter (ec);
6152 public override void EmitStatement (EmitContext ec)
6154 if (is_type_parameter)
6155 throw new InvalidOperationException ();
6157 if (DoEmit (ec, false))
6158 ec.ig.Emit (OpCodes.Pop);
6161 public void AddressOf (EmitContext ec, AddressOp Mode)
6163 if (is_type_parameter)
6164 throw new InvalidOperationException ();
6166 if (!type.IsValueType){
6168 // We throw an exception. So far, I believe we only need to support
6170 // foreach (int j in new StructType ())
6173 throw new Exception ("AddressOf should not be used for classes");
6176 if (!value_target_set)
6177 value_target = new LocalTemporary (ec, type);
6179 IMemoryLocation ml = (IMemoryLocation) value_target;
6180 ml.AddressOf (ec, AddressOp.Store);
6182 Invocation.EmitArguments (ec, method, Arguments, false, null);
6185 ec.ig.Emit (OpCodes.Initobj, type);
6187 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6189 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
6194 /// 14.5.10.2: Represents an array creation expression.
6198 /// There are two possible scenarios here: one is an array creation
6199 /// expression that specifies the dimensions and optionally the
6200 /// initialization data and the other which does not need dimensions
6201 /// specified but where initialization data is mandatory.
6203 public class ArrayCreation : Expression {
6204 Expression requested_base_type;
6205 ArrayList initializers;
6208 // The list of Argument types.
6209 // This is used to construct the `newarray' or constructor signature
6211 ArrayList arguments;
6214 // Method used to create the array object.
6216 MethodBase new_method = null;
6218 Type array_element_type;
6219 Type underlying_type;
6220 bool is_one_dimensional = false;
6221 bool is_builtin_type = false;
6222 bool expect_initializers = false;
6223 int num_arguments = 0;
6227 ArrayList array_data;
6232 // The number of array initializers that we can handle
6233 // via the InitializeArray method - through EmitStaticInitializers
6235 int num_automatic_initializers;
6237 const int max_automatic_initializers = 6;
6239 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
6241 this.requested_base_type = requested_base_type;
6242 this.initializers = initializers;
6246 arguments = new ArrayList ();
6248 foreach (Expression e in exprs) {
6249 arguments.Add (new Argument (e, Argument.AType.Expression));
6254 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
6256 this.requested_base_type = requested_base_type;
6257 this.initializers = initializers;
6261 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
6263 //string tmp = rank.Substring (rank.LastIndexOf ('['));
6265 //dimensions = tmp.Length - 1;
6266 expect_initializers = true;
6269 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
6271 StringBuilder sb = new StringBuilder (rank);
6274 for (int i = 1; i < idx_count; i++)
6279 return new ComposedCast (base_type, sb.ToString (), loc);
6282 void Error_IncorrectArrayInitializer ()
6284 Error (178, "Incorrectly structured array initializer");
6287 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
6289 if (specified_dims) {
6290 Argument a = (Argument) arguments [idx];
6292 if (!a.Resolve (ec, loc))
6295 if (!(a.Expr is Constant)) {
6296 Error (150, "A constant value is expected");
6300 int value = (int) ((Constant) a.Expr).GetValue ();
6302 if (value != probe.Count) {
6303 Error_IncorrectArrayInitializer ();
6307 bounds [idx] = value;
6310 int child_bounds = -1;
6311 for (int i = 0; i < probe.Count; ++i) {
6312 object o = probe [i];
6313 if (o is ArrayList) {
6314 ArrayList sub_probe = o as ArrayList;
6315 int current_bounds = sub_probe.Count;
6317 if (child_bounds == -1)
6318 child_bounds = current_bounds;
6320 else if (child_bounds != current_bounds){
6321 Error_IncorrectArrayInitializer ();
6324 if (specified_dims && (idx + 1 >= arguments.Count)){
6325 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
6329 bool ret = CheckIndices (ec, sub_probe, idx + 1, specified_dims);
6333 if (child_bounds != -1){
6334 Error_IncorrectArrayInitializer ();
6338 Expression tmp = (Expression) o;
6339 tmp = tmp.Resolve (ec);
6344 // Console.WriteLine ("I got: " + tmp);
6345 // Handle initialization from vars, fields etc.
6347 Expression conv = Convert.ImplicitConversionRequired (
6348 ec, tmp, underlying_type, loc);
6353 if (conv is StringConstant || conv is DecimalConstant || conv is NullCast) {
6354 // These are subclasses of Constant that can appear as elements of an
6355 // array that cannot be statically initialized (with num_automatic_initializers
6356 // > max_automatic_initializers), so num_automatic_initializers should be left as zero.
6357 array_data.Add (conv);
6358 } else if (conv is Constant) {
6359 // These are the types of Constant that can appear in arrays that can be
6360 // statically allocated.
6361 array_data.Add (conv);
6362 num_automatic_initializers++;
6364 array_data.Add (conv);
6371 public void UpdateIndices (EmitContext ec)
6374 for (ArrayList probe = initializers; probe != null;) {
6375 if (probe.Count > 0 && probe [0] is ArrayList) {
6376 Expression e = new IntConstant (probe.Count);
6377 arguments.Add (new Argument (e, Argument.AType.Expression));
6379 bounds [i++] = probe.Count;
6381 probe = (ArrayList) probe [0];
6384 Expression e = new IntConstant (probe.Count);
6385 arguments.Add (new Argument (e, Argument.AType.Expression));
6387 bounds [i++] = probe.Count;
6394 public bool ValidateInitializers (EmitContext ec, Type array_type)
6396 if (initializers == null) {
6397 if (expect_initializers)
6403 if (underlying_type == null)
6407 // We use this to store all the date values in the order in which we
6408 // will need to store them in the byte blob later
6410 array_data = new ArrayList ();
6411 bounds = new Hashtable ();
6415 if (arguments != null) {
6416 ret = CheckIndices (ec, initializers, 0, true);
6419 arguments = new ArrayList ();
6421 ret = CheckIndices (ec, initializers, 0, false);
6428 if (arguments.Count != dimensions) {
6429 Error_IncorrectArrayInitializer ();
6438 // Creates the type of the array
6440 bool LookupType (EmitContext ec)
6442 StringBuilder array_qualifier = new StringBuilder (rank);
6445 // `In the first form allocates an array instace of the type that results
6446 // from deleting each of the individual expression from the expression list'
6448 if (num_arguments > 0) {
6449 array_qualifier.Append ("[");
6450 for (int i = num_arguments-1; i > 0; i--)
6451 array_qualifier.Append (",");
6452 array_qualifier.Append ("]");
6458 TypeExpr array_type_expr;
6459 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
6460 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec);
6461 if (array_type_expr == null)
6464 type = array_type_expr.Type;
6466 if (!type.IsArray) {
6467 Error (622, "Can only use array initializer expressions to assign to array types. Try using a new expression instead.");
6470 underlying_type = TypeManager.GetElementType (type);
6471 dimensions = type.GetArrayRank ();
6476 public override Expression DoResolve (EmitContext ec)
6480 if (!LookupType (ec))
6484 // First step is to validate the initializers and fill
6485 // in any missing bits
6487 if (!ValidateInitializers (ec, type))
6490 if (arguments == null)
6493 arg_count = arguments.Count;
6494 foreach (Argument a in arguments){
6495 if (!a.Resolve (ec, loc))
6498 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
6499 if (real_arg == null)
6506 array_element_type = TypeManager.GetElementType (type);
6508 if (array_element_type.IsAbstract && array_element_type.IsSealed) {
6509 Report.Error (719, loc, "'{0}': array elements cannot be of static type", TypeManager.CSharpName (array_element_type));
6513 if (arg_count == 1) {
6514 is_one_dimensional = true;
6515 eclass = ExprClass.Value;
6519 is_builtin_type = TypeManager.IsBuiltinType (type);
6521 if (is_builtin_type) {
6524 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
6525 AllBindingFlags, loc);
6527 if (!(ml is MethodGroupExpr)) {
6528 ml.Error_UnexpectedKind ("method group", loc);
6533 Error (-6, "New invocation: Can not find a constructor for " +
6534 "this argument list");
6538 new_method = Invocation.OverloadResolve (
6539 ec, (MethodGroupExpr) ml, arguments, false, loc);
6541 if (new_method == null) {
6542 Error (-6, "New invocation: Can not find a constructor for " +
6543 "this argument list");
6547 eclass = ExprClass.Value;
6550 ModuleBuilder mb = CodeGen.Module.Builder;
6551 ArrayList args = new ArrayList ();
6553 if (arguments != null) {
6554 for (int i = 0; i < arg_count; i++)
6555 args.Add (TypeManager.int32_type);
6558 Type [] arg_types = null;
6561 arg_types = new Type [args.Count];
6563 args.CopyTo (arg_types, 0);
6565 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
6568 if (new_method == null) {
6569 Error (-6, "New invocation: Can not find a constructor for " +
6570 "this argument list");
6574 eclass = ExprClass.Value;
6579 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
6584 int count = array_data.Count;
6586 if (underlying_type.IsEnum)
6587 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
6589 factor = GetTypeSize (underlying_type);
6591 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
6593 data = new byte [(count * factor + 4) & ~3];
6596 for (int i = 0; i < count; ++i) {
6597 object v = array_data [i];
6599 if (v is EnumConstant)
6600 v = ((EnumConstant) v).Child;
6602 if (v is Constant && !(v is StringConstant))
6603 v = ((Constant) v).GetValue ();
6609 if (underlying_type == TypeManager.int64_type){
6610 if (!(v is Expression)){
6611 long val = (long) v;
6613 for (int j = 0; j < factor; ++j) {
6614 data [idx + j] = (byte) (val & 0xFF);
6618 } else if (underlying_type == TypeManager.uint64_type){
6619 if (!(v is Expression)){
6620 ulong val = (ulong) v;
6622 for (int j = 0; j < factor; ++j) {
6623 data [idx + j] = (byte) (val & 0xFF);
6627 } else if (underlying_type == TypeManager.float_type) {
6628 if (!(v is Expression)){
6629 element = BitConverter.GetBytes ((float) v);
6631 for (int j = 0; j < factor; ++j)
6632 data [idx + j] = element [j];
6634 } else if (underlying_type == TypeManager.double_type) {
6635 if (!(v is Expression)){
6636 element = BitConverter.GetBytes ((double) v);
6638 for (int j = 0; j < factor; ++j)
6639 data [idx + j] = element [j];
6641 } else if (underlying_type == TypeManager.char_type){
6642 if (!(v is Expression)){
6643 int val = (int) ((char) v);
6645 data [idx] = (byte) (val & 0xff);
6646 data [idx+1] = (byte) (val >> 8);
6648 } else if (underlying_type == TypeManager.short_type){
6649 if (!(v is Expression)){
6650 int val = (int) ((short) v);
6652 data [idx] = (byte) (val & 0xff);
6653 data [idx+1] = (byte) (val >> 8);
6655 } else if (underlying_type == TypeManager.ushort_type){
6656 if (!(v is Expression)){
6657 int val = (int) ((ushort) v);
6659 data [idx] = (byte) (val & 0xff);
6660 data [idx+1] = (byte) (val >> 8);
6662 } else if (underlying_type == TypeManager.int32_type) {
6663 if (!(v is Expression)){
6666 data [idx] = (byte) (val & 0xff);
6667 data [idx+1] = (byte) ((val >> 8) & 0xff);
6668 data [idx+2] = (byte) ((val >> 16) & 0xff);
6669 data [idx+3] = (byte) (val >> 24);
6671 } else if (underlying_type == TypeManager.uint32_type) {
6672 if (!(v is Expression)){
6673 uint val = (uint) v;
6675 data [idx] = (byte) (val & 0xff);
6676 data [idx+1] = (byte) ((val >> 8) & 0xff);
6677 data [idx+2] = (byte) ((val >> 16) & 0xff);
6678 data [idx+3] = (byte) (val >> 24);
6680 } else if (underlying_type == TypeManager.sbyte_type) {
6681 if (!(v is Expression)){
6682 sbyte val = (sbyte) v;
6683 data [idx] = (byte) val;
6685 } else if (underlying_type == TypeManager.byte_type) {
6686 if (!(v is Expression)){
6687 byte val = (byte) v;
6688 data [idx] = (byte) val;
6690 } else if (underlying_type == TypeManager.bool_type) {
6691 if (!(v is Expression)){
6692 bool val = (bool) v;
6693 data [idx] = (byte) (val ? 1 : 0);
6695 } else if (underlying_type == TypeManager.decimal_type){
6696 if (!(v is Expression)){
6697 int [] bits = Decimal.GetBits ((decimal) v);
6700 // FIXME: For some reason, this doesn't work on the MS runtime.
6701 int [] nbits = new int [4];
6702 nbits [0] = bits [3];
6703 nbits [1] = bits [2];
6704 nbits [2] = bits [0];
6705 nbits [3] = bits [1];
6707 for (int j = 0; j < 4; j++){
6708 data [p++] = (byte) (nbits [j] & 0xff);
6709 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6710 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6711 data [p++] = (byte) (nbits [j] >> 24);
6715 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6724 // Emits the initializers for the array
6726 void EmitStaticInitializers (EmitContext ec)
6729 // First, the static data
6732 ILGenerator ig = ec.ig;
6734 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6736 fb = RootContext.MakeStaticData (data);
6738 ig.Emit (OpCodes.Dup);
6739 ig.Emit (OpCodes.Ldtoken, fb);
6740 ig.Emit (OpCodes.Call,
6741 TypeManager.void_initializearray_array_fieldhandle);
6745 // Emits pieces of the array that can not be computed at compile
6746 // time (variables and string locations).
6748 // This always expect the top value on the stack to be the array
6750 void EmitDynamicInitializers (EmitContext ec)
6752 ILGenerator ig = ec.ig;
6753 int dims = bounds.Count;
6754 int [] current_pos = new int [dims];
6755 int top = array_data.Count;
6757 MethodInfo set = null;
6761 ModuleBuilder mb = null;
6762 mb = CodeGen.Module.Builder;
6763 args = new Type [dims + 1];
6766 for (j = 0; j < dims; j++)
6767 args [j] = TypeManager.int32_type;
6769 args [j] = array_element_type;
6771 set = mb.GetArrayMethod (
6773 CallingConventions.HasThis | CallingConventions.Standard,
6774 TypeManager.void_type, args);
6777 for (int i = 0; i < top; i++){
6779 Expression e = null;
6781 if (array_data [i] is Expression)
6782 e = (Expression) array_data [i];
6786 // Basically we do this for string literals and
6787 // other non-literal expressions
6789 if (e is EnumConstant){
6790 e = ((EnumConstant) e).Child;
6793 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6794 num_automatic_initializers <= max_automatic_initializers) {
6795 Type etype = e.Type;
6797 ig.Emit (OpCodes.Dup);
6799 for (int idx = 0; idx < dims; idx++)
6800 IntConstant.EmitInt (ig, current_pos [idx]);
6803 // If we are dealing with a struct, get the
6804 // address of it, so we can store it.
6806 if ((dims == 1) && etype.IsValueType &&
6807 (!TypeManager.IsBuiltinOrEnum (etype) ||
6808 etype == TypeManager.decimal_type)) {
6813 // Let new know that we are providing
6814 // the address where to store the results
6816 n.DisableTemporaryValueType ();
6819 ig.Emit (OpCodes.Ldelema, etype);
6825 bool is_stobj, has_type_arg;
6826 OpCode op = ArrayAccess.GetStoreOpcode (
6827 etype, out is_stobj,
6830 ig.Emit (OpCodes.Stobj, etype);
6831 else if (has_type_arg)
6832 ig.Emit (op, etype);
6836 ig.Emit (OpCodes.Call, set);
6843 for (int j = dims - 1; j >= 0; j--){
6845 if (current_pos [j] < (int) bounds [j])
6847 current_pos [j] = 0;
6852 void EmitArrayArguments (EmitContext ec)
6854 ILGenerator ig = ec.ig;
6856 foreach (Argument a in arguments) {
6857 Type atype = a.Type;
6860 if (atype == TypeManager.uint64_type)
6861 ig.Emit (OpCodes.Conv_Ovf_U4);
6862 else if (atype == TypeManager.int64_type)
6863 ig.Emit (OpCodes.Conv_Ovf_I4);
6867 public override void Emit (EmitContext ec)
6869 ILGenerator ig = ec.ig;
6871 EmitArrayArguments (ec);
6872 if (is_one_dimensional)
6873 ig.Emit (OpCodes.Newarr, array_element_type);
6875 if (is_builtin_type)
6876 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6878 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6881 if (initializers != null){
6883 // FIXME: Set this variable correctly.
6885 bool dynamic_initializers = true;
6887 // This will never be true for array types that cannot be statically
6888 // initialized. num_automatic_initializers will always be zero. See
6890 if (num_automatic_initializers > max_automatic_initializers)
6891 EmitStaticInitializers (ec);
6893 if (dynamic_initializers)
6894 EmitDynamicInitializers (ec);
6898 public object EncodeAsAttribute ()
6900 if (!is_one_dimensional){
6901 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6905 if (array_data == null){
6906 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6910 object [] ret = new object [array_data.Count];
6912 foreach (Expression e in array_data){
6915 if (e is NullLiteral)
6918 if (!Attribute.GetAttributeArgumentExpression (e, Location, array_element_type, out v))
6928 /// Represents the `this' construct
6930 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6933 VariableInfo variable_info;
6935 public This (Block block, Location loc)
6941 public This (Location loc)
6946 public VariableInfo VariableInfo {
6947 get { return variable_info; }
6950 public bool VerifyFixed (bool is_expression)
6952 if ((variable_info == null) || (variable_info.LocalInfo == null))
6955 return variable_info.LocalInfo.IsFixed;
6958 public bool ResolveBase (EmitContext ec)
6960 eclass = ExprClass.Variable;
6962 if (ec.TypeContainer.CurrentType != null)
6963 type = ec.TypeContainer.CurrentType;
6965 type = ec.ContainerType;
6968 Error (26, "Keyword this not valid in static code");
6972 if ((block != null) && (block.ThisVariable != null))
6973 variable_info = block.ThisVariable.VariableInfo;
6975 if (ec.CurrentAnonymousMethod != null)
6981 public override Expression DoResolve (EmitContext ec)
6983 if (!ResolveBase (ec))
6986 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
6987 Error (188, "The this object cannot be used before all " +
6988 "of its fields are assigned to");
6989 variable_info.SetAssigned (ec);
6993 if (ec.IsFieldInitializer) {
6994 Error (27, "Keyword `this' can't be used outside a constructor, " +
6995 "a method or a property.");
7002 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
7004 if (!ResolveBase (ec))
7007 if (variable_info != null)
7008 variable_info.SetAssigned (ec);
7010 if (ec.TypeContainer is Class){
7011 Error (1604, "Cannot assign to 'this' because it is read-only");
7018 public void Emit (EmitContext ec, bool leave_copy)
7022 ec.ig.Emit (OpCodes.Dup);
7025 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
7027 ILGenerator ig = ec.ig;
7029 if (ec.TypeContainer is Struct){
7033 ec.ig.Emit (OpCodes.Dup);
7034 ig.Emit (OpCodes.Stobj, type);
7036 throw new Exception ("how did you get here");
7040 public override void Emit (EmitContext ec)
7042 ILGenerator ig = ec.ig;
7045 if (ec.TypeContainer is Struct)
7046 ig.Emit (OpCodes.Ldobj, type);
7049 public override int GetHashCode()
7051 return block.GetHashCode ();
7054 public override bool Equals (object obj)
7056 This t = obj as This;
7060 return block == t.block;
7063 public void AddressOf (EmitContext ec, AddressOp mode)
7068 // FIGURE OUT WHY LDARG_S does not work
7070 // consider: struct X { int val; int P { set { val = value; }}}
7072 // Yes, this looks very bad. Look at `NOTAS' for
7074 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
7079 /// Represents the `__arglist' construct
7081 public class ArglistAccess : Expression
7083 public ArglistAccess (Location loc)
7088 public bool ResolveBase (EmitContext ec)
7090 eclass = ExprClass.Variable;
7091 type = TypeManager.runtime_argument_handle_type;
7095 public override Expression DoResolve (EmitContext ec)
7097 if (!ResolveBase (ec))
7100 if (ec.IsFieldInitializer || !ec.CurrentBlock.HasVarargs) {
7101 Error (190, "The __arglist construct is valid only within " +
7102 "a variable argument method.");
7109 public override void Emit (EmitContext ec)
7111 ec.ig.Emit (OpCodes.Arglist);
7116 /// Represents the `__arglist (....)' construct
7118 public class Arglist : Expression
7120 public readonly Argument[] Arguments;
7122 public Arglist (Argument[] args, Location l)
7128 public Type[] ArgumentTypes {
7130 Type[] retval = new Type [Arguments.Length];
7131 for (int i = 0; i < Arguments.Length; i++)
7132 retval [i] = Arguments [i].Type;
7137 public override Expression DoResolve (EmitContext ec)
7139 eclass = ExprClass.Variable;
7140 type = TypeManager.runtime_argument_handle_type;
7142 foreach (Argument arg in Arguments) {
7143 if (!arg.Resolve (ec, loc))
7150 public override void Emit (EmitContext ec)
7152 foreach (Argument arg in Arguments)
7158 // This produces the value that renders an instance, used by the iterators code
7160 public class ProxyInstance : Expression, IMemoryLocation {
7161 public override Expression DoResolve (EmitContext ec)
7163 eclass = ExprClass.Variable;
7164 type = ec.ContainerType;
7168 public override void Emit (EmitContext ec)
7170 ec.ig.Emit (OpCodes.Ldarg_0);
7174 public void AddressOf (EmitContext ec, AddressOp mode)
7176 ec.ig.Emit (OpCodes.Ldarg_0);
7181 /// Implements the typeof operator
7183 public class TypeOf : Expression {
7184 public Expression QueriedType;
7185 protected Type typearg;
7187 public TypeOf (Expression queried_type, Location l)
7189 QueriedType = queried_type;
7193 public override Expression DoResolve (EmitContext ec)
7195 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec);
7199 typearg = texpr.Type;
7201 if (typearg == TypeManager.void_type) {
7202 Error (673, "System.Void cannot be used from C# - " +
7203 "use typeof (void) to get the void type object");
7207 if (typearg.IsPointer && !ec.InUnsafe){
7211 CheckObsoleteAttribute (typearg);
7213 type = TypeManager.type_type;
7214 eclass = ExprClass.Type;
7218 public override void Emit (EmitContext ec)
7220 ec.ig.Emit (OpCodes.Ldtoken, typearg);
7221 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
7224 public Type TypeArg {
7225 get { return typearg; }
7230 /// Implements the `typeof (void)' operator
7232 public class TypeOfVoid : TypeOf {
7233 public TypeOfVoid (Location l) : base (null, l)
7238 public override Expression DoResolve (EmitContext ec)
7240 type = TypeManager.type_type;
7241 typearg = TypeManager.void_type;
7242 eclass = ExprClass.Type;
7248 /// Implements the sizeof expression
7250 public class SizeOf : Expression {
7251 public Expression QueriedType;
7254 public SizeOf (Expression queried_type, Location l)
7256 this.QueriedType = queried_type;
7260 public override Expression DoResolve (EmitContext ec)
7262 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec);
7266 if (texpr is TypeParameterExpr){
7267 ((TypeParameterExpr)texpr).Error_CannotUseAsUnmanagedType (loc);
7271 type_queried = texpr.Type;
7273 int size_of = GetTypeSize (type_queried);
7275 return new IntConstant (size_of);
7279 Report.Error (233, loc, "'{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)",
7280 TypeManager.CSharpName (type_queried));
7284 CheckObsoleteAttribute (type_queried);
7286 if (!TypeManager.IsUnmanagedType (type_queried)){
7287 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
7291 type = TypeManager.int32_type;
7292 eclass = ExprClass.Value;
7296 public override void Emit (EmitContext ec)
7298 int size = GetTypeSize (type_queried);
7301 ec.ig.Emit (OpCodes.Sizeof, type_queried);
7303 IntConstant.EmitInt (ec.ig, size);
7308 /// Implements the member access expression
7310 public class MemberAccess : Expression {
7311 public string Identifier;
7312 protected Expression expr;
7313 protected TypeArguments args;
7315 public MemberAccess (Expression expr, string id, Location l)
7322 public MemberAccess (Expression expr, string id, TypeArguments args,
7324 : this (expr, id, l)
7329 public Expression Expr {
7335 public virtual Expression DoResolve (EmitContext ec, Expression right_side,
7339 throw new Exception ();
7342 // Resolve the expression with flow analysis turned off, we'll do the definite
7343 // assignment checks later. This is because we don't know yet what the expression
7344 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7345 // definite assignment check on the actual field and not on the whole struct.
7348 SimpleName original = expr as SimpleName;
7349 expr = expr.Resolve (ec, flags | ResolveFlags.Intermediate | ResolveFlags.DisableFlowAnalysis);
7353 if (expr is Namespace) {
7354 Namespace ns = (Namespace) expr;
7355 string lookup_id = MemberName.MakeName (Identifier, args);
7356 FullNamedExpression retval = ns.Lookup (ec.DeclSpace, lookup_id, loc);
7357 if ((retval != null) && (args != null))
7358 retval = new ConstructedType (retval, args, loc).ResolveAsTypeStep (ec);
7360 Report.Error (234, loc, "The type or namespace name `{0}' could not be found in namespace `{1}'", Identifier, ns.FullName);
7365 // TODO: I mailed Ravi about this, and apparently we can get rid
7366 // of this and put it in the right place.
7368 // Handle enums here when they are in transit.
7369 // Note that we cannot afford to hit MemberLookup in this case because
7370 // it will fail to find any members at all
7374 if (expr is TypeExpr){
7375 expr_type = expr.Type;
7377 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
7378 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", expr_type);
7382 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
7383 Enum en = TypeManager.LookupEnum (expr_type);
7386 object value = en.LookupEnumValue (Identifier, loc);
7389 MemberCore mc = en.GetDefinition (Identifier);
7390 ObsoleteAttribute oa = mc.GetObsoleteAttribute (en);
7392 AttributeTester.Report_ObsoleteMessage (oa, mc.GetSignatureForError (), Location);
7394 oa = en.GetObsoleteAttribute (en);
7396 AttributeTester.Report_ObsoleteMessage (oa, en.GetSignatureForError (), Location);
7399 Constant c = Constantify (value, en.UnderlyingType);
7400 return new EnumConstant (c, expr_type);
7403 CheckObsoleteAttribute (expr_type);
7405 FieldInfo fi = expr_type.GetField (Identifier);
7407 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
7409 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), Location);
7414 expr_type = expr.Type;
7416 if (expr_type.IsPointer){
7417 Error (23, "The `.' operator can not be applied to pointer operands (" +
7418 TypeManager.CSharpName (expr_type) + ")");
7422 Expression member_lookup;
7423 member_lookup = MemberLookup (
7424 ec, expr_type, expr_type, Identifier, loc);
7425 if ((member_lookup == null) && (args != null)) {
7426 string lookup_id = MemberName.MakeName (Identifier, args);
7427 member_lookup = MemberLookup (
7428 ec, expr_type, expr_type, lookup_id, loc);
7430 if (member_lookup == null) {
7431 MemberLookupFailed (
7432 ec, expr_type, expr_type, Identifier, null, false, loc);
7436 if (member_lookup is TypeExpr) {
7437 if (!(expr is TypeExpr) &&
7438 (original == null || !original.IdenticalNameAndTypeName (ec, expr, loc))) {
7439 Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
7440 member_lookup.Type + "' instead");
7444 return member_lookup;
7447 MemberExpr me = (MemberExpr) member_lookup;
7448 member_lookup = me.ResolveMemberAccess (ec, expr, loc, original);
7449 if (member_lookup == null)
7453 MethodGroupExpr mg = member_lookup as MethodGroupExpr;
7455 throw new InternalErrorException ();
7457 return mg.ResolveGeneric (ec, args);
7460 // The following DoResolve/DoResolveLValue will do the definite assignment
7463 if (right_side != null)
7464 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
7466 member_lookup = member_lookup.DoResolve (ec);
7468 return member_lookup;
7471 public override Expression DoResolve (EmitContext ec)
7473 return DoResolve (ec, null, ResolveFlags.VariableOrValue | ResolveFlags.Type);
7476 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7478 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue | ResolveFlags.Type);
7481 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
7483 return ResolveNamespaceOrType (ec, false);
7486 public FullNamedExpression ResolveNamespaceOrType (EmitContext ec, bool silent)
7488 FullNamedExpression new_expr = expr.ResolveAsTypeStep (ec);
7490 if (new_expr == null)
7493 string lookup_id = MemberName.MakeName (Identifier, args);
7495 if (new_expr is Namespace) {
7496 Namespace ns = (Namespace) new_expr;
7497 FullNamedExpression retval = ns.Lookup (ec.DeclSpace, lookup_id, loc);
7498 if ((retval != null) && (args != null))
7499 retval = new ConstructedType (retval, args, loc).ResolveAsTypeStep (ec);
7500 if (!silent && retval == null)
7501 Report.Error (234, loc, "The type or namespace name `{0}' could not be found in namespace `{1}'", Identifier, ns.FullName);
7505 TypeExpr tnew_expr = new_expr.ResolveAsTypeTerminal (ec);
7506 if (tnew_expr == null)
7509 Type expr_type = tnew_expr.Type;
7511 if (expr_type.IsPointer){
7512 Error (23, "The `.' operator can not be applied to pointer operands (" +
7513 TypeManager.CSharpName (expr_type) + ")");
7517 Expression member_lookup = MemberLookup (ec, expr_type, expr_type, lookup_id, loc);
7518 if (member_lookup == null) {
7519 int errors = Report.Errors;
7520 MemberLookupFailed (ec, expr_type, expr_type, lookup_id, null, false, loc);
7522 if (!silent && errors == Report.Errors)
7523 Report.Error (234, loc, "The type name `{0}' could not be found in type `{1}'",
7524 lookup_id, new_expr.FullName);
7528 if (!(member_lookup is TypeExpr)) {
7529 Report.Error (118, loc, "'{0}.{1}' denotes a '{2}', where a type was expected",
7530 new_expr.FullName, lookup_id, member_lookup.ExprClassName ());
7534 TypeExpr texpr = member_lookup.ResolveAsTypeTerminal (ec);
7538 TypeArguments the_args = args;
7539 if (TypeManager.HasGenericArguments (expr_type)) {
7540 Type[] decl_args = TypeManager.GetTypeArguments (expr_type);
7542 TypeArguments new_args = new TypeArguments (loc);
7543 foreach (Type decl in decl_args)
7544 new_args.Add (new TypeExpression (decl, loc));
7547 new_args.Add (args);
7549 the_args = new_args;
7552 if (the_args != null) {
7553 ConstructedType ctype = new ConstructedType (texpr.Type, the_args, loc);
7554 return ctype.ResolveAsTypeStep (ec);
7560 public override void Emit (EmitContext ec)
7562 throw new Exception ("Should not happen");
7565 public override string ToString ()
7567 return expr + "." + MemberName.MakeName (Identifier, args);
7572 /// Implements checked expressions
7574 public class CheckedExpr : Expression {
7576 public Expression Expr;
7578 public CheckedExpr (Expression e, Location l)
7584 public override Expression DoResolve (EmitContext ec)
7586 bool last_check = ec.CheckState;
7587 bool last_const_check = ec.ConstantCheckState;
7589 ec.CheckState = true;
7590 ec.ConstantCheckState = true;
7591 Expr = Expr.Resolve (ec);
7592 ec.CheckState = last_check;
7593 ec.ConstantCheckState = last_const_check;
7598 if (Expr is Constant)
7601 eclass = Expr.eclass;
7606 public override void Emit (EmitContext ec)
7608 bool last_check = ec.CheckState;
7609 bool last_const_check = ec.ConstantCheckState;
7611 ec.CheckState = true;
7612 ec.ConstantCheckState = true;
7614 ec.CheckState = last_check;
7615 ec.ConstantCheckState = last_const_check;
7621 /// Implements the unchecked expression
7623 public class UnCheckedExpr : Expression {
7625 public Expression Expr;
7627 public UnCheckedExpr (Expression e, Location l)
7633 public override Expression DoResolve (EmitContext ec)
7635 bool last_check = ec.CheckState;
7636 bool last_const_check = ec.ConstantCheckState;
7638 ec.CheckState = false;
7639 ec.ConstantCheckState = false;
7640 Expr = Expr.Resolve (ec);
7641 ec.CheckState = last_check;
7642 ec.ConstantCheckState = last_const_check;
7647 if (Expr is Constant)
7650 eclass = Expr.eclass;
7655 public override void Emit (EmitContext ec)
7657 bool last_check = ec.CheckState;
7658 bool last_const_check = ec.ConstantCheckState;
7660 ec.CheckState = false;
7661 ec.ConstantCheckState = false;
7663 ec.CheckState = last_check;
7664 ec.ConstantCheckState = last_const_check;
7670 /// An Element Access expression.
7672 /// During semantic analysis these are transformed into
7673 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7675 public class ElementAccess : Expression {
7676 public ArrayList Arguments;
7677 public Expression Expr;
7679 public ElementAccess (Expression e, ArrayList e_list, Location l)
7688 Arguments = new ArrayList ();
7689 foreach (Expression tmp in e_list)
7690 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7694 bool CommonResolve (EmitContext ec)
7696 Expr = Expr.Resolve (ec);
7701 if (Arguments == null)
7704 foreach (Argument a in Arguments){
7705 if (!a.Resolve (ec, loc))
7712 Expression MakePointerAccess (EmitContext ec, Type t)
7714 if (t == TypeManager.void_ptr_type){
7715 Error (242, "The array index operation is not valid for void pointers");
7718 if (Arguments.Count != 1){
7719 Error (196, "A pointer must be indexed by a single value");
7724 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc).Resolve (ec);
7727 return new Indirection (p, loc).Resolve (ec);
7730 public override Expression DoResolve (EmitContext ec)
7732 if (!CommonResolve (ec))
7736 // We perform some simple tests, and then to "split" the emit and store
7737 // code we create an instance of a different class, and return that.
7739 // I am experimenting with this pattern.
7743 if (t == TypeManager.array_type){
7744 Report.Error (21, loc, "Cannot use indexer on System.Array");
7749 return (new ArrayAccess (this, loc)).Resolve (ec);
7751 return MakePointerAccess (ec, Expr.Type);
7753 FieldExpr fe = Expr as FieldExpr;
7755 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
7757 return MakePointerAccess (ec, ff.ElementType);
7760 return (new IndexerAccess (this, loc)).Resolve (ec);
7763 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7765 if (!CommonResolve (ec))
7770 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
7773 return MakePointerAccess (ec, Expr.Type);
7775 FieldExpr fe = Expr as FieldExpr;
7777 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
7779 if (!(fe.InstanceExpression is LocalVariableReference) &&
7780 !(fe.InstanceExpression is This)) {
7781 Error (1708, "Fixed buffers can only be accessed through locals or fields");
7784 // TODO: not sure whether it is correct
7785 // if (!ec.InFixedInitializer) {
7786 // Error (1666, "You cannot use fixed sized buffers contained in unfixed expressions. Try using the fixed statement");
7789 return MakePointerAccess (ec, ff.ElementType);
7792 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
7795 public override void Emit (EmitContext ec)
7797 throw new Exception ("Should never be reached");
7802 /// Implements array access
7804 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7806 // Points to our "data" repository
7810 LocalTemporary temp;
7813 public ArrayAccess (ElementAccess ea_data, Location l)
7816 eclass = ExprClass.Variable;
7820 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7822 return DoResolve (ec);
7825 public override Expression DoResolve (EmitContext ec)
7828 ExprClass eclass = ea.Expr.eclass;
7830 // As long as the type is valid
7831 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7832 eclass == ExprClass.Value)) {
7833 ea.Expr.Error_UnexpectedKind ("variable or value");
7838 Type t = ea.Expr.Type;
7839 if (t.GetArrayRank () != ea.Arguments.Count){
7841 "Incorrect number of indexes for array " +
7842 " expected: " + t.GetArrayRank () + " got: " +
7843 ea.Arguments.Count);
7847 type = TypeManager.GetElementType (t);
7848 if (type.IsPointer && !ec.InUnsafe){
7849 UnsafeError (ea.Location);
7853 foreach (Argument a in ea.Arguments){
7854 Type argtype = a.Type;
7856 if (argtype == TypeManager.int32_type ||
7857 argtype == TypeManager.uint32_type ||
7858 argtype == TypeManager.int64_type ||
7859 argtype == TypeManager.uint64_type) {
7860 Constant c = a.Expr as Constant;
7861 if (c != null && c.IsNegative) {
7862 Report.Warning (251, 2, a.Expr.Location, "Indexing an array with a negative index (array indices always start at zero)");
7868 // Mhm. This is strage, because the Argument.Type is not the same as
7869 // Argument.Expr.Type: the value changes depending on the ref/out setting.
7871 // Wonder if I will run into trouble for this.
7873 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
7878 eclass = ExprClass.Variable;
7884 /// Emits the right opcode to load an object of Type `t'
7885 /// from an array of T
7887 static public void EmitLoadOpcode (ILGenerator ig, Type type)
7889 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7890 ig.Emit (OpCodes.Ldelem_U1);
7891 else if (type == TypeManager.sbyte_type)
7892 ig.Emit (OpCodes.Ldelem_I1);
7893 else if (type == TypeManager.short_type)
7894 ig.Emit (OpCodes.Ldelem_I2);
7895 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7896 ig.Emit (OpCodes.Ldelem_U2);
7897 else if (type == TypeManager.int32_type)
7898 ig.Emit (OpCodes.Ldelem_I4);
7899 else if (type == TypeManager.uint32_type)
7900 ig.Emit (OpCodes.Ldelem_U4);
7901 else if (type == TypeManager.uint64_type)
7902 ig.Emit (OpCodes.Ldelem_I8);
7903 else if (type == TypeManager.int64_type)
7904 ig.Emit (OpCodes.Ldelem_I8);
7905 else if (type == TypeManager.float_type)
7906 ig.Emit (OpCodes.Ldelem_R4);
7907 else if (type == TypeManager.double_type)
7908 ig.Emit (OpCodes.Ldelem_R8);
7909 else if (type == TypeManager.intptr_type)
7910 ig.Emit (OpCodes.Ldelem_I);
7911 else if (TypeManager.IsEnumType (type)){
7912 EmitLoadOpcode (ig, TypeManager.EnumToUnderlying (type));
7913 } else if (type.IsValueType){
7914 ig.Emit (OpCodes.Ldelema, type);
7915 ig.Emit (OpCodes.Ldobj, type);
7916 } else if (type.IsGenericParameter)
7917 ig.Emit (OpCodes.Ldelem_Any, type);
7919 ig.Emit (OpCodes.Ldelem_Ref);
7923 /// Returns the right opcode to store an object of Type `t'
7924 /// from an array of T.
7926 static public OpCode GetStoreOpcode (Type t, out bool is_stobj, out bool has_type_arg)
7928 //Console.WriteLine (new System.Diagnostics.StackTrace ());
7929 has_type_arg = false; is_stobj = false;
7930 t = TypeManager.TypeToCoreType (t);
7931 if (TypeManager.IsEnumType (t))
7932 t = TypeManager.EnumToUnderlying (t);
7933 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
7934 t == TypeManager.bool_type)
7935 return OpCodes.Stelem_I1;
7936 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
7937 t == TypeManager.char_type)
7938 return OpCodes.Stelem_I2;
7939 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
7940 return OpCodes.Stelem_I4;
7941 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
7942 return OpCodes.Stelem_I8;
7943 else if (t == TypeManager.float_type)
7944 return OpCodes.Stelem_R4;
7945 else if (t == TypeManager.double_type)
7946 return OpCodes.Stelem_R8;
7947 else if (t == TypeManager.intptr_type) {
7948 has_type_arg = true;
7950 return OpCodes.Stobj;
7951 } else if (t.IsValueType) {
7952 has_type_arg = true;
7954 return OpCodes.Stobj;
7955 } else if (t.IsGenericParameter) {
7956 has_type_arg = true;
7957 return OpCodes.Stelem_Any;
7959 return OpCodes.Stelem_Ref;
7962 MethodInfo FetchGetMethod ()
7964 ModuleBuilder mb = CodeGen.Module.Builder;
7965 int arg_count = ea.Arguments.Count;
7966 Type [] args = new Type [arg_count];
7969 for (int i = 0; i < arg_count; i++){
7970 //args [i++] = a.Type;
7971 args [i] = TypeManager.int32_type;
7974 get = mb.GetArrayMethod (
7975 ea.Expr.Type, "Get",
7976 CallingConventions.HasThis |
7977 CallingConventions.Standard,
7983 MethodInfo FetchAddressMethod ()
7985 ModuleBuilder mb = CodeGen.Module.Builder;
7986 int arg_count = ea.Arguments.Count;
7987 Type [] args = new Type [arg_count];
7991 ret_type = TypeManager.GetReferenceType (type);
7993 for (int i = 0; i < arg_count; i++){
7994 //args [i++] = a.Type;
7995 args [i] = TypeManager.int32_type;
7998 address = mb.GetArrayMethod (
7999 ea.Expr.Type, "Address",
8000 CallingConventions.HasThis |
8001 CallingConventions.Standard,
8008 // Load the array arguments into the stack.
8010 // If we have been requested to cache the values (cached_locations array
8011 // initialized), then load the arguments the first time and store them
8012 // in locals. otherwise load from local variables.
8014 void LoadArrayAndArguments (EmitContext ec)
8016 ILGenerator ig = ec.ig;
8019 foreach (Argument a in ea.Arguments){
8020 Type argtype = a.Expr.Type;
8024 if (argtype == TypeManager.int64_type)
8025 ig.Emit (OpCodes.Conv_Ovf_I);
8026 else if (argtype == TypeManager.uint64_type)
8027 ig.Emit (OpCodes.Conv_Ovf_I_Un);
8031 public void Emit (EmitContext ec, bool leave_copy)
8033 int rank = ea.Expr.Type.GetArrayRank ();
8034 ILGenerator ig = ec.ig;
8037 LoadArrayAndArguments (ec);
8040 EmitLoadOpcode (ig, type);
8044 method = FetchGetMethod ();
8045 ig.Emit (OpCodes.Call, method);
8048 LoadFromPtr (ec.ig, this.type);
8051 ec.ig.Emit (OpCodes.Dup);
8052 temp = new LocalTemporary (ec, this.type);
8057 public override void Emit (EmitContext ec)
8062 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8064 int rank = ea.Expr.Type.GetArrayRank ();
8065 ILGenerator ig = ec.ig;
8066 Type t = source.Type;
8067 prepared = prepare_for_load;
8069 if (prepare_for_load) {
8070 AddressOf (ec, AddressOp.LoadStore);
8071 ec.ig.Emit (OpCodes.Dup);
8074 ec.ig.Emit (OpCodes.Dup);
8075 temp = new LocalTemporary (ec, this.type);
8078 StoreFromPtr (ec.ig, t);
8086 LoadArrayAndArguments (ec);
8089 bool is_stobj, has_type_arg;
8090 OpCode op = GetStoreOpcode (t, out is_stobj, out has_type_arg);
8093 // The stobj opcode used by value types will need
8094 // an address on the stack, not really an array/array
8098 ig.Emit (OpCodes.Ldelema, t);
8102 ec.ig.Emit (OpCodes.Dup);
8103 temp = new LocalTemporary (ec, this.type);
8108 ig.Emit (OpCodes.Stobj, t);
8109 else if (has_type_arg)
8114 ModuleBuilder mb = CodeGen.Module.Builder;
8115 int arg_count = ea.Arguments.Count;
8116 Type [] args = new Type [arg_count + 1];
8121 ec.ig.Emit (OpCodes.Dup);
8122 temp = new LocalTemporary (ec, this.type);
8126 for (int i = 0; i < arg_count; i++){
8127 //args [i++] = a.Type;
8128 args [i] = TypeManager.int32_type;
8131 args [arg_count] = type;
8133 set = mb.GetArrayMethod (
8134 ea.Expr.Type, "Set",
8135 CallingConventions.HasThis |
8136 CallingConventions.Standard,
8137 TypeManager.void_type, args);
8139 ig.Emit (OpCodes.Call, set);
8146 public void AddressOf (EmitContext ec, AddressOp mode)
8148 int rank = ea.Expr.Type.GetArrayRank ();
8149 ILGenerator ig = ec.ig;
8151 LoadArrayAndArguments (ec);
8154 ig.Emit (OpCodes.Ldelema, type);
8156 MethodInfo address = FetchAddressMethod ();
8157 ig.Emit (OpCodes.Call, address);
8164 public ArrayList Properties;
8165 static Hashtable map;
8167 public struct Indexer {
8168 public readonly Type Type;
8169 public readonly MethodInfo Getter, Setter;
8171 public Indexer (Type type, MethodInfo get, MethodInfo set)
8181 map = new Hashtable ();
8186 Properties = new ArrayList ();
8189 void Append (MemberInfo [] mi)
8191 foreach (PropertyInfo property in mi){
8192 MethodInfo get, set;
8194 get = property.GetGetMethod (true);
8195 set = property.GetSetMethod (true);
8196 Properties.Add (new Indexer (property.PropertyType, get, set));
8200 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
8202 string p_name = TypeManager.IndexerPropertyName (lookup_type);
8204 MemberInfo [] mi = TypeManager.MemberLookup (
8205 caller_type, caller_type, lookup_type, MemberTypes.Property,
8206 BindingFlags.Public | BindingFlags.Instance |
8207 BindingFlags.DeclaredOnly, p_name, null);
8209 if (mi == null || mi.Length == 0)
8215 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
8217 Indexers ix = (Indexers) map [lookup_type];
8222 Type copy = lookup_type;
8223 while (copy != TypeManager.object_type && copy != null){
8224 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
8228 ix = new Indexers ();
8233 copy = copy.BaseType;
8236 if (!lookup_type.IsInterface)
8239 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
8240 if (ifaces != null) {
8241 foreach (Type itype in ifaces) {
8242 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
8245 ix = new Indexers ();
8257 /// Expressions that represent an indexer call.
8259 public class IndexerAccess : Expression, IAssignMethod {
8261 // Points to our "data" repository
8263 MethodInfo get, set;
8264 ArrayList set_arguments;
8265 bool is_base_indexer;
8267 protected Type indexer_type;
8268 protected Type current_type;
8269 protected Expression instance_expr;
8270 protected ArrayList arguments;
8272 public IndexerAccess (ElementAccess ea, Location loc)
8273 : this (ea.Expr, false, loc)
8275 this.arguments = ea.Arguments;
8278 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
8281 this.instance_expr = instance_expr;
8282 this.is_base_indexer = is_base_indexer;
8283 this.eclass = ExprClass.Value;
8287 protected virtual bool CommonResolve (EmitContext ec)
8289 indexer_type = instance_expr.Type;
8290 current_type = ec.ContainerType;
8295 public override Expression DoResolve (EmitContext ec)
8297 ArrayList AllGetters = new ArrayList();
8298 if (!CommonResolve (ec))
8302 // Step 1: Query for all `Item' *properties*. Notice
8303 // that the actual methods are pointed from here.
8305 // This is a group of properties, piles of them.
8307 bool found_any = false, found_any_getters = false;
8308 Type lookup_type = indexer_type;
8311 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
8312 if (ilist != null) {
8314 if (ilist.Properties != null) {
8315 foreach (Indexers.Indexer ix in ilist.Properties) {
8316 if (ix.Getter != null)
8317 AllGetters.Add(ix.Getter);
8322 if (AllGetters.Count > 0) {
8323 found_any_getters = true;
8324 get = (MethodInfo) Invocation.OverloadResolve (
8325 ec, new MethodGroupExpr (AllGetters, loc),
8326 arguments, false, loc);
8330 Report.Error (21, loc,
8331 "Type `" + TypeManager.CSharpName (indexer_type) +
8332 "' does not have any indexers defined");
8336 if (!found_any_getters) {
8337 Error (154, "indexer can not be used in this context, because " +
8338 "it lacks a `get' accessor");
8343 Error (1501, "No Overload for method `this' takes `" +
8344 arguments.Count + "' arguments");
8349 // Only base will allow this invocation to happen.
8351 if (get.IsAbstract && this is BaseIndexerAccess){
8352 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
8356 type = get.ReturnType;
8357 if (type.IsPointer && !ec.InUnsafe){
8362 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8364 eclass = ExprClass.IndexerAccess;
8368 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8370 ArrayList AllSetters = new ArrayList();
8371 if (!CommonResolve (ec))
8374 bool found_any = false, found_any_setters = false;
8376 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
8377 if (ilist != null) {
8379 if (ilist.Properties != null) {
8380 foreach (Indexers.Indexer ix in ilist.Properties) {
8381 if (ix.Setter != null)
8382 AllSetters.Add(ix.Setter);
8386 if (AllSetters.Count > 0) {
8387 found_any_setters = true;
8388 set_arguments = (ArrayList) arguments.Clone ();
8389 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
8390 set = (MethodInfo) Invocation.OverloadResolve (
8391 ec, new MethodGroupExpr (AllSetters, loc),
8392 set_arguments, false, loc);
8396 Report.Error (21, loc,
8397 "Type `" + TypeManager.CSharpName (indexer_type) +
8398 "' does not have any indexers defined");
8402 if (!found_any_setters) {
8403 Error (154, "indexer can not be used in this context, because " +
8404 "it lacks a `set' accessor");
8409 Error (1501, "No Overload for method `this' takes `" +
8410 arguments.Count + "' arguments");
8415 // Only base will allow this invocation to happen.
8417 if (set.IsAbstract && this is BaseIndexerAccess){
8418 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
8423 // Now look for the actual match in the list of indexers to set our "return" type
8425 type = TypeManager.void_type; // default value
8426 foreach (Indexers.Indexer ix in ilist.Properties){
8427 if (ix.Setter == set){
8433 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8435 eclass = ExprClass.IndexerAccess;
8439 bool prepared = false;
8440 LocalTemporary temp;
8442 public void Emit (EmitContext ec, bool leave_copy)
8444 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc, prepared, false);
8446 ec.ig.Emit (OpCodes.Dup);
8447 temp = new LocalTemporary (ec, Type);
8453 // source is ignored, because we already have a copy of it from the
8454 // LValue resolution and we have already constructed a pre-cached
8455 // version of the arguments (ea.set_arguments);
8457 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8459 prepared = prepare_for_load;
8460 Argument a = (Argument) set_arguments [set_arguments.Count - 1];
8465 ec.ig.Emit (OpCodes.Dup);
8466 temp = new LocalTemporary (ec, Type);
8469 } else if (leave_copy) {
8470 temp = new LocalTemporary (ec, Type);
8476 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc, false, prepared);
8483 public override void Emit (EmitContext ec)
8490 /// The base operator for method names
8492 public class BaseAccess : Expression {
8495 public BaseAccess (string member, Location l)
8497 this.member = member;
8501 public override Expression DoResolve (EmitContext ec)
8503 Expression c = CommonResolve (ec);
8509 // MethodGroups use this opportunity to flag an error on lacking ()
8511 if (!(c is MethodGroupExpr))
8512 return c.Resolve (ec);
8516 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8518 Expression c = CommonResolve (ec);
8524 // MethodGroups use this opportunity to flag an error on lacking ()
8526 if (! (c is MethodGroupExpr))
8527 return c.DoResolveLValue (ec, right_side);
8532 Expression CommonResolve (EmitContext ec)
8534 Expression member_lookup;
8535 Type current_type = ec.ContainerType;
8536 Type base_type = current_type.BaseType;
8539 Error (1511, "Keyword base is not allowed in static method");
8543 if (ec.IsFieldInitializer){
8544 Error (1512, "Keyword base is not available in the current context");
8548 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type,
8549 member, AllMemberTypes, AllBindingFlags,
8551 if (member_lookup == null) {
8552 MemberLookupFailed (ec, base_type, base_type, member, null, true, loc);
8559 left = new TypeExpression (base_type, loc);
8561 left = ec.GetThis (loc);
8563 MemberExpr me = (MemberExpr) member_lookup;
8565 Expression e = me.ResolveMemberAccess (ec, left, loc, null);
8567 if (e is PropertyExpr) {
8568 PropertyExpr pe = (PropertyExpr) e;
8573 if (e is MethodGroupExpr)
8574 ((MethodGroupExpr) e).IsBase = true;
8579 public override void Emit (EmitContext ec)
8581 throw new Exception ("Should never be called");
8586 /// The base indexer operator
8588 public class BaseIndexerAccess : IndexerAccess {
8589 public BaseIndexerAccess (ArrayList args, Location loc)
8590 : base (null, true, loc)
8592 arguments = new ArrayList ();
8593 foreach (Expression tmp in args)
8594 arguments.Add (new Argument (tmp, Argument.AType.Expression));
8597 protected override bool CommonResolve (EmitContext ec)
8599 instance_expr = ec.GetThis (loc);
8601 current_type = ec.ContainerType.BaseType;
8602 indexer_type = current_type;
8604 foreach (Argument a in arguments){
8605 if (!a.Resolve (ec, loc))
8614 /// This class exists solely to pass the Type around and to be a dummy
8615 /// that can be passed to the conversion functions (this is used by
8616 /// foreach implementation to typecast the object return value from
8617 /// get_Current into the proper type. All code has been generated and
8618 /// we only care about the side effect conversions to be performed
8620 /// This is also now used as a placeholder where a no-action expression
8621 /// is needed (the `New' class).
8623 public class EmptyExpression : Expression {
8624 public static readonly EmptyExpression Null = new EmptyExpression ();
8626 // TODO: should be protected
8627 public EmptyExpression ()
8629 type = TypeManager.object_type;
8630 eclass = ExprClass.Value;
8631 loc = Location.Null;
8634 public EmptyExpression (Type t)
8637 eclass = ExprClass.Value;
8638 loc = Location.Null;
8641 public override Expression DoResolve (EmitContext ec)
8646 public override void Emit (EmitContext ec)
8648 // nothing, as we only exist to not do anything.
8652 // This is just because we might want to reuse this bad boy
8653 // instead of creating gazillions of EmptyExpressions.
8654 // (CanImplicitConversion uses it)
8656 public void SetType (Type t)
8662 public class UserCast : Expression {
8666 public UserCast (MethodInfo method, Expression source, Location l)
8668 this.method = method;
8669 this.source = source;
8670 type = method.ReturnType;
8671 eclass = ExprClass.Value;
8675 public Expression Source {
8681 public override Expression DoResolve (EmitContext ec)
8684 // We are born fully resolved
8689 public override void Emit (EmitContext ec)
8691 ILGenerator ig = ec.ig;
8695 if (method is MethodInfo)
8696 ig.Emit (OpCodes.Call, (MethodInfo) method);
8698 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
8704 // This class is used to "construct" the type during a typecast
8705 // operation. Since the Type.GetType class in .NET can parse
8706 // the type specification, we just use this to construct the type
8707 // one bit at a time.
8709 public class ComposedCast : TypeExpr {
8713 public ComposedCast (Expression left, string dim, Location l)
8720 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
8722 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec);
8726 Type ltype = lexpr.Type;
8728 if ((ltype == TypeManager.void_type) && (dim != "*")) {
8729 Report.Error (1547, Location,
8730 "Keyword 'void' cannot be used in this context");
8734 if ((dim.Length > 0) && (dim [0] == '?')) {
8735 TypeExpr nullable = new NullableType (left, loc);
8737 nullable = new ComposedCast (nullable, dim.Substring (1), loc);
8738 return nullable.ResolveAsTypeTerminal (ec);
8741 if (dim == "*" && !TypeManager.IsUnmanagedType (ltype)) {
8742 Report.Error (208, loc, "Cannot declare a pointer to a managed type ('{0}')", ltype);
8747 type = TypeManager.GetConstructedType (ltype, dim);
8752 throw new InternalErrorException ("Couldn't create computed type " + ltype + dim);
8755 if (!ec.InUnsafe && type.IsPointer){
8760 if (type.IsArray && (type.GetElementType () == TypeManager.arg_iterator_type ||
8761 type.GetElementType () == TypeManager.typed_reference_type)) {
8762 Report.Error (611, loc, "Array elements cannot be of type '{0}'", TypeManager.CSharpName (type.GetElementType ()));
8766 eclass = ExprClass.Type;
8770 public override string Name {
8776 public override string FullName {
8778 return type.FullName;
8783 public class FixedBufferPtr: Expression {
8786 public FixedBufferPtr (Expression array, Type array_type, Location l)
8791 type = TypeManager.GetPointerType (array_type);
8792 eclass = ExprClass.Value;
8795 public override void Emit(EmitContext ec)
8800 public override Expression DoResolve (EmitContext ec)
8803 // We are born fully resolved
8811 // This class is used to represent the address of an array, used
8812 // only by the Fixed statement, this generates "&a [0]" construct
8813 // for fixed (char *pa = a)
8815 public class ArrayPtr : FixedBufferPtr {
8818 public ArrayPtr (Expression array, Type array_type, Location l):
8819 base (array, array_type, l)
8821 this.array_type = array_type;
8824 public override void Emit (EmitContext ec)
8828 ILGenerator ig = ec.ig;
8829 IntLiteral.EmitInt (ig, 0);
8830 ig.Emit (OpCodes.Ldelema, array_type);
8835 // Used by the fixed statement
8837 public class StringPtr : Expression {
8840 public StringPtr (LocalBuilder b, Location l)
8843 eclass = ExprClass.Value;
8844 type = TypeManager.char_ptr_type;
8848 public override Expression DoResolve (EmitContext ec)
8850 // This should never be invoked, we are born in fully
8851 // initialized state.
8856 public override void Emit (EmitContext ec)
8858 ILGenerator ig = ec.ig;
8860 ig.Emit (OpCodes.Ldloc, b);
8861 ig.Emit (OpCodes.Conv_I);
8862 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
8863 ig.Emit (OpCodes.Add);
8868 // Implements the `stackalloc' keyword
8870 public class StackAlloc : Expression {
8875 public StackAlloc (Expression type, Expression count, Location l)
8882 public override Expression DoResolve (EmitContext ec)
8884 count = count.Resolve (ec);
8888 if (count.Type != TypeManager.int32_type){
8889 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8894 Constant c = count as Constant;
8895 if (c != null && c.IsNegative) {
8896 Report.Error (247, loc, "Cannot use a negative size with stackalloc");
8900 if (ec.CurrentBranching.InCatch () ||
8901 ec.CurrentBranching.InFinally (true)) {
8903 "stackalloc can not be used in a catch or finally block");
8907 TypeExpr texpr = t.ResolveAsTypeTerminal (ec);
8913 if (!TypeManager.VerifyUnManaged (otype, loc))
8916 type = TypeManager.GetPointerType (otype);
8917 eclass = ExprClass.Value;
8922 public override void Emit (EmitContext ec)
8924 int size = GetTypeSize (otype);
8925 ILGenerator ig = ec.ig;
8928 ig.Emit (OpCodes.Sizeof, otype);
8930 IntConstant.EmitInt (ig, size);
8932 ig.Emit (OpCodes.Mul);
8933 ig.Emit (OpCodes.Localloc);