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 ();
2263 // This is used to check if a test 'x == null' can be optimized to a reference equals,
2264 // i.e., not invoke op_Equality.
2266 static bool EqualsNullIsReferenceEquals (Type t)
2268 return t == TypeManager.object_type || t == TypeManager.string_type ||
2269 t == TypeManager.delegate_type || t.IsSubclassOf (TypeManager.delegate_type);
2272 Expression ResolveOperator (EmitContext ec)
2275 Type r = right.Type;
2277 if (oper == Operator.Equality || oper == Operator.Inequality){
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 // Optimize out call to op_Equality in a few cases.
2303 if ((l == TypeManager.null_type && EqualsNullIsReferenceEquals (r)) ||
2304 (r == TypeManager.null_type && EqualsNullIsReferenceEquals (l))) {
2305 Type = TypeManager.bool_type;
2311 if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
2312 Type = TypeManager.bool_type;
2319 // Do not perform operator overload resolution when both sides are
2322 if (!(TypeManager.IsPrimitiveType (l) && TypeManager.IsPrimitiveType (r))){
2324 // Step 1: Perform Operator Overload location
2326 Expression left_expr, right_expr;
2328 string op = oper_names [(int) oper];
2330 MethodGroupExpr union;
2331 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2333 right_expr = MemberLookup (
2334 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2335 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2337 union = (MethodGroupExpr) left_expr;
2339 if (union != null) {
2340 ArrayList args = new ArrayList (2);
2341 args.Add (new Argument (left, Argument.AType.Expression));
2342 args.Add (new Argument (right, Argument.AType.Expression));
2344 MethodBase method = Invocation.OverloadResolve (
2345 ec, union, args, true, Location.Null);
2347 if (method != null) {
2348 MethodInfo mi = (MethodInfo) method;
2350 return new BinaryMethod (mi.ReturnType, method, args);
2356 // Step 0: String concatenation (because overloading will get this wrong)
2358 if (oper == Operator.Addition){
2360 // If any of the arguments is a string, cast to string
2363 // Simple constant folding
2364 if (left is StringConstant && right is StringConstant)
2365 return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value);
2367 if (l == TypeManager.string_type || r == TypeManager.string_type) {
2369 if (r == TypeManager.void_type || l == TypeManager.void_type) {
2370 Error_OperatorCannotBeApplied ();
2374 // try to fold it in on the left
2375 if (left is StringConcat) {
2378 // We have to test here for not-null, since we can be doubly-resolved
2379 // take care of not appending twice
2382 type = TypeManager.string_type;
2383 ((StringConcat) left).Append (ec, right);
2384 return left.Resolve (ec);
2390 // Otherwise, start a new concat expression
2391 return new StringConcat (ec, loc, left, right).Resolve (ec);
2395 // Transform a + ( - b) into a - b
2397 if (right is Unary){
2398 Unary right_unary = (Unary) right;
2400 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2401 oper = Operator.Subtraction;
2402 right = right_unary.Expr;
2408 if (oper == Operator.Equality || oper == Operator.Inequality){
2409 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2410 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2411 Error_OperatorCannotBeApplied ();
2415 type = TypeManager.bool_type;
2419 if (l.IsPointer || r.IsPointer) {
2420 if (l.IsPointer && r.IsPointer) {
2421 type = TypeManager.bool_type;
2425 if (l.IsPointer && r == TypeManager.null_type) {
2426 right = new EmptyCast (NullPointer.Null, l);
2427 type = TypeManager.bool_type;
2431 if (r.IsPointer && l == TypeManager.null_type) {
2432 left = new EmptyCast (NullPointer.Null, r);
2433 type = TypeManager.bool_type;
2439 // operator != (object a, object b)
2440 // operator == (object a, object b)
2442 // For this to be used, both arguments have to be reference-types.
2443 // Read the rationale on the spec (14.9.6)
2445 // Also, if at compile time we know that the classes do not inherit
2446 // one from the other, then we catch the error there.
2448 if (!(l.IsValueType || r.IsValueType)){
2449 type = TypeManager.bool_type;
2454 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2458 // Also, a standard conversion must exist from either one
2460 if (!(Convert.ImplicitStandardConversionExists (ec, left, r) ||
2461 Convert.ImplicitStandardConversionExists (ec, right, l))){
2462 Error_OperatorCannotBeApplied ();
2466 // We are going to have to convert to an object to compare
2468 if (l != TypeManager.object_type)
2469 left = new EmptyCast (left, TypeManager.object_type);
2470 if (r != TypeManager.object_type)
2471 right = new EmptyCast (right, TypeManager.object_type);
2474 // FIXME: CSC here catches errors cs254 and cs252
2480 // One of them is a valuetype, but the other one is not.
2482 if (!l.IsValueType || !r.IsValueType) {
2483 Error_OperatorCannotBeApplied ();
2488 // Only perform numeric promotions on:
2489 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2491 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2492 if (TypeManager.IsDelegateType (l)){
2493 if (((right.eclass == ExprClass.MethodGroup) ||
2494 (r == TypeManager.anonymous_method_type))){
2495 if ((RootContext.Version != LanguageVersion.ISO_1)){
2496 Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2504 if (TypeManager.IsDelegateType (r)){
2506 ArrayList args = new ArrayList (2);
2508 args = new ArrayList (2);
2509 args.Add (new Argument (left, Argument.AType.Expression));
2510 args.Add (new Argument (right, Argument.AType.Expression));
2512 if (oper == Operator.Addition)
2513 method = TypeManager.delegate_combine_delegate_delegate;
2515 method = TypeManager.delegate_remove_delegate_delegate;
2517 if (!TypeManager.IsEqual (l, r)) {
2518 Error_OperatorCannotBeApplied ();
2522 return new BinaryDelegate (l, method, args);
2527 // Pointer arithmetic:
2529 // T* operator + (T* x, int y);
2530 // T* operator + (T* x, uint y);
2531 // T* operator + (T* x, long y);
2532 // T* operator + (T* x, ulong y);
2534 // T* operator + (int y, T* x);
2535 // T* operator + (uint y, T *x);
2536 // T* operator + (long y, T *x);
2537 // T* operator + (ulong y, T *x);
2539 // T* operator - (T* x, int y);
2540 // T* operator - (T* x, uint y);
2541 // T* operator - (T* x, long y);
2542 // T* operator - (T* x, ulong y);
2544 // long operator - (T* x, T *y)
2547 if (r.IsPointer && oper == Operator.Subtraction){
2549 return new PointerArithmetic (
2550 false, left, right, TypeManager.int64_type,
2553 Expression t = Make32or64 (ec, right);
2555 return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc).Resolve (ec);
2557 } else if (r.IsPointer && oper == Operator.Addition){
2558 Expression t = Make32or64 (ec, left);
2560 return new PointerArithmetic (true, right, t, r, loc).Resolve (ec);
2565 // Enumeration operators
2567 bool lie = TypeManager.IsEnumType (l);
2568 bool rie = TypeManager.IsEnumType (r);
2572 // U operator - (E e, E f)
2574 if (oper == Operator.Subtraction){
2576 type = TypeManager.EnumToUnderlying (l);
2579 Error_OperatorCannotBeApplied ();
2585 // operator + (E e, U x)
2586 // operator - (E e, U x)
2588 if (oper == Operator.Addition || oper == Operator.Subtraction){
2589 Type enum_type = lie ? l : r;
2590 Type other_type = lie ? r : l;
2591 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2593 if (underlying_type != other_type){
2594 temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
2604 Error_OperatorCannotBeApplied ();
2613 temp = Convert.ImplicitConversion (ec, right, l, loc);
2617 Error_OperatorCannotBeApplied ();
2621 temp = Convert.ImplicitConversion (ec, left, r, loc);
2626 Error_OperatorCannotBeApplied ();
2631 if (oper == Operator.Equality || oper == Operator.Inequality ||
2632 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2633 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2634 if (left.Type != right.Type){
2635 Error_OperatorCannotBeApplied ();
2638 type = TypeManager.bool_type;
2642 if (oper == Operator.BitwiseAnd ||
2643 oper == Operator.BitwiseOr ||
2644 oper == Operator.ExclusiveOr){
2645 if (left.Type != right.Type){
2646 Error_OperatorCannotBeApplied ();
2652 Error_OperatorCannotBeApplied ();
2656 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2657 return CheckShiftArguments (ec);
2659 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2660 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2661 type = TypeManager.bool_type;
2666 Error_OperatorCannotBeApplied ();
2670 Expression e = new ConditionalLogicalOperator (
2671 oper == Operator.LogicalAnd, left, right, l, loc);
2672 return e.Resolve (ec);
2676 // operator & (bool x, bool y)
2677 // operator | (bool x, bool y)
2678 // operator ^ (bool x, bool y)
2680 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2681 if (oper == Operator.BitwiseAnd ||
2682 oper == Operator.BitwiseOr ||
2683 oper == Operator.ExclusiveOr){
2690 // Pointer comparison
2692 if (l.IsPointer && r.IsPointer){
2693 if (oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2694 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2695 type = TypeManager.bool_type;
2701 // This will leave left or right set to null if there is an error
2703 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2704 DoNumericPromotions (ec, l, r, check_user_conv);
2705 if (left == null || right == null){
2706 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2711 // reload our cached types if required
2716 if (oper == Operator.BitwiseAnd ||
2717 oper == Operator.BitwiseOr ||
2718 oper == Operator.ExclusiveOr){
2720 if (((l == TypeManager.int32_type) ||
2721 (l == TypeManager.uint32_type) ||
2722 (l == TypeManager.short_type) ||
2723 (l == TypeManager.ushort_type) ||
2724 (l == TypeManager.int64_type) ||
2725 (l == TypeManager.uint64_type))){
2728 Error_OperatorCannotBeApplied ();
2732 Error_OperatorCannotBeApplied ();
2737 if (oper == Operator.Equality ||
2738 oper == Operator.Inequality ||
2739 oper == Operator.LessThanOrEqual ||
2740 oper == Operator.LessThan ||
2741 oper == Operator.GreaterThanOrEqual ||
2742 oper == Operator.GreaterThan){
2743 type = TypeManager.bool_type;
2749 public override Expression DoResolve (EmitContext ec)
2751 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2752 left = ((ParenthesizedExpression) left).Expr;
2753 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2757 if (left.eclass == ExprClass.Type) {
2758 Error (75, "Casting a negative value needs to have the value in parentheses.");
2762 left = left.Resolve (ec);
2767 Constant lc = left as Constant;
2768 if (lc != null && lc.Type == TypeManager.bool_type &&
2769 ((oper == Operator.LogicalAnd && (bool)lc.GetValue () == false) ||
2770 (oper == Operator.LogicalOr && (bool)lc.GetValue () == true))) {
2772 // TODO: make a sense to resolve unreachable expression as we do for statement
2773 Report.Warning (429, 4, loc, "Unreachable expression code detected");
2777 right = right.Resolve (ec);
2781 eclass = ExprClass.Value;
2783 Constant rc = right as Constant;
2785 if (oper == Operator.BitwiseAnd) {
2786 if (rc != null && rc.IsZeroInteger) {
2787 return lc is EnumConstant ?
2788 new EnumConstant (rc, lc.Type):
2792 if (lc != null && lc.IsZeroInteger) {
2793 return rc is EnumConstant ?
2794 new EnumConstant (lc, rc.Type):
2799 if (rc != null && lc != null){
2800 Expression e = ConstantFold.BinaryFold (
2801 ec, oper, lc, rc, loc);
2806 if (TypeManager.IsNullableType (left.Type) || TypeManager.IsNullableType (right.Type))
2807 return new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
2809 return ResolveOperator (ec);
2813 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2814 /// context of a conditional bool expression. This function will return
2815 /// false if it is was possible to use EmitBranchable, or true if it was.
2817 /// The expression's code is generated, and we will generate a branch to `target'
2818 /// if the resulting expression value is equal to isTrue
2820 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2822 ILGenerator ig = ec.ig;
2825 // This is more complicated than it looks, but its just to avoid
2826 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2827 // but on top of that we want for == and != to use a special path
2828 // if we are comparing against null
2830 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
2831 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2834 // put the constant on the rhs, for simplicity
2836 if (left is Constant) {
2837 Expression swap = right;
2842 if (((Constant) right).IsZeroInteger) {
2845 ig.Emit (OpCodes.Brtrue, target);
2847 ig.Emit (OpCodes.Brfalse, target);
2850 } else if (right is BoolConstant){
2852 if (my_on_true != ((BoolConstant) right).Value)
2853 ig.Emit (OpCodes.Brtrue, target);
2855 ig.Emit (OpCodes.Brfalse, target);
2860 } else if (oper == Operator.LogicalAnd) {
2863 Label tests_end = ig.DefineLabel ();
2865 left.EmitBranchable (ec, tests_end, false);
2866 right.EmitBranchable (ec, target, true);
2867 ig.MarkLabel (tests_end);
2869 left.EmitBranchable (ec, target, false);
2870 right.EmitBranchable (ec, target, false);
2875 } else if (oper == Operator.LogicalOr){
2877 left.EmitBranchable (ec, target, true);
2878 right.EmitBranchable (ec, target, true);
2881 Label tests_end = ig.DefineLabel ();
2882 left.EmitBranchable (ec, tests_end, true);
2883 right.EmitBranchable (ec, target, false);
2884 ig.MarkLabel (tests_end);
2889 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2890 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2891 oper == Operator.Equality || oper == Operator.Inequality)) {
2892 base.EmitBranchable (ec, target, onTrue);
2900 bool isUnsigned = is_unsigned (t) || t == TypeManager.double_type || t == TypeManager.float_type;
2903 case Operator.Equality:
2905 ig.Emit (OpCodes.Beq, target);
2907 ig.Emit (OpCodes.Bne_Un, target);
2910 case Operator.Inequality:
2912 ig.Emit (OpCodes.Bne_Un, target);
2914 ig.Emit (OpCodes.Beq, target);
2917 case Operator.LessThan:
2920 ig.Emit (OpCodes.Blt_Un, target);
2922 ig.Emit (OpCodes.Blt, target);
2925 ig.Emit (OpCodes.Bge_Un, target);
2927 ig.Emit (OpCodes.Bge, target);
2930 case Operator.GreaterThan:
2933 ig.Emit (OpCodes.Bgt_Un, target);
2935 ig.Emit (OpCodes.Bgt, target);
2938 ig.Emit (OpCodes.Ble_Un, target);
2940 ig.Emit (OpCodes.Ble, target);
2943 case Operator.LessThanOrEqual:
2946 ig.Emit (OpCodes.Ble_Un, target);
2948 ig.Emit (OpCodes.Ble, target);
2951 ig.Emit (OpCodes.Bgt_Un, target);
2953 ig.Emit (OpCodes.Bgt, target);
2957 case Operator.GreaterThanOrEqual:
2960 ig.Emit (OpCodes.Bge_Un, target);
2962 ig.Emit (OpCodes.Bge, target);
2965 ig.Emit (OpCodes.Blt_Un, target);
2967 ig.Emit (OpCodes.Blt, target);
2970 Console.WriteLine (oper);
2971 throw new Exception ("what is THAT");
2975 public override void Emit (EmitContext ec)
2977 ILGenerator ig = ec.ig;
2982 // Handle short-circuit operators differently
2985 if (oper == Operator.LogicalAnd) {
2986 Label load_zero = ig.DefineLabel ();
2987 Label end = ig.DefineLabel ();
2989 left.EmitBranchable (ec, load_zero, false);
2991 ig.Emit (OpCodes.Br, end);
2993 ig.MarkLabel (load_zero);
2994 ig.Emit (OpCodes.Ldc_I4_0);
2997 } else if (oper == Operator.LogicalOr) {
2998 Label load_one = ig.DefineLabel ();
2999 Label end = ig.DefineLabel ();
3001 left.EmitBranchable (ec, load_one, true);
3003 ig.Emit (OpCodes.Br, end);
3005 ig.MarkLabel (load_one);
3006 ig.Emit (OpCodes.Ldc_I4_1);
3014 bool isUnsigned = is_unsigned (left.Type);
3017 case Operator.Multiply:
3019 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3020 opcode = OpCodes.Mul_Ovf;
3021 else if (isUnsigned)
3022 opcode = OpCodes.Mul_Ovf_Un;
3024 opcode = OpCodes.Mul;
3026 opcode = OpCodes.Mul;
3030 case Operator.Division:
3032 opcode = OpCodes.Div_Un;
3034 opcode = OpCodes.Div;
3037 case Operator.Modulus:
3039 opcode = OpCodes.Rem_Un;
3041 opcode = OpCodes.Rem;
3044 case Operator.Addition:
3046 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3047 opcode = OpCodes.Add_Ovf;
3048 else if (isUnsigned)
3049 opcode = OpCodes.Add_Ovf_Un;
3051 opcode = OpCodes.Add;
3053 opcode = OpCodes.Add;
3056 case Operator.Subtraction:
3058 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3059 opcode = OpCodes.Sub_Ovf;
3060 else if (isUnsigned)
3061 opcode = OpCodes.Sub_Ovf_Un;
3063 opcode = OpCodes.Sub;
3065 opcode = OpCodes.Sub;
3068 case Operator.RightShift:
3070 opcode = OpCodes.Shr_Un;
3072 opcode = OpCodes.Shr;
3075 case Operator.LeftShift:
3076 opcode = OpCodes.Shl;
3079 case Operator.Equality:
3080 opcode = OpCodes.Ceq;
3083 case Operator.Inequality:
3084 ig.Emit (OpCodes.Ceq);
3085 ig.Emit (OpCodes.Ldc_I4_0);
3087 opcode = OpCodes.Ceq;
3090 case Operator.LessThan:
3092 opcode = OpCodes.Clt_Un;
3094 opcode = OpCodes.Clt;
3097 case Operator.GreaterThan:
3099 opcode = OpCodes.Cgt_Un;
3101 opcode = OpCodes.Cgt;
3104 case Operator.LessThanOrEqual:
3105 Type lt = left.Type;
3107 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
3108 ig.Emit (OpCodes.Cgt_Un);
3110 ig.Emit (OpCodes.Cgt);
3111 ig.Emit (OpCodes.Ldc_I4_0);
3113 opcode = OpCodes.Ceq;
3116 case Operator.GreaterThanOrEqual:
3117 Type le = left.Type;
3119 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3120 ig.Emit (OpCodes.Clt_Un);
3122 ig.Emit (OpCodes.Clt);
3124 ig.Emit (OpCodes.Ldc_I4_0);
3126 opcode = OpCodes.Ceq;
3129 case Operator.BitwiseOr:
3130 opcode = OpCodes.Or;
3133 case Operator.BitwiseAnd:
3134 opcode = OpCodes.And;
3137 case Operator.ExclusiveOr:
3138 opcode = OpCodes.Xor;
3142 throw new Exception ("This should not happen: Operator = "
3143 + oper.ToString ());
3151 // Object created by Binary when the binary operator uses an method instead of being
3152 // a binary operation that maps to a CIL binary operation.
3154 public class BinaryMethod : Expression {
3155 public MethodBase method;
3156 public ArrayList Arguments;
3158 public BinaryMethod (Type t, MethodBase m, ArrayList args)
3163 eclass = ExprClass.Value;
3166 public override Expression DoResolve (EmitContext ec)
3171 public override void Emit (EmitContext ec)
3173 ILGenerator ig = ec.ig;
3175 if (Arguments != null)
3176 Invocation.EmitArguments (ec, method, Arguments, false, null);
3178 if (method is MethodInfo)
3179 ig.Emit (OpCodes.Call, (MethodInfo) method);
3181 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3186 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3187 // b, c, d... may be strings or objects.
3189 public class StringConcat : Expression {
3191 bool invalid = false;
3192 bool emit_conv_done = false;
3194 // Are we also concating objects?
3196 bool is_strings_only = true;
3198 public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
3201 type = TypeManager.string_type;
3202 eclass = ExprClass.Value;
3204 operands = new ArrayList (2);
3209 public override Expression DoResolve (EmitContext ec)
3217 public void Append (EmitContext ec, Expression operand)
3222 if (operand is StringConstant && operands.Count != 0) {
3223 StringConstant last_operand = operands [operands.Count - 1] as StringConstant;
3224 if (last_operand != null) {
3225 operands [operands.Count - 1] = new StringConstant (last_operand.Value + ((StringConstant) operand).Value);
3231 // Conversion to object
3233 if (operand.Type != TypeManager.string_type) {
3234 Expression no = Convert.ImplicitConversion (ec, operand, TypeManager.object_type, loc);
3237 Binary.Error_OperatorCannotBeApplied (loc, "+", TypeManager.string_type, operand.Type);
3243 operands.Add (operand);
3246 public override void Emit (EmitContext ec)
3248 MethodInfo concat_method = null;
3251 // Do conversion to arguments; check for strings only
3254 // This can get called multiple times, so we have to deal with that.
3255 if (!emit_conv_done) {
3256 emit_conv_done = true;
3257 for (int i = 0; i < operands.Count; i ++) {
3258 Expression e = (Expression) operands [i];
3259 is_strings_only &= e.Type == TypeManager.string_type;
3262 for (int i = 0; i < operands.Count; i ++) {
3263 Expression e = (Expression) operands [i];
3265 if (! is_strings_only && e.Type == TypeManager.string_type) {
3266 // need to make sure this is an object, because the EmitParams
3267 // method might look at the type of this expression, see it is a
3268 // string and emit a string [] when we want an object [];
3270 e = new EmptyCast (e, TypeManager.object_type);
3272 operands [i] = new Argument (e, Argument.AType.Expression);
3277 // Find the right method
3279 switch (operands.Count) {
3282 // This should not be possible, because simple constant folding
3283 // is taken care of in the Binary code.
3285 throw new Exception ("how did you get here?");
3288 concat_method = is_strings_only ?
3289 TypeManager.string_concat_string_string :
3290 TypeManager.string_concat_object_object ;
3293 concat_method = is_strings_only ?
3294 TypeManager.string_concat_string_string_string :
3295 TypeManager.string_concat_object_object_object ;
3299 // There is not a 4 param overlaod for object (the one that there is
3300 // is actually a varargs methods, and is only in corlib because it was
3301 // introduced there before.).
3303 if (!is_strings_only)
3306 concat_method = TypeManager.string_concat_string_string_string_string;
3309 concat_method = is_strings_only ?
3310 TypeManager.string_concat_string_dot_dot_dot :
3311 TypeManager.string_concat_object_dot_dot_dot ;
3315 Invocation.EmitArguments (ec, concat_method, operands, false, null);
3316 ec.ig.Emit (OpCodes.Call, concat_method);
3321 // Object created with +/= on delegates
3323 public class BinaryDelegate : Expression {
3327 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3332 eclass = ExprClass.Value;
3335 public override Expression DoResolve (EmitContext ec)
3340 public override void Emit (EmitContext ec)
3342 ILGenerator ig = ec.ig;
3344 Invocation.EmitArguments (ec, method, args, false, null);
3346 ig.Emit (OpCodes.Call, (MethodInfo) method);
3347 ig.Emit (OpCodes.Castclass, type);
3350 public Expression Right {
3352 Argument arg = (Argument) args [1];
3357 public bool IsAddition {
3359 return method == TypeManager.delegate_combine_delegate_delegate;
3365 // User-defined conditional logical operator
3366 public class ConditionalLogicalOperator : Expression {
3367 Expression left, right;
3370 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3373 eclass = ExprClass.Value;
3377 this.is_and = is_and;
3380 protected void Error19 ()
3382 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3385 protected void Error218 ()
3387 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3388 "declarations of operator true and operator false");
3391 Expression op_true, op_false, op;
3392 LocalTemporary left_temp;
3394 public override Expression DoResolve (EmitContext ec)
3397 Expression operator_group;
3399 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3400 if (operator_group == null) {
3405 left_temp = new LocalTemporary (ec, type);
3407 ArrayList arguments = new ArrayList ();
3408 arguments.Add (new Argument (left_temp, Argument.AType.Expression));
3409 arguments.Add (new Argument (right, Argument.AType.Expression));
3410 method = Invocation.OverloadResolve (
3411 ec, (MethodGroupExpr) operator_group, arguments, false, loc)
3413 if (method == null) {
3418 if (method.ReturnType != type) {
3419 Report.Error (217, loc, "In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') " +
3420 "must have the same return type as the type of its 2 parameters", TypeManager.CSharpSignature (method));
3424 op = new StaticCallExpr (method, arguments, loc);
3426 op_true = GetOperatorTrue (ec, left_temp, loc);
3427 op_false = GetOperatorFalse (ec, left_temp, loc);
3428 if ((op_true == null) || (op_false == null)) {
3436 public override void Emit (EmitContext ec)
3438 ILGenerator ig = ec.ig;
3439 Label false_target = ig.DefineLabel ();
3440 Label end_target = ig.DefineLabel ();
3443 left_temp.Store (ec);
3445 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
3446 left_temp.Emit (ec);
3447 ig.Emit (OpCodes.Br, end_target);
3448 ig.MarkLabel (false_target);
3450 ig.MarkLabel (end_target);
3454 public class PointerArithmetic : Expression {
3455 Expression left, right;
3459 // We assume that `l' is always a pointer
3461 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3467 is_add = is_addition;
3470 public override Expression DoResolve (EmitContext ec)
3472 eclass = ExprClass.Variable;
3474 if (left.Type == TypeManager.void_ptr_type) {
3475 Error (242, "The operation in question is undefined on void pointers");
3482 public override void Emit (EmitContext ec)
3484 Type op_type = left.Type;
3485 ILGenerator ig = ec.ig;
3487 // It must be either array or fixed buffer
3488 Type element = TypeManager.HasElementType (op_type) ?
3489 element = TypeManager.GetElementType (op_type) :
3490 element = AttributeTester.GetFixedBuffer (((FieldExpr)left).FieldInfo).ElementType;
3492 int size = GetTypeSize (element);
3493 Type rtype = right.Type;
3495 if (rtype.IsPointer){
3497 // handle (pointer - pointer)
3501 ig.Emit (OpCodes.Sub);
3505 ig.Emit (OpCodes.Sizeof, element);
3507 IntLiteral.EmitInt (ig, size);
3508 ig.Emit (OpCodes.Div);
3510 ig.Emit (OpCodes.Conv_I8);
3513 // handle + and - on (pointer op int)
3516 ig.Emit (OpCodes.Conv_I);
3518 Constant right_const = right as Constant;
3519 if (right_const != null && size != 0) {
3520 Expression ex = ConstantFold.BinaryFold (ec, Binary.Operator.Multiply, new IntConstant (size), right_const, loc);
3528 ig.Emit (OpCodes.Sizeof, element);
3530 IntLiteral.EmitInt (ig, size);
3531 if (rtype == TypeManager.int64_type)
3532 ig.Emit (OpCodes.Conv_I8);
3533 else if (rtype == TypeManager.uint64_type)
3534 ig.Emit (OpCodes.Conv_U8);
3535 ig.Emit (OpCodes.Mul);
3539 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
3540 ig.Emit (OpCodes.Conv_I);
3543 ig.Emit (OpCodes.Add);
3545 ig.Emit (OpCodes.Sub);
3551 /// Implements the ternary conditional operator (?:)
3553 public class Conditional : Expression {
3554 Expression expr, trueExpr, falseExpr;
3556 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3559 this.trueExpr = trueExpr;
3560 this.falseExpr = falseExpr;
3564 public Expression Expr {
3570 public Expression TrueExpr {
3576 public Expression FalseExpr {
3582 public override Expression DoResolve (EmitContext ec)
3584 expr = expr.Resolve (ec);
3589 if (TypeManager.IsNullableType (expr.Type))
3590 return new Nullable.LiftedConditional (expr, trueExpr, falseExpr, loc).Resolve (ec);
3592 if (expr.Type != TypeManager.bool_type){
3593 expr = Expression.ResolveBoolean (
3600 trueExpr = trueExpr.Resolve (ec);
3601 falseExpr = falseExpr.Resolve (ec);
3603 if (trueExpr == null || falseExpr == null)
3606 eclass = ExprClass.Value;
3607 if (trueExpr.Type == falseExpr.Type)
3608 type = trueExpr.Type;
3611 Type true_type = trueExpr.Type;
3612 Type false_type = falseExpr.Type;
3615 // First, if an implicit conversion exists from trueExpr
3616 // to falseExpr, then the result type is of type falseExpr.Type
3618 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3621 // Check if both can convert implicitl to each other's type
3623 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3625 "Can not compute type of conditional expression " +
3626 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3627 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3628 "' convert implicitly to each other");
3633 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3637 Error (173, "The type of the conditional expression can " +
3638 "not be computed because there is no implicit conversion" +
3639 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3640 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3645 // Dead code optimalization
3646 if (expr is BoolConstant){
3647 BoolConstant bc = (BoolConstant) expr;
3649 Report.Warning (429, 4, bc.Value ? falseExpr.Location : trueExpr.Location, "Unreachable expression code detected");
3650 return bc.Value ? trueExpr : falseExpr;
3656 public override void Emit (EmitContext ec)
3658 ILGenerator ig = ec.ig;
3659 Label false_target = ig.DefineLabel ();
3660 Label end_target = ig.DefineLabel ();
3662 expr.EmitBranchable (ec, false_target, false);
3664 ig.Emit (OpCodes.Br, end_target);
3665 ig.MarkLabel (false_target);
3666 falseExpr.Emit (ec);
3667 ig.MarkLabel (end_target);
3675 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3676 public readonly string Name;
3677 public readonly Block Block;
3678 public LocalInfo local_info;
3681 LocalTemporary temp;
3683 public LocalVariableReference (Block block, string name, Location l)
3688 eclass = ExprClass.Variable;
3692 // Setting `is_readonly' to false will allow you to create a writable
3693 // reference to a read-only variable. This is used by foreach and using.
3695 public LocalVariableReference (Block block, string name, Location l,
3696 LocalInfo local_info, bool is_readonly)
3697 : this (block, name, l)
3699 this.local_info = local_info;
3700 this.is_readonly = is_readonly;
3703 public VariableInfo VariableInfo {
3705 return local_info.VariableInfo;
3709 public bool IsReadOnly {
3715 protected Expression DoResolveBase (EmitContext ec, Expression lvalue_right_side)
3717 if (local_info == null) {
3718 local_info = Block.GetLocalInfo (Name);
3721 if (lvalue_right_side == EmptyExpression.Null)
3722 local_info.Used = true;
3724 is_readonly = local_info.ReadOnly;
3727 type = local_info.VariableType;
3729 VariableInfo variable_info = local_info.VariableInfo;
3730 if (lvalue_right_side != null){
3732 if (lvalue_right_side is LocalVariableReference || lvalue_right_side == EmptyExpression.Null)
3733 Report.Error (1657, loc, "Cannot pass '{0}' with '{1}' modifier because it is a '{2}'",
3734 Name, lvalue_right_side == EmptyExpression.Null ? "out" : "ref",
3735 local_info.GetReadOnlyContext ());
3737 Report.Error (1656, loc, "Cannot assign to '{0}' because it is a '{1}'",
3738 Name, local_info.GetReadOnlyContext ());
3742 if (variable_info != null)
3743 variable_info.SetAssigned (ec);
3746 Expression e = Block.GetConstantExpression (Name);
3748 local_info.Used = true;
3749 eclass = ExprClass.Value;
3750 return e.Resolve (ec);
3753 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3756 if (lvalue_right_side == null)
3757 local_info.Used = true;
3759 if (ec.CurrentAnonymousMethod != null){
3761 // If we are referencing a variable from the external block
3762 // flag it for capturing
3764 if (local_info.Block.Toplevel != ec.CurrentBlock.Toplevel){
3765 if (local_info.AddressTaken){
3766 AnonymousMethod.Error_AddressOfCapturedVar (local_info.Name, loc);
3769 ec.CaptureVariable (local_info);
3776 public override Expression DoResolve (EmitContext ec)
3778 return DoResolveBase (ec, null);
3781 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3783 Expression ret = DoResolveBase (ec, right_side);
3785 CheckObsoleteAttribute (ret.Type);
3790 public bool VerifyFixed (bool is_expression)
3792 return !is_expression || local_info.IsFixed;
3795 public override int GetHashCode()
3797 return Name.GetHashCode ();
3800 public override bool Equals (object obj)
3802 LocalVariableReference lvr = obj as LocalVariableReference;
3806 return Name == lvr.Name && Block == lvr.Block;
3809 public override void Emit (EmitContext ec)
3811 ILGenerator ig = ec.ig;
3813 if (local_info.FieldBuilder == null){
3815 // A local variable on the local CLR stack
3817 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3820 // A local variable captured by anonymous methods.
3823 ec.EmitCapturedVariableInstance (local_info);
3825 ig.Emit (OpCodes.Ldfld, local_info.FieldBuilder);
3829 public void Emit (EmitContext ec, bool leave_copy)
3833 ec.ig.Emit (OpCodes.Dup);
3834 if (local_info.FieldBuilder != null){
3835 temp = new LocalTemporary (ec, Type);
3841 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3843 ILGenerator ig = ec.ig;
3844 prepared = prepare_for_load;
3846 if (local_info.FieldBuilder == null){
3848 // A local variable on the local CLR stack
3850 if (local_info.LocalBuilder == null)
3851 throw new Exception ("This should not happen: both Field and Local are null");
3855 ec.ig.Emit (OpCodes.Dup);
3856 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3859 // A local variable captured by anonymous methods or itereators.
3861 ec.EmitCapturedVariableInstance (local_info);
3863 if (prepare_for_load)
3864 ig.Emit (OpCodes.Dup);
3867 ig.Emit (OpCodes.Dup);
3868 temp = new LocalTemporary (ec, Type);
3871 ig.Emit (OpCodes.Stfld, local_info.FieldBuilder);
3877 public void AddressOf (EmitContext ec, AddressOp mode)
3879 ILGenerator ig = ec.ig;
3881 if (local_info.FieldBuilder == null){
3883 // A local variable on the local CLR stack
3885 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3888 // A local variable captured by anonymous methods or iterators
3890 ec.EmitCapturedVariableInstance (local_info);
3891 ig.Emit (OpCodes.Ldflda, local_info.FieldBuilder);
3895 public override string ToString ()
3897 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3902 /// This represents a reference to a parameter in the intermediate
3905 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3911 public Parameter.Modifier mod;
3912 public bool is_ref, is_out, prepared;
3926 LocalTemporary temp;
3928 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3935 eclass = ExprClass.Variable;
3938 public VariableInfo VariableInfo {
3942 public bool VerifyFixed (bool is_expression)
3944 return !is_expression || TypeManager.IsValueType (type);
3947 public bool IsAssigned (EmitContext ec, Location loc)
3949 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsAssigned (vi))
3952 Report.Error (269, loc,
3953 "Use of unassigned out parameter '{0}'", name);
3957 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3959 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3962 Report.Error (170, loc,
3963 "Use of possibly unassigned field `" + field_name + "'");
3967 public void SetAssigned (EmitContext ec)
3969 if (is_out && ec.DoFlowAnalysis)
3970 ec.CurrentBranching.SetAssigned (vi);
3973 public void SetFieldAssigned (EmitContext ec, string field_name)
3975 if (is_out && ec.DoFlowAnalysis)
3976 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3979 protected void DoResolveBase (EmitContext ec)
3981 type = pars.GetParameterInfo (ec, idx, out mod);
3982 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3983 is_out = (mod & Parameter.Modifier.OUT) != 0;
3984 eclass = ExprClass.Variable;
3987 vi = block.ParameterMap [idx];
3989 if (ec.CurrentAnonymousMethod != null){
3991 Report.Error (1628, Location,
3992 "Can not reference a ref or out parameter in an anonymous method");
3997 // If we are referencing the parameter from the external block
3998 // flag it for capturing
4000 //Console.WriteLine ("Is parameter `{0}' local? {1}", name, block.IsLocalParameter (name));
4001 if (!block.Toplevel.IsLocalParameter (name)){
4002 ec.CaptureParameter (name, type, idx);
4007 public override int GetHashCode()
4009 return name.GetHashCode ();
4012 public override bool Equals (object obj)
4014 ParameterReference pr = obj as ParameterReference;
4018 return name == pr.name && block == pr.block;
4022 // Notice that for ref/out parameters, the type exposed is not the
4023 // same type exposed externally.
4026 // externally we expose "int&"
4027 // here we expose "int".
4029 // We record this in "is_ref". This means that the type system can treat
4030 // the type as it is expected, but when we generate the code, we generate
4031 // the alternate kind of code.
4033 public override Expression DoResolve (EmitContext ec)
4037 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
4040 if (ec.RemapToProxy)
4041 return ec.RemapParameter (idx);
4046 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4052 if (ec.RemapToProxy)
4053 return ec.RemapParameterLValue (idx, right_side);
4058 static public void EmitLdArg (ILGenerator ig, int x)
4062 case 0: ig.Emit (OpCodes.Ldarg_0); break;
4063 case 1: ig.Emit (OpCodes.Ldarg_1); break;
4064 case 2: ig.Emit (OpCodes.Ldarg_2); break;
4065 case 3: ig.Emit (OpCodes.Ldarg_3); break;
4066 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
4069 ig.Emit (OpCodes.Ldarg, x);
4073 // This method is used by parameters that are references, that are
4074 // being passed as references: we only want to pass the pointer (that
4075 // is already stored in the parameter, not the address of the pointer,
4076 // and not the value of the variable).
4078 public void EmitLoad (EmitContext ec)
4080 ILGenerator ig = ec.ig;
4083 if (!ec.MethodIsStatic)
4087 EmitLdArg (ig, arg_idx);
4090 // FIXME: Review for anonymous methods
4094 public override void Emit (EmitContext ec)
4096 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4097 ec.EmitParameter (name);
4104 public void Emit (EmitContext ec, bool leave_copy)
4106 ILGenerator ig = ec.ig;
4109 if (!ec.MethodIsStatic)
4112 EmitLdArg (ig, arg_idx);
4116 ec.ig.Emit (OpCodes.Dup);
4119 // If we are a reference, we loaded on the stack a pointer
4120 // Now lets load the real value
4122 LoadFromPtr (ig, type);
4126 ec.ig.Emit (OpCodes.Dup);
4129 temp = new LocalTemporary (ec, type);
4135 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
4137 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4138 ec.EmitAssignParameter (name, source, leave_copy, prepare_for_load);
4142 ILGenerator ig = ec.ig;
4145 prepared = prepare_for_load;
4147 if (!ec.MethodIsStatic)
4150 if (is_ref && !prepared)
4151 EmitLdArg (ig, arg_idx);
4156 ec.ig.Emit (OpCodes.Dup);
4160 temp = new LocalTemporary (ec, type);
4164 StoreFromPtr (ig, type);
4170 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
4172 ig.Emit (OpCodes.Starg, arg_idx);
4176 public void AddressOf (EmitContext ec, AddressOp mode)
4178 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4179 ec.EmitAddressOfParameter (name);
4185 if (!ec.MethodIsStatic)
4190 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
4192 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
4195 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
4197 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
4204 /// Used for arguments to New(), Invocation()
4206 public class Argument {
4207 public enum AType : byte {
4214 public readonly AType ArgType;
4215 public Expression Expr;
4217 public Argument (Expression expr, AType type)
4220 this.ArgType = type;
4223 public Argument (Expression expr)
4226 this.ArgType = AType.Expression;
4231 if (ArgType == AType.Ref || ArgType == AType.Out)
4232 return TypeManager.GetReferenceType (Expr.Type);
4238 public Parameter.Modifier Modifier
4243 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
4246 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
4249 return Parameter.Modifier.NONE;
4254 public static string FullDesc (Argument a)
4256 if (a.ArgType == AType.ArgList)
4259 return (a.ArgType == AType.Ref ? "ref " :
4260 (a.ArgType == AType.Out ? "out " : "")) +
4261 TypeManager.CSharpName (a.Expr.Type);
4264 public bool ResolveMethodGroup (EmitContext ec, Location loc)
4266 SimpleName sn = Expr as SimpleName;
4268 Expr = sn.GetMethodGroup ();
4270 // FIXME: csc doesn't report any error if you try to use `ref' or
4271 // `out' in a delegate creation expression.
4272 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4279 void Error_LValueRequired (Location loc)
4281 Report.Error (1510, loc, "An lvalue is required as an argument to out or ref");
4284 public bool Resolve (EmitContext ec, Location loc)
4286 bool old_do_flow_analysis = ec.DoFlowAnalysis;
4287 ec.DoFlowAnalysis = true;
4289 if (ArgType == AType.Ref) {
4290 ec.InRefOutArgumentResolving = true;
4291 Expr = Expr.Resolve (ec);
4292 ec.InRefOutArgumentResolving = false;
4294 ec.DoFlowAnalysis = old_do_flow_analysis;
4298 Expr = Expr.DoResolveLValue (ec, Expr);
4300 Error_LValueRequired (loc);
4301 } else if (ArgType == AType.Out) {
4302 ec.InRefOutArgumentResolving = true;
4303 Expr = Expr.DoResolveLValue (ec, EmptyExpression.Null);
4304 ec.InRefOutArgumentResolving = false;
4307 Error_LValueRequired (loc);
4310 Expr = Expr.Resolve (ec);
4312 ec.DoFlowAnalysis = old_do_flow_analysis;
4317 if (ArgType == AType.Expression)
4321 // Catch errors where fields of a MarshalByRefObject are passed as ref or out
4322 // This is only allowed for `this'
4324 FieldExpr fe = Expr as FieldExpr;
4325 if (fe != null && !fe.IsStatic){
4326 Expression instance = fe.InstanceExpression;
4328 if (instance.GetType () != typeof (This)){
4329 if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
4330 Report.SymbolRelatedToPreviousError (fe.InstanceExpression.Type);
4331 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",
4339 if (Expr.eclass != ExprClass.Variable){
4341 // We just probe to match the CSC output
4343 if (Expr.eclass == ExprClass.PropertyAccess ||
4344 Expr.eclass == ExprClass.IndexerAccess){
4347 "A property or indexer can not be passed as an out or ref " +
4350 Error_LValueRequired (loc);
4358 public void Emit (EmitContext ec)
4361 // Ref and Out parameters need to have their addresses taken.
4363 // ParameterReferences might already be references, so we want
4364 // to pass just the value
4366 if (ArgType == AType.Ref || ArgType == AType.Out){
4367 AddressOp mode = AddressOp.Store;
4369 if (ArgType == AType.Ref)
4370 mode |= AddressOp.Load;
4372 if (Expr is ParameterReference){
4373 ParameterReference pr = (ParameterReference) Expr;
4379 pr.AddressOf (ec, mode);
4382 if (Expr is IMemoryLocation)
4383 ((IMemoryLocation) Expr).AddressOf (ec, mode);
4386 1510, Expr.Location,
4387 "An lvalue is required as an argument to out or ref");
4397 /// Invocation of methods or delegates.
4399 public class Invocation : ExpressionStatement {
4400 public readonly ArrayList Arguments;
4403 MethodBase method = null;
4406 // arguments is an ArrayList, but we do not want to typecast,
4407 // as it might be null.
4409 // FIXME: only allow expr to be a method invocation or a
4410 // delegate invocation (7.5.5)
4412 public Invocation (Expression expr, ArrayList arguments, Location l)
4415 Arguments = arguments;
4419 public Expression Expr {
4426 /// Determines "better conversion" as specified in 7.4.2.3
4428 /// Returns : p if a->p is better,
4429 /// q if a->q is better,
4430 /// null if neither is better
4432 static Type BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
4434 Type argument_type = TypeManager.TypeToCoreType (a.Type);
4435 Expression argument_expr = a.Expr;
4437 // p = TypeManager.TypeToCoreType (p);
4438 // q = TypeManager.TypeToCoreType (q);
4440 if (argument_type == null)
4441 throw new Exception ("Expression of type " + a.Expr +
4442 " does not resolve its type");
4444 if (p == null || q == null)
4445 throw new InternalErrorException ("BetterConversion Got a null conversion");
4450 if (argument_expr is NullLiteral) {
4452 // If the argument is null and one of the types to compare is 'object' and
4453 // the other is a reference type, we prefer the other.
4455 // This follows from the usual rules:
4456 // * There is an implicit conversion from 'null' to type 'object'
4457 // * There is an implicit conversion from 'null' to any reference type
4458 // * There is an implicit conversion from any reference type to type 'object'
4459 // * There is no implicit conversion from type 'object' to other reference types
4460 // => Conversion of 'null' to a reference type is better than conversion to 'object'
4462 // FIXME: This probably isn't necessary, since the type of a NullLiteral is the
4463 // null type. I think it used to be 'object' and thus needed a special
4464 // case to avoid the immediately following two checks.
4466 if (!p.IsValueType && q == TypeManager.object_type)
4468 if (!q.IsValueType && p == TypeManager.object_type)
4472 if (argument_type == p)
4475 if (argument_type == q)
4478 Expression p_tmp = new EmptyExpression (p);
4479 Expression q_tmp = new EmptyExpression (q);
4481 bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
4482 bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
4484 if (p_to_q && !q_to_p)
4487 if (q_to_p && !p_to_q)
4490 if (p == TypeManager.sbyte_type)
4491 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4492 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4494 if (q == TypeManager.sbyte_type)
4495 if (p == TypeManager.byte_type || p == TypeManager.ushort_type ||
4496 p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4499 if (p == TypeManager.short_type)
4500 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4501 q == TypeManager.uint64_type)
4504 if (q == TypeManager.short_type)
4505 if (p == TypeManager.ushort_type || p == TypeManager.uint32_type ||
4506 p == TypeManager.uint64_type)
4509 if (p == TypeManager.int32_type)
4510 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4513 if (q == TypeManager.int32_type)
4514 if (p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4517 if (p == TypeManager.int64_type)
4518 if (q == TypeManager.uint64_type)
4520 if (q == TypeManager.int64_type)
4521 if (p == TypeManager.uint64_type)
4528 /// Determines "Better function" between candidate
4529 /// and the current best match
4532 /// Returns a boolean indicating :
4533 /// false if candidate ain't better
4534 /// true if candidate is better than the current best match
4536 static bool BetterFunction (EmitContext ec, ArrayList args, int argument_count,
4537 MethodBase candidate, bool candidate_params,
4538 MethodBase best, bool best_params, Location loc)
4540 ParameterData candidate_pd = TypeManager.GetParameterData (candidate);
4541 ParameterData best_pd = TypeManager.GetParameterData (best);
4543 bool better_at_least_one = false;
4545 for (int j = 0; j < argument_count; ++j) {
4546 Argument a = (Argument) args [j];
4548 Type ct = TypeManager.TypeToCoreType (candidate_pd.ParameterType (j));
4549 Type bt = TypeManager.TypeToCoreType (best_pd.ParameterType (j));
4551 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4552 if (candidate_params)
4553 ct = TypeManager.GetElementType (ct);
4555 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4557 bt = TypeManager.GetElementType (bt);
4563 Type better = BetterConversion (ec, a, ct, bt, loc);
4564 // for each argument, the conversion to 'ct' should be no worse than
4565 // the conversion to 'bt'.
4569 // for at least one argument, the conversion to 'ct' should be better than
4570 // the conversion to 'bt'.
4572 better_at_least_one = true;
4575 if (better_at_least_one)
4582 // If two methods have equal parameter types, but
4583 // only one of them is generic, the non-generic one wins.
4585 if (TypeManager.IsGenericMethod (best) && !TypeManager.IsGenericMethod (candidate))
4587 else if (!TypeManager.IsGenericMethod (best) && TypeManager.IsGenericMethod (candidate))
4591 // Note that this is not just an optimization. This handles the case
4592 // This handles the case
4594 // Add (float f1, float f2, float f3);
4595 // Add (params decimal [] foo);
4597 // The call Add (3, 4, 5) should be ambiguous. Without this check, the
4598 // first candidate would've chosen as better.
4601 // This handles the following cases:
4603 // Trim () is better than Trim (params char[] chars)
4604 // Concat (string s1, string s2, string s3) is better than
4605 // Concat (string s1, params string [] srest)
4607 return !candidate_params && best_params;
4610 static bool IsOverride (MethodBase cand_method, MethodBase base_method)
4612 if (!IsAncestralType (base_method.DeclaringType, cand_method.DeclaringType))
4615 ParameterData cand_pd = TypeManager.GetParameterData (cand_method);
4616 ParameterData base_pd = TypeManager.GetParameterData (base_method);
4618 if (cand_pd.Count != base_pd.Count)
4621 for (int j = 0; j < cand_pd.Count; ++j) {
4622 Parameter.Modifier cm = cand_pd.ParameterModifier (j);
4623 Parameter.Modifier bm = base_pd.ParameterModifier (j);
4624 Type ct = TypeManager.TypeToCoreType (cand_pd.ParameterType (j));
4625 Type bt = TypeManager.TypeToCoreType (base_pd.ParameterType (j));
4627 if (cm != bm || ct != bt)
4634 public static string FullMethodDesc (MethodBase mb)
4636 string ret_type = "";
4641 if (mb is MethodInfo)
4642 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
4644 StringBuilder sb = new StringBuilder (ret_type);
4646 sb.Append (mb.ReflectedType.ToString ());
4648 sb.Append (mb.Name);
4650 ParameterData pd = TypeManager.GetParameterData (mb);
4652 int count = pd.Count;
4655 for (int i = count; i > 0; ) {
4658 sb.Append (pd.ParameterDesc (count - i - 1));
4664 return sb.ToString ();
4667 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4669 MemberInfo [] miset;
4670 MethodGroupExpr union;
4675 return (MethodGroupExpr) mg2;
4678 return (MethodGroupExpr) mg1;
4681 MethodGroupExpr left_set = null, right_set = null;
4682 int length1 = 0, length2 = 0;
4684 left_set = (MethodGroupExpr) mg1;
4685 length1 = left_set.Methods.Length;
4687 right_set = (MethodGroupExpr) mg2;
4688 length2 = right_set.Methods.Length;
4690 ArrayList common = new ArrayList ();
4692 foreach (MethodBase r in right_set.Methods){
4693 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
4697 miset = new MemberInfo [length1 + length2 - common.Count];
4698 left_set.Methods.CopyTo (miset, 0);
4702 foreach (MethodBase r in right_set.Methods) {
4703 if (!common.Contains (r))
4707 union = new MethodGroupExpr (miset, loc);
4712 public static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4713 ArrayList arguments, int arg_count,
4714 ref MethodBase candidate)
4716 return IsParamsMethodApplicable (
4717 ec, me, arguments, arg_count, false, ref candidate) ||
4718 IsParamsMethodApplicable (
4719 ec, me, arguments, arg_count, true, ref candidate);
4724 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4725 ArrayList arguments, int arg_count,
4726 bool do_varargs, ref MethodBase candidate)
4728 if (!me.HasTypeArguments &&
4729 !TypeManager.InferParamsTypeArguments (ec, arguments, ref candidate))
4732 return IsParamsMethodApplicable (
4733 ec, arguments, arg_count, candidate, do_varargs);
4737 /// Determines if the candidate method, if a params method, is applicable
4738 /// in its expanded form to the given set of arguments
4740 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
4741 int arg_count, MethodBase candidate,
4744 ParameterData pd = TypeManager.GetParameterData (candidate);
4746 int pd_count = pd.Count;
4751 int count = pd_count - 1;
4753 if (pd.ParameterModifier (count) != Parameter.Modifier.ARGLIST)
4755 if (pd_count != arg_count)
4758 if (pd.ParameterModifier (count) != Parameter.Modifier.PARAMS)
4762 if (count > arg_count)
4765 if (pd_count == 1 && arg_count == 0)
4769 // If we have come this far, the case which
4770 // remains is when the number of parameters is
4771 // less than or equal to the argument count.
4773 for (int i = 0; i < count; ++i) {
4775 Argument a = (Argument) arguments [i];
4777 Parameter.Modifier a_mod = a.Modifier &
4778 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4779 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4780 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4782 if (a_mod == p_mod) {
4784 if (a_mod == Parameter.Modifier.NONE)
4785 if (!Convert.ImplicitConversionExists (ec,
4787 pd.ParameterType (i)))
4790 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4791 Type pt = pd.ParameterType (i);
4794 pt = TypeManager.GetReferenceType (pt);
4805 Argument a = (Argument) arguments [count];
4806 if (!(a.Expr is Arglist))
4812 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4814 for (int i = pd_count - 1; i < arg_count; i++) {
4815 Argument a = (Argument) arguments [i];
4817 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4824 public static bool IsApplicable (EmitContext ec, MethodGroupExpr me,
4825 ArrayList arguments, int arg_count,
4826 ref MethodBase candidate)
4828 if (!me.HasTypeArguments &&
4829 !TypeManager.InferTypeArguments (ec, arguments, ref candidate))
4832 return IsApplicable (ec, arguments, arg_count, candidate);
4836 /// Determines if the candidate method is applicable (section 14.4.2.1)
4837 /// to the given set of arguments
4839 static bool IsApplicable (EmitContext ec, ArrayList arguments, int arg_count,
4840 MethodBase candidate)
4842 ParameterData pd = TypeManager.GetParameterData (candidate);
4844 if (arg_count != pd.Count)
4847 for (int i = arg_count; i > 0; ) {
4850 Argument a = (Argument) arguments [i];
4852 Parameter.Modifier a_mod = a.Modifier &
4853 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4854 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4855 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4858 if (a_mod == p_mod ||
4859 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4860 if (a_mod == Parameter.Modifier.NONE) {
4861 if (!Convert.ImplicitConversionExists (ec,
4863 pd.ParameterType (i)))
4867 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4868 Type pt = pd.ParameterType (i);
4871 pt = TypeManager.GetReferenceType (pt);
4883 static private bool IsAncestralType (Type first_type, Type second_type)
4885 return first_type != second_type &&
4886 (second_type.IsSubclassOf (first_type) ||
4887 TypeManager.ImplementsInterface (second_type, first_type));
4891 /// Find the Applicable Function Members (7.4.2.1)
4893 /// me: Method Group expression with the members to select.
4894 /// it might contain constructors or methods (or anything
4895 /// that maps to a method).
4897 /// Arguments: ArrayList containing resolved Argument objects.
4899 /// loc: The location if we want an error to be reported, or a Null
4900 /// location for "probing" purposes.
4902 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4903 /// that is the best match of me on Arguments.
4906 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4907 ArrayList Arguments, bool may_fail,
4910 MethodBase method = null;
4911 bool method_params = false;
4912 Type applicable_type = null;
4914 ArrayList candidates = new ArrayList (2);
4915 ArrayList candidate_overrides = null;
4918 // Used to keep a map between the candidate
4919 // and whether it is being considered in its
4920 // normal or expanded form
4922 // false is normal form, true is expanded form
4924 Hashtable candidate_to_form = null;
4926 if (Arguments != null)
4927 arg_count = Arguments.Count;
4929 if ((me.Name == "Invoke") &&
4930 TypeManager.IsDelegateType (me.DeclaringType)) {
4931 Error_InvokeOnDelegate (loc);
4935 MethodBase[] methods = me.Methods;
4938 // First we construct the set of applicable methods
4940 bool is_sorted = true;
4941 for (int i = 0; i < methods.Length; i++){
4942 Type decl_type = methods [i].DeclaringType;
4945 // If we have already found an applicable method
4946 // we eliminate all base types (Section 14.5.5.1)
4948 if ((applicable_type != null) &&
4949 IsAncestralType (decl_type, applicable_type))
4953 // Methods marked 'override' don't take part in 'applicable_type'
4954 // computation, nor in the actual overload resolution.
4955 // However, they still need to be emitted instead of a base virtual method.
4956 // We avoid doing the 'applicable' test here, since it'll anyway be applied
4957 // to the base virtual function, and IsOverride is much faster than IsApplicable.
4959 if (!me.IsBase && TypeManager.IsOverride (methods [i])) {
4960 if (candidate_overrides == null)
4961 candidate_overrides = new ArrayList ();
4962 candidate_overrides.Add (methods [i]);
4967 // Check if candidate is applicable (section 14.4.2.1)
4968 // Is candidate applicable in normal form?
4970 bool is_applicable = IsApplicable (
4971 ec, me, Arguments, arg_count, ref methods [i]);
4973 if (!is_applicable &&
4974 (IsParamsMethodApplicable (
4975 ec, me, Arguments, arg_count, ref methods [i]))) {
4976 MethodBase candidate = methods [i];
4977 if (candidate_to_form == null)
4978 candidate_to_form = new PtrHashtable ();
4979 candidate_to_form [candidate] = candidate;
4980 // Candidate is applicable in expanded form
4981 is_applicable = true;
4987 candidates.Add (methods [i]);
4989 if (applicable_type == null)
4990 applicable_type = decl_type;
4991 else if (applicable_type != decl_type) {
4993 if (IsAncestralType (applicable_type, decl_type))
4994 applicable_type = decl_type;
4998 int candidate_top = candidates.Count;
5000 if (applicable_type == null) {
5002 // Okay so we have failed to find anything so we
5003 // return by providing info about the closest match
5005 for (int i = 0; i < methods.Length; ++i) {
5006 MethodBase c = (MethodBase) methods [i];
5007 ParameterData pd = TypeManager.GetParameterData (c);
5009 if (pd.Count != arg_count)
5012 if (!TypeManager.InferTypeArguments (ec, Arguments, ref c))
5015 VerifyArgumentsCompat (ec, Arguments, arg_count,
5016 c, false, null, may_fail, loc);
5021 string report_name = me.Name;
5022 if (report_name == ".ctor")
5023 report_name = me.DeclaringType.ToString ();
5025 for (int i = 0; i < methods.Length; ++i) {
5026 MethodBase c = methods [i];
5027 ParameterData pd = TypeManager.GetParameterData (c);
5029 if (pd.Count != arg_count)
5032 if (TypeManager.InferTypeArguments (ec, Arguments, ref c))
5036 411, loc, "The type arguments for " +
5037 "method `{0}' cannot be infered from " +
5038 "the usage. Try specifying the type " +
5039 "arguments explicitly.", report_name);
5043 Error_WrongNumArguments (
5044 loc, report_name, arg_count);
5053 // At this point, applicable_type is _one_ of the most derived types
5054 // in the set of types containing the methods in this MethodGroup.
5055 // Filter the candidates so that they only contain methods from the
5056 // most derived types.
5059 int finalized = 0; // Number of finalized candidates
5062 // Invariant: applicable_type is a most derived type
5064 // We'll try to complete Section 14.5.5.1 for 'applicable_type' by
5065 // eliminating all it's base types. At the same time, we'll also move
5066 // every unrelated type to the end of the array, and pick the next
5067 // 'applicable_type'.
5069 Type next_applicable_type = null;
5070 int j = finalized; // where to put the next finalized candidate
5071 int k = finalized; // where to put the next undiscarded candidate
5072 for (int i = finalized; i < candidate_top; ++i) {
5073 MethodBase candidate = (MethodBase) candidates [i];
5074 Type decl_type = candidate.DeclaringType;
5076 if (decl_type == applicable_type) {
5077 candidates [k++] = candidates [j];
5078 candidates [j++] = candidates [i];
5082 if (IsAncestralType (decl_type, applicable_type))
5085 if (next_applicable_type != null &&
5086 IsAncestralType (decl_type, next_applicable_type))
5089 candidates [k++] = candidates [i];
5091 if (next_applicable_type == null ||
5092 IsAncestralType (next_applicable_type, decl_type))
5093 next_applicable_type = decl_type;
5096 applicable_type = next_applicable_type;
5099 } while (applicable_type != null);
5103 // Now we actually find the best method
5106 method = (MethodBase) candidates [0];
5107 method_params = candidate_to_form != null && candidate_to_form.Contains (method);
5108 for (int ix = 1; ix < candidate_top; ix++){
5109 MethodBase candidate = (MethodBase) candidates [ix];
5111 if (candidate == method)
5114 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
5116 if (BetterFunction (ec, Arguments, arg_count,
5117 candidate, cand_params,
5118 method, method_params, loc)) {
5120 method_params = cand_params;
5125 // Now check that there are no ambiguities i.e the selected method
5126 // should be better than all the others
5128 bool ambiguous = false;
5129 for (int ix = 0; ix < candidate_top; ix++){
5130 MethodBase candidate = (MethodBase) candidates [ix];
5132 if (candidate == method)
5135 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
5136 if (!BetterFunction (ec, Arguments, arg_count,
5137 method, method_params,
5138 candidate, cand_params,
5140 Report.SymbolRelatedToPreviousError (candidate);
5146 Report.SymbolRelatedToPreviousError (method);
5147 Report.Error (121, loc, "Ambiguous call when selecting function due to implicit casts");
5152 // If the method is a virtual function, pick an override closer to the LHS type.
5154 if (!me.IsBase && method.IsVirtual) {
5155 if (TypeManager.IsOverride (method))
5156 throw new InternalErrorException (
5157 "Should not happen. An 'override' method took part in overload resolution: " + method);
5159 if (candidate_overrides != null)
5160 foreach (MethodBase candidate in candidate_overrides) {
5161 if (IsOverride (candidate, method))
5167 // And now check if the arguments are all
5168 // compatible, perform conversions if
5169 // necessary etc. and return if everything is
5172 if (!VerifyArgumentsCompat (ec, Arguments, arg_count, method,
5173 method_params, null, may_fail, loc))
5176 if (method != null) {
5177 IMethodData data = TypeManager.GetMethod (method);
5179 data.SetMemberIsUsed ();
5184 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
5186 if (name == "Finalize" && arg_count == 0) {
5187 Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
5190 Report.Error (1501, loc,
5191 "No overload for method `" + name + "' takes `" +
5192 arg_count + "' arguments");
5196 static void Error_InvokeOnDelegate (Location loc)
5198 Report.Error (1533, loc,
5199 "Invoke cannot be called directly on a delegate");
5202 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
5203 Type delegate_type, Argument a, ParameterData expected_par)
5205 if (delegate_type == null)
5206 Report.Error (1502, loc, "The best overloaded match for method '{0}' has some invalid arguments",
5207 TypeManager.CSharpSignature (method));
5209 Report.Error (1594, loc,
5210 "Delegate '" + delegate_type.ToString () +
5211 "' has some invalid arguments.");
5213 string par_desc = expected_par.ParameterDesc (idx);
5215 if (a.Modifier != expected_par.ParameterModifier (idx)) {
5216 if ((expected_par.ParameterModifier (idx) & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) == 0)
5217 Report.Error (1615, loc, "Argument '{0}' should not be passed with the '{1}' keyword",
5218 idx + 1, Parameter.GetModifierSignature (a.Modifier));
5220 Report.Error (1620, loc, "Argument '{0}' must be passed with the '{1}' keyword",
5221 idx + 1, Parameter.GetModifierSignature (expected_par.ParameterModifier (idx)));
5225 Report.Error (1503, loc,
5226 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
5227 idx + 1, Argument.FullDesc (a), par_desc));
5230 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
5231 int arg_count, MethodBase method,
5232 bool chose_params_expanded,
5233 Type delegate_type, bool may_fail,
5236 ParameterData pd = TypeManager.GetParameterData (method);
5237 int pd_count = pd.Count;
5239 for (int j = 0; j < arg_count; j++) {
5240 Argument a = (Argument) Arguments [j];
5241 Expression a_expr = a.Expr;
5242 Type parameter_type = pd.ParameterType (j);
5243 Parameter.Modifier pm = pd.ParameterModifier (j);
5245 if (pm == Parameter.Modifier.PARAMS){
5246 if ((pm & ~Parameter.Modifier.PARAMS) != a.Modifier) {
5248 Error_InvalidArguments (
5249 loc, j, method, delegate_type,
5254 if (chose_params_expanded)
5255 parameter_type = TypeManager.GetElementType (parameter_type);
5256 } else if (pm == Parameter.Modifier.ARGLIST){
5262 if (pd.ParameterModifier (j) != a.Modifier){
5264 Error_InvalidArguments (
5265 loc, j, method, delegate_type,
5274 if (!TypeManager.IsEqual (a.Type, parameter_type)){
5277 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
5281 Error_InvalidArguments (loc, j, method, delegate_type, a, pd);
5286 // Update the argument with the implicit conversion
5292 if (parameter_type.IsPointer){
5299 Parameter.Modifier a_mod = a.Modifier &
5300 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5301 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
5302 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5304 if (a_mod != p_mod &&
5305 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
5307 Report.Error (1502, loc,
5308 "The best overloaded match for method '" + FullMethodDesc (method)+
5309 "' has some invalid arguments");
5310 Report.Error (1503, loc,
5311 "Argument " + (j+1) +
5312 ": Cannot convert from '" + Argument.FullDesc (a)
5313 + "' to '" + pd.ParameterDesc (j) + "'");
5323 public override Expression DoResolve (EmitContext ec)
5326 // First, resolve the expression that is used to
5327 // trigger the invocation
5329 SimpleName sn = expr as SimpleName;
5331 expr = sn.GetMethodGroup ();
5333 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
5337 if (!(expr is MethodGroupExpr)) {
5338 Type expr_type = expr.Type;
5340 if (expr_type != null){
5341 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
5343 return (new DelegateInvocation (
5344 this.expr, Arguments, loc)).Resolve (ec);
5348 if (!(expr is MethodGroupExpr)){
5349 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup, loc);
5354 // Next, evaluate all the expressions in the argument list
5356 if (Arguments != null){
5357 foreach (Argument a in Arguments){
5358 if (!a.Resolve (ec, loc))
5363 MethodGroupExpr mg = (MethodGroupExpr) expr;
5364 method = OverloadResolve (ec, mg, Arguments, false, loc);
5369 MethodInfo mi = method as MethodInfo;
5371 type = TypeManager.TypeToCoreType (mi.ReturnType);
5372 Expression iexpr = mg.InstanceExpression;
5374 if (iexpr == null ||
5375 iexpr is This || iexpr is EmptyExpression ||
5376 mg.IdenticalTypeName) {
5377 mg.InstanceExpression = null;
5379 MemberExpr.error176 (loc, mi.Name);
5383 if (iexpr == null || iexpr is EmptyExpression) {
5384 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
5390 if (type.IsPointer){
5398 // Only base will allow this invocation to happen.
5400 if (mg.IsBase && method.IsAbstract){
5401 Report.Error (205, loc, "Cannot call an abstract base member: " +
5402 FullMethodDesc (method));
5406 if (method.Name == "Finalize" && Arguments == null) {
5407 Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
5411 if ((method.Attributes & MethodAttributes.SpecialName) != 0){
5412 if (TypeManager.LookupDeclSpace (method.DeclaringType) != null || TypeManager.IsSpecialMethod (method)) {
5413 Report.Error (571, loc, TypeManager.CSharpSignature (method) + ": can not call operator or accessor");
5418 if (mg.InstanceExpression != null)
5419 mg.InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
5421 eclass = ExprClass.Value;
5426 // Emits the list of arguments as an array
5428 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
5430 ILGenerator ig = ec.ig;
5431 int count = arguments.Count - idx;
5432 Argument a = (Argument) arguments [idx];
5433 Type t = a.Expr.Type;
5435 IntConstant.EmitInt (ig, count);
5436 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
5438 int top = arguments.Count;
5439 for (int j = idx; j < top; j++){
5440 a = (Argument) arguments [j];
5442 ig.Emit (OpCodes.Dup);
5443 IntConstant.EmitInt (ig, j - idx);
5445 bool is_stobj, has_type_arg;
5446 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj, out has_type_arg);
5448 ig.Emit (OpCodes.Ldelema, t);
5460 /// Emits a list of resolved Arguments that are in the arguments
5463 /// The MethodBase argument might be null if the
5464 /// emission of the arguments is known not to contain
5465 /// a `params' field (for example in constructors or other routines
5466 /// that keep their arguments in this structure)
5468 /// if `dup_args' is true, a copy of the arguments will be left
5469 /// on the stack. If `dup_args' is true, you can specify `this_arg'
5470 /// which will be duplicated before any other args. Only EmitCall
5471 /// should be using this interface.
5473 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments, bool dup_args, LocalTemporary this_arg)
5477 pd = TypeManager.GetParameterData (mb);
5481 LocalTemporary [] temps = null;
5484 temps = new LocalTemporary [arguments.Count];
5487 // If we are calling a params method with no arguments, special case it
5489 if (arguments == null){
5490 if (pd != null && pd.Count > 0 &&
5491 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
5492 ILGenerator ig = ec.ig;
5494 IntConstant.EmitInt (ig, 0);
5495 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
5501 int top = arguments.Count;
5503 for (int i = 0; i < top; i++){
5504 Argument a = (Argument) arguments [i];
5507 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
5509 // Special case if we are passing the same data as the
5510 // params argument, do not put it in an array.
5512 if (pd.ParameterType (i) == a.Type)
5515 EmitParams (ec, i, arguments);
5522 ec.ig.Emit (OpCodes.Dup);
5523 (temps [i] = new LocalTemporary (ec, a.Type)).Store (ec);
5528 if (this_arg != null)
5531 for (int i = 0; i < top; i ++)
5532 temps [i].Emit (ec);
5535 if (pd != null && pd.Count > top &&
5536 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
5537 ILGenerator ig = ec.ig;
5539 IntConstant.EmitInt (ig, 0);
5540 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
5544 static Type[] GetVarargsTypes (EmitContext ec, MethodBase mb,
5545 ArrayList arguments)
5547 ParameterData pd = TypeManager.GetParameterData (mb);
5549 if (arguments == null)
5550 return new Type [0];
5552 Argument a = (Argument) arguments [pd.Count - 1];
5553 Arglist list = (Arglist) a.Expr;
5555 return list.ArgumentTypes;
5559 /// This checks the ConditionalAttribute on the method
5561 static bool IsMethodExcluded (MethodBase method, EmitContext ec)
5563 if (method.IsConstructor)
5566 IMethodData md = TypeManager.GetMethod (method);
5568 return md.IsExcluded (ec);
5570 // For some methods (generated by delegate class) GetMethod returns null
5571 // because they are not included in builder_to_method table
5572 if (method.DeclaringType is TypeBuilder)
5575 return AttributeTester.IsConditionalMethodExcluded (method);
5579 /// is_base tells whether we want to force the use of the `call'
5580 /// opcode instead of using callvirt. Call is required to call
5581 /// a specific method, while callvirt will always use the most
5582 /// recent method in the vtable.
5584 /// is_static tells whether this is an invocation on a static method
5586 /// instance_expr is an expression that represents the instance
5587 /// it must be non-null if is_static is false.
5589 /// method is the method to invoke.
5591 /// Arguments is the list of arguments to pass to the method or constructor.
5593 public static void EmitCall (EmitContext ec, bool is_base,
5594 bool is_static, Expression instance_expr,
5595 MethodBase method, ArrayList Arguments, Location loc)
5597 EmitCall (ec, is_base, is_static, instance_expr, method, Arguments, loc, false, false);
5600 // `dup_args' leaves an extra copy of the arguments on the stack
5601 // `omit_args' does not leave any arguments at all.
5602 // So, basically, you could make one call with `dup_args' set to true,
5603 // and then another with `omit_args' set to true, and the two calls
5604 // would have the same set of arguments. However, each argument would
5605 // only have been evaluated once.
5606 public static void EmitCall (EmitContext ec, bool is_base,
5607 bool is_static, Expression instance_expr,
5608 MethodBase method, ArrayList Arguments, Location loc,
5609 bool dup_args, bool omit_args)
5611 ILGenerator ig = ec.ig;
5612 bool struct_call = false;
5613 bool this_call = false;
5614 LocalTemporary this_arg = null;
5616 Type decl_type = method.DeclaringType;
5618 if (!RootContext.StdLib) {
5619 // Replace any calls to the system's System.Array type with calls to
5620 // the newly created one.
5621 if (method == TypeManager.system_int_array_get_length)
5622 method = TypeManager.int_array_get_length;
5623 else if (method == TypeManager.system_int_array_get_rank)
5624 method = TypeManager.int_array_get_rank;
5625 else if (method == TypeManager.system_object_array_clone)
5626 method = TypeManager.object_array_clone;
5627 else if (method == TypeManager.system_int_array_get_length_int)
5628 method = TypeManager.int_array_get_length_int;
5629 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5630 method = TypeManager.int_array_get_lower_bound_int;
5631 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5632 method = TypeManager.int_array_get_upper_bound_int;
5633 else if (method == TypeManager.system_void_array_copyto_array_int)
5634 method = TypeManager.void_array_copyto_array_int;
5637 if (ec.TestObsoleteMethodUsage) {
5639 // This checks ObsoleteAttribute on the method and on the declaring type
5641 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
5643 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
5645 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
5647 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
5651 if (IsMethodExcluded (method, ec))
5655 this_call = instance_expr == null;
5656 if (decl_type.IsValueType || (!this_call && instance_expr.Type.IsValueType))
5660 // If this is ourselves, push "this"
5665 ig.Emit (OpCodes.Ldarg_0);
5668 Type iexpr_type = instance_expr.Type;
5671 // Push the instance expression
5673 if (TypeManager.IsValueType (iexpr_type)) {
5675 // Special case: calls to a function declared in a
5676 // reference-type with a value-type argument need
5677 // to have their value boxed.
5678 if (decl_type.IsValueType ||
5679 iexpr_type.IsGenericParameter) {
5681 // If the expression implements IMemoryLocation, then
5682 // we can optimize and use AddressOf on the
5685 // If not we have to use some temporary storage for
5687 if (instance_expr is IMemoryLocation) {
5688 ((IMemoryLocation)instance_expr).
5689 AddressOf (ec, AddressOp.LoadStore);
5691 LocalTemporary temp = new LocalTemporary (ec, iexpr_type);
5692 instance_expr.Emit (ec);
5694 temp.AddressOf (ec, AddressOp.Load);
5697 // avoid the overhead of doing this all the time.
5699 t = TypeManager.GetReferenceType (iexpr_type);
5701 instance_expr.Emit (ec);
5702 ig.Emit (OpCodes.Box, instance_expr.Type);
5703 t = TypeManager.object_type;
5706 instance_expr.Emit (ec);
5707 t = instance_expr.Type;
5712 this_arg = new LocalTemporary (ec, t);
5713 ig.Emit (OpCodes.Dup);
5714 this_arg.Store (ec);
5720 EmitArguments (ec, method, Arguments, dup_args, this_arg);
5722 if ((instance_expr != null) && (instance_expr.Type.IsGenericParameter))
5723 ig.Emit (OpCodes.Constrained, instance_expr.Type);
5726 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
5727 call_op = OpCodes.Call;
5729 call_op = OpCodes.Callvirt;
5731 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
5732 Type[] varargs_types = GetVarargsTypes (ec, method, Arguments);
5733 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
5740 // and DoFoo is not virtual, you can omit the callvirt,
5741 // because you don't need the null checking behavior.
5743 if (method is MethodInfo)
5744 ig.Emit (call_op, (MethodInfo) method);
5746 ig.Emit (call_op, (ConstructorInfo) method);
5749 public override void Emit (EmitContext ec)
5751 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5753 EmitCall (ec, mg.IsBase, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5756 public override void EmitStatement (EmitContext ec)
5761 // Pop the return value if there is one
5763 if (method is MethodInfo){
5764 Type ret = ((MethodInfo)method).ReturnType;
5765 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5766 ec.ig.Emit (OpCodes.Pop);
5771 public class InvocationOrCast : ExpressionStatement
5774 Expression argument;
5776 public InvocationOrCast (Expression expr, Expression argument, Location loc)
5779 this.argument = argument;
5783 public override Expression DoResolve (EmitContext ec)
5786 // First try to resolve it as a cast.
5788 TypeExpr te = expr.ResolveAsTypeStep (ec) as TypeExpr;
5789 if ((te != null) && (te.eclass == ExprClass.Type)) {
5790 Cast cast = new Cast (te, argument, loc);
5791 return cast.Resolve (ec);
5795 // This can either be a type or a delegate invocation.
5796 // Let's just resolve it and see what we'll get.
5798 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5803 // Ok, so it's a Cast.
5805 if (expr.eclass == ExprClass.Type) {
5806 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
5807 return cast.Resolve (ec);
5811 // It's a delegate invocation.
5813 if (!TypeManager.IsDelegateType (expr.Type)) {
5814 Error (149, "Method name expected");
5818 ArrayList args = new ArrayList ();
5819 args.Add (new Argument (argument, Argument.AType.Expression));
5820 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5821 return invocation.Resolve (ec);
5826 Error (201, "Only assignment, call, increment, decrement and new object " +
5827 "expressions can be used as a statement");
5830 public override ExpressionStatement ResolveStatement (EmitContext ec)
5833 // First try to resolve it as a cast.
5835 TypeExpr te = expr.ResolveAsTypeStep (ec) as TypeExpr;
5836 if ((te != null) && (te.eclass == ExprClass.Type)) {
5842 // This can either be a type or a delegate invocation.
5843 // Let's just resolve it and see what we'll get.
5845 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5846 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5852 // It's a delegate invocation.
5854 if (!TypeManager.IsDelegateType (expr.Type)) {
5855 Error (149, "Method name expected");
5859 ArrayList args = new ArrayList ();
5860 args.Add (new Argument (argument, Argument.AType.Expression));
5861 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5862 return invocation.ResolveStatement (ec);
5865 public override void Emit (EmitContext ec)
5867 throw new Exception ("Cannot happen");
5870 public override void EmitStatement (EmitContext ec)
5872 throw new Exception ("Cannot happen");
5877 // This class is used to "disable" the code generation for the
5878 // temporary variable when initializing value types.
5880 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5881 public void AddressOf (EmitContext ec, AddressOp Mode)
5888 /// Implements the new expression
5890 public class New : ExpressionStatement, IMemoryLocation {
5891 public readonly ArrayList Arguments;
5894 // During bootstrap, it contains the RequestedType,
5895 // but if `type' is not null, it *might* contain a NewDelegate
5896 // (because of field multi-initialization)
5898 public Expression RequestedType;
5900 MethodBase method = null;
5903 // If set, the new expression is for a value_target, and
5904 // we will not leave anything on the stack.
5906 Expression value_target;
5907 bool value_target_set = false;
5908 bool is_type_parameter = false;
5910 public New (Expression requested_type, ArrayList arguments, Location l)
5912 RequestedType = requested_type;
5913 Arguments = arguments;
5917 public bool SetValueTypeVariable (Expression value)
5919 value_target = value;
5920 value_target_set = true;
5921 if (!(value_target is IMemoryLocation)){
5922 Error_UnexpectedKind ("variable", loc);
5929 // This function is used to disable the following code sequence for
5930 // value type initialization:
5932 // AddressOf (temporary)
5936 // Instead the provide will have provided us with the address on the
5937 // stack to store the results.
5939 static Expression MyEmptyExpression;
5941 public void DisableTemporaryValueType ()
5943 if (MyEmptyExpression == null)
5944 MyEmptyExpression = new EmptyAddressOf ();
5947 // To enable this, look into:
5948 // test-34 and test-89 and self bootstrapping.
5950 // For instance, we can avoid a copy by using `newobj'
5951 // instead of Call + Push-temp on value types.
5952 // value_target = MyEmptyExpression;
5957 /// Converts complex core type syntax like 'new int ()' to simple constant
5959 Expression Constantify (Type t)
5961 if (t == TypeManager.int32_type)
5962 return new IntConstant (0);
5963 if (t == TypeManager.uint32_type)
5964 return new UIntConstant (0);
5965 if (t == TypeManager.int64_type)
5966 return new LongConstant (0);
5967 if (t == TypeManager.uint64_type)
5968 return new ULongConstant (0);
5969 if (t == TypeManager.float_type)
5970 return new FloatConstant (0);
5971 if (t == TypeManager.double_type)
5972 return new DoubleConstant (0);
5973 if (t == TypeManager.short_type)
5974 return new ShortConstant (0);
5975 if (t == TypeManager.ushort_type)
5976 return new UShortConstant (0);
5977 if (t == TypeManager.sbyte_type)
5978 return new SByteConstant (0);
5979 if (t == TypeManager.byte_type)
5980 return new ByteConstant (0);
5981 if (t == TypeManager.char_type)
5982 return new CharConstant ('\0');
5983 if (t == TypeManager.bool_type)
5984 return new BoolConstant (false);
5985 if (t == TypeManager.decimal_type)
5986 return new DecimalConstant (0);
5991 public override Expression DoResolve (EmitContext ec)
5994 // The New DoResolve might be called twice when initializing field
5995 // expressions (see EmitFieldInitializers, the call to
5996 // GetInitializerExpression will perform a resolve on the expression,
5997 // and later the assign will trigger another resolution
5999 // This leads to bugs (#37014)
6002 if (RequestedType is NewDelegate)
6003 return RequestedType;
6007 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec);
6011 if (Arguments == null) {
6012 Expression c = Constantify (type);
6021 CheckObsoleteAttribute (type);
6023 bool IsDelegate = TypeManager.IsDelegateType (type);
6026 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
6027 if (RequestedType != null)
6028 if (!(RequestedType is DelegateCreation))
6029 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
6030 return RequestedType;
6033 if (type.IsGenericParameter) {
6034 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (type);
6036 if ((gc == null) || (!gc.HasConstructorConstraint && !gc.IsValueType)) {
6037 Error (304, String.Format (
6038 "Cannot create an instance of the " +
6039 "variable type '{0}' because it " +
6040 "doesn't have the new() constraint",
6045 if ((Arguments != null) && (Arguments.Count != 0)) {
6046 Error (417, String.Format (
6047 "`{0}': cannot provide arguments " +
6048 "when creating an instance of a " +
6049 "variable type.", type));
6053 is_type_parameter = true;
6054 eclass = ExprClass.Value;
6058 if (type.IsAbstract && type.IsSealed) {
6059 Report.Error (712, loc, "Cannot create an instance of the static class '{0}'", TypeManager.CSharpName (type));
6063 if (type.IsInterface || type.IsAbstract){
6064 Error (144, "It is not possible to create instances of interfaces or abstract classes");
6068 bool is_struct = type.IsValueType;
6069 eclass = ExprClass.Value;
6072 // SRE returns a match for .ctor () on structs (the object constructor),
6073 // so we have to manually ignore it.
6075 if (is_struct && Arguments == null)
6079 ml = MemberLookupFinal (ec, type, type, ".ctor",
6080 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
6081 MemberTypes.Constructor,
6082 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
6087 if (! (ml is MethodGroupExpr)){
6089 ml.Error_UnexpectedKind ("method group", loc);
6095 if (Arguments != null){
6096 foreach (Argument a in Arguments){
6097 if (!a.Resolve (ec, loc))
6102 method = Invocation.OverloadResolve (
6103 ec, (MethodGroupExpr) ml, Arguments, true, loc);
6107 if (method == null) {
6108 if (almostMatchedMembers.Count != 0) {
6109 MemberLookupFailed (ec, type, type, ".ctor", null, true, loc);
6113 if (!is_struct || Arguments.Count > 0) {
6114 Error (1501, String.Format (
6115 "New invocation: Can not find a constructor in `{0}' for this argument list",
6116 TypeManager.CSharpName (type)));
6124 bool DoEmitTypeParameter (EmitContext ec)
6126 ILGenerator ig = ec.ig;
6128 ig.Emit (OpCodes.Ldtoken, type);
6129 ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6130 ig.Emit (OpCodes.Call, TypeManager.activator_create_instance);
6131 ig.Emit (OpCodes.Unbox_Any, type);
6137 // This DoEmit can be invoked in two contexts:
6138 // * As a mechanism that will leave a value on the stack (new object)
6139 // * As one that wont (init struct)
6141 // You can control whether a value is required on the stack by passing
6142 // need_value_on_stack. The code *might* leave a value on the stack
6143 // so it must be popped manually
6145 // If we are dealing with a ValueType, we have a few
6146 // situations to deal with:
6148 // * The target is a ValueType, and we have been provided
6149 // the instance (this is easy, we are being assigned).
6151 // * The target of New is being passed as an argument,
6152 // to a boxing operation or a function that takes a
6155 // In this case, we need to create a temporary variable
6156 // that is the argument of New.
6158 // Returns whether a value is left on the stack
6160 bool DoEmit (EmitContext ec, bool need_value_on_stack)
6162 bool is_value_type = TypeManager.IsValueType (type);
6163 ILGenerator ig = ec.ig;
6168 // Allow DoEmit() to be called multiple times.
6169 // We need to create a new LocalTemporary each time since
6170 // you can't share LocalBuilders among ILGeneators.
6171 if (!value_target_set)
6172 value_target = new LocalTemporary (ec, type);
6174 ml = (IMemoryLocation) value_target;
6175 ml.AddressOf (ec, AddressOp.Store);
6179 Invocation.EmitArguments (ec, method, Arguments, false, null);
6183 ig.Emit (OpCodes.Initobj, type);
6185 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6186 if (need_value_on_stack){
6187 value_target.Emit (ec);
6192 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
6197 public override void Emit (EmitContext ec)
6199 if (is_type_parameter)
6200 DoEmitTypeParameter (ec);
6205 public override void EmitStatement (EmitContext ec)
6207 if (is_type_parameter)
6208 throw new InvalidOperationException ();
6210 if (DoEmit (ec, false))
6211 ec.ig.Emit (OpCodes.Pop);
6214 public void AddressOf (EmitContext ec, AddressOp Mode)
6216 if (is_type_parameter)
6217 throw new InvalidOperationException ();
6219 if (!type.IsValueType){
6221 // We throw an exception. So far, I believe we only need to support
6223 // foreach (int j in new StructType ())
6226 throw new Exception ("AddressOf should not be used for classes");
6229 if (!value_target_set)
6230 value_target = new LocalTemporary (ec, type);
6232 IMemoryLocation ml = (IMemoryLocation) value_target;
6233 ml.AddressOf (ec, AddressOp.Store);
6235 Invocation.EmitArguments (ec, method, Arguments, false, null);
6238 ec.ig.Emit (OpCodes.Initobj, type);
6240 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6242 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
6247 /// 14.5.10.2: Represents an array creation expression.
6251 /// There are two possible scenarios here: one is an array creation
6252 /// expression that specifies the dimensions and optionally the
6253 /// initialization data and the other which does not need dimensions
6254 /// specified but where initialization data is mandatory.
6256 public class ArrayCreation : Expression {
6257 Expression requested_base_type;
6258 ArrayList initializers;
6261 // The list of Argument types.
6262 // This is used to construct the `newarray' or constructor signature
6264 ArrayList arguments;
6267 // Method used to create the array object.
6269 MethodBase new_method = null;
6271 Type array_element_type;
6272 Type underlying_type;
6273 bool is_one_dimensional = false;
6274 bool is_builtin_type = false;
6275 bool expect_initializers = false;
6276 int num_arguments = 0;
6280 ArrayList array_data;
6285 // The number of array initializers that we can handle
6286 // via the InitializeArray method - through EmitStaticInitializers
6288 int num_automatic_initializers;
6290 const int max_automatic_initializers = 6;
6292 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
6294 this.requested_base_type = requested_base_type;
6295 this.initializers = initializers;
6299 arguments = new ArrayList ();
6301 foreach (Expression e in exprs) {
6302 arguments.Add (new Argument (e, Argument.AType.Expression));
6307 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
6309 this.requested_base_type = requested_base_type;
6310 this.initializers = initializers;
6314 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
6316 //string tmp = rank.Substring (rank.LastIndexOf ('['));
6318 //dimensions = tmp.Length - 1;
6319 expect_initializers = true;
6322 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
6324 StringBuilder sb = new StringBuilder (rank);
6327 for (int i = 1; i < idx_count; i++)
6332 return new ComposedCast (base_type, sb.ToString (), loc);
6335 void Error_IncorrectArrayInitializer ()
6337 Error (178, "Incorrectly structured array initializer");
6340 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
6342 if (specified_dims) {
6343 Argument a = (Argument) arguments [idx];
6345 if (!a.Resolve (ec, loc))
6348 if (!(a.Expr is Constant)) {
6349 Error (150, "A constant value is expected");
6353 int value = (int) ((Constant) a.Expr).GetValue ();
6355 if (value != probe.Count) {
6356 Error_IncorrectArrayInitializer ();
6360 bounds [idx] = value;
6363 int child_bounds = -1;
6364 for (int i = 0; i < probe.Count; ++i) {
6365 object o = probe [i];
6366 if (o is ArrayList) {
6367 ArrayList sub_probe = o as ArrayList;
6368 int current_bounds = sub_probe.Count;
6370 if (child_bounds == -1)
6371 child_bounds = current_bounds;
6373 else if (child_bounds != current_bounds){
6374 Error_IncorrectArrayInitializer ();
6377 if (specified_dims && (idx + 1 >= arguments.Count)){
6378 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
6382 bool ret = CheckIndices (ec, sub_probe, idx + 1, specified_dims);
6386 if (child_bounds != -1){
6387 Error_IncorrectArrayInitializer ();
6391 Expression tmp = (Expression) o;
6392 tmp = tmp.Resolve (ec);
6397 // Console.WriteLine ("I got: " + tmp);
6398 // Handle initialization from vars, fields etc.
6400 Expression conv = Convert.ImplicitConversionRequired (
6401 ec, tmp, underlying_type, loc);
6406 if (conv is StringConstant || conv is DecimalConstant || conv is NullCast) {
6407 // These are subclasses of Constant that can appear as elements of an
6408 // array that cannot be statically initialized (with num_automatic_initializers
6409 // > max_automatic_initializers), so num_automatic_initializers should be left as zero.
6410 array_data.Add (conv);
6411 } else if (conv is Constant) {
6412 // These are the types of Constant that can appear in arrays that can be
6413 // statically allocated.
6414 array_data.Add (conv);
6415 num_automatic_initializers++;
6417 array_data.Add (conv);
6424 public void UpdateIndices (EmitContext ec)
6427 for (ArrayList probe = initializers; probe != null;) {
6428 if (probe.Count > 0 && probe [0] is ArrayList) {
6429 Expression e = new IntConstant (probe.Count);
6430 arguments.Add (new Argument (e, Argument.AType.Expression));
6432 bounds [i++] = probe.Count;
6434 probe = (ArrayList) probe [0];
6437 Expression e = new IntConstant (probe.Count);
6438 arguments.Add (new Argument (e, Argument.AType.Expression));
6440 bounds [i++] = probe.Count;
6447 public bool ValidateInitializers (EmitContext ec, Type array_type)
6449 if (initializers == null) {
6450 if (expect_initializers)
6456 if (underlying_type == null)
6460 // We use this to store all the date values in the order in which we
6461 // will need to store them in the byte blob later
6463 array_data = new ArrayList ();
6464 bounds = new Hashtable ();
6468 if (arguments != null) {
6469 ret = CheckIndices (ec, initializers, 0, true);
6472 arguments = new ArrayList ();
6474 ret = CheckIndices (ec, initializers, 0, false);
6481 if (arguments.Count != dimensions) {
6482 Error_IncorrectArrayInitializer ();
6491 // Creates the type of the array
6493 bool LookupType (EmitContext ec)
6495 StringBuilder array_qualifier = new StringBuilder (rank);
6498 // `In the first form allocates an array instace of the type that results
6499 // from deleting each of the individual expression from the expression list'
6501 if (num_arguments > 0) {
6502 array_qualifier.Append ("[");
6503 for (int i = num_arguments-1; i > 0; i--)
6504 array_qualifier.Append (",");
6505 array_qualifier.Append ("]");
6511 TypeExpr array_type_expr;
6512 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
6513 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec);
6514 if (array_type_expr == null)
6517 type = array_type_expr.Type;
6519 if (!type.IsArray) {
6520 Error (622, "Can only use array initializer expressions to assign to array types. Try using a new expression instead.");
6523 underlying_type = TypeManager.GetElementType (type);
6524 dimensions = type.GetArrayRank ();
6529 public override Expression DoResolve (EmitContext ec)
6533 if (!LookupType (ec))
6537 // First step is to validate the initializers and fill
6538 // in any missing bits
6540 if (!ValidateInitializers (ec, type))
6543 if (arguments == null)
6546 arg_count = arguments.Count;
6547 foreach (Argument a in arguments){
6548 if (!a.Resolve (ec, loc))
6551 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
6552 if (real_arg == null)
6559 array_element_type = TypeManager.GetElementType (type);
6561 if (array_element_type.IsAbstract && array_element_type.IsSealed) {
6562 Report.Error (719, loc, "'{0}': array elements cannot be of static type", TypeManager.CSharpName (array_element_type));
6566 if (arg_count == 1) {
6567 is_one_dimensional = true;
6568 eclass = ExprClass.Value;
6572 is_builtin_type = TypeManager.IsBuiltinType (type);
6574 if (is_builtin_type) {
6577 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
6578 AllBindingFlags, loc);
6580 if (!(ml is MethodGroupExpr)) {
6581 ml.Error_UnexpectedKind ("method group", loc);
6586 Error (-6, "New invocation: Can not find a constructor for " +
6587 "this argument list");
6591 new_method = Invocation.OverloadResolve (
6592 ec, (MethodGroupExpr) ml, arguments, false, loc);
6594 if (new_method == null) {
6595 Error (-6, "New invocation: Can not find a constructor for " +
6596 "this argument list");
6600 eclass = ExprClass.Value;
6603 ModuleBuilder mb = CodeGen.Module.Builder;
6604 ArrayList args = new ArrayList ();
6606 if (arguments != null) {
6607 for (int i = 0; i < arg_count; i++)
6608 args.Add (TypeManager.int32_type);
6611 Type [] arg_types = null;
6614 arg_types = new Type [args.Count];
6616 args.CopyTo (arg_types, 0);
6618 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
6621 if (new_method == null) {
6622 Error (-6, "New invocation: Can not find a constructor for " +
6623 "this argument list");
6627 eclass = ExprClass.Value;
6632 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
6637 int count = array_data.Count;
6639 if (underlying_type.IsEnum)
6640 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
6642 factor = GetTypeSize (underlying_type);
6644 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
6646 data = new byte [(count * factor + 4) & ~3];
6649 for (int i = 0; i < count; ++i) {
6650 object v = array_data [i];
6652 if (v is EnumConstant)
6653 v = ((EnumConstant) v).Child;
6655 if (v is Constant && !(v is StringConstant))
6656 v = ((Constant) v).GetValue ();
6662 if (underlying_type == TypeManager.int64_type){
6663 if (!(v is Expression)){
6664 long val = (long) v;
6666 for (int j = 0; j < factor; ++j) {
6667 data [idx + j] = (byte) (val & 0xFF);
6671 } else if (underlying_type == TypeManager.uint64_type){
6672 if (!(v is Expression)){
6673 ulong val = (ulong) v;
6675 for (int j = 0; j < factor; ++j) {
6676 data [idx + j] = (byte) (val & 0xFF);
6680 } else if (underlying_type == TypeManager.float_type) {
6681 if (!(v is Expression)){
6682 element = BitConverter.GetBytes ((float) v);
6684 for (int j = 0; j < factor; ++j)
6685 data [idx + j] = element [j];
6687 } else if (underlying_type == TypeManager.double_type) {
6688 if (!(v is Expression)){
6689 element = BitConverter.GetBytes ((double) v);
6691 for (int j = 0; j < factor; ++j)
6692 data [idx + j] = element [j];
6694 } else if (underlying_type == TypeManager.char_type){
6695 if (!(v is Expression)){
6696 int val = (int) ((char) v);
6698 data [idx] = (byte) (val & 0xff);
6699 data [idx+1] = (byte) (val >> 8);
6701 } else if (underlying_type == TypeManager.short_type){
6702 if (!(v is Expression)){
6703 int val = (int) ((short) v);
6705 data [idx] = (byte) (val & 0xff);
6706 data [idx+1] = (byte) (val >> 8);
6708 } else if (underlying_type == TypeManager.ushort_type){
6709 if (!(v is Expression)){
6710 int val = (int) ((ushort) v);
6712 data [idx] = (byte) (val & 0xff);
6713 data [idx+1] = (byte) (val >> 8);
6715 } else if (underlying_type == TypeManager.int32_type) {
6716 if (!(v is Expression)){
6719 data [idx] = (byte) (val & 0xff);
6720 data [idx+1] = (byte) ((val >> 8) & 0xff);
6721 data [idx+2] = (byte) ((val >> 16) & 0xff);
6722 data [idx+3] = (byte) (val >> 24);
6724 } else if (underlying_type == TypeManager.uint32_type) {
6725 if (!(v is Expression)){
6726 uint val = (uint) v;
6728 data [idx] = (byte) (val & 0xff);
6729 data [idx+1] = (byte) ((val >> 8) & 0xff);
6730 data [idx+2] = (byte) ((val >> 16) & 0xff);
6731 data [idx+3] = (byte) (val >> 24);
6733 } else if (underlying_type == TypeManager.sbyte_type) {
6734 if (!(v is Expression)){
6735 sbyte val = (sbyte) v;
6736 data [idx] = (byte) val;
6738 } else if (underlying_type == TypeManager.byte_type) {
6739 if (!(v is Expression)){
6740 byte val = (byte) v;
6741 data [idx] = (byte) val;
6743 } else if (underlying_type == TypeManager.bool_type) {
6744 if (!(v is Expression)){
6745 bool val = (bool) v;
6746 data [idx] = (byte) (val ? 1 : 0);
6748 } else if (underlying_type == TypeManager.decimal_type){
6749 if (!(v is Expression)){
6750 int [] bits = Decimal.GetBits ((decimal) v);
6753 // FIXME: For some reason, this doesn't work on the MS runtime.
6754 int [] nbits = new int [4];
6755 nbits [0] = bits [3];
6756 nbits [1] = bits [2];
6757 nbits [2] = bits [0];
6758 nbits [3] = bits [1];
6760 for (int j = 0; j < 4; j++){
6761 data [p++] = (byte) (nbits [j] & 0xff);
6762 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6763 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6764 data [p++] = (byte) (nbits [j] >> 24);
6768 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6777 // Emits the initializers for the array
6779 void EmitStaticInitializers (EmitContext ec)
6782 // First, the static data
6785 ILGenerator ig = ec.ig;
6787 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6789 fb = RootContext.MakeStaticData (data);
6791 ig.Emit (OpCodes.Dup);
6792 ig.Emit (OpCodes.Ldtoken, fb);
6793 ig.Emit (OpCodes.Call,
6794 TypeManager.void_initializearray_array_fieldhandle);
6798 // Emits pieces of the array that can not be computed at compile
6799 // time (variables and string locations).
6801 // This always expect the top value on the stack to be the array
6803 void EmitDynamicInitializers (EmitContext ec)
6805 ILGenerator ig = ec.ig;
6806 int dims = bounds.Count;
6807 int [] current_pos = new int [dims];
6808 int top = array_data.Count;
6810 MethodInfo set = null;
6814 ModuleBuilder mb = null;
6815 mb = CodeGen.Module.Builder;
6816 args = new Type [dims + 1];
6819 for (j = 0; j < dims; j++)
6820 args [j] = TypeManager.int32_type;
6822 args [j] = array_element_type;
6824 set = mb.GetArrayMethod (
6826 CallingConventions.HasThis | CallingConventions.Standard,
6827 TypeManager.void_type, args);
6830 for (int i = 0; i < top; i++){
6832 Expression e = null;
6834 if (array_data [i] is Expression)
6835 e = (Expression) array_data [i];
6839 // Basically we do this for string literals and
6840 // other non-literal expressions
6842 if (e is EnumConstant){
6843 e = ((EnumConstant) e).Child;
6846 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6847 num_automatic_initializers <= max_automatic_initializers) {
6848 Type etype = e.Type;
6850 ig.Emit (OpCodes.Dup);
6852 for (int idx = 0; idx < dims; idx++)
6853 IntConstant.EmitInt (ig, current_pos [idx]);
6856 // If we are dealing with a struct, get the
6857 // address of it, so we can store it.
6859 if ((dims == 1) && etype.IsValueType &&
6860 (!TypeManager.IsBuiltinOrEnum (etype) ||
6861 etype == TypeManager.decimal_type)) {
6866 // Let new know that we are providing
6867 // the address where to store the results
6869 n.DisableTemporaryValueType ();
6872 ig.Emit (OpCodes.Ldelema, etype);
6878 bool is_stobj, has_type_arg;
6879 OpCode op = ArrayAccess.GetStoreOpcode (
6880 etype, out is_stobj,
6883 ig.Emit (OpCodes.Stobj, etype);
6884 else if (has_type_arg)
6885 ig.Emit (op, etype);
6889 ig.Emit (OpCodes.Call, set);
6896 for (int j = dims - 1; j >= 0; j--){
6898 if (current_pos [j] < (int) bounds [j])
6900 current_pos [j] = 0;
6905 void EmitArrayArguments (EmitContext ec)
6907 ILGenerator ig = ec.ig;
6909 foreach (Argument a in arguments) {
6910 Type atype = a.Type;
6913 if (atype == TypeManager.uint64_type)
6914 ig.Emit (OpCodes.Conv_Ovf_U4);
6915 else if (atype == TypeManager.int64_type)
6916 ig.Emit (OpCodes.Conv_Ovf_I4);
6920 public override void Emit (EmitContext ec)
6922 ILGenerator ig = ec.ig;
6924 EmitArrayArguments (ec);
6925 if (is_one_dimensional)
6926 ig.Emit (OpCodes.Newarr, array_element_type);
6928 if (is_builtin_type)
6929 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6931 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6934 if (initializers != null){
6936 // FIXME: Set this variable correctly.
6938 bool dynamic_initializers = true;
6940 // This will never be true for array types that cannot be statically
6941 // initialized. num_automatic_initializers will always be zero. See
6943 if (num_automatic_initializers > max_automatic_initializers)
6944 EmitStaticInitializers (ec);
6946 if (dynamic_initializers)
6947 EmitDynamicInitializers (ec);
6951 public object EncodeAsAttribute ()
6953 if (!is_one_dimensional){
6954 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6958 if (array_data == null){
6959 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6963 object [] ret = new object [array_data.Count];
6965 foreach (Expression e in array_data){
6968 if (e is NullLiteral)
6971 if (!Attribute.GetAttributeArgumentExpression (e, Location, array_element_type, out v))
6981 /// Represents the `this' construct
6983 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6986 VariableInfo variable_info;
6988 public This (Block block, Location loc)
6994 public This (Location loc)
6999 public VariableInfo VariableInfo {
7000 get { return variable_info; }
7003 public bool VerifyFixed (bool is_expression)
7005 if ((variable_info == null) || (variable_info.LocalInfo == null))
7008 return variable_info.LocalInfo.IsFixed;
7011 public bool ResolveBase (EmitContext ec)
7013 eclass = ExprClass.Variable;
7015 if (ec.TypeContainer.CurrentType != null)
7016 type = ec.TypeContainer.CurrentType;
7018 type = ec.ContainerType;
7021 Error (26, "Keyword this not valid in static code");
7025 if ((block != null) && (block.ThisVariable != null))
7026 variable_info = block.ThisVariable.VariableInfo;
7028 if (ec.CurrentAnonymousMethod != null)
7034 public override Expression DoResolve (EmitContext ec)
7036 if (!ResolveBase (ec))
7039 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
7040 Error (188, "The this object cannot be used before all " +
7041 "of its fields are assigned to");
7042 variable_info.SetAssigned (ec);
7046 if (ec.IsFieldInitializer) {
7047 Error (27, "Keyword `this' can't be used outside a constructor, " +
7048 "a method or a property.");
7055 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
7057 if (!ResolveBase (ec))
7060 if (variable_info != null)
7061 variable_info.SetAssigned (ec);
7063 if (ec.TypeContainer is Class){
7064 Error (1604, "Cannot assign to 'this' because it is read-only");
7071 public void Emit (EmitContext ec, bool leave_copy)
7075 ec.ig.Emit (OpCodes.Dup);
7078 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
7080 ILGenerator ig = ec.ig;
7082 if (ec.TypeContainer is Struct){
7086 ec.ig.Emit (OpCodes.Dup);
7087 ig.Emit (OpCodes.Stobj, type);
7089 throw new Exception ("how did you get here");
7093 public override void Emit (EmitContext ec)
7095 ILGenerator ig = ec.ig;
7098 if (ec.TypeContainer is Struct)
7099 ig.Emit (OpCodes.Ldobj, type);
7102 public override int GetHashCode()
7104 return block.GetHashCode ();
7107 public override bool Equals (object obj)
7109 This t = obj as This;
7113 return block == t.block;
7116 public void AddressOf (EmitContext ec, AddressOp mode)
7121 // FIGURE OUT WHY LDARG_S does not work
7123 // consider: struct X { int val; int P { set { val = value; }}}
7125 // Yes, this looks very bad. Look at `NOTAS' for
7127 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
7132 /// Represents the `__arglist' construct
7134 public class ArglistAccess : Expression
7136 public ArglistAccess (Location loc)
7141 public bool ResolveBase (EmitContext ec)
7143 eclass = ExprClass.Variable;
7144 type = TypeManager.runtime_argument_handle_type;
7148 public override Expression DoResolve (EmitContext ec)
7150 if (!ResolveBase (ec))
7153 if (ec.IsFieldInitializer || !ec.CurrentBlock.HasVarargs) {
7154 Error (190, "The __arglist construct is valid only within " +
7155 "a variable argument method.");
7162 public override void Emit (EmitContext ec)
7164 ec.ig.Emit (OpCodes.Arglist);
7169 /// Represents the `__arglist (....)' construct
7171 public class Arglist : Expression
7173 public readonly Argument[] Arguments;
7175 public Arglist (Argument[] args, Location l)
7181 public Type[] ArgumentTypes {
7183 Type[] retval = new Type [Arguments.Length];
7184 for (int i = 0; i < Arguments.Length; i++)
7185 retval [i] = Arguments [i].Type;
7190 public override Expression DoResolve (EmitContext ec)
7192 eclass = ExprClass.Variable;
7193 type = TypeManager.runtime_argument_handle_type;
7195 foreach (Argument arg in Arguments) {
7196 if (!arg.Resolve (ec, loc))
7203 public override void Emit (EmitContext ec)
7205 foreach (Argument arg in Arguments)
7211 // This produces the value that renders an instance, used by the iterators code
7213 public class ProxyInstance : Expression, IMemoryLocation {
7214 public override Expression DoResolve (EmitContext ec)
7216 eclass = ExprClass.Variable;
7217 type = ec.ContainerType;
7221 public override void Emit (EmitContext ec)
7223 ec.ig.Emit (OpCodes.Ldarg_0);
7227 public void AddressOf (EmitContext ec, AddressOp mode)
7229 ec.ig.Emit (OpCodes.Ldarg_0);
7234 /// Implements the typeof operator
7236 public class TypeOf : Expression {
7237 public Expression QueriedType;
7238 protected Type typearg;
7240 public TypeOf (Expression queried_type, Location l)
7242 QueriedType = queried_type;
7246 public override Expression DoResolve (EmitContext ec)
7248 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec);
7252 typearg = texpr.Type;
7254 if (typearg == TypeManager.void_type) {
7255 Error (673, "System.Void cannot be used from C# - " +
7256 "use typeof (void) to get the void type object");
7260 if (typearg.IsPointer && !ec.InUnsafe){
7264 CheckObsoleteAttribute (typearg);
7266 type = TypeManager.type_type;
7267 eclass = ExprClass.Type;
7271 public override void Emit (EmitContext ec)
7273 ec.ig.Emit (OpCodes.Ldtoken, typearg);
7274 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
7277 public Type TypeArg {
7278 get { return typearg; }
7283 /// Implements the `typeof (void)' operator
7285 public class TypeOfVoid : TypeOf {
7286 public TypeOfVoid (Location l) : base (null, l)
7291 public override Expression DoResolve (EmitContext ec)
7293 type = TypeManager.type_type;
7294 typearg = TypeManager.void_type;
7295 eclass = ExprClass.Type;
7301 /// Implements the sizeof expression
7303 public class SizeOf : Expression {
7304 public Expression QueriedType;
7307 public SizeOf (Expression queried_type, Location l)
7309 this.QueriedType = queried_type;
7313 public override Expression DoResolve (EmitContext ec)
7315 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec);
7319 if (texpr is TypeParameterExpr){
7320 ((TypeParameterExpr)texpr).Error_CannotUseAsUnmanagedType (loc);
7324 type_queried = texpr.Type;
7326 int size_of = GetTypeSize (type_queried);
7328 return new IntConstant (size_of);
7332 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)",
7333 TypeManager.CSharpName (type_queried));
7337 CheckObsoleteAttribute (type_queried);
7339 if (!TypeManager.IsUnmanagedType (type_queried)){
7340 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
7344 type = TypeManager.int32_type;
7345 eclass = ExprClass.Value;
7349 public override void Emit (EmitContext ec)
7351 int size = GetTypeSize (type_queried);
7354 ec.ig.Emit (OpCodes.Sizeof, type_queried);
7356 IntConstant.EmitInt (ec.ig, size);
7361 /// Implements the member access expression
7363 public class MemberAccess : Expression {
7364 public string Identifier;
7365 protected Expression expr;
7366 protected TypeArguments args;
7368 public MemberAccess (Expression expr, string id, Location l)
7375 public MemberAccess (Expression expr, string id, TypeArguments args,
7377 : this (expr, id, l)
7382 public Expression Expr {
7388 public virtual Expression DoResolve (EmitContext ec, Expression right_side,
7392 throw new Exception ();
7395 // Resolve the expression with flow analysis turned off, we'll do the definite
7396 // assignment checks later. This is because we don't know yet what the expression
7397 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7398 // definite assignment check on the actual field and not on the whole struct.
7401 SimpleName original = expr as SimpleName;
7402 expr = expr.Resolve (ec, flags | ResolveFlags.Intermediate | ResolveFlags.DisableFlowAnalysis);
7406 if (expr is Namespace) {
7407 Namespace ns = (Namespace) expr;
7408 string lookup_id = MemberName.MakeName (Identifier, args);
7409 FullNamedExpression retval = ns.Lookup (ec.DeclSpace, lookup_id, loc);
7410 if ((retval != null) && (args != null))
7411 retval = new ConstructedType (retval, args, loc).ResolveAsTypeStep (ec);
7413 Report.Error (234, loc, "The type or namespace name `{0}' could not be found in namespace `{1}'", Identifier, ns.FullName);
7418 // TODO: I mailed Ravi about this, and apparently we can get rid
7419 // of this and put it in the right place.
7421 // Handle enums here when they are in transit.
7422 // Note that we cannot afford to hit MemberLookup in this case because
7423 // it will fail to find any members at all
7427 if (expr is TypeExpr){
7428 expr_type = expr.Type;
7430 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
7431 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", expr_type);
7435 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
7436 Enum en = TypeManager.LookupEnum (expr_type);
7439 object value = en.LookupEnumValue (Identifier, loc);
7442 MemberCore mc = en.GetDefinition (Identifier);
7443 ObsoleteAttribute oa = mc.GetObsoleteAttribute (en);
7445 AttributeTester.Report_ObsoleteMessage (oa, mc.GetSignatureForError (), Location);
7447 oa = en.GetObsoleteAttribute (en);
7449 AttributeTester.Report_ObsoleteMessage (oa, en.GetSignatureForError (), Location);
7452 Constant c = Constantify (value, en.UnderlyingType);
7453 return new EnumConstant (c, expr_type);
7456 CheckObsoleteAttribute (expr_type);
7458 FieldInfo fi = expr_type.GetField (Identifier);
7460 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
7462 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), Location);
7467 expr_type = expr.Type;
7469 if (expr_type.IsPointer){
7470 Error (23, "The `.' operator can not be applied to pointer operands (" +
7471 TypeManager.CSharpName (expr_type) + ")");
7475 Expression member_lookup;
7476 member_lookup = MemberLookup (
7477 ec, expr_type, expr_type, Identifier, loc);
7478 if ((member_lookup == null) && (args != null)) {
7479 string lookup_id = MemberName.MakeName (Identifier, args);
7480 member_lookup = MemberLookup (
7481 ec, expr_type, expr_type, lookup_id, loc);
7483 if (member_lookup == null) {
7484 MemberLookupFailed (
7485 ec, expr_type, expr_type, Identifier, null, true, loc);
7489 if (member_lookup is TypeExpr) {
7490 if (!(expr is TypeExpr) &&
7491 (original == null || !original.IdenticalNameAndTypeName (ec, expr, loc))) {
7492 Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
7493 member_lookup.Type + "' instead");
7497 return member_lookup;
7500 MemberExpr me = (MemberExpr) member_lookup;
7501 member_lookup = me.ResolveMemberAccess (ec, expr, loc, original);
7502 if (member_lookup == null)
7506 MethodGroupExpr mg = member_lookup as MethodGroupExpr;
7508 throw new InternalErrorException ();
7510 return mg.ResolveGeneric (ec, args);
7513 // The following DoResolve/DoResolveLValue will do the definite assignment
7516 if (right_side != null)
7517 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
7519 member_lookup = member_lookup.DoResolve (ec);
7521 return member_lookup;
7524 public override Expression DoResolve (EmitContext ec)
7526 return DoResolve (ec, null, ResolveFlags.VariableOrValue | ResolveFlags.Type);
7529 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7531 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue | ResolveFlags.Type);
7534 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
7536 return ResolveNamespaceOrType (ec, false);
7539 public FullNamedExpression ResolveNamespaceOrType (EmitContext ec, bool silent)
7541 FullNamedExpression new_expr = expr.ResolveAsTypeStep (ec);
7543 if (new_expr == null)
7546 string lookup_id = MemberName.MakeName (Identifier, args);
7548 if (new_expr is Namespace) {
7549 Namespace ns = (Namespace) new_expr;
7550 FullNamedExpression retval = ns.Lookup (ec.DeclSpace, lookup_id, loc);
7551 if ((retval != null) && (args != null))
7552 retval = new ConstructedType (retval, args, loc).ResolveAsTypeStep (ec);
7553 if (!silent && retval == null)
7554 Report.Error (234, loc, "The type or namespace name `{0}' could not be found in namespace `{1}'", Identifier, ns.FullName);
7558 TypeExpr tnew_expr = new_expr.ResolveAsTypeTerminal (ec);
7559 if (tnew_expr == null)
7562 Type expr_type = tnew_expr.Type;
7564 if (expr_type.IsPointer){
7565 Error (23, "The `.' operator can not be applied to pointer operands (" +
7566 TypeManager.CSharpName (expr_type) + ")");
7570 Expression member_lookup = MemberLookup (ec, expr_type, expr_type, lookup_id, loc);
7571 if (member_lookup == null) {
7572 int errors = Report.Errors;
7573 MemberLookupFailed (ec, expr_type, expr_type, lookup_id, null, false, loc);
7575 if (!silent && errors == Report.Errors)
7576 Report.Error (234, loc, "The type name `{0}' could not be found in type `{1}'",
7577 lookup_id, new_expr.FullName);
7581 if (!(member_lookup is TypeExpr)) {
7582 Report.Error (118, loc, "'{0}.{1}' denotes a '{2}', where a type was expected",
7583 new_expr.FullName, lookup_id, member_lookup.ExprClassName ());
7587 TypeExpr texpr = member_lookup.ResolveAsTypeTerminal (ec);
7591 TypeArguments the_args = args;
7592 if (TypeManager.HasGenericArguments (expr_type)) {
7593 Type[] decl_args = TypeManager.GetTypeArguments (expr_type);
7595 TypeArguments new_args = new TypeArguments (loc);
7596 foreach (Type decl in decl_args)
7597 new_args.Add (new TypeExpression (decl, loc));
7600 new_args.Add (args);
7602 the_args = new_args;
7605 if (the_args != null) {
7606 ConstructedType ctype = new ConstructedType (texpr.Type, the_args, loc);
7607 return ctype.ResolveAsTypeStep (ec);
7613 public override void Emit (EmitContext ec)
7615 throw new Exception ("Should not happen");
7618 public override string ToString ()
7620 return expr + "." + MemberName.MakeName (Identifier, args);
7625 /// Implements checked expressions
7627 public class CheckedExpr : Expression {
7629 public Expression Expr;
7631 public CheckedExpr (Expression e, Location l)
7637 public override Expression DoResolve (EmitContext ec)
7639 bool last_check = ec.CheckState;
7640 bool last_const_check = ec.ConstantCheckState;
7642 ec.CheckState = true;
7643 ec.ConstantCheckState = true;
7644 Expr = Expr.Resolve (ec);
7645 ec.CheckState = last_check;
7646 ec.ConstantCheckState = last_const_check;
7651 if (Expr is Constant)
7654 eclass = Expr.eclass;
7659 public override void Emit (EmitContext ec)
7661 bool last_check = ec.CheckState;
7662 bool last_const_check = ec.ConstantCheckState;
7664 ec.CheckState = true;
7665 ec.ConstantCheckState = true;
7667 ec.CheckState = last_check;
7668 ec.ConstantCheckState = last_const_check;
7674 /// Implements the unchecked expression
7676 public class UnCheckedExpr : Expression {
7678 public Expression Expr;
7680 public UnCheckedExpr (Expression e, Location l)
7686 public override Expression DoResolve (EmitContext ec)
7688 bool last_check = ec.CheckState;
7689 bool last_const_check = ec.ConstantCheckState;
7691 ec.CheckState = false;
7692 ec.ConstantCheckState = false;
7693 Expr = Expr.Resolve (ec);
7694 ec.CheckState = last_check;
7695 ec.ConstantCheckState = last_const_check;
7700 if (Expr is Constant)
7703 eclass = Expr.eclass;
7708 public override void Emit (EmitContext ec)
7710 bool last_check = ec.CheckState;
7711 bool last_const_check = ec.ConstantCheckState;
7713 ec.CheckState = false;
7714 ec.ConstantCheckState = false;
7716 ec.CheckState = last_check;
7717 ec.ConstantCheckState = last_const_check;
7723 /// An Element Access expression.
7725 /// During semantic analysis these are transformed into
7726 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7728 public class ElementAccess : Expression {
7729 public ArrayList Arguments;
7730 public Expression Expr;
7732 public ElementAccess (Expression e, ArrayList e_list, Location l)
7741 Arguments = new ArrayList ();
7742 foreach (Expression tmp in e_list)
7743 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7747 bool CommonResolve (EmitContext ec)
7749 Expr = Expr.Resolve (ec);
7754 if (Arguments == null)
7757 foreach (Argument a in Arguments){
7758 if (!a.Resolve (ec, loc))
7765 Expression MakePointerAccess (EmitContext ec, Type t)
7767 if (t == TypeManager.void_ptr_type){
7768 Error (242, "The array index operation is not valid for void pointers");
7771 if (Arguments.Count != 1){
7772 Error (196, "A pointer must be indexed by a single value");
7777 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc).Resolve (ec);
7780 return new Indirection (p, loc).Resolve (ec);
7783 public override Expression DoResolve (EmitContext ec)
7785 if (!CommonResolve (ec))
7789 // We perform some simple tests, and then to "split" the emit and store
7790 // code we create an instance of a different class, and return that.
7792 // I am experimenting with this pattern.
7796 if (t == TypeManager.array_type){
7797 Report.Error (21, loc, "Cannot use indexer on System.Array");
7802 return (new ArrayAccess (this, loc)).Resolve (ec);
7804 return MakePointerAccess (ec, Expr.Type);
7806 FieldExpr fe = Expr as FieldExpr;
7808 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
7810 return MakePointerAccess (ec, ff.ElementType);
7813 return (new IndexerAccess (this, loc)).Resolve (ec);
7816 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7818 if (!CommonResolve (ec))
7823 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
7826 return MakePointerAccess (ec, Expr.Type);
7828 FieldExpr fe = Expr as FieldExpr;
7830 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
7832 if (!(fe.InstanceExpression is LocalVariableReference) &&
7833 !(fe.InstanceExpression is This)) {
7834 Error (1708, "Fixed buffers can only be accessed through locals or fields");
7837 // TODO: not sure whether it is correct
7838 // if (!ec.InFixedInitializer) {
7839 // Error (1666, "You cannot use fixed sized buffers contained in unfixed expressions. Try using the fixed statement");
7842 return MakePointerAccess (ec, ff.ElementType);
7845 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
7848 public override void Emit (EmitContext ec)
7850 throw new Exception ("Should never be reached");
7855 /// Implements array access
7857 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7859 // Points to our "data" repository
7863 LocalTemporary temp;
7866 public ArrayAccess (ElementAccess ea_data, Location l)
7869 eclass = ExprClass.Variable;
7873 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7875 return DoResolve (ec);
7878 public override Expression DoResolve (EmitContext ec)
7881 ExprClass eclass = ea.Expr.eclass;
7883 // As long as the type is valid
7884 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7885 eclass == ExprClass.Value)) {
7886 ea.Expr.Error_UnexpectedKind ("variable or value");
7891 Type t = ea.Expr.Type;
7892 if (t.GetArrayRank () != ea.Arguments.Count){
7894 "Incorrect number of indexes for array " +
7895 " expected: " + t.GetArrayRank () + " got: " +
7896 ea.Arguments.Count);
7900 type = TypeManager.GetElementType (t);
7901 if (type.IsPointer && !ec.InUnsafe){
7902 UnsafeError (ea.Location);
7906 foreach (Argument a in ea.Arguments){
7907 Type argtype = a.Type;
7909 if (argtype == TypeManager.int32_type ||
7910 argtype == TypeManager.uint32_type ||
7911 argtype == TypeManager.int64_type ||
7912 argtype == TypeManager.uint64_type) {
7913 Constant c = a.Expr as Constant;
7914 if (c != null && c.IsNegative) {
7915 Report.Warning (251, 2, a.Expr.Location, "Indexing an array with a negative index (array indices always start at zero)");
7921 // Mhm. This is strage, because the Argument.Type is not the same as
7922 // Argument.Expr.Type: the value changes depending on the ref/out setting.
7924 // Wonder if I will run into trouble for this.
7926 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
7931 eclass = ExprClass.Variable;
7937 /// Emits the right opcode to load an object of Type `t'
7938 /// from an array of T
7940 static public void EmitLoadOpcode (ILGenerator ig, Type type)
7942 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7943 ig.Emit (OpCodes.Ldelem_U1);
7944 else if (type == TypeManager.sbyte_type)
7945 ig.Emit (OpCodes.Ldelem_I1);
7946 else if (type == TypeManager.short_type)
7947 ig.Emit (OpCodes.Ldelem_I2);
7948 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7949 ig.Emit (OpCodes.Ldelem_U2);
7950 else if (type == TypeManager.int32_type)
7951 ig.Emit (OpCodes.Ldelem_I4);
7952 else if (type == TypeManager.uint32_type)
7953 ig.Emit (OpCodes.Ldelem_U4);
7954 else if (type == TypeManager.uint64_type)
7955 ig.Emit (OpCodes.Ldelem_I8);
7956 else if (type == TypeManager.int64_type)
7957 ig.Emit (OpCodes.Ldelem_I8);
7958 else if (type == TypeManager.float_type)
7959 ig.Emit (OpCodes.Ldelem_R4);
7960 else if (type == TypeManager.double_type)
7961 ig.Emit (OpCodes.Ldelem_R8);
7962 else if (type == TypeManager.intptr_type)
7963 ig.Emit (OpCodes.Ldelem_I);
7964 else if (TypeManager.IsEnumType (type)){
7965 EmitLoadOpcode (ig, TypeManager.EnumToUnderlying (type));
7966 } else if (type.IsValueType){
7967 ig.Emit (OpCodes.Ldelema, type);
7968 ig.Emit (OpCodes.Ldobj, type);
7969 } else if (type.IsGenericParameter)
7970 ig.Emit (OpCodes.Ldelem_Any, type);
7972 ig.Emit (OpCodes.Ldelem_Ref);
7976 /// Returns the right opcode to store an object of Type `t'
7977 /// from an array of T.
7979 static public OpCode GetStoreOpcode (Type t, out bool is_stobj, out bool has_type_arg)
7981 //Console.WriteLine (new System.Diagnostics.StackTrace ());
7982 has_type_arg = false; is_stobj = false;
7983 t = TypeManager.TypeToCoreType (t);
7984 if (TypeManager.IsEnumType (t))
7985 t = TypeManager.EnumToUnderlying (t);
7986 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
7987 t == TypeManager.bool_type)
7988 return OpCodes.Stelem_I1;
7989 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
7990 t == TypeManager.char_type)
7991 return OpCodes.Stelem_I2;
7992 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
7993 return OpCodes.Stelem_I4;
7994 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
7995 return OpCodes.Stelem_I8;
7996 else if (t == TypeManager.float_type)
7997 return OpCodes.Stelem_R4;
7998 else if (t == TypeManager.double_type)
7999 return OpCodes.Stelem_R8;
8000 else if (t == TypeManager.intptr_type) {
8001 has_type_arg = true;
8003 return OpCodes.Stobj;
8004 } else if (t.IsValueType) {
8005 has_type_arg = true;
8007 return OpCodes.Stobj;
8008 } else if (t.IsGenericParameter) {
8009 has_type_arg = true;
8010 return OpCodes.Stelem_Any;
8012 return OpCodes.Stelem_Ref;
8015 MethodInfo FetchGetMethod ()
8017 ModuleBuilder mb = CodeGen.Module.Builder;
8018 int arg_count = ea.Arguments.Count;
8019 Type [] args = new Type [arg_count];
8022 for (int i = 0; i < arg_count; i++){
8023 //args [i++] = a.Type;
8024 args [i] = TypeManager.int32_type;
8027 get = mb.GetArrayMethod (
8028 ea.Expr.Type, "Get",
8029 CallingConventions.HasThis |
8030 CallingConventions.Standard,
8036 MethodInfo FetchAddressMethod ()
8038 ModuleBuilder mb = CodeGen.Module.Builder;
8039 int arg_count = ea.Arguments.Count;
8040 Type [] args = new Type [arg_count];
8044 ret_type = TypeManager.GetReferenceType (type);
8046 for (int i = 0; i < arg_count; i++){
8047 //args [i++] = a.Type;
8048 args [i] = TypeManager.int32_type;
8051 address = mb.GetArrayMethod (
8052 ea.Expr.Type, "Address",
8053 CallingConventions.HasThis |
8054 CallingConventions.Standard,
8061 // Load the array arguments into the stack.
8063 // If we have been requested to cache the values (cached_locations array
8064 // initialized), then load the arguments the first time and store them
8065 // in locals. otherwise load from local variables.
8067 void LoadArrayAndArguments (EmitContext ec)
8069 ILGenerator ig = ec.ig;
8072 foreach (Argument a in ea.Arguments){
8073 Type argtype = a.Expr.Type;
8077 if (argtype == TypeManager.int64_type)
8078 ig.Emit (OpCodes.Conv_Ovf_I);
8079 else if (argtype == TypeManager.uint64_type)
8080 ig.Emit (OpCodes.Conv_Ovf_I_Un);
8084 public void Emit (EmitContext ec, bool leave_copy)
8086 int rank = ea.Expr.Type.GetArrayRank ();
8087 ILGenerator ig = ec.ig;
8090 LoadArrayAndArguments (ec);
8093 EmitLoadOpcode (ig, type);
8097 method = FetchGetMethod ();
8098 ig.Emit (OpCodes.Call, method);
8101 LoadFromPtr (ec.ig, this.type);
8104 ec.ig.Emit (OpCodes.Dup);
8105 temp = new LocalTemporary (ec, this.type);
8110 public override void Emit (EmitContext ec)
8115 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8117 int rank = ea.Expr.Type.GetArrayRank ();
8118 ILGenerator ig = ec.ig;
8119 Type t = source.Type;
8120 prepared = prepare_for_load;
8122 if (prepare_for_load) {
8123 AddressOf (ec, AddressOp.LoadStore);
8124 ec.ig.Emit (OpCodes.Dup);
8127 ec.ig.Emit (OpCodes.Dup);
8128 temp = new LocalTemporary (ec, this.type);
8131 StoreFromPtr (ec.ig, t);
8139 LoadArrayAndArguments (ec);
8142 bool is_stobj, has_type_arg;
8143 OpCode op = GetStoreOpcode (t, out is_stobj, out has_type_arg);
8146 // The stobj opcode used by value types will need
8147 // an address on the stack, not really an array/array
8151 ig.Emit (OpCodes.Ldelema, t);
8155 ec.ig.Emit (OpCodes.Dup);
8156 temp = new LocalTemporary (ec, this.type);
8161 ig.Emit (OpCodes.Stobj, t);
8162 else if (has_type_arg)
8167 ModuleBuilder mb = CodeGen.Module.Builder;
8168 int arg_count = ea.Arguments.Count;
8169 Type [] args = new Type [arg_count + 1];
8174 ec.ig.Emit (OpCodes.Dup);
8175 temp = new LocalTemporary (ec, this.type);
8179 for (int i = 0; i < arg_count; i++){
8180 //args [i++] = a.Type;
8181 args [i] = TypeManager.int32_type;
8184 args [arg_count] = type;
8186 set = mb.GetArrayMethod (
8187 ea.Expr.Type, "Set",
8188 CallingConventions.HasThis |
8189 CallingConventions.Standard,
8190 TypeManager.void_type, args);
8192 ig.Emit (OpCodes.Call, set);
8199 public void AddressOf (EmitContext ec, AddressOp mode)
8201 int rank = ea.Expr.Type.GetArrayRank ();
8202 ILGenerator ig = ec.ig;
8204 LoadArrayAndArguments (ec);
8207 ig.Emit (OpCodes.Ldelema, type);
8209 MethodInfo address = FetchAddressMethod ();
8210 ig.Emit (OpCodes.Call, address);
8214 public void EmitGetLength (EmitContext ec, int dim)
8216 int rank = ea.Expr.Type.GetArrayRank ();
8217 ILGenerator ig = ec.ig;
8221 ig.Emit (OpCodes.Ldlen);
8222 ig.Emit (OpCodes.Conv_I4);
8224 IntLiteral.EmitInt (ig, dim);
8225 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
8231 public ArrayList Properties;
8232 static Hashtable map;
8234 public struct Indexer {
8235 public readonly Type Type;
8236 public readonly MethodInfo Getter, Setter;
8238 public Indexer (Type type, MethodInfo get, MethodInfo set)
8248 map = new Hashtable ();
8253 Properties = new ArrayList ();
8256 void Append (MemberInfo [] mi)
8258 foreach (PropertyInfo property in mi){
8259 MethodInfo get, set;
8261 get = property.GetGetMethod (true);
8262 set = property.GetSetMethod (true);
8263 Properties.Add (new Indexer (property.PropertyType, get, set));
8267 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
8269 string p_name = TypeManager.IndexerPropertyName (lookup_type);
8271 MemberInfo [] mi = TypeManager.MemberLookup (
8272 caller_type, caller_type, lookup_type, MemberTypes.Property,
8273 BindingFlags.Public | BindingFlags.Instance |
8274 BindingFlags.DeclaredOnly, p_name, null);
8276 if (mi == null || mi.Length == 0)
8282 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
8284 Indexers ix = (Indexers) map [lookup_type];
8289 Type copy = lookup_type;
8290 while (copy != TypeManager.object_type && copy != null){
8291 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
8295 ix = new Indexers ();
8300 copy = copy.BaseType;
8303 if (!lookup_type.IsInterface)
8306 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
8307 if (ifaces != null) {
8308 foreach (Type itype in ifaces) {
8309 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
8312 ix = new Indexers ();
8324 /// Expressions that represent an indexer call.
8326 public class IndexerAccess : Expression, IAssignMethod {
8328 // Points to our "data" repository
8330 MethodInfo get, set;
8331 ArrayList set_arguments;
8332 bool is_base_indexer;
8334 protected Type indexer_type;
8335 protected Type current_type;
8336 protected Expression instance_expr;
8337 protected ArrayList arguments;
8339 public IndexerAccess (ElementAccess ea, Location loc)
8340 : this (ea.Expr, false, loc)
8342 this.arguments = ea.Arguments;
8345 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
8348 this.instance_expr = instance_expr;
8349 this.is_base_indexer = is_base_indexer;
8350 this.eclass = ExprClass.Value;
8354 protected virtual bool CommonResolve (EmitContext ec)
8356 indexer_type = instance_expr.Type;
8357 current_type = ec.ContainerType;
8362 public override Expression DoResolve (EmitContext ec)
8364 ArrayList AllGetters = new ArrayList();
8365 if (!CommonResolve (ec))
8369 // Step 1: Query for all `Item' *properties*. Notice
8370 // that the actual methods are pointed from here.
8372 // This is a group of properties, piles of them.
8374 bool found_any = false, found_any_getters = false;
8375 Type lookup_type = indexer_type;
8378 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
8379 if (ilist != null) {
8381 if (ilist.Properties != null) {
8382 foreach (Indexers.Indexer ix in ilist.Properties) {
8383 if (ix.Getter != null)
8384 AllGetters.Add(ix.Getter);
8389 if (AllGetters.Count > 0) {
8390 found_any_getters = true;
8391 get = (MethodInfo) Invocation.OverloadResolve (
8392 ec, new MethodGroupExpr (AllGetters, loc),
8393 arguments, false, loc);
8397 Report.Error (21, loc,
8398 "Type `" + TypeManager.CSharpName (indexer_type) +
8399 "' does not have any indexers defined");
8403 if (!found_any_getters) {
8404 Error (154, "indexer can not be used in this context, because " +
8405 "it lacks a `get' accessor");
8410 Error (1501, "No Overload for method `this' takes `" +
8411 arguments.Count + "' arguments");
8416 // Only base will allow this invocation to happen.
8418 if (get.IsAbstract && this is BaseIndexerAccess){
8419 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
8423 type = get.ReturnType;
8424 if (type.IsPointer && !ec.InUnsafe){
8429 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8431 eclass = ExprClass.IndexerAccess;
8435 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8437 ArrayList AllSetters = new ArrayList();
8438 if (!CommonResolve (ec))
8441 bool found_any = false, found_any_setters = false;
8443 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
8444 if (ilist != null) {
8446 if (ilist.Properties != null) {
8447 foreach (Indexers.Indexer ix in ilist.Properties) {
8448 if (ix.Setter != null)
8449 AllSetters.Add(ix.Setter);
8453 if (AllSetters.Count > 0) {
8454 found_any_setters = true;
8455 set_arguments = (ArrayList) arguments.Clone ();
8456 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
8457 set = (MethodInfo) Invocation.OverloadResolve (
8458 ec, new MethodGroupExpr (AllSetters, loc),
8459 set_arguments, false, loc);
8463 Report.Error (21, loc,
8464 "Type `" + TypeManager.CSharpName (indexer_type) +
8465 "' does not have any indexers defined");
8469 if (!found_any_setters) {
8470 Error (154, "indexer can not be used in this context, because " +
8471 "it lacks a `set' accessor");
8476 Error (1501, "No Overload for method `this' takes `" +
8477 arguments.Count + "' arguments");
8482 // Only base will allow this invocation to happen.
8484 if (set.IsAbstract && this is BaseIndexerAccess){
8485 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
8490 // Now look for the actual match in the list of indexers to set our "return" type
8492 type = TypeManager.void_type; // default value
8493 foreach (Indexers.Indexer ix in ilist.Properties){
8494 if (ix.Setter == set){
8500 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8502 eclass = ExprClass.IndexerAccess;
8506 bool prepared = false;
8507 LocalTemporary temp;
8509 public void Emit (EmitContext ec, bool leave_copy)
8511 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc, prepared, false);
8513 ec.ig.Emit (OpCodes.Dup);
8514 temp = new LocalTemporary (ec, Type);
8520 // source is ignored, because we already have a copy of it from the
8521 // LValue resolution and we have already constructed a pre-cached
8522 // version of the arguments (ea.set_arguments);
8524 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8526 prepared = prepare_for_load;
8527 Argument a = (Argument) set_arguments [set_arguments.Count - 1];
8532 ec.ig.Emit (OpCodes.Dup);
8533 temp = new LocalTemporary (ec, Type);
8536 } else if (leave_copy) {
8537 temp = new LocalTemporary (ec, Type);
8543 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc, false, prepared);
8550 public override void Emit (EmitContext ec)
8557 /// The base operator for method names
8559 public class BaseAccess : Expression {
8562 public BaseAccess (string member, Location l)
8564 this.member = member;
8568 public override Expression DoResolve (EmitContext ec)
8570 Expression c = CommonResolve (ec);
8576 // MethodGroups use this opportunity to flag an error on lacking ()
8578 if (!(c is MethodGroupExpr))
8579 return c.Resolve (ec);
8583 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8585 Expression c = CommonResolve (ec);
8591 // MethodGroups use this opportunity to flag an error on lacking ()
8593 if (! (c is MethodGroupExpr))
8594 return c.DoResolveLValue (ec, right_side);
8599 Expression CommonResolve (EmitContext ec)
8601 Expression member_lookup;
8602 Type current_type = ec.ContainerType;
8603 Type base_type = current_type.BaseType;
8606 Error (1511, "Keyword base is not allowed in static method");
8610 if (ec.IsFieldInitializer){
8611 Error (1512, "Keyword base is not available in the current context");
8615 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type,
8616 member, AllMemberTypes, AllBindingFlags,
8618 if (member_lookup == null) {
8619 MemberLookupFailed (ec, base_type, base_type, member, null, true, loc);
8626 left = new TypeExpression (base_type, loc);
8628 left = ec.GetThis (loc);
8630 MemberExpr me = (MemberExpr) member_lookup;
8632 Expression e = me.ResolveMemberAccess (ec, left, loc, null);
8634 if (e is PropertyExpr) {
8635 PropertyExpr pe = (PropertyExpr) e;
8640 if (e is MethodGroupExpr)
8641 ((MethodGroupExpr) e).IsBase = true;
8646 public override void Emit (EmitContext ec)
8648 throw new Exception ("Should never be called");
8653 /// The base indexer operator
8655 public class BaseIndexerAccess : IndexerAccess {
8656 public BaseIndexerAccess (ArrayList args, Location loc)
8657 : base (null, true, loc)
8659 arguments = new ArrayList ();
8660 foreach (Expression tmp in args)
8661 arguments.Add (new Argument (tmp, Argument.AType.Expression));
8664 protected override bool CommonResolve (EmitContext ec)
8666 instance_expr = ec.GetThis (loc);
8668 current_type = ec.ContainerType.BaseType;
8669 indexer_type = current_type;
8671 foreach (Argument a in arguments){
8672 if (!a.Resolve (ec, loc))
8681 /// This class exists solely to pass the Type around and to be a dummy
8682 /// that can be passed to the conversion functions (this is used by
8683 /// foreach implementation to typecast the object return value from
8684 /// get_Current into the proper type. All code has been generated and
8685 /// we only care about the side effect conversions to be performed
8687 /// This is also now used as a placeholder where a no-action expression
8688 /// is needed (the `New' class).
8690 public class EmptyExpression : Expression {
8691 public static readonly EmptyExpression Null = new EmptyExpression ();
8693 // TODO: should be protected
8694 public EmptyExpression ()
8696 type = TypeManager.object_type;
8697 eclass = ExprClass.Value;
8698 loc = Location.Null;
8701 public EmptyExpression (Type t)
8704 eclass = ExprClass.Value;
8705 loc = Location.Null;
8708 public override Expression DoResolve (EmitContext ec)
8713 public override void Emit (EmitContext ec)
8715 // nothing, as we only exist to not do anything.
8719 // This is just because we might want to reuse this bad boy
8720 // instead of creating gazillions of EmptyExpressions.
8721 // (CanImplicitConversion uses it)
8723 public void SetType (Type t)
8729 public class UserCast : Expression {
8733 public UserCast (MethodInfo method, Expression source, Location l)
8735 this.method = method;
8736 this.source = source;
8737 type = method.ReturnType;
8738 eclass = ExprClass.Value;
8742 public Expression Source {
8748 public override Expression DoResolve (EmitContext ec)
8751 // We are born fully resolved
8756 public override void Emit (EmitContext ec)
8758 ILGenerator ig = ec.ig;
8762 if (method is MethodInfo)
8763 ig.Emit (OpCodes.Call, (MethodInfo) method);
8765 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
8771 // This class is used to "construct" the type during a typecast
8772 // operation. Since the Type.GetType class in .NET can parse
8773 // the type specification, we just use this to construct the type
8774 // one bit at a time.
8776 public class ComposedCast : TypeExpr {
8780 public ComposedCast (Expression left, string dim, Location l)
8787 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
8789 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec);
8793 Type ltype = lexpr.Type;
8795 if ((ltype == TypeManager.void_type) && (dim != "*")) {
8796 Report.Error (1547, Location,
8797 "Keyword 'void' cannot be used in this context");
8801 if ((dim.Length > 0) && (dim [0] == '?')) {
8802 TypeExpr nullable = new NullableType (left, loc);
8804 nullable = new ComposedCast (nullable, dim.Substring (1), loc);
8805 return nullable.ResolveAsTypeTerminal (ec);
8808 if (dim == "*" && !TypeManager.IsUnmanagedType (ltype)) {
8809 Report.Error (208, loc, "Cannot declare a pointer to a managed type ('{0}')", ltype);
8814 type = TypeManager.GetConstructedType (ltype, dim);
8819 throw new InternalErrorException ("Couldn't create computed type " + ltype + dim);
8822 if (!ec.InUnsafe && type.IsPointer){
8827 if (type.IsArray && (type.GetElementType () == TypeManager.arg_iterator_type ||
8828 type.GetElementType () == TypeManager.typed_reference_type)) {
8829 Report.Error (611, loc, "Array elements cannot be of type '{0}'", TypeManager.CSharpName (type.GetElementType ()));
8833 eclass = ExprClass.Type;
8837 public override string Name {
8843 public override string FullName {
8845 return type.FullName;
8850 public class FixedBufferPtr: Expression {
8853 public FixedBufferPtr (Expression array, Type array_type, Location l)
8858 type = TypeManager.GetPointerType (array_type);
8859 eclass = ExprClass.Value;
8862 public override void Emit(EmitContext ec)
8867 public override Expression DoResolve (EmitContext ec)
8870 // We are born fully resolved
8878 // This class is used to represent the address of an array, used
8879 // only by the Fixed statement, this generates "&a [0]" construct
8880 // for fixed (char *pa = a)
8882 public class ArrayPtr : FixedBufferPtr {
8885 public ArrayPtr (Expression array, Type array_type, Location l):
8886 base (array, array_type, l)
8888 this.array_type = array_type;
8891 public override void Emit (EmitContext ec)
8895 ILGenerator ig = ec.ig;
8896 IntLiteral.EmitInt (ig, 0);
8897 ig.Emit (OpCodes.Ldelema, array_type);
8902 // Used by the fixed statement
8904 public class StringPtr : Expression {
8907 public StringPtr (LocalBuilder b, Location l)
8910 eclass = ExprClass.Value;
8911 type = TypeManager.char_ptr_type;
8915 public override Expression DoResolve (EmitContext ec)
8917 // This should never be invoked, we are born in fully
8918 // initialized state.
8923 public override void Emit (EmitContext ec)
8925 ILGenerator ig = ec.ig;
8927 ig.Emit (OpCodes.Ldloc, b);
8928 ig.Emit (OpCodes.Conv_I);
8929 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
8930 ig.Emit (OpCodes.Add);
8935 // Implements the `stackalloc' keyword
8937 public class StackAlloc : Expression {
8942 public StackAlloc (Expression type, Expression count, Location l)
8949 public override Expression DoResolve (EmitContext ec)
8951 count = count.Resolve (ec);
8955 if (count.Type != TypeManager.int32_type){
8956 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8961 Constant c = count as Constant;
8962 if (c != null && c.IsNegative) {
8963 Report.Error (247, loc, "Cannot use a negative size with stackalloc");
8967 if (ec.InCatch || ec.InFinally) {
8969 "stackalloc can not be used in a catch or finally block");
8973 TypeExpr texpr = t.ResolveAsTypeTerminal (ec);
8979 if (!TypeManager.VerifyUnManaged (otype, loc))
8982 type = TypeManager.GetPointerType (otype);
8983 eclass = ExprClass.Value;
8988 public override void Emit (EmitContext ec)
8990 int size = GetTypeSize (otype);
8991 ILGenerator ig = ec.ig;
8994 ig.Emit (OpCodes.Sizeof, otype);
8996 IntConstant.EmitInt (ig, size);
8998 ig.Emit (OpCodes.Mul);
8999 ig.Emit (OpCodes.Localloc);