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)
176 Report.Error (23, loc, "Operator `{0}' cannot be applied to operand of type `{1}'",
177 OperName (Oper), TypeManager.CSharpName (t));
181 /// The result has been already resolved:
183 /// FIXME: a minus constant -128 sbyte cant be turned into a
186 static Expression TryReduceNegative (Constant expr)
190 if (expr is IntConstant)
191 e = new IntConstant (-((IntConstant) expr).Value);
192 else if (expr is UIntConstant){
193 uint value = ((UIntConstant) expr).Value;
195 if (value < 2147483649)
196 return new IntConstant (-(int)value);
198 e = new LongConstant (-value);
200 else if (expr is LongConstant)
201 e = new LongConstant (-((LongConstant) expr).Value);
202 else if (expr is ULongConstant){
203 ulong value = ((ULongConstant) expr).Value;
205 if (value < 9223372036854775809)
206 return new LongConstant(-(long)value);
208 else if (expr is FloatConstant)
209 e = new FloatConstant (-((FloatConstant) expr).Value);
210 else if (expr is DoubleConstant)
211 e = new DoubleConstant (-((DoubleConstant) expr).Value);
212 else if (expr is DecimalConstant)
213 e = new DecimalConstant (-((DecimalConstant) expr).Value);
214 else if (expr is ShortConstant)
215 e = new IntConstant (-((ShortConstant) expr).Value);
216 else if (expr is UShortConstant)
217 e = new IntConstant (-((UShortConstant) expr).Value);
218 else if (expr is SByteConstant)
219 e = new IntConstant (-((SByteConstant) expr).Value);
220 else if (expr is ByteConstant)
221 e = new IntConstant (-((ByteConstant) expr).Value);
226 // This routine will attempt to simplify the unary expression when the
227 // argument is a constant. The result is returned in `result' and the
228 // function returns true or false depending on whether a reduction
229 // was performed or not
231 bool Reduce (EmitContext ec, Constant e, out Expression result)
233 Type expr_type = e.Type;
236 case Operator.UnaryPlus:
237 if (expr_type == TypeManager.bool_type){
246 case Operator.UnaryNegation:
247 result = TryReduceNegative (e);
248 return result != null;
250 case Operator.LogicalNot:
251 if (expr_type != TypeManager.bool_type) {
257 BoolConstant b = (BoolConstant) e;
258 result = new BoolConstant (!(b.Value));
261 case Operator.OnesComplement:
262 if (!((expr_type == TypeManager.int32_type) ||
263 (expr_type == TypeManager.uint32_type) ||
264 (expr_type == TypeManager.int64_type) ||
265 (expr_type == TypeManager.uint64_type) ||
266 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
269 if (Convert.ImplicitConversionExists (ec, e, TypeManager.int32_type)){
270 result = new Cast (new TypeExpression (TypeManager.int32_type, loc), e, loc);
271 result = result.Resolve (ec);
272 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint32_type)){
273 result = new Cast (new TypeExpression (TypeManager.uint32_type, loc), e, loc);
274 result = result.Resolve (ec);
275 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.int64_type)){
276 result = new Cast (new TypeExpression (TypeManager.int64_type, loc), e, loc);
277 result = result.Resolve (ec);
278 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint64_type)){
279 result = new Cast (new TypeExpression (TypeManager.uint64_type, loc), e, loc);
280 result = result.Resolve (ec);
283 if (result == null || !(result is Constant)){
289 expr_type = result.Type;
290 e = (Constant) result;
293 if (e is EnumConstant){
294 EnumConstant enum_constant = (EnumConstant) e;
297 if (Reduce (ec, enum_constant.Child, out reduced)){
298 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
306 if (expr_type == TypeManager.int32_type){
307 result = new IntConstant (~ ((IntConstant) e).Value);
308 } else if (expr_type == TypeManager.uint32_type){
309 result = new UIntConstant (~ ((UIntConstant) e).Value);
310 } else if (expr_type == TypeManager.int64_type){
311 result = new LongConstant (~ ((LongConstant) e).Value);
312 } else if (expr_type == TypeManager.uint64_type){
313 result = new ULongConstant (~ ((ULongConstant) e).Value);
321 case Operator.AddressOf:
325 case Operator.Indirection:
329 throw new Exception ("Can not constant fold: " + Oper.ToString());
332 Expression ResolveOperator (EmitContext ec)
335 // Step 1: Default operations on CLI native types.
338 // Attempt to use a constant folding operation.
339 if (Expr is Constant){
342 if (Reduce (ec, (Constant) Expr, out result))
347 // Step 2: Perform Operator Overload location
349 Type expr_type = Expr.Type;
353 op_name = oper_names [(int) Oper];
355 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
358 Expression e = StaticCallExpr.MakeSimpleCall (
359 ec, (MethodGroupExpr) mg, Expr, loc);
369 // Only perform numeric promotions on:
372 if (expr_type == null)
376 case Operator.LogicalNot:
377 if (expr_type != TypeManager.bool_type) {
378 Expr = ResolveBoolean (ec, Expr, loc);
385 type = TypeManager.bool_type;
388 case Operator.OnesComplement:
389 if (!((expr_type == TypeManager.int32_type) ||
390 (expr_type == TypeManager.uint32_type) ||
391 (expr_type == TypeManager.int64_type) ||
392 (expr_type == TypeManager.uint64_type) ||
393 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
396 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
398 type = TypeManager.int32_type;
401 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint32_type, loc);
403 type = TypeManager.uint32_type;
406 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
408 type = TypeManager.int64_type;
411 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint64_type, loc);
413 type = TypeManager.uint64_type;
422 case Operator.AddressOf:
428 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
432 IVariable variable = Expr as IVariable;
433 bool is_fixed = variable != null && variable.VerifyFixed ();
435 if (!ec.InFixedInitializer && !is_fixed) {
436 Error (212, "You can only take the address of unfixed expression inside " +
437 "of a fixed statement initializer");
441 if (ec.InFixedInitializer && is_fixed) {
442 Error (213, "You cannot use the fixed statement to take the address of an already fixed expression");
446 LocalVariableReference lr = Expr as LocalVariableReference;
448 if (lr.local_info.IsCaptured){
449 AnonymousMethod.Error_AddressOfCapturedVar (lr.Name, loc);
452 lr.local_info.AddressTaken = true;
453 lr.local_info.Used = true;
456 // According to the specs, a variable is considered definitely assigned if you take
458 if ((variable != null) && (variable.VariableInfo != null))
459 variable.VariableInfo.SetAssigned (ec);
461 type = TypeManager.GetPointerType (Expr.Type);
464 case Operator.Indirection:
470 if (!expr_type.IsPointer){
471 Error (193, "The * or -> operator must be applied to a pointer");
476 // We create an Indirection expression, because
477 // it can implement the IMemoryLocation.
479 return new Indirection (Expr, loc);
481 case Operator.UnaryPlus:
483 // A plus in front of something is just a no-op, so return the child.
487 case Operator.UnaryNegation:
489 // Deals with -literals
490 // int operator- (int x)
491 // long operator- (long x)
492 // float operator- (float f)
493 // double operator- (double d)
494 // decimal operator- (decimal d)
496 Expression expr = null;
499 // transform - - expr into expr
502 Unary unary = (Unary) Expr;
504 if (unary.Oper == Operator.UnaryNegation)
509 // perform numeric promotions to int,
513 // The following is inneficient, because we call
514 // ImplicitConversion too many times.
516 // It is also not clear if we should convert to Float
517 // or Double initially.
519 if (expr_type == TypeManager.uint32_type){
521 // FIXME: handle exception to this rule that
522 // permits the int value -2147483648 (-2^31) to
523 // bt wrote as a decimal interger literal
525 type = TypeManager.int64_type;
526 Expr = Convert.ImplicitConversion (ec, Expr, type, loc);
530 if (expr_type == TypeManager.uint64_type){
532 // FIXME: Handle exception of `long value'
533 // -92233720368547758087 (-2^63) to be wrote as
534 // decimal integer literal.
540 if (expr_type == TypeManager.float_type){
545 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
552 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
559 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.double_type, loc);
570 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
571 TypeManager.CSharpName (expr_type) + "'");
575 public override Expression DoResolve (EmitContext ec)
577 if (Oper == Operator.AddressOf) {
578 Expr = Expr.DoResolveLValue (ec, new EmptyExpression ());
580 if (Expr == null || Expr.eclass != ExprClass.Variable){
581 Error (211, "Cannot take the address of the given expression");
586 Expr = Expr.Resolve (ec);
591 if (TypeManager.IsNullableType (Expr.Type))
592 return new Nullable.LiftedUnaryOperator (Oper, Expr, loc).Resolve (ec);
594 eclass = ExprClass.Value;
595 return ResolveOperator (ec);
598 public override Expression DoResolveLValue (EmitContext ec, Expression right)
600 if (Oper == Operator.Indirection)
601 return DoResolve (ec);
606 public override void Emit (EmitContext ec)
608 ILGenerator ig = ec.ig;
611 case Operator.UnaryPlus:
612 throw new Exception ("This should be caught by Resolve");
614 case Operator.UnaryNegation:
616 ig.Emit (OpCodes.Ldc_I4_0);
617 if (type == TypeManager.int64_type)
618 ig.Emit (OpCodes.Conv_U8);
620 ig.Emit (OpCodes.Sub_Ovf);
623 ig.Emit (OpCodes.Neg);
628 case Operator.LogicalNot:
630 ig.Emit (OpCodes.Ldc_I4_0);
631 ig.Emit (OpCodes.Ceq);
634 case Operator.OnesComplement:
636 ig.Emit (OpCodes.Not);
639 case Operator.AddressOf:
640 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
644 throw new Exception ("This should not happen: Operator = "
649 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
651 if (Oper == Operator.LogicalNot)
652 Expr.EmitBranchable (ec, target, !onTrue);
654 base.EmitBranchable (ec, target, onTrue);
657 public override string ToString ()
659 return "Unary (" + Oper + ", " + Expr + ")";
665 // Unary operators are turned into Indirection expressions
666 // after semantic analysis (this is so we can take the address
667 // of an indirection).
669 public class Indirection : Expression, IMemoryLocation, IAssignMethod, IVariable {
671 LocalTemporary temporary;
674 public Indirection (Expression expr, Location l)
677 type = TypeManager.HasElementType (expr.Type) ? TypeManager.GetElementType (expr.Type) : expr.Type;
678 eclass = ExprClass.Variable;
682 public override void Emit (EmitContext ec)
687 LoadFromPtr (ec.ig, Type);
690 public void Emit (EmitContext ec, bool leave_copy)
694 ec.ig.Emit (OpCodes.Dup);
695 temporary = new LocalTemporary (ec, expr.Type);
696 temporary.Store (ec);
700 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
702 prepared = prepare_for_load;
706 if (prepare_for_load)
707 ec.ig.Emit (OpCodes.Dup);
711 ec.ig.Emit (OpCodes.Dup);
712 temporary = new LocalTemporary (ec, expr.Type);
713 temporary.Store (ec);
716 StoreFromPtr (ec.ig, type);
718 if (temporary != null)
722 public void AddressOf (EmitContext ec, AddressOp Mode)
727 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
729 return DoResolve (ec);
732 public override Expression DoResolve (EmitContext ec)
735 // Born fully resolved
740 public override string ToString ()
742 return "*(" + expr + ")";
745 #region IVariable Members
747 public VariableInfo VariableInfo {
753 public bool VerifyFixed ()
755 // A pointer-indirection is always fixed.
763 /// Unary Mutator expressions (pre and post ++ and --)
767 /// UnaryMutator implements ++ and -- expressions. It derives from
768 /// ExpressionStatement becuase the pre/post increment/decrement
769 /// operators can be used in a statement context.
771 /// FIXME: Idea, we could split this up in two classes, one simpler
772 /// for the common case, and one with the extra fields for more complex
773 /// classes (indexers require temporary access; overloaded require method)
776 public class UnaryMutator : ExpressionStatement {
778 public enum Mode : byte {
785 PreDecrement = IsDecrement,
786 PostIncrement = IsPost,
787 PostDecrement = IsPost | IsDecrement
791 bool is_expr = false;
792 bool recurse = false;
797 // This is expensive for the simplest case.
799 StaticCallExpr method;
801 public UnaryMutator (Mode m, Expression e, Location l)
808 static string OperName (Mode mode)
810 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
815 /// Returns whether an object of type `t' can be incremented
816 /// or decremented with add/sub (ie, basically whether we can
817 /// use pre-post incr-decr operations on it, but it is not a
818 /// System.Decimal, which we require operator overloading to catch)
820 static bool IsIncrementableNumber (Type t)
822 return (t == TypeManager.sbyte_type) ||
823 (t == TypeManager.byte_type) ||
824 (t == TypeManager.short_type) ||
825 (t == TypeManager.ushort_type) ||
826 (t == TypeManager.int32_type) ||
827 (t == TypeManager.uint32_type) ||
828 (t == TypeManager.int64_type) ||
829 (t == TypeManager.uint64_type) ||
830 (t == TypeManager.char_type) ||
831 (t.IsSubclassOf (TypeManager.enum_type)) ||
832 (t == TypeManager.float_type) ||
833 (t == TypeManager.double_type) ||
834 (t.IsPointer && t != TypeManager.void_ptr_type);
837 Expression ResolveOperator (EmitContext ec)
839 Type expr_type = expr.Type;
842 // Step 1: Perform Operator Overload location
847 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
848 op_name = "op_Increment";
850 op_name = "op_Decrement";
852 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
855 method = StaticCallExpr.MakeSimpleCall (
856 ec, (MethodGroupExpr) mg, expr, loc);
859 } else if (!IsIncrementableNumber (expr_type)) {
860 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
861 TypeManager.CSharpName (expr_type) + "'");
866 // The operand of the prefix/postfix increment decrement operators
867 // should be an expression that is classified as a variable,
868 // a property access or an indexer access
871 if (expr.eclass == ExprClass.Variable){
872 LocalVariableReference var = expr as LocalVariableReference;
873 if ((var != null) && var.IsReadOnly) {
874 Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
877 } else if (expr.eclass == ExprClass.IndexerAccess || expr.eclass == ExprClass.PropertyAccess){
878 expr = expr.ResolveLValue (ec, this, Location);
882 expr.Error_UnexpectedKind ("variable, indexer or property access", loc);
889 public override Expression DoResolve (EmitContext ec)
891 expr = expr.Resolve (ec);
896 eclass = ExprClass.Value;
898 if (TypeManager.IsNullableType (expr.Type))
899 return new Nullable.LiftedUnaryMutator (mode, expr, loc).Resolve (ec);
901 return ResolveOperator (ec);
904 static int PtrTypeSize (Type t)
906 return GetTypeSize (TypeManager.GetElementType (t));
910 // Loads the proper "1" into the stack based on the type, then it emits the
911 // opcode for the operation requested
913 void LoadOneAndEmitOp (EmitContext ec, Type t)
916 // Measure if getting the typecode and using that is more/less efficient
917 // that comparing types. t.GetTypeCode() is an internal call.
919 ILGenerator ig = ec.ig;
921 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
922 LongConstant.EmitLong (ig, 1);
923 else if (t == TypeManager.double_type)
924 ig.Emit (OpCodes.Ldc_R8, 1.0);
925 else if (t == TypeManager.float_type)
926 ig.Emit (OpCodes.Ldc_R4, 1.0F);
927 else if (t.IsPointer){
928 int n = PtrTypeSize (t);
931 ig.Emit (OpCodes.Sizeof, t);
933 IntConstant.EmitInt (ig, n);
935 ig.Emit (OpCodes.Ldc_I4_1);
938 // Now emit the operation
941 if (t == TypeManager.int32_type ||
942 t == TypeManager.int64_type){
943 if ((mode & Mode.IsDecrement) != 0)
944 ig.Emit (OpCodes.Sub_Ovf);
946 ig.Emit (OpCodes.Add_Ovf);
947 } else if (t == TypeManager.uint32_type ||
948 t == TypeManager.uint64_type){
949 if ((mode & Mode.IsDecrement) != 0)
950 ig.Emit (OpCodes.Sub_Ovf_Un);
952 ig.Emit (OpCodes.Add_Ovf_Un);
954 if ((mode & Mode.IsDecrement) != 0)
955 ig.Emit (OpCodes.Sub_Ovf);
957 ig.Emit (OpCodes.Add_Ovf);
960 if ((mode & Mode.IsDecrement) != 0)
961 ig.Emit (OpCodes.Sub);
963 ig.Emit (OpCodes.Add);
966 if (t == TypeManager.sbyte_type){
968 ig.Emit (OpCodes.Conv_Ovf_I1);
970 ig.Emit (OpCodes.Conv_I1);
971 } else if (t == TypeManager.byte_type){
973 ig.Emit (OpCodes.Conv_Ovf_U1);
975 ig.Emit (OpCodes.Conv_U1);
976 } else if (t == TypeManager.short_type){
978 ig.Emit (OpCodes.Conv_Ovf_I2);
980 ig.Emit (OpCodes.Conv_I2);
981 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
983 ig.Emit (OpCodes.Conv_Ovf_U2);
985 ig.Emit (OpCodes.Conv_U2);
990 void EmitCode (EmitContext ec, bool is_expr)
993 this.is_expr = is_expr;
994 ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
997 public override void Emit (EmitContext ec)
1000 // We use recurse to allow ourselfs to be the source
1001 // of an assignment. This little hack prevents us from
1002 // having to allocate another expression
1005 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
1007 LoadOneAndEmitOp (ec, expr.Type);
1009 ec.ig.Emit (OpCodes.Call, method.Method);
1014 EmitCode (ec, true);
1017 public override void EmitStatement (EmitContext ec)
1019 EmitCode (ec, false);
1024 /// Base class for the `Is' and `As' classes.
1028 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1031 public abstract class Probe : Expression {
1032 public Expression ProbeType;
1033 protected Expression expr;
1034 protected Type probe_type;
1036 public Probe (Expression expr, Expression probe_type, Location l)
1038 ProbeType = probe_type;
1043 public Expression Expr {
1049 public override Expression DoResolve (EmitContext ec)
1051 TypeExpr texpr = ProbeType.ResolveAsTypeTerminal (ec);
1054 probe_type = texpr.Type;
1056 CheckObsoleteAttribute (probe_type);
1058 expr = expr.Resolve (ec);
1062 if (expr.Type.IsPointer) {
1063 Report.Error (244, loc, "\"is\" or \"as\" are not valid on pointer types");
1071 /// Implementation of the `is' operator.
1073 public class Is : Probe {
1074 public Is (Expression expr, Expression probe_type, Location l)
1075 : base (expr, probe_type, l)
1080 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1085 public override void Emit (EmitContext ec)
1087 ILGenerator ig = ec.ig;
1092 case Action.AlwaysFalse:
1093 ig.Emit (OpCodes.Pop);
1094 IntConstant.EmitInt (ig, 0);
1096 case Action.AlwaysTrue:
1097 ig.Emit (OpCodes.Pop);
1098 IntConstant.EmitInt (ig, 1);
1100 case Action.LeaveOnStack:
1101 // the `e != null' rule.
1102 ig.Emit (OpCodes.Ldnull);
1103 ig.Emit (OpCodes.Ceq);
1104 ig.Emit (OpCodes.Ldc_I4_0);
1105 ig.Emit (OpCodes.Ceq);
1108 ig.Emit (OpCodes.Isinst, probe_type);
1109 ig.Emit (OpCodes.Ldnull);
1110 ig.Emit (OpCodes.Cgt_Un);
1113 throw new Exception ("never reached");
1116 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
1118 ILGenerator ig = ec.ig;
1121 case Action.AlwaysFalse:
1123 ig.Emit (OpCodes.Br, target);
1126 case Action.AlwaysTrue:
1128 ig.Emit (OpCodes.Br, target);
1131 case Action.LeaveOnStack:
1132 // the `e != null' rule.
1134 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1138 ig.Emit (OpCodes.Isinst, probe_type);
1139 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1142 throw new Exception ("never reached");
1145 public override Expression DoResolve (EmitContext ec)
1147 Expression e = base.DoResolve (ec);
1149 if ((e == null) || (expr == null))
1152 Type etype = expr.Type;
1153 bool warning_always_matches = false;
1154 bool warning_never_matches = false;
1156 type = TypeManager.bool_type;
1157 eclass = ExprClass.Value;
1160 // First case, if at compile time, there is an implicit conversion
1161 // then e != null (objects) or true (value types)
1163 e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1166 if (etype.IsValueType)
1167 action = Action.AlwaysTrue;
1169 action = Action.LeaveOnStack;
1171 warning_always_matches = true;
1172 } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1173 if (etype.IsGenericParameter)
1174 expr = new BoxedCast (expr, etype);
1177 // Second case: explicit reference convresion
1179 if (expr is NullLiteral)
1180 action = Action.AlwaysFalse;
1182 action = Action.Probe;
1184 action = Action.AlwaysFalse;
1185 warning_never_matches = true;
1188 if (warning_always_matches)
1189 Warning (183, "The given expression is always of the provided (`{0}') type", TypeManager.CSharpName (probe_type));
1190 else if (warning_never_matches){
1191 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1192 Warning (184, "The given expression is never of the provided (`{0}') type", TypeManager.CSharpName (probe_type));
1200 /// Implementation of the `as' operator.
1202 public class As : Probe {
1203 public As (Expression expr, Expression probe_type, Location l)
1204 : base (expr, probe_type, l)
1208 bool do_isinst = false;
1210 public override void Emit (EmitContext ec)
1212 ILGenerator ig = ec.ig;
1217 ig.Emit (OpCodes.Isinst, probe_type);
1220 static void Error_CannotConvertType (Type source, Type target, Location loc)
1222 Report.Error (39, loc, "Cannot convert type `{0}' to `{1}' via a built-in conversion",
1223 TypeManager.CSharpName (source),
1224 TypeManager.CSharpName (target));
1227 public override Expression DoResolve (EmitContext ec)
1229 Expression e = base.DoResolve (ec);
1235 eclass = ExprClass.Value;
1236 Type etype = expr.Type;
1238 if (TypeManager.IsValueType (probe_type)){
1239 Report.Error (77, loc, "The as operator must be used with a reference type (`" +
1240 TypeManager.CSharpName (probe_type) + "' is a value type)");
1245 e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1252 if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1253 if (etype.IsGenericParameter)
1254 expr = new BoxedCast (expr, etype);
1260 Error_CannotConvertType (etype, probe_type, loc);
1266 /// This represents a typecast in the source language.
1268 /// FIXME: Cast expressions have an unusual set of parsing
1269 /// rules, we need to figure those out.
1271 public class Cast : Expression {
1272 Expression target_type;
1275 public Cast (Expression cast_type, Expression expr, Location loc)
1277 this.target_type = cast_type;
1282 public Expression TargetType {
1288 public Expression Expr {
1297 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1299 if (!ec.ConstantCheckState)
1302 if ((value < min) || (value > max)) {
1303 Error (221, "Constant value `" + value + "' cannot be converted " +
1304 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1305 "syntax to override)");
1312 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1314 if (!ec.ConstantCheckState)
1318 Error (221, "Constant value `" + value + "' cannot be converted " +
1319 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1320 "syntax to override)");
1327 bool CheckUnsigned (EmitContext ec, long value, Type type)
1329 if (!ec.ConstantCheckState)
1333 Error (221, "Constant value `" + value + "' cannot be converted " +
1334 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1335 "syntax to override)");
1343 /// Attempts to do a compile-time folding of a constant cast.
1345 Expression TryReduce (EmitContext ec, Type target_type)
1347 Expression real_expr = expr;
1348 if (real_expr is EnumConstant)
1349 real_expr = ((EnumConstant) real_expr).Child;
1351 if (real_expr is ByteConstant){
1352 byte v = ((ByteConstant) real_expr).Value;
1354 if (target_type == TypeManager.sbyte_type) {
1355 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1357 return new SByteConstant ((sbyte) v);
1359 if (target_type == TypeManager.short_type)
1360 return new ShortConstant ((short) v);
1361 if (target_type == TypeManager.ushort_type)
1362 return new UShortConstant ((ushort) v);
1363 if (target_type == TypeManager.int32_type)
1364 return new IntConstant ((int) v);
1365 if (target_type == TypeManager.uint32_type)
1366 return new UIntConstant ((uint) v);
1367 if (target_type == TypeManager.int64_type)
1368 return new LongConstant ((long) v);
1369 if (target_type == TypeManager.uint64_type)
1370 return new ULongConstant ((ulong) v);
1371 if (target_type == TypeManager.float_type)
1372 return new FloatConstant ((float) v);
1373 if (target_type == TypeManager.double_type)
1374 return new DoubleConstant ((double) v);
1375 if (target_type == TypeManager.char_type)
1376 return new CharConstant ((char) v);
1377 if (target_type == TypeManager.decimal_type)
1378 return new DecimalConstant ((decimal) v);
1380 if (real_expr is SByteConstant){
1381 sbyte v = ((SByteConstant) real_expr).Value;
1383 if (target_type == TypeManager.byte_type) {
1384 if (!CheckUnsigned (ec, v, target_type))
1386 return new ByteConstant ((byte) v);
1388 if (target_type == TypeManager.short_type)
1389 return new ShortConstant ((short) v);
1390 if (target_type == TypeManager.ushort_type) {
1391 if (!CheckUnsigned (ec, v, target_type))
1393 return new UShortConstant ((ushort) v);
1394 } if (target_type == TypeManager.int32_type)
1395 return new IntConstant ((int) v);
1396 if (target_type == TypeManager.uint32_type) {
1397 if (!CheckUnsigned (ec, v, target_type))
1399 return new UIntConstant ((uint) v);
1400 } if (target_type == TypeManager.int64_type)
1401 return new LongConstant ((long) v);
1402 if (target_type == TypeManager.uint64_type) {
1403 if (!CheckUnsigned (ec, v, target_type))
1405 return new ULongConstant ((ulong) v);
1407 if (target_type == TypeManager.float_type)
1408 return new FloatConstant ((float) v);
1409 if (target_type == TypeManager.double_type)
1410 return new DoubleConstant ((double) v);
1411 if (target_type == TypeManager.char_type) {
1412 if (!CheckUnsigned (ec, v, target_type))
1414 return new CharConstant ((char) v);
1416 if (target_type == TypeManager.decimal_type)
1417 return new DecimalConstant ((decimal) v);
1419 if (real_expr is ShortConstant){
1420 short v = ((ShortConstant) real_expr).Value;
1422 if (target_type == TypeManager.byte_type) {
1423 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1425 return new ByteConstant ((byte) v);
1427 if (target_type == TypeManager.sbyte_type) {
1428 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1430 return new SByteConstant ((sbyte) v);
1432 if (target_type == TypeManager.ushort_type) {
1433 if (!CheckUnsigned (ec, v, target_type))
1435 return new UShortConstant ((ushort) v);
1437 if (target_type == TypeManager.int32_type)
1438 return new IntConstant ((int) v);
1439 if (target_type == TypeManager.uint32_type) {
1440 if (!CheckUnsigned (ec, v, target_type))
1442 return new UIntConstant ((uint) v);
1444 if (target_type == TypeManager.int64_type)
1445 return new LongConstant ((long) v);
1446 if (target_type == TypeManager.uint64_type) {
1447 if (!CheckUnsigned (ec, v, target_type))
1449 return new ULongConstant ((ulong) v);
1451 if (target_type == TypeManager.float_type)
1452 return new FloatConstant ((float) v);
1453 if (target_type == TypeManager.double_type)
1454 return new DoubleConstant ((double) v);
1455 if (target_type == TypeManager.char_type) {
1456 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1458 return new CharConstant ((char) v);
1460 if (target_type == TypeManager.decimal_type)
1461 return new DecimalConstant ((decimal) v);
1463 if (real_expr is UShortConstant){
1464 ushort v = ((UShortConstant) real_expr).Value;
1466 if (target_type == TypeManager.byte_type) {
1467 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1469 return new ByteConstant ((byte) v);
1471 if (target_type == TypeManager.sbyte_type) {
1472 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1474 return new SByteConstant ((sbyte) v);
1476 if (target_type == TypeManager.short_type) {
1477 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1479 return new ShortConstant ((short) v);
1481 if (target_type == TypeManager.int32_type)
1482 return new IntConstant ((int) v);
1483 if (target_type == TypeManager.uint32_type)
1484 return new UIntConstant ((uint) v);
1485 if (target_type == TypeManager.int64_type)
1486 return new LongConstant ((long) v);
1487 if (target_type == TypeManager.uint64_type)
1488 return new ULongConstant ((ulong) v);
1489 if (target_type == TypeManager.float_type)
1490 return new FloatConstant ((float) v);
1491 if (target_type == TypeManager.double_type)
1492 return new DoubleConstant ((double) v);
1493 if (target_type == TypeManager.char_type) {
1494 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1496 return new CharConstant ((char) v);
1498 if (target_type == TypeManager.decimal_type)
1499 return new DecimalConstant ((decimal) v);
1501 if (real_expr is IntConstant){
1502 int v = ((IntConstant) real_expr).Value;
1504 if (target_type == TypeManager.byte_type) {
1505 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1507 return new ByteConstant ((byte) v);
1509 if (target_type == TypeManager.sbyte_type) {
1510 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1512 return new SByteConstant ((sbyte) v);
1514 if (target_type == TypeManager.short_type) {
1515 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1517 return new ShortConstant ((short) v);
1519 if (target_type == TypeManager.ushort_type) {
1520 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1522 return new UShortConstant ((ushort) v);
1524 if (target_type == TypeManager.uint32_type) {
1525 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1527 return new UIntConstant ((uint) v);
1529 if (target_type == TypeManager.int64_type)
1530 return new LongConstant ((long) v);
1531 if (target_type == TypeManager.uint64_type) {
1532 if (!CheckUnsigned (ec, v, target_type))
1534 return new ULongConstant ((ulong) v);
1536 if (target_type == TypeManager.float_type)
1537 return new FloatConstant ((float) v);
1538 if (target_type == TypeManager.double_type)
1539 return new DoubleConstant ((double) v);
1540 if (target_type == TypeManager.char_type) {
1541 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1543 return new CharConstant ((char) v);
1545 if (target_type == TypeManager.decimal_type)
1546 return new DecimalConstant ((decimal) v);
1548 if (real_expr is UIntConstant){
1549 uint v = ((UIntConstant) real_expr).Value;
1551 if (target_type == TypeManager.byte_type) {
1552 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1554 return new ByteConstant ((byte) v);
1556 if (target_type == TypeManager.sbyte_type) {
1557 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1559 return new SByteConstant ((sbyte) v);
1561 if (target_type == TypeManager.short_type) {
1562 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1564 return new ShortConstant ((short) v);
1566 if (target_type == TypeManager.ushort_type) {
1567 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1569 return new UShortConstant ((ushort) v);
1571 if (target_type == TypeManager.int32_type) {
1572 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1574 return new IntConstant ((int) v);
1576 if (target_type == TypeManager.int64_type)
1577 return new LongConstant ((long) v);
1578 if (target_type == TypeManager.uint64_type)
1579 return new ULongConstant ((ulong) v);
1580 if (target_type == TypeManager.float_type)
1581 return new FloatConstant ((float) v);
1582 if (target_type == TypeManager.double_type)
1583 return new DoubleConstant ((double) v);
1584 if (target_type == TypeManager.char_type) {
1585 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1587 return new CharConstant ((char) v);
1589 if (target_type == TypeManager.decimal_type)
1590 return new DecimalConstant ((decimal) v);
1592 if (real_expr is LongConstant){
1593 long v = ((LongConstant) real_expr).Value;
1595 if (target_type == TypeManager.byte_type) {
1596 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1598 return new ByteConstant ((byte) v);
1600 if (target_type == TypeManager.sbyte_type) {
1601 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1603 return new SByteConstant ((sbyte) v);
1605 if (target_type == TypeManager.short_type) {
1606 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1608 return new ShortConstant ((short) v);
1610 if (target_type == TypeManager.ushort_type) {
1611 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1613 return new UShortConstant ((ushort) v);
1615 if (target_type == TypeManager.int32_type) {
1616 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1618 return new IntConstant ((int) v);
1620 if (target_type == TypeManager.uint32_type) {
1621 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1623 return new UIntConstant ((uint) v);
1625 if (target_type == TypeManager.uint64_type) {
1626 if (!CheckUnsigned (ec, v, target_type))
1628 return new ULongConstant ((ulong) v);
1630 if (target_type == TypeManager.float_type)
1631 return new FloatConstant ((float) v);
1632 if (target_type == TypeManager.double_type)
1633 return new DoubleConstant ((double) v);
1634 if (target_type == TypeManager.char_type) {
1635 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1637 return new CharConstant ((char) v);
1639 if (target_type == TypeManager.decimal_type)
1640 return new DecimalConstant ((decimal) v);
1642 if (real_expr is ULongConstant){
1643 ulong v = ((ULongConstant) real_expr).Value;
1645 if (target_type == TypeManager.byte_type) {
1646 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1648 return new ByteConstant ((byte) v);
1650 if (target_type == TypeManager.sbyte_type) {
1651 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1653 return new SByteConstant ((sbyte) v);
1655 if (target_type == TypeManager.short_type) {
1656 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1658 return new ShortConstant ((short) v);
1660 if (target_type == TypeManager.ushort_type) {
1661 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1663 return new UShortConstant ((ushort) v);
1665 if (target_type == TypeManager.int32_type) {
1666 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1668 return new IntConstant ((int) v);
1670 if (target_type == TypeManager.uint32_type) {
1671 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1673 return new UIntConstant ((uint) v);
1675 if (target_type == TypeManager.int64_type) {
1676 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1678 return new LongConstant ((long) v);
1680 if (target_type == TypeManager.float_type)
1681 return new FloatConstant ((float) v);
1682 if (target_type == TypeManager.double_type)
1683 return new DoubleConstant ((double) v);
1684 if (target_type == TypeManager.char_type) {
1685 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1687 return new CharConstant ((char) v);
1689 if (target_type == TypeManager.decimal_type)
1690 return new DecimalConstant ((decimal) v);
1692 if (real_expr is FloatConstant){
1693 float v = ((FloatConstant) real_expr).Value;
1695 if (target_type == TypeManager.byte_type)
1696 return new ByteConstant ((byte) v);
1697 if (target_type == TypeManager.sbyte_type)
1698 return new SByteConstant ((sbyte) v);
1699 if (target_type == TypeManager.short_type)
1700 return new ShortConstant ((short) v);
1701 if (target_type == TypeManager.ushort_type)
1702 return new UShortConstant ((ushort) v);
1703 if (target_type == TypeManager.int32_type)
1704 return new IntConstant ((int) v);
1705 if (target_type == TypeManager.uint32_type)
1706 return new UIntConstant ((uint) v);
1707 if (target_type == TypeManager.int64_type)
1708 return new LongConstant ((long) v);
1709 if (target_type == TypeManager.uint64_type)
1710 return new ULongConstant ((ulong) v);
1711 if (target_type == TypeManager.double_type)
1712 return new DoubleConstant ((double) v);
1713 if (target_type == TypeManager.char_type)
1714 return new CharConstant ((char) v);
1715 if (target_type == TypeManager.decimal_type)
1716 return new DecimalConstant ((decimal) v);
1718 if (real_expr is DoubleConstant){
1719 double v = ((DoubleConstant) real_expr).Value;
1721 if (target_type == TypeManager.byte_type){
1722 return new ByteConstant ((byte) v);
1723 } if (target_type == TypeManager.sbyte_type)
1724 return new SByteConstant ((sbyte) v);
1725 if (target_type == TypeManager.short_type)
1726 return new ShortConstant ((short) v);
1727 if (target_type == TypeManager.ushort_type)
1728 return new UShortConstant ((ushort) v);
1729 if (target_type == TypeManager.int32_type)
1730 return new IntConstant ((int) v);
1731 if (target_type == TypeManager.uint32_type)
1732 return new UIntConstant ((uint) v);
1733 if (target_type == TypeManager.int64_type)
1734 return new LongConstant ((long) v);
1735 if (target_type == TypeManager.uint64_type)
1736 return new ULongConstant ((ulong) v);
1737 if (target_type == TypeManager.float_type)
1738 return new FloatConstant ((float) v);
1739 if (target_type == TypeManager.char_type)
1740 return new CharConstant ((char) v);
1741 if (target_type == TypeManager.decimal_type)
1742 return new DecimalConstant ((decimal) v);
1745 if (real_expr is CharConstant){
1746 char v = ((CharConstant) real_expr).Value;
1748 if (target_type == TypeManager.byte_type) {
1749 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1751 return new ByteConstant ((byte) v);
1753 if (target_type == TypeManager.sbyte_type) {
1754 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1756 return new SByteConstant ((sbyte) v);
1758 if (target_type == TypeManager.short_type) {
1759 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1761 return new ShortConstant ((short) v);
1763 if (target_type == TypeManager.int32_type)
1764 return new IntConstant ((int) v);
1765 if (target_type == TypeManager.uint32_type)
1766 return new UIntConstant ((uint) v);
1767 if (target_type == TypeManager.int64_type)
1768 return new LongConstant ((long) v);
1769 if (target_type == TypeManager.uint64_type)
1770 return new ULongConstant ((ulong) v);
1771 if (target_type == TypeManager.float_type)
1772 return new FloatConstant ((float) v);
1773 if (target_type == TypeManager.double_type)
1774 return new DoubleConstant ((double) v);
1775 if (target_type == TypeManager.char_type) {
1776 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1778 return new CharConstant ((char) v);
1780 if (target_type == TypeManager.decimal_type)
1781 return new DecimalConstant ((decimal) v);
1787 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1789 expr = expr.DoResolveLValue (ec, right_side);
1793 return ResolveRest (ec);
1796 public override Expression DoResolve (EmitContext ec)
1798 expr = expr.Resolve (ec);
1802 return ResolveRest (ec);
1805 Expression ResolveRest (EmitContext ec)
1807 TypeExpr target = target_type.ResolveAsTypeTerminal (ec);
1813 CheckObsoleteAttribute (type);
1815 if (type.IsAbstract && type.IsSealed) {
1816 Report.Error (716, loc, "Cannot convert to static type `{0}'", TypeManager.CSharpName (type));
1820 eclass = ExprClass.Value;
1822 if (expr is Constant){
1823 Expression e = TryReduce (ec, type);
1829 if (type.IsPointer && !ec.InUnsafe) {
1833 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1837 public override void Emit (EmitContext ec)
1840 // This one will never happen
1842 throw new Exception ("Should not happen");
1847 /// Binary operators
1849 public class Binary : Expression {
1850 public enum Operator : byte {
1851 Multiply, Division, Modulus,
1852 Addition, Subtraction,
1853 LeftShift, RightShift,
1854 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1855 Equality, Inequality,
1865 Expression left, right;
1867 // This must be kept in sync with Operator!!!
1868 public static readonly string [] oper_names;
1872 oper_names = new string [(int) Operator.TOP];
1874 oper_names [(int) Operator.Multiply] = "op_Multiply";
1875 oper_names [(int) Operator.Division] = "op_Division";
1876 oper_names [(int) Operator.Modulus] = "op_Modulus";
1877 oper_names [(int) Operator.Addition] = "op_Addition";
1878 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1879 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1880 oper_names [(int) Operator.RightShift] = "op_RightShift";
1881 oper_names [(int) Operator.LessThan] = "op_LessThan";
1882 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1883 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1884 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1885 oper_names [(int) Operator.Equality] = "op_Equality";
1886 oper_names [(int) Operator.Inequality] = "op_Inequality";
1887 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1888 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1889 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1890 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1891 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1894 public Binary (Operator oper, Expression left, Expression right, Location loc)
1902 public Operator Oper {
1911 public Expression Left {
1920 public Expression Right {
1931 /// Returns a stringified representation of the Operator
1933 static string OperName (Operator oper)
1936 case Operator.Multiply:
1938 case Operator.Division:
1940 case Operator.Modulus:
1942 case Operator.Addition:
1944 case Operator.Subtraction:
1946 case Operator.LeftShift:
1948 case Operator.RightShift:
1950 case Operator.LessThan:
1952 case Operator.GreaterThan:
1954 case Operator.LessThanOrEqual:
1956 case Operator.GreaterThanOrEqual:
1958 case Operator.Equality:
1960 case Operator.Inequality:
1962 case Operator.BitwiseAnd:
1964 case Operator.BitwiseOr:
1966 case Operator.ExclusiveOr:
1968 case Operator.LogicalOr:
1970 case Operator.LogicalAnd:
1974 return oper.ToString ();
1977 public override string ToString ()
1979 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1980 right.ToString () + ")";
1983 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1985 if (expr.Type == target_type)
1988 return Convert.ImplicitConversion (ec, expr, target_type, loc);
1991 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1994 34, loc, "Operator `" + OperName (oper)
1995 + "' is ambiguous on operands of type `"
1996 + TypeManager.CSharpName (l) + "' "
1997 + "and `" + TypeManager.CSharpName (r)
2001 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
2003 if ((l == t) || (r == t))
2006 if (!check_user_conversions)
2009 if (Convert.ImplicitUserConversionExists (ec, l, t))
2011 else if (Convert.ImplicitUserConversionExists (ec, r, t))
2018 // Note that handling the case l == Decimal || r == Decimal
2019 // is taken care of by the Step 1 Operator Overload resolution.
2021 // If `check_user_conv' is true, we also check whether a user-defined conversion
2022 // exists. Note that we only need to do this if both arguments are of a user-defined
2023 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
2024 // so we don't explicitly check for performance reasons.
2026 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
2028 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
2030 // If either operand is of type double, the other operand is
2031 // conveted to type double.
2033 if (r != TypeManager.double_type)
2034 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
2035 if (l != TypeManager.double_type)
2036 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
2038 type = TypeManager.double_type;
2039 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
2041 // if either operand is of type float, the other operand is
2042 // converted to type float.
2044 if (r != TypeManager.double_type)
2045 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
2046 if (l != TypeManager.double_type)
2047 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
2048 type = TypeManager.float_type;
2049 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2053 // If either operand is of type ulong, the other operand is
2054 // converted to type ulong. or an error ocurrs if the other
2055 // operand is of type sbyte, short, int or long
2057 if (l == TypeManager.uint64_type){
2058 if (r != TypeManager.uint64_type){
2059 if (right is IntConstant){
2060 IntConstant ic = (IntConstant) right;
2062 e = Convert.TryImplicitIntConversion (l, ic);
2065 } else if (right is LongConstant){
2066 long ll = ((LongConstant) right).Value;
2069 right = new ULongConstant ((ulong) ll);
2071 e = Convert.ImplicitNumericConversion (ec, right, l, loc);
2078 if (left is IntConstant){
2079 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
2082 } else if (left is LongConstant){
2083 long ll = ((LongConstant) left).Value;
2086 left = new ULongConstant ((ulong) ll);
2088 e = Convert.ImplicitNumericConversion (ec, left, r, loc);
2095 if ((other == TypeManager.sbyte_type) ||
2096 (other == TypeManager.short_type) ||
2097 (other == TypeManager.int32_type) ||
2098 (other == TypeManager.int64_type))
2099 Error_OperatorAmbiguous (loc, oper, l, r);
2101 left = ForceConversion (ec, left, TypeManager.uint64_type);
2102 right = ForceConversion (ec, right, TypeManager.uint64_type);
2104 type = TypeManager.uint64_type;
2105 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2107 // If either operand is of type long, the other operand is converted
2110 if (l != TypeManager.int64_type)
2111 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
2112 if (r != TypeManager.int64_type)
2113 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
2115 type = TypeManager.int64_type;
2116 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2118 // If either operand is of type uint, and the other
2119 // operand is of type sbyte, short or int, othe operands are
2120 // converted to type long (unless we have an int constant).
2124 if (l == TypeManager.uint32_type){
2125 if (right is IntConstant){
2126 IntConstant ic = (IntConstant) right;
2130 right = new UIntConstant ((uint) val);
2137 } else if (r == TypeManager.uint32_type){
2138 if (left is IntConstant){
2139 IntConstant ic = (IntConstant) left;
2143 left = new UIntConstant ((uint) val);
2152 if ((other == TypeManager.sbyte_type) ||
2153 (other == TypeManager.short_type) ||
2154 (other == TypeManager.int32_type)){
2155 left = ForceConversion (ec, left, TypeManager.int64_type);
2156 right = ForceConversion (ec, right, TypeManager.int64_type);
2157 type = TypeManager.int64_type;
2160 // if either operand is of type uint, the other
2161 // operand is converd to type uint
2163 left = ForceConversion (ec, left, TypeManager.uint32_type);
2164 right = ForceConversion (ec, right, TypeManager.uint32_type);
2165 type = TypeManager.uint32_type;
2167 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2168 if (l != TypeManager.decimal_type)
2169 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
2171 if (r != TypeManager.decimal_type)
2172 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
2173 type = TypeManager.decimal_type;
2175 left = ForceConversion (ec, left, TypeManager.int32_type);
2176 right = ForceConversion (ec, right, TypeManager.int32_type);
2178 type = TypeManager.int32_type;
2181 return (left != null) && (right != null);
2184 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2186 Report.Error (19, loc, "Operator `{0}' cannot be applied to operands of type `{1}' and `{2}'",
2187 name, TypeManager.CSharpName (l), TypeManager.CSharpName (r));
2190 void Error_OperatorCannotBeApplied ()
2192 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2195 static bool is_unsigned (Type t)
2197 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2198 t == TypeManager.short_type || t == TypeManager.byte_type);
2201 static bool is_user_defined (Type t)
2203 if (t.IsSubclassOf (TypeManager.value_type) &&
2204 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2210 Expression Make32or64 (EmitContext ec, Expression e)
2214 if (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2215 t == TypeManager.int64_type || t == TypeManager.uint64_type)
2217 Expression ee = Convert.ImplicitConversion (ec, e, TypeManager.int32_type, loc);
2220 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint32_type, loc);
2223 ee = Convert.ImplicitConversion (ec, e, TypeManager.int64_type, loc);
2226 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint64_type, loc);
2232 Expression CheckShiftArguments (EmitContext ec)
2236 e = ForceConversion (ec, right, TypeManager.int32_type);
2238 Error_OperatorCannotBeApplied ();
2243 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
2244 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
2245 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
2246 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
2250 if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
2251 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (31), loc);
2252 right = right.DoResolve (ec);
2254 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (63), loc);
2255 right = right.DoResolve (ec);
2260 Error_OperatorCannotBeApplied ();
2265 // This is used to check if a test 'x == null' can be optimized to a reference equals,
2266 // i.e., not invoke op_Equality.
2268 static bool EqualsNullIsReferenceEquals (Type t)
2270 return t == TypeManager.object_type || t == TypeManager.string_type ||
2271 t == TypeManager.delegate_type || t.IsSubclassOf (TypeManager.delegate_type);
2274 Expression ResolveOperator (EmitContext ec)
2277 Type r = right.Type;
2279 if (oper == Operator.Equality || oper == Operator.Inequality){
2280 if (l.IsGenericParameter && (right is NullLiteral)) {
2281 if (l.BaseType == TypeManager.value_type) {
2282 Error_OperatorCannotBeApplied ();
2286 left = new BoxedCast (left);
2287 Type = TypeManager.bool_type;
2291 if (r.IsGenericParameter && (left is NullLiteral)) {
2292 if (r.BaseType == TypeManager.value_type) {
2293 Error_OperatorCannotBeApplied ();
2297 right = new BoxedCast (right);
2298 Type = TypeManager.bool_type;
2303 // Optimize out call to op_Equality in a few cases.
2305 if ((l == TypeManager.null_type && EqualsNullIsReferenceEquals (r)) ||
2306 (r == TypeManager.null_type && EqualsNullIsReferenceEquals (l))) {
2307 Type = TypeManager.bool_type;
2313 if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
2314 Type = TypeManager.bool_type;
2321 // Do not perform operator overload resolution when both sides are
2324 if (!(TypeManager.IsPrimitiveType (l) && TypeManager.IsPrimitiveType (r))){
2326 // Step 1: Perform Operator Overload location
2328 Expression left_expr, right_expr;
2330 string op = oper_names [(int) oper];
2332 MethodGroupExpr union;
2333 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2335 right_expr = MemberLookup (
2336 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2337 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2339 union = (MethodGroupExpr) left_expr;
2341 if (union != null) {
2342 ArrayList args = new ArrayList (2);
2343 args.Add (new Argument (left, Argument.AType.Expression));
2344 args.Add (new Argument (right, Argument.AType.Expression));
2346 MethodBase method = Invocation.OverloadResolve (
2347 ec, union, args, true, Location.Null);
2349 if (method != null) {
2350 MethodInfo mi = (MethodInfo) method;
2352 return new BinaryMethod (mi.ReturnType, method, args);
2358 // Step 0: String concatenation (because overloading will get this wrong)
2360 if (oper == Operator.Addition){
2362 // If any of the arguments is a string, cast to string
2365 // Simple constant folding
2366 if (left is StringConstant && right is StringConstant)
2367 return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value);
2369 if (l == TypeManager.string_type || r == TypeManager.string_type) {
2371 if (r == TypeManager.void_type || l == TypeManager.void_type) {
2372 Error_OperatorCannotBeApplied ();
2376 // try to fold it in on the left
2377 if (left is StringConcat) {
2380 // We have to test here for not-null, since we can be doubly-resolved
2381 // take care of not appending twice
2384 type = TypeManager.string_type;
2385 ((StringConcat) left).Append (ec, right);
2386 return left.Resolve (ec);
2392 // Otherwise, start a new concat expression
2393 return new StringConcat (ec, loc, left, right).Resolve (ec);
2397 // Transform a + ( - b) into a - b
2399 if (right is Unary){
2400 Unary right_unary = (Unary) right;
2402 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2403 oper = Operator.Subtraction;
2404 right = right_unary.Expr;
2410 if (oper == Operator.Equality || oper == Operator.Inequality){
2411 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2412 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2413 Error_OperatorCannotBeApplied ();
2417 type = TypeManager.bool_type;
2421 if (l.IsPointer || r.IsPointer) {
2422 if (l.IsPointer && r.IsPointer) {
2423 type = TypeManager.bool_type;
2427 if (l.IsPointer && r == TypeManager.null_type) {
2428 right = new EmptyCast (NullPointer.Null, l);
2429 type = TypeManager.bool_type;
2433 if (r.IsPointer && l == TypeManager.null_type) {
2434 left = new EmptyCast (NullPointer.Null, r);
2435 type = TypeManager.bool_type;
2441 // operator != (object a, object b)
2442 // operator == (object a, object b)
2444 // For this to be used, both arguments have to be reference-types.
2445 // Read the rationale on the spec (14.9.6)
2447 // Also, if at compile time we know that the classes do not inherit
2448 // one from the other, then we catch the error there.
2450 if (!(l.IsValueType || r.IsValueType)){
2451 type = TypeManager.bool_type;
2456 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2460 // Also, a standard conversion must exist from either one
2462 if (!(Convert.ImplicitStandardConversionExists (ec, left, r) ||
2463 Convert.ImplicitStandardConversionExists (ec, right, l))){
2464 Error_OperatorCannotBeApplied ();
2468 // We are going to have to convert to an object to compare
2470 if (l != TypeManager.object_type)
2471 left = new EmptyCast (left, TypeManager.object_type);
2472 if (r != TypeManager.object_type)
2473 right = new EmptyCast (right, TypeManager.object_type);
2476 // FIXME: CSC here catches errors cs254 and cs252
2482 // One of them is a valuetype, but the other one is not.
2484 if (!l.IsValueType || !r.IsValueType) {
2485 Error_OperatorCannotBeApplied ();
2490 // Only perform numeric promotions on:
2491 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2493 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2494 if (TypeManager.IsDelegateType (l)){
2495 if (((right.eclass == ExprClass.MethodGroup) ||
2496 (r == TypeManager.anonymous_method_type))){
2497 if ((RootContext.Version != LanguageVersion.ISO_1)){
2498 Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2506 if (TypeManager.IsDelegateType (r)){
2508 ArrayList args = new ArrayList (2);
2510 args = new ArrayList (2);
2511 args.Add (new Argument (left, Argument.AType.Expression));
2512 args.Add (new Argument (right, Argument.AType.Expression));
2514 if (oper == Operator.Addition)
2515 method = TypeManager.delegate_combine_delegate_delegate;
2517 method = TypeManager.delegate_remove_delegate_delegate;
2519 if (!TypeManager.IsEqual (l, r)) {
2520 Error_OperatorCannotBeApplied ();
2524 return new BinaryDelegate (l, method, args);
2529 // Pointer arithmetic:
2531 // T* operator + (T* x, int y);
2532 // T* operator + (T* x, uint y);
2533 // T* operator + (T* x, long y);
2534 // T* operator + (T* x, ulong y);
2536 // T* operator + (int y, T* x);
2537 // T* operator + (uint y, T *x);
2538 // T* operator + (long y, T *x);
2539 // T* operator + (ulong y, T *x);
2541 // T* operator - (T* x, int y);
2542 // T* operator - (T* x, uint y);
2543 // T* operator - (T* x, long y);
2544 // T* operator - (T* x, ulong y);
2546 // long operator - (T* x, T *y)
2549 if (r.IsPointer && oper == Operator.Subtraction){
2551 return new PointerArithmetic (
2552 false, left, right, TypeManager.int64_type,
2555 Expression t = Make32or64 (ec, right);
2557 return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc).Resolve (ec);
2559 } else if (r.IsPointer && oper == Operator.Addition){
2560 Expression t = Make32or64 (ec, left);
2562 return new PointerArithmetic (true, right, t, r, loc).Resolve (ec);
2567 // Enumeration operators
2569 bool lie = TypeManager.IsEnumType (l);
2570 bool rie = TypeManager.IsEnumType (r);
2574 // U operator - (E e, E f)
2576 if (oper == Operator.Subtraction){
2578 type = TypeManager.EnumToUnderlying (l);
2581 Error_OperatorCannotBeApplied ();
2587 // operator + (E e, U x)
2588 // operator - (E e, U x)
2590 if (oper == Operator.Addition || oper == Operator.Subtraction){
2591 Type enum_type = lie ? l : r;
2592 Type other_type = lie ? r : l;
2593 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2595 if (underlying_type != other_type){
2596 temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
2606 Error_OperatorCannotBeApplied ();
2615 temp = Convert.ImplicitConversion (ec, right, l, loc);
2619 Error_OperatorCannotBeApplied ();
2623 temp = Convert.ImplicitConversion (ec, left, r, loc);
2628 Error_OperatorCannotBeApplied ();
2633 if (oper == Operator.Equality || oper == Operator.Inequality ||
2634 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2635 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2636 if (left.Type != right.Type){
2637 Error_OperatorCannotBeApplied ();
2640 type = TypeManager.bool_type;
2644 if (oper == Operator.BitwiseAnd ||
2645 oper == Operator.BitwiseOr ||
2646 oper == Operator.ExclusiveOr){
2647 if (left.Type != right.Type){
2648 Error_OperatorCannotBeApplied ();
2654 Error_OperatorCannotBeApplied ();
2658 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2659 return CheckShiftArguments (ec);
2661 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2662 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2663 type = TypeManager.bool_type;
2668 Error_OperatorCannotBeApplied ();
2672 Expression e = new ConditionalLogicalOperator (
2673 oper == Operator.LogicalAnd, left, right, l, loc);
2674 return e.Resolve (ec);
2678 // operator & (bool x, bool y)
2679 // operator | (bool x, bool y)
2680 // operator ^ (bool x, bool y)
2682 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2683 if (oper == Operator.BitwiseAnd ||
2684 oper == Operator.BitwiseOr ||
2685 oper == Operator.ExclusiveOr){
2692 // Pointer comparison
2694 if (l.IsPointer && r.IsPointer){
2695 if (oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2696 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2697 type = TypeManager.bool_type;
2703 // This will leave left or right set to null if there is an error
2705 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2706 DoNumericPromotions (ec, l, r, check_user_conv);
2707 if (left == null || right == null){
2708 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2713 // reload our cached types if required
2718 if (oper == Operator.BitwiseAnd ||
2719 oper == Operator.BitwiseOr ||
2720 oper == Operator.ExclusiveOr){
2722 if (((l == TypeManager.int32_type) ||
2723 (l == TypeManager.uint32_type) ||
2724 (l == TypeManager.short_type) ||
2725 (l == TypeManager.ushort_type) ||
2726 (l == TypeManager.int64_type) ||
2727 (l == TypeManager.uint64_type))){
2730 Error_OperatorCannotBeApplied ();
2734 Error_OperatorCannotBeApplied ();
2739 if (oper == Operator.Equality ||
2740 oper == Operator.Inequality ||
2741 oper == Operator.LessThanOrEqual ||
2742 oper == Operator.LessThan ||
2743 oper == Operator.GreaterThanOrEqual ||
2744 oper == Operator.GreaterThan){
2745 type = TypeManager.bool_type;
2751 public override Expression DoResolve (EmitContext ec)
2753 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2754 left = ((ParenthesizedExpression) left).Expr;
2755 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2759 if (left.eclass == ExprClass.Type) {
2760 Error (75, "To cast a negative value, you must enclose the value in parentheses");
2764 left = left.Resolve (ec);
2769 Constant lc = left as Constant;
2770 if (lc != null && lc.Type == TypeManager.bool_type &&
2771 ((oper == Operator.LogicalAnd && (bool)lc.GetValue () == false) ||
2772 (oper == Operator.LogicalOr && (bool)lc.GetValue () == true))) {
2774 // TODO: make a sense to resolve unreachable expression as we do for statement
2775 Report.Warning (429, 4, loc, "Unreachable expression code detected");
2779 right = right.Resolve (ec);
2783 eclass = ExprClass.Value;
2785 Constant rc = right as Constant;
2787 if (oper == Operator.BitwiseAnd) {
2788 if (rc != null && rc.IsZeroInteger) {
2789 return lc is EnumConstant ?
2790 new EnumConstant (rc, lc.Type):
2794 if (lc != null && lc.IsZeroInteger) {
2795 return rc is EnumConstant ?
2796 new EnumConstant (lc, rc.Type):
2801 if (rc != null && lc != null){
2802 Expression e = ConstantFold.BinaryFold (
2803 ec, oper, lc, rc, loc);
2808 if (TypeManager.IsNullableType (left.Type) || TypeManager.IsNullableType (right.Type))
2809 return new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
2811 return ResolveOperator (ec);
2815 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2816 /// context of a conditional bool expression. This function will return
2817 /// false if it is was possible to use EmitBranchable, or true if it was.
2819 /// The expression's code is generated, and we will generate a branch to `target'
2820 /// if the resulting expression value is equal to isTrue
2822 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2824 ILGenerator ig = ec.ig;
2827 // This is more complicated than it looks, but its just to avoid
2828 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2829 // but on top of that we want for == and != to use a special path
2830 // if we are comparing against null
2832 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
2833 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2836 // put the constant on the rhs, for simplicity
2838 if (left is Constant) {
2839 Expression swap = right;
2844 if (((Constant) right).IsZeroInteger) {
2847 ig.Emit (OpCodes.Brtrue, target);
2849 ig.Emit (OpCodes.Brfalse, target);
2852 } else if (right is BoolConstant){
2854 if (my_on_true != ((BoolConstant) right).Value)
2855 ig.Emit (OpCodes.Brtrue, target);
2857 ig.Emit (OpCodes.Brfalse, target);
2862 } else if (oper == Operator.LogicalAnd) {
2865 Label tests_end = ig.DefineLabel ();
2867 left.EmitBranchable (ec, tests_end, false);
2868 right.EmitBranchable (ec, target, true);
2869 ig.MarkLabel (tests_end);
2871 left.EmitBranchable (ec, target, false);
2872 right.EmitBranchable (ec, target, false);
2877 } else if (oper == Operator.LogicalOr){
2879 left.EmitBranchable (ec, target, true);
2880 right.EmitBranchable (ec, target, true);
2883 Label tests_end = ig.DefineLabel ();
2884 left.EmitBranchable (ec, tests_end, true);
2885 right.EmitBranchable (ec, target, false);
2886 ig.MarkLabel (tests_end);
2891 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2892 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2893 oper == Operator.Equality || oper == Operator.Inequality)) {
2894 base.EmitBranchable (ec, target, onTrue);
2902 bool isUnsigned = is_unsigned (t) || t == TypeManager.double_type || t == TypeManager.float_type;
2905 case Operator.Equality:
2907 ig.Emit (OpCodes.Beq, target);
2909 ig.Emit (OpCodes.Bne_Un, target);
2912 case Operator.Inequality:
2914 ig.Emit (OpCodes.Bne_Un, target);
2916 ig.Emit (OpCodes.Beq, target);
2919 case Operator.LessThan:
2922 ig.Emit (OpCodes.Blt_Un, target);
2924 ig.Emit (OpCodes.Blt, target);
2927 ig.Emit (OpCodes.Bge_Un, target);
2929 ig.Emit (OpCodes.Bge, target);
2932 case Operator.GreaterThan:
2935 ig.Emit (OpCodes.Bgt_Un, target);
2937 ig.Emit (OpCodes.Bgt, target);
2940 ig.Emit (OpCodes.Ble_Un, target);
2942 ig.Emit (OpCodes.Ble, target);
2945 case Operator.LessThanOrEqual:
2948 ig.Emit (OpCodes.Ble_Un, target);
2950 ig.Emit (OpCodes.Ble, target);
2953 ig.Emit (OpCodes.Bgt_Un, target);
2955 ig.Emit (OpCodes.Bgt, target);
2959 case Operator.GreaterThanOrEqual:
2962 ig.Emit (OpCodes.Bge_Un, target);
2964 ig.Emit (OpCodes.Bge, target);
2967 ig.Emit (OpCodes.Blt_Un, target);
2969 ig.Emit (OpCodes.Blt, target);
2972 Console.WriteLine (oper);
2973 throw new Exception ("what is THAT");
2977 public override void Emit (EmitContext ec)
2979 ILGenerator ig = ec.ig;
2984 // Handle short-circuit operators differently
2987 if (oper == Operator.LogicalAnd) {
2988 Label load_zero = ig.DefineLabel ();
2989 Label end = ig.DefineLabel ();
2991 left.EmitBranchable (ec, load_zero, false);
2993 ig.Emit (OpCodes.Br, end);
2995 ig.MarkLabel (load_zero);
2996 ig.Emit (OpCodes.Ldc_I4_0);
2999 } else if (oper == Operator.LogicalOr) {
3000 Label load_one = ig.DefineLabel ();
3001 Label end = ig.DefineLabel ();
3003 left.EmitBranchable (ec, load_one, true);
3005 ig.Emit (OpCodes.Br, end);
3007 ig.MarkLabel (load_one);
3008 ig.Emit (OpCodes.Ldc_I4_1);
3016 bool isUnsigned = is_unsigned (left.Type);
3019 case Operator.Multiply:
3021 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3022 opcode = OpCodes.Mul_Ovf;
3023 else if (isUnsigned)
3024 opcode = OpCodes.Mul_Ovf_Un;
3026 opcode = OpCodes.Mul;
3028 opcode = OpCodes.Mul;
3032 case Operator.Division:
3034 opcode = OpCodes.Div_Un;
3036 opcode = OpCodes.Div;
3039 case Operator.Modulus:
3041 opcode = OpCodes.Rem_Un;
3043 opcode = OpCodes.Rem;
3046 case Operator.Addition:
3048 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3049 opcode = OpCodes.Add_Ovf;
3050 else if (isUnsigned)
3051 opcode = OpCodes.Add_Ovf_Un;
3053 opcode = OpCodes.Add;
3055 opcode = OpCodes.Add;
3058 case Operator.Subtraction:
3060 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3061 opcode = OpCodes.Sub_Ovf;
3062 else if (isUnsigned)
3063 opcode = OpCodes.Sub_Ovf_Un;
3065 opcode = OpCodes.Sub;
3067 opcode = OpCodes.Sub;
3070 case Operator.RightShift:
3072 opcode = OpCodes.Shr_Un;
3074 opcode = OpCodes.Shr;
3077 case Operator.LeftShift:
3078 opcode = OpCodes.Shl;
3081 case Operator.Equality:
3082 opcode = OpCodes.Ceq;
3085 case Operator.Inequality:
3086 ig.Emit (OpCodes.Ceq);
3087 ig.Emit (OpCodes.Ldc_I4_0);
3089 opcode = OpCodes.Ceq;
3092 case Operator.LessThan:
3094 opcode = OpCodes.Clt_Un;
3096 opcode = OpCodes.Clt;
3099 case Operator.GreaterThan:
3101 opcode = OpCodes.Cgt_Un;
3103 opcode = OpCodes.Cgt;
3106 case Operator.LessThanOrEqual:
3107 Type lt = left.Type;
3109 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
3110 ig.Emit (OpCodes.Cgt_Un);
3112 ig.Emit (OpCodes.Cgt);
3113 ig.Emit (OpCodes.Ldc_I4_0);
3115 opcode = OpCodes.Ceq;
3118 case Operator.GreaterThanOrEqual:
3119 Type le = left.Type;
3121 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3122 ig.Emit (OpCodes.Clt_Un);
3124 ig.Emit (OpCodes.Clt);
3126 ig.Emit (OpCodes.Ldc_I4_0);
3128 opcode = OpCodes.Ceq;
3131 case Operator.BitwiseOr:
3132 opcode = OpCodes.Or;
3135 case Operator.BitwiseAnd:
3136 opcode = OpCodes.And;
3139 case Operator.ExclusiveOr:
3140 opcode = OpCodes.Xor;
3144 throw new Exception ("This should not happen: Operator = "
3145 + oper.ToString ());
3153 // Object created by Binary when the binary operator uses an method instead of being
3154 // a binary operation that maps to a CIL binary operation.
3156 public class BinaryMethod : Expression {
3157 public MethodBase method;
3158 public ArrayList Arguments;
3160 public BinaryMethod (Type t, MethodBase m, ArrayList args)
3165 eclass = ExprClass.Value;
3168 public override Expression DoResolve (EmitContext ec)
3173 public override void Emit (EmitContext ec)
3175 ILGenerator ig = ec.ig;
3177 if (Arguments != null)
3178 Invocation.EmitArguments (ec, method, Arguments, false, null);
3180 if (method is MethodInfo)
3181 ig.Emit (OpCodes.Call, (MethodInfo) method);
3183 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3188 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3189 // b, c, d... may be strings or objects.
3191 public class StringConcat : Expression {
3193 bool invalid = false;
3194 bool emit_conv_done = false;
3196 // Are we also concating objects?
3198 bool is_strings_only = true;
3200 public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
3203 type = TypeManager.string_type;
3204 eclass = ExprClass.Value;
3206 operands = new ArrayList (2);
3211 public override Expression DoResolve (EmitContext ec)
3219 public void Append (EmitContext ec, Expression operand)
3224 if (operand is StringConstant && operands.Count != 0) {
3225 StringConstant last_operand = operands [operands.Count - 1] as StringConstant;
3226 if (last_operand != null) {
3227 operands [operands.Count - 1] = new StringConstant (last_operand.Value + ((StringConstant) operand).Value);
3233 // Conversion to object
3235 if (operand.Type != TypeManager.string_type) {
3236 Expression no = Convert.ImplicitConversion (ec, operand, TypeManager.object_type, loc);
3239 Binary.Error_OperatorCannotBeApplied (loc, "+", TypeManager.string_type, operand.Type);
3245 operands.Add (operand);
3248 public override void Emit (EmitContext ec)
3250 MethodInfo concat_method = null;
3253 // Do conversion to arguments; check for strings only
3256 // This can get called multiple times, so we have to deal with that.
3257 if (!emit_conv_done) {
3258 emit_conv_done = true;
3259 for (int i = 0; i < operands.Count; i ++) {
3260 Expression e = (Expression) operands [i];
3261 is_strings_only &= e.Type == TypeManager.string_type;
3264 for (int i = 0; i < operands.Count; i ++) {
3265 Expression e = (Expression) operands [i];
3267 if (! is_strings_only && e.Type == TypeManager.string_type) {
3268 // need to make sure this is an object, because the EmitParams
3269 // method might look at the type of this expression, see it is a
3270 // string and emit a string [] when we want an object [];
3272 e = new EmptyCast (e, TypeManager.object_type);
3274 operands [i] = new Argument (e, Argument.AType.Expression);
3279 // Find the right method
3281 switch (operands.Count) {
3284 // This should not be possible, because simple constant folding
3285 // is taken care of in the Binary code.
3287 throw new Exception ("how did you get here?");
3290 concat_method = is_strings_only ?
3291 TypeManager.string_concat_string_string :
3292 TypeManager.string_concat_object_object ;
3295 concat_method = is_strings_only ?
3296 TypeManager.string_concat_string_string_string :
3297 TypeManager.string_concat_object_object_object ;
3301 // There is not a 4 param overlaod for object (the one that there is
3302 // is actually a varargs methods, and is only in corlib because it was
3303 // introduced there before.).
3305 if (!is_strings_only)
3308 concat_method = TypeManager.string_concat_string_string_string_string;
3311 concat_method = is_strings_only ?
3312 TypeManager.string_concat_string_dot_dot_dot :
3313 TypeManager.string_concat_object_dot_dot_dot ;
3317 Invocation.EmitArguments (ec, concat_method, operands, false, null);
3318 ec.ig.Emit (OpCodes.Call, concat_method);
3323 // Object created with +/= on delegates
3325 public class BinaryDelegate : Expression {
3329 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3334 eclass = ExprClass.Value;
3337 public override Expression DoResolve (EmitContext ec)
3342 public override void Emit (EmitContext ec)
3344 ILGenerator ig = ec.ig;
3346 Invocation.EmitArguments (ec, method, args, false, null);
3348 ig.Emit (OpCodes.Call, (MethodInfo) method);
3349 ig.Emit (OpCodes.Castclass, type);
3352 public Expression Right {
3354 Argument arg = (Argument) args [1];
3359 public bool IsAddition {
3361 return method == TypeManager.delegate_combine_delegate_delegate;
3367 // User-defined conditional logical operator
3368 public class ConditionalLogicalOperator : Expression {
3369 Expression left, right;
3372 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3375 eclass = ExprClass.Value;
3379 this.is_and = is_and;
3382 protected void Error19 ()
3384 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3387 protected void Error218 ()
3389 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3390 "declarations of operator true and operator false");
3393 Expression op_true, op_false, op;
3394 LocalTemporary left_temp;
3396 public override Expression DoResolve (EmitContext ec)
3399 Expression operator_group;
3401 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3402 if (operator_group == null) {
3407 left_temp = new LocalTemporary (ec, type);
3409 ArrayList arguments = new ArrayList ();
3410 arguments.Add (new Argument (left_temp, Argument.AType.Expression));
3411 arguments.Add (new Argument (right, Argument.AType.Expression));
3412 method = Invocation.OverloadResolve (
3413 ec, (MethodGroupExpr) operator_group, arguments, false, loc)
3415 if (method == null) {
3420 if (method.ReturnType != type) {
3421 Report.Error (217, loc, "In order to be applicable as a short circuit operator a user-defined logical operator `{0}' " +
3422 "must have the same return type as the type of its 2 parameters", TypeManager.CSharpSignature (method));
3426 op = new StaticCallExpr (method, arguments, loc);
3428 op_true = GetOperatorTrue (ec, left_temp, loc);
3429 op_false = GetOperatorFalse (ec, left_temp, loc);
3430 if ((op_true == null) || (op_false == null)) {
3438 public override void Emit (EmitContext ec)
3440 ILGenerator ig = ec.ig;
3441 Label false_target = ig.DefineLabel ();
3442 Label end_target = ig.DefineLabel ();
3445 left_temp.Store (ec);
3447 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
3448 left_temp.Emit (ec);
3449 ig.Emit (OpCodes.Br, end_target);
3450 ig.MarkLabel (false_target);
3452 ig.MarkLabel (end_target);
3456 public class PointerArithmetic : Expression {
3457 Expression left, right;
3461 // We assume that `l' is always a pointer
3463 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3469 is_add = is_addition;
3472 public override Expression DoResolve (EmitContext ec)
3474 eclass = ExprClass.Variable;
3476 if (left.Type == TypeManager.void_ptr_type) {
3477 Error (242, "The operation in question is undefined on void pointers");
3484 public override void Emit (EmitContext ec)
3486 Type op_type = left.Type;
3487 ILGenerator ig = ec.ig;
3489 // It must be either array or fixed buffer
3490 Type element = TypeManager.HasElementType (op_type) ?
3491 element = TypeManager.GetElementType (op_type) :
3492 element = AttributeTester.GetFixedBuffer (((FieldExpr)left).FieldInfo).ElementType;
3494 int size = GetTypeSize (element);
3495 Type rtype = right.Type;
3497 if (rtype.IsPointer){
3499 // handle (pointer - pointer)
3503 ig.Emit (OpCodes.Sub);
3507 ig.Emit (OpCodes.Sizeof, element);
3509 IntLiteral.EmitInt (ig, size);
3510 ig.Emit (OpCodes.Div);
3512 ig.Emit (OpCodes.Conv_I8);
3515 // handle + and - on (pointer op int)
3518 ig.Emit (OpCodes.Conv_I);
3520 Constant right_const = right as Constant;
3521 if (right_const != null && size != 0) {
3522 Expression ex = ConstantFold.BinaryFold (ec, Binary.Operator.Multiply, new IntConstant (size), right_const, loc);
3530 ig.Emit (OpCodes.Sizeof, element);
3532 IntLiteral.EmitInt (ig, size);
3533 if (rtype == TypeManager.int64_type)
3534 ig.Emit (OpCodes.Conv_I8);
3535 else if (rtype == TypeManager.uint64_type)
3536 ig.Emit (OpCodes.Conv_U8);
3537 ig.Emit (OpCodes.Mul);
3541 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
3542 ig.Emit (OpCodes.Conv_I);
3545 ig.Emit (OpCodes.Add);
3547 ig.Emit (OpCodes.Sub);
3553 /// Implements the ternary conditional operator (?:)
3555 public class Conditional : Expression {
3556 Expression expr, trueExpr, falseExpr;
3558 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3561 this.trueExpr = trueExpr;
3562 this.falseExpr = falseExpr;
3566 public Expression Expr {
3572 public Expression TrueExpr {
3578 public Expression FalseExpr {
3584 public override Expression DoResolve (EmitContext ec)
3586 expr = expr.Resolve (ec);
3591 if (TypeManager.IsNullableType (expr.Type))
3592 return new Nullable.LiftedConditional (expr, trueExpr, falseExpr, loc).Resolve (ec);
3594 if (expr.Type != TypeManager.bool_type){
3595 expr = Expression.ResolveBoolean (
3602 trueExpr = trueExpr.Resolve (ec);
3603 falseExpr = falseExpr.Resolve (ec);
3605 if (trueExpr == null || falseExpr == null)
3608 eclass = ExprClass.Value;
3609 if (trueExpr.Type == falseExpr.Type)
3610 type = trueExpr.Type;
3613 Type true_type = trueExpr.Type;
3614 Type false_type = falseExpr.Type;
3617 // First, if an implicit conversion exists from trueExpr
3618 // to falseExpr, then the result type is of type falseExpr.Type
3620 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3623 // Check if both can convert implicitl to each other's type
3625 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3627 "Can not compute type of conditional expression " +
3628 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3629 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3630 "' convert implicitly to each other");
3635 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3639 Report.Error (173, loc, "Type of conditional expression cannot be determined because there is no implicit conversion between `{0}' and `{1}'",
3640 trueExpr.GetSignatureForError (), falseExpr.GetSignatureForError ());
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}' as a ref or out argument because it is a `{1}'",
3734 Name, local_info.GetReadOnlyContext ());
3736 Report.Error (1656, loc, "Cannot assign to `{0}' because it is a `{1}'",
3737 Name, local_info.GetReadOnlyContext ());
3741 if (variable_info != null)
3742 variable_info.SetAssigned (ec);
3745 Expression e = Block.GetConstantExpression (Name);
3747 local_info.Used = true;
3748 eclass = ExprClass.Value;
3749 return e.Resolve (ec);
3752 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3755 if (lvalue_right_side == null)
3756 local_info.Used = true;
3758 if (ec.CurrentAnonymousMethod != null){
3760 // If we are referencing a variable from the external block
3761 // flag it for capturing
3763 if ((local_info.Block.Toplevel != ec.CurrentBlock.Toplevel) ||
3764 ec.CurrentAnonymousMethod.IsIterator)
3766 if (local_info.AddressTaken){
3767 AnonymousMethod.Error_AddressOfCapturedVar (local_info.Name, loc);
3770 ec.CaptureVariable (local_info);
3777 public override Expression DoResolve (EmitContext ec)
3779 return DoResolveBase (ec, null);
3782 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3784 Expression ret = DoResolveBase (ec, right_side);
3786 CheckObsoleteAttribute (ret.Type);
3791 public bool VerifyFixed ()
3793 // A local Variable is always fixed.
3797 public override int GetHashCode()
3799 return Name.GetHashCode ();
3802 public override bool Equals (object obj)
3804 LocalVariableReference lvr = obj as LocalVariableReference;
3808 return Name == lvr.Name && Block == lvr.Block;
3811 public override void Emit (EmitContext ec)
3813 ILGenerator ig = ec.ig;
3815 if (local_info.FieldBuilder == null){
3817 // A local variable on the local CLR stack
3819 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3822 // A local variable captured by anonymous methods.
3825 ec.EmitCapturedVariableInstance (local_info);
3827 ig.Emit (OpCodes.Ldfld, local_info.FieldBuilder);
3831 public void Emit (EmitContext ec, bool leave_copy)
3835 ec.ig.Emit (OpCodes.Dup);
3836 if (local_info.FieldBuilder != null){
3837 temp = new LocalTemporary (ec, Type);
3843 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3845 ILGenerator ig = ec.ig;
3846 prepared = prepare_for_load;
3848 if (local_info.FieldBuilder == null){
3850 // A local variable on the local CLR stack
3852 if (local_info.LocalBuilder == null)
3853 throw new Exception ("This should not happen: both Field and Local are null");
3857 ec.ig.Emit (OpCodes.Dup);
3858 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3861 // A local variable captured by anonymous methods or itereators.
3863 ec.EmitCapturedVariableInstance (local_info);
3865 if (prepare_for_load)
3866 ig.Emit (OpCodes.Dup);
3869 ig.Emit (OpCodes.Dup);
3870 temp = new LocalTemporary (ec, Type);
3873 ig.Emit (OpCodes.Stfld, local_info.FieldBuilder);
3879 public void AddressOf (EmitContext ec, AddressOp mode)
3881 ILGenerator ig = ec.ig;
3883 if (local_info.FieldBuilder == null){
3885 // A local variable on the local CLR stack
3887 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3890 // A local variable captured by anonymous methods or iterators
3892 ec.EmitCapturedVariableInstance (local_info);
3893 ig.Emit (OpCodes.Ldflda, local_info.FieldBuilder);
3897 public override string ToString ()
3899 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3904 /// This represents a reference to a parameter in the intermediate
3907 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3913 public Parameter.Modifier mod;
3914 public bool is_ref, is_out, prepared;
3928 LocalTemporary temp;
3930 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3937 eclass = ExprClass.Variable;
3940 public ParameterReference (InternalParameters pars, Block block, int idx, Location loc)
3941 : this (pars.Parameters, block, idx, pars.ParameterName (idx), loc)
3944 public VariableInfo VariableInfo {
3948 public bool VerifyFixed ()
3950 // A parameter is fixed if it's a value parameter (i.e., no modifier like out, ref, param).
3951 return mod == Parameter.Modifier.NONE;
3954 public bool IsAssigned (EmitContext ec, Location loc)
3956 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsAssigned (vi))
3959 Report.Error (269, loc,
3960 "Use of unassigned out parameter `{0}'", name);
3964 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3966 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3969 Report.Error (170, loc,
3970 "Use of possibly unassigned field `" + field_name + "'");
3974 public void SetAssigned (EmitContext ec)
3976 if (is_out && ec.DoFlowAnalysis)
3977 ec.CurrentBranching.SetAssigned (vi);
3980 public void SetFieldAssigned (EmitContext ec, string field_name)
3982 if (is_out && ec.DoFlowAnalysis)
3983 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3986 protected void DoResolveBase (EmitContext ec)
3988 type = pars.GetParameterInfo (ec, idx, out mod);
3989 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3990 is_out = (mod & Parameter.Modifier.OUT) != 0;
3991 eclass = ExprClass.Variable;
3994 vi = block.ParameterMap [idx];
3996 if (ec.CurrentAnonymousMethod != null){
3998 Report.Error (1628, Location, "Cannot use ref or out parameter `{0}' inside an anonymous method block",
4004 // If we are referencing the parameter from the external block
4005 // flag it for capturing
4007 //Console.WriteLine ("Is parameter `{0}' local? {1}", name, block.IsLocalParameter (name));
4008 if (!block.Toplevel.IsLocalParameter (name)){
4009 ec.CaptureParameter (name, type, idx);
4014 public override int GetHashCode()
4016 return name.GetHashCode ();
4019 public override bool Equals (object obj)
4021 ParameterReference pr = obj as ParameterReference;
4025 return name == pr.name && block == pr.block;
4029 // Notice that for ref/out parameters, the type exposed is not the
4030 // same type exposed externally.
4033 // externally we expose "int&"
4034 // here we expose "int".
4036 // We record this in "is_ref". This means that the type system can treat
4037 // the type as it is expected, but when we generate the code, we generate
4038 // the alternate kind of code.
4040 public override Expression DoResolve (EmitContext ec)
4044 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
4050 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4059 static public void EmitLdArg (ILGenerator ig, int x)
4063 case 0: ig.Emit (OpCodes.Ldarg_0); break;
4064 case 1: ig.Emit (OpCodes.Ldarg_1); break;
4065 case 2: ig.Emit (OpCodes.Ldarg_2); break;
4066 case 3: ig.Emit (OpCodes.Ldarg_3); break;
4067 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
4070 ig.Emit (OpCodes.Ldarg, x);
4074 // This method is used by parameters that are references, that are
4075 // being passed as references: we only want to pass the pointer (that
4076 // is already stored in the parameter, not the address of the pointer,
4077 // and not the value of the variable).
4079 public void EmitLoad (EmitContext ec)
4081 ILGenerator ig = ec.ig;
4084 if (!ec.MethodIsStatic)
4087 EmitLdArg (ig, arg_idx);
4090 // FIXME: Review for anonymous methods
4094 public override void Emit (EmitContext ec)
4099 public void Emit (EmitContext ec, bool leave_copy)
4101 ILGenerator ig = ec.ig;
4104 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4106 throw new InternalErrorException ();
4108 ec.EmitParameter (name);
4112 if (!ec.MethodIsStatic)
4115 EmitLdArg (ig, arg_idx);
4119 ec.ig.Emit (OpCodes.Dup);
4122 // If we are a reference, we loaded on the stack a pointer
4123 // Now lets load the real value
4125 LoadFromPtr (ig, type);
4129 ec.ig.Emit (OpCodes.Dup);
4132 temp = new LocalTemporary (ec, type);
4138 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
4140 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4141 ec.EmitAssignParameter (name, source, leave_copy, prepare_for_load);
4145 ILGenerator ig = ec.ig;
4148 prepared = prepare_for_load;
4150 if (!ec.MethodIsStatic)
4153 if (is_ref && !prepared)
4154 EmitLdArg (ig, arg_idx);
4159 ec.ig.Emit (OpCodes.Dup);
4163 temp = new LocalTemporary (ec, type);
4167 StoreFromPtr (ig, type);
4173 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
4175 ig.Emit (OpCodes.Starg, arg_idx);
4179 public void AddressOf (EmitContext ec, AddressOp mode)
4181 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4182 ec.EmitAddressOfParameter (name);
4188 if (!ec.MethodIsStatic)
4193 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
4195 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
4198 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
4200 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
4207 /// Used for arguments to New(), Invocation()
4209 public class Argument {
4210 public enum AType : byte {
4217 public readonly AType ArgType;
4218 public Expression Expr;
4220 public Argument (Expression expr, AType type)
4223 this.ArgType = type;
4226 public Argument (Expression expr)
4229 this.ArgType = AType.Expression;
4234 if (ArgType == AType.Ref || ArgType == AType.Out)
4235 return TypeManager.GetReferenceType (Expr.Type);
4241 public Parameter.Modifier Modifier
4246 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
4249 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
4252 return Parameter.Modifier.NONE;
4257 public static string FullDesc (Argument a)
4259 if (a.ArgType == AType.ArgList)
4262 return (a.ArgType == AType.Ref ? "ref " :
4263 (a.ArgType == AType.Out ? "out " : "")) +
4264 TypeManager.CSharpName (a.Expr.Type);
4267 public bool ResolveMethodGroup (EmitContext ec, Location loc)
4269 SimpleName sn = Expr as SimpleName;
4271 Expr = sn.GetMethodGroup ();
4273 // FIXME: csc doesn't report any error if you try to use `ref' or
4274 // `out' in a delegate creation expression.
4275 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4282 void Error_LValueRequired (Location loc)
4284 Report.Error (1510, loc, "A ref or out argument must be an assignable variable");
4287 public bool Resolve (EmitContext ec, Location loc)
4289 bool old_do_flow_analysis = ec.DoFlowAnalysis;
4290 ec.DoFlowAnalysis = true;
4292 if (ArgType == AType.Ref) {
4293 ec.InRefOutArgumentResolving = true;
4294 Expr = Expr.Resolve (ec);
4295 ec.InRefOutArgumentResolving = false;
4297 ec.DoFlowAnalysis = old_do_flow_analysis;
4301 Expr = Expr.DoResolveLValue (ec, Expr);
4303 Error_LValueRequired (loc);
4304 } else if (ArgType == AType.Out) {
4305 ec.InRefOutArgumentResolving = true;
4306 Expr = Expr.DoResolveLValue (ec, EmptyExpression.Null);
4307 ec.InRefOutArgumentResolving = false;
4310 Error_LValueRequired (loc);
4313 Expr = Expr.Resolve (ec);
4315 ec.DoFlowAnalysis = old_do_flow_analysis;
4320 if (ArgType == AType.Expression)
4324 // Catch errors where fields of a MarshalByRefObject are passed as ref or out
4325 // This is only allowed for `this'
4327 FieldExpr fe = Expr as FieldExpr;
4328 if (fe != null && !fe.IsStatic){
4329 Expression instance = fe.InstanceExpression;
4331 if (instance.GetType () != typeof (This)){
4332 if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
4333 Report.SymbolRelatedToPreviousError (fe.InstanceExpression.Type);
4334 Report.Warning (197, 1, loc,
4335 "Passing `{0}' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class",
4336 fe.GetSignatureForError ());
4343 if (Expr.eclass != ExprClass.Variable){
4345 // We just probe to match the CSC output
4347 if (Expr.eclass == ExprClass.PropertyAccess ||
4348 Expr.eclass == ExprClass.IndexerAccess){
4349 Report.Error (206, loc, "A property or indexer `{0}' may not be passed as an out or ref parameter",
4350 Expr.GetSignatureForError ());
4352 Error_LValueRequired (loc);
4360 public void Emit (EmitContext ec)
4363 // Ref and Out parameters need to have their addresses taken.
4365 // ParameterReferences might already be references, so we want
4366 // to pass just the value
4368 if (ArgType == AType.Ref || ArgType == AType.Out){
4369 AddressOp mode = AddressOp.Store;
4371 if (ArgType == AType.Ref)
4372 mode |= AddressOp.Load;
4374 if (Expr is ParameterReference){
4375 ParameterReference pr = (ParameterReference) Expr;
4381 pr.AddressOf (ec, mode);
4384 if (Expr is IMemoryLocation)
4385 ((IMemoryLocation) Expr).AddressOf (ec, mode);
4387 Error_LValueRequired (Expr.Location);
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)
4640 if (mb is MethodInfo) {
4641 sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
4645 sb = new StringBuilder ();
4647 sb.Append (TypeManager.CSharpSignature (mb));
4648 return sb.ToString ();
4651 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4653 MemberInfo [] miset;
4654 MethodGroupExpr union;
4659 return (MethodGroupExpr) mg2;
4662 return (MethodGroupExpr) mg1;
4665 MethodGroupExpr left_set = null, right_set = null;
4666 int length1 = 0, length2 = 0;
4668 left_set = (MethodGroupExpr) mg1;
4669 length1 = left_set.Methods.Length;
4671 right_set = (MethodGroupExpr) mg2;
4672 length2 = right_set.Methods.Length;
4674 ArrayList common = new ArrayList ();
4676 foreach (MethodBase r in right_set.Methods){
4677 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
4681 miset = new MemberInfo [length1 + length2 - common.Count];
4682 left_set.Methods.CopyTo (miset, 0);
4686 foreach (MethodBase r in right_set.Methods) {
4687 if (!common.Contains (r))
4691 union = new MethodGroupExpr (miset, loc);
4696 public static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4697 ArrayList arguments, int arg_count,
4698 ref MethodBase candidate)
4700 return IsParamsMethodApplicable (
4701 ec, me, arguments, arg_count, false, ref candidate) ||
4702 IsParamsMethodApplicable (
4703 ec, me, arguments, arg_count, true, ref candidate);
4708 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4709 ArrayList arguments, int arg_count,
4710 bool do_varargs, ref MethodBase candidate)
4712 if (!me.HasTypeArguments &&
4713 !TypeManager.InferParamsTypeArguments (ec, arguments, ref candidate))
4716 return IsParamsMethodApplicable (
4717 ec, arguments, arg_count, candidate, do_varargs);
4721 /// Determines if the candidate method, if a params method, is applicable
4722 /// in its expanded form to the given set of arguments
4724 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
4725 int arg_count, MethodBase candidate,
4728 ParameterData pd = TypeManager.GetParameterData (candidate);
4730 int pd_count = pd.Count;
4735 int count = pd_count - 1;
4737 if (pd.ParameterModifier (count) != Parameter.Modifier.ARGLIST)
4739 if (pd_count != arg_count)
4742 if (pd.ParameterModifier (count) != Parameter.Modifier.PARAMS)
4746 if (count > arg_count)
4749 if (pd_count == 1 && arg_count == 0)
4753 // If we have come this far, the case which
4754 // remains is when the number of parameters is
4755 // less than or equal to the argument count.
4757 for (int i = 0; i < count; ++i) {
4759 Argument a = (Argument) arguments [i];
4761 Parameter.Modifier a_mod = a.Modifier &
4762 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4763 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4764 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4766 if (a_mod == p_mod) {
4768 if (a_mod == Parameter.Modifier.NONE)
4769 if (!Convert.ImplicitConversionExists (ec,
4771 pd.ParameterType (i)))
4774 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4775 Type pt = pd.ParameterType (i);
4778 pt = TypeManager.GetReferenceType (pt);
4789 Argument a = (Argument) arguments [count];
4790 if (!(a.Expr is Arglist))
4796 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4798 for (int i = pd_count - 1; i < arg_count; i++) {
4799 Argument a = (Argument) arguments [i];
4801 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4808 public static bool IsApplicable (EmitContext ec, MethodGroupExpr me,
4809 ArrayList arguments, int arg_count,
4810 ref MethodBase candidate)
4812 if (!me.HasTypeArguments &&
4813 !TypeManager.InferTypeArguments (ec, arguments, ref candidate))
4816 return IsApplicable (ec, arguments, arg_count, candidate);
4820 /// Determines if the candidate method is applicable (section 14.4.2.1)
4821 /// to the given set of arguments
4823 static bool IsApplicable (EmitContext ec, ArrayList arguments, int arg_count,
4824 MethodBase candidate)
4826 ParameterData pd = TypeManager.GetParameterData (candidate);
4828 if (arg_count != pd.Count)
4831 for (int i = arg_count; i > 0; ) {
4834 Argument a = (Argument) arguments [i];
4836 Parameter.Modifier a_mod = a.Modifier &
4837 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4838 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4839 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4841 if (a_mod == p_mod ||
4842 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4843 if (a_mod == Parameter.Modifier.NONE) {
4844 if (!Convert.ImplicitConversionExists (ec,
4846 pd.ParameterType (i)))
4850 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4851 Type pt = pd.ParameterType (i);
4854 pt = TypeManager.GetReferenceType (pt);
4866 static private bool IsAncestralType (Type first_type, Type second_type)
4868 return first_type != second_type &&
4869 (second_type.IsSubclassOf (first_type) ||
4870 TypeManager.ImplementsInterface (second_type, first_type));
4874 /// Find the Applicable Function Members (7.4.2.1)
4876 /// me: Method Group expression with the members to select.
4877 /// it might contain constructors or methods (or anything
4878 /// that maps to a method).
4880 /// Arguments: ArrayList containing resolved Argument objects.
4882 /// loc: The location if we want an error to be reported, or a Null
4883 /// location for "probing" purposes.
4885 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4886 /// that is the best match of me on Arguments.
4889 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4890 ArrayList Arguments, bool may_fail,
4893 MethodBase method = null;
4894 bool method_params = false;
4895 Type applicable_type = null;
4897 ArrayList candidates = new ArrayList (2);
4898 ArrayList candidate_overrides = null;
4901 // Used to keep a map between the candidate
4902 // and whether it is being considered in its
4903 // normal or expanded form
4905 // false is normal form, true is expanded form
4907 Hashtable candidate_to_form = null;
4909 if (Arguments != null)
4910 arg_count = Arguments.Count;
4912 if ((me.Name == "Invoke") &&
4913 TypeManager.IsDelegateType (me.DeclaringType)) {
4914 Error_InvokeOnDelegate (loc);
4918 MethodBase[] methods = me.Methods;
4921 // First we construct the set of applicable methods
4923 bool is_sorted = true;
4924 for (int i = 0; i < methods.Length; i++){
4925 Type decl_type = methods [i].DeclaringType;
4928 // If we have already found an applicable method
4929 // we eliminate all base types (Section 14.5.5.1)
4931 if ((applicable_type != null) &&
4932 IsAncestralType (decl_type, applicable_type))
4936 // Methods marked 'override' don't take part in 'applicable_type'
4937 // computation, nor in the actual overload resolution.
4938 // However, they still need to be emitted instead of a base virtual method.
4939 // We avoid doing the 'applicable' test here, since it'll anyway be applied
4940 // to the base virtual function, and IsOverride is much faster than IsApplicable.
4942 if (!me.IsBase && TypeManager.IsOverride (methods [i])) {
4943 if (candidate_overrides == null)
4944 candidate_overrides = new ArrayList ();
4945 candidate_overrides.Add (methods [i]);
4950 // Check if candidate is applicable (section 14.4.2.1)
4951 // Is candidate applicable in normal form?
4953 bool is_applicable = IsApplicable (
4954 ec, me, Arguments, arg_count, ref methods [i]);
4956 if (!is_applicable &&
4957 (IsParamsMethodApplicable (
4958 ec, me, Arguments, arg_count, ref methods [i]))) {
4959 MethodBase candidate = methods [i];
4960 if (candidate_to_form == null)
4961 candidate_to_form = new PtrHashtable ();
4962 candidate_to_form [candidate] = candidate;
4963 // Candidate is applicable in expanded form
4964 is_applicable = true;
4970 candidates.Add (methods [i]);
4972 if (applicable_type == null)
4973 applicable_type = decl_type;
4974 else if (applicable_type != decl_type) {
4976 if (IsAncestralType (applicable_type, decl_type))
4977 applicable_type = decl_type;
4981 int candidate_top = candidates.Count;
4983 if (applicable_type == null) {
4985 // Okay so we have failed to find anything so we
4986 // return by providing info about the closest match
4988 for (int i = 0; i < methods.Length; ++i) {
4989 MethodBase c = (MethodBase) methods [i];
4990 ParameterData pd = TypeManager.GetParameterData (c);
4992 if (pd.Count != arg_count)
4995 if (!TypeManager.InferTypeArguments (ec, Arguments, ref c))
4998 VerifyArgumentsCompat (ec, Arguments, arg_count,
4999 c, false, null, may_fail, loc);
5005 string report_name = me.Name;
5006 if (report_name == ".ctor")
5007 report_name = me.DeclaringType.ToString ();
5009 for (int i = 0; i < methods.Length; ++i) {
5010 MethodBase c = methods [i];
5011 ParameterData pd = TypeManager.GetParameterData (c);
5013 if (pd.Count != arg_count)
5016 if (TypeManager.InferTypeArguments (ec, Arguments, ref c))
5020 411, loc, "The type arguments for " +
5021 "method `{0}' cannot be infered from " +
5022 "the usage. Try specifying the type " +
5023 "arguments explicitly.", report_name);
5027 Error_WrongNumArguments (
5028 loc, report_name, arg_count);
5037 // At this point, applicable_type is _one_ of the most derived types
5038 // in the set of types containing the methods in this MethodGroup.
5039 // Filter the candidates so that they only contain methods from the
5040 // most derived types.
5043 int finalized = 0; // Number of finalized candidates
5046 // Invariant: applicable_type is a most derived type
5048 // We'll try to complete Section 14.5.5.1 for 'applicable_type' by
5049 // eliminating all it's base types. At the same time, we'll also move
5050 // every unrelated type to the end of the array, and pick the next
5051 // 'applicable_type'.
5053 Type next_applicable_type = null;
5054 int j = finalized; // where to put the next finalized candidate
5055 int k = finalized; // where to put the next undiscarded candidate
5056 for (int i = finalized; i < candidate_top; ++i) {
5057 MethodBase candidate = (MethodBase) candidates [i];
5058 Type decl_type = candidate.DeclaringType;
5060 if (decl_type == applicable_type) {
5061 candidates [k++] = candidates [j];
5062 candidates [j++] = candidates [i];
5066 if (IsAncestralType (decl_type, applicable_type))
5069 if (next_applicable_type != null &&
5070 IsAncestralType (decl_type, next_applicable_type))
5073 candidates [k++] = candidates [i];
5075 if (next_applicable_type == null ||
5076 IsAncestralType (next_applicable_type, decl_type))
5077 next_applicable_type = decl_type;
5080 applicable_type = next_applicable_type;
5083 } while (applicable_type != null);
5087 // Now we actually find the best method
5090 method = (MethodBase) candidates [0];
5091 method_params = candidate_to_form != null && candidate_to_form.Contains (method);
5092 for (int ix = 1; ix < candidate_top; ix++){
5093 MethodBase candidate = (MethodBase) candidates [ix];
5095 if (candidate == method)
5098 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
5100 if (BetterFunction (ec, Arguments, arg_count,
5101 candidate, cand_params,
5102 method, method_params, loc)) {
5104 method_params = cand_params;
5109 // Now check that there are no ambiguities i.e the selected method
5110 // should be better than all the others
5112 MethodBase ambiguous = null;
5113 for (int ix = 0; ix < candidate_top; ix++){
5114 MethodBase candidate = (MethodBase) candidates [ix];
5116 if (candidate == method)
5119 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
5120 if (!BetterFunction (ec, Arguments, arg_count,
5121 method, method_params,
5122 candidate, cand_params,
5124 Report.SymbolRelatedToPreviousError (candidate);
5125 ambiguous = candidate;
5129 if (ambiguous != null) {
5130 Report.SymbolRelatedToPreviousError (method);
5131 Report.Error (121, loc, "The call is ambiguous between the following methods or properties: `{0}' and `{1}'",
5132 TypeManager.CSharpSignature (ambiguous), TypeManager.CSharpSignature (method));
5137 // If the method is a virtual function, pick an override closer to the LHS type.
5139 if (!me.IsBase && method.IsVirtual) {
5140 if (TypeManager.IsOverride (method))
5141 throw new InternalErrorException (
5142 "Should not happen. An 'override' method took part in overload resolution: " + method);
5144 if (candidate_overrides != null)
5145 foreach (MethodBase candidate in candidate_overrides) {
5146 if (IsOverride (candidate, method))
5152 // And now check if the arguments are all
5153 // compatible, perform conversions if
5154 // necessary etc. and return if everything is
5157 if (!VerifyArgumentsCompat (ec, Arguments, arg_count, method,
5158 method_params, null, may_fail, loc))
5161 if (method != null) {
5162 MethodBase the_method = method;
5163 if (the_method.Mono_IsInflatedMethod)
5164 the_method = the_method.GetGenericMethodDefinition ();
5165 IMethodData data = TypeManager.GetMethod (the_method);
5167 data.SetMemberIsUsed ();
5172 public static void Error_WrongNumArguments (Location loc, String name, int arg_count)
5174 if (name == "Finalize" && arg_count == 0) {
5175 Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
5178 Report.Error (1501, loc, "No overload for method `{0}' takes `{1}' arguments",
5183 static void Error_InvokeOnDelegate (Location loc)
5185 Report.Error (1533, loc,
5186 "Invoke cannot be called directly on a delegate");
5189 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
5190 Type delegate_type, Argument a, ParameterData expected_par)
5192 if (delegate_type == null)
5193 Report.Error (1502, loc, "The best overloaded method match for `{0}' has some invalid arguments",
5194 TypeManager.CSharpSignature (method));
5196 Report.Error (1594, loc, "Delegate `{0}' has some invalid arguments",
5197 TypeManager.CSharpName (delegate_type));
5199 string par_desc = expected_par.ParameterDesc (idx);
5201 if (a.Modifier != expected_par.ParameterModifier (idx)) {
5202 if ((expected_par.ParameterModifier (idx) & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) == 0)
5203 Report.Error (1615, loc, "Argument `{0}' should not be passed with the `{1}' keyword",
5204 idx + 1, Parameter.GetModifierSignature (a.Modifier));
5206 Report.Error (1620, loc, "Argument `{0}' must be passed with the `{1}' keyword",
5207 idx + 1, Parameter.GetModifierSignature (expected_par.ParameterModifier (idx)));
5211 Report.Error (1503, loc,
5212 String.Format ("Argument {0}: Cannot convert from `{1}' to `{2}'",
5213 idx + 1, Argument.FullDesc (a), par_desc));
5216 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
5217 int arg_count, MethodBase method,
5218 bool chose_params_expanded,
5219 Type delegate_type, bool may_fail,
5222 ParameterData pd = TypeManager.GetParameterData (method);
5223 int pd_count = pd.Count;
5225 for (int j = 0; j < arg_count; j++) {
5226 Argument a = (Argument) Arguments [j];
5227 Expression a_expr = a.Expr;
5228 Type parameter_type = pd.ParameterType (j);
5229 Parameter.Modifier pm = pd.ParameterModifier (j);
5231 if (pm == Parameter.Modifier.PARAMS){
5232 if ((pm & ~Parameter.Modifier.PARAMS) != a.Modifier) {
5234 Error_InvalidArguments (
5235 loc, j, method, delegate_type,
5240 if (chose_params_expanded)
5241 parameter_type = TypeManager.GetElementType (parameter_type);
5242 } else if (pm == Parameter.Modifier.ARGLIST){
5248 if (pd.ParameterModifier (j) != a.Modifier){
5250 Error_InvalidArguments (
5251 loc, j, method, delegate_type,
5260 if (!TypeManager.IsEqual (a.Type, parameter_type)){
5263 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
5267 Error_InvalidArguments (loc, j, method, delegate_type, a, pd);
5272 // Update the argument with the implicit conversion
5278 if (parameter_type.IsPointer){
5285 Parameter.Modifier a_mod = a.Modifier &
5286 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5287 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
5288 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5290 if (a_mod != p_mod &&
5291 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
5293 Invocation.Error_InvalidArguments (loc, j, method, null, a, pd);
5303 public override Expression DoResolve (EmitContext ec)
5306 // First, resolve the expression that is used to
5307 // trigger the invocation
5309 SimpleName sn = expr as SimpleName;
5311 expr = sn.GetMethodGroup ();
5313 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
5317 if (!(expr is MethodGroupExpr)) {
5318 Type expr_type = expr.Type;
5320 if (expr_type != null){
5321 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
5323 return (new DelegateInvocation (
5324 this.expr, Arguments, loc)).Resolve (ec);
5328 if (!(expr is MethodGroupExpr)){
5329 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup, loc);
5334 // Next, evaluate all the expressions in the argument list
5336 if (Arguments != null){
5337 foreach (Argument a in Arguments){
5338 if (!a.Resolve (ec, loc))
5343 MethodGroupExpr mg = (MethodGroupExpr) expr;
5344 method = OverloadResolve (ec, mg, Arguments, false, loc);
5349 MethodInfo mi = method as MethodInfo;
5351 type = TypeManager.TypeToCoreType (mi.ReturnType);
5352 Expression iexpr = mg.InstanceExpression;
5354 if (iexpr == null ||
5355 iexpr is This || iexpr is EmptyExpression ||
5356 mg.IdenticalTypeName) {
5357 mg.InstanceExpression = null;
5359 MemberExpr.error176 (loc, TypeManager.CSharpSignature (mi));
5363 if (iexpr == null || iexpr is EmptyExpression) {
5364 SimpleName.Error_ObjectRefRequired (ec, loc, TypeManager.CSharpSignature (mi));
5370 if (type.IsPointer){
5378 // Only base will allow this invocation to happen.
5380 if (mg.IsBase && method.IsAbstract){
5381 Error_CannotCallAbstractBase (TypeManager.CSharpSignature (method));
5385 if (method.Name == "Finalize" && Arguments == null) {
5386 Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
5390 if ((method.Attributes & MethodAttributes.SpecialName) != 0){
5391 if (TypeManager.LookupDeclSpace (method.DeclaringType) != null || TypeManager.IsSpecialMethod (method)) {
5392 Report.Error (571, loc, "`{0}': cannot explicitly call operator or accessor",
5393 TypeManager.CSharpSignature (method, true));
5398 if (mg.InstanceExpression != null)
5399 mg.InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
5401 eclass = ExprClass.Value;
5406 // Emits the list of arguments as an array
5408 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
5410 ILGenerator ig = ec.ig;
5411 int count = arguments.Count - idx;
5412 Argument a = (Argument) arguments [idx];
5413 Type t = a.Expr.Type;
5415 IntConstant.EmitInt (ig, count);
5416 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
5418 int top = arguments.Count;
5419 for (int j = idx; j < top; j++){
5420 a = (Argument) arguments [j];
5422 ig.Emit (OpCodes.Dup);
5423 IntConstant.EmitInt (ig, j - idx);
5425 bool is_stobj, has_type_arg;
5426 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj, out has_type_arg);
5428 ig.Emit (OpCodes.Ldelema, t);
5440 /// Emits a list of resolved Arguments that are in the arguments
5443 /// The MethodBase argument might be null if the
5444 /// emission of the arguments is known not to contain
5445 /// a `params' field (for example in constructors or other routines
5446 /// that keep their arguments in this structure)
5448 /// if `dup_args' is true, a copy of the arguments will be left
5449 /// on the stack. If `dup_args' is true, you can specify `this_arg'
5450 /// which will be duplicated before any other args. Only EmitCall
5451 /// should be using this interface.
5453 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments, bool dup_args, LocalTemporary this_arg)
5457 pd = TypeManager.GetParameterData (mb);
5461 LocalTemporary [] temps = null;
5464 temps = new LocalTemporary [arguments.Count];
5467 // If we are calling a params method with no arguments, special case it
5469 if (arguments == null){
5470 if (pd != null && pd.Count > 0 &&
5471 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
5472 ILGenerator ig = ec.ig;
5474 IntConstant.EmitInt (ig, 0);
5475 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
5481 int top = arguments.Count;
5483 for (int i = 0; i < top; i++){
5484 Argument a = (Argument) arguments [i];
5487 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
5489 // Special case if we are passing the same data as the
5490 // params argument, do not put it in an array.
5492 if (pd.ParameterType (i) == a.Type)
5495 EmitParams (ec, i, arguments);
5502 ec.ig.Emit (OpCodes.Dup);
5503 (temps [i] = new LocalTemporary (ec, a.Type)).Store (ec);
5508 if (this_arg != null)
5511 for (int i = 0; i < top; i ++)
5512 temps [i].Emit (ec);
5515 if (pd != null && pd.Count > top &&
5516 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
5517 ILGenerator ig = ec.ig;
5519 IntConstant.EmitInt (ig, 0);
5520 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
5524 static Type[] GetVarargsTypes (EmitContext ec, MethodBase mb,
5525 ArrayList arguments)
5527 ParameterData pd = TypeManager.GetParameterData (mb);
5529 if (arguments == null)
5530 return new Type [0];
5532 Argument a = (Argument) arguments [pd.Count - 1];
5533 Arglist list = (Arglist) a.Expr;
5535 return list.ArgumentTypes;
5539 /// This checks the ConditionalAttribute on the method
5541 static bool IsMethodExcluded (MethodBase method, EmitContext ec)
5543 if (method.IsConstructor)
5546 IMethodData md = TypeManager.GetMethod (method);
5548 return md.IsExcluded (ec);
5550 // For some methods (generated by delegate class) GetMethod returns null
5551 // because they are not included in builder_to_method table
5552 if (method.DeclaringType is TypeBuilder)
5555 return AttributeTester.IsConditionalMethodExcluded (method);
5559 /// is_base tells whether we want to force the use of the `call'
5560 /// opcode instead of using callvirt. Call is required to call
5561 /// a specific method, while callvirt will always use the most
5562 /// recent method in the vtable.
5564 /// is_static tells whether this is an invocation on a static method
5566 /// instance_expr is an expression that represents the instance
5567 /// it must be non-null if is_static is false.
5569 /// method is the method to invoke.
5571 /// Arguments is the list of arguments to pass to the method or constructor.
5573 public static void EmitCall (EmitContext ec, bool is_base,
5574 bool is_static, Expression instance_expr,
5575 MethodBase method, ArrayList Arguments, Location loc)
5577 EmitCall (ec, is_base, is_static, instance_expr, method, Arguments, loc, false, false);
5580 // `dup_args' leaves an extra copy of the arguments on the stack
5581 // `omit_args' does not leave any arguments at all.
5582 // So, basically, you could make one call with `dup_args' set to true,
5583 // and then another with `omit_args' set to true, and the two calls
5584 // would have the same set of arguments. However, each argument would
5585 // only have been evaluated once.
5586 public static void EmitCall (EmitContext ec, bool is_base,
5587 bool is_static, Expression instance_expr,
5588 MethodBase method, ArrayList Arguments, Location loc,
5589 bool dup_args, bool omit_args)
5591 ILGenerator ig = ec.ig;
5592 bool struct_call = false;
5593 bool this_call = false;
5594 LocalTemporary this_arg = null;
5596 Type decl_type = method.DeclaringType;
5598 if (!RootContext.StdLib) {
5599 // Replace any calls to the system's System.Array type with calls to
5600 // the newly created one.
5601 if (method == TypeManager.system_int_array_get_length)
5602 method = TypeManager.int_array_get_length;
5603 else if (method == TypeManager.system_int_array_get_rank)
5604 method = TypeManager.int_array_get_rank;
5605 else if (method == TypeManager.system_object_array_clone)
5606 method = TypeManager.object_array_clone;
5607 else if (method == TypeManager.system_int_array_get_length_int)
5608 method = TypeManager.int_array_get_length_int;
5609 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5610 method = TypeManager.int_array_get_lower_bound_int;
5611 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5612 method = TypeManager.int_array_get_upper_bound_int;
5613 else if (method == TypeManager.system_void_array_copyto_array_int)
5614 method = TypeManager.void_array_copyto_array_int;
5617 if (ec.TestObsoleteMethodUsage) {
5619 // This checks ObsoleteAttribute on the method and on the declaring type
5621 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
5623 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
5625 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
5627 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
5631 if (IsMethodExcluded (method, ec))
5635 if (instance_expr == EmptyExpression.Null) {
5636 SimpleName.Error_ObjectRefRequired (ec, loc, TypeManager.CSharpSignature (method));
5640 this_call = instance_expr is This;
5641 if (decl_type.IsValueType || (!this_call && instance_expr.Type.IsValueType))
5645 // If this is ourselves, push "this"
5650 ig.Emit (OpCodes.Ldarg_0);
5653 Type iexpr_type = instance_expr.Type;
5656 // Push the instance expression
5658 if (TypeManager.IsValueType (iexpr_type)) {
5660 // Special case: calls to a function declared in a
5661 // reference-type with a value-type argument need
5662 // to have their value boxed.
5663 if (decl_type.IsValueType ||
5664 iexpr_type.IsGenericParameter) {
5666 // If the expression implements IMemoryLocation, then
5667 // we can optimize and use AddressOf on the
5670 // If not we have to use some temporary storage for
5672 if (instance_expr is IMemoryLocation) {
5673 ((IMemoryLocation)instance_expr).
5674 AddressOf (ec, AddressOp.LoadStore);
5676 LocalTemporary temp = new LocalTemporary (ec, iexpr_type);
5677 instance_expr.Emit (ec);
5679 temp.AddressOf (ec, AddressOp.Load);
5682 // avoid the overhead of doing this all the time.
5684 t = TypeManager.GetReferenceType (iexpr_type);
5686 instance_expr.Emit (ec);
5687 ig.Emit (OpCodes.Box, instance_expr.Type);
5688 t = TypeManager.object_type;
5691 instance_expr.Emit (ec);
5692 t = instance_expr.Type;
5697 this_arg = new LocalTemporary (ec, t);
5698 ig.Emit (OpCodes.Dup);
5699 this_arg.Store (ec);
5705 EmitArguments (ec, method, Arguments, dup_args, this_arg);
5707 if ((instance_expr != null) && (instance_expr.Type.IsGenericParameter))
5708 ig.Emit (OpCodes.Constrained, instance_expr.Type);
5711 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
5712 call_op = OpCodes.Call;
5714 call_op = OpCodes.Callvirt;
5716 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
5717 Type[] varargs_types = GetVarargsTypes (ec, method, Arguments);
5718 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
5725 // and DoFoo is not virtual, you can omit the callvirt,
5726 // because you don't need the null checking behavior.
5728 if (method is MethodInfo)
5729 ig.Emit (call_op, (MethodInfo) method);
5731 ig.Emit (call_op, (ConstructorInfo) method);
5734 public override void Emit (EmitContext ec)
5736 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5738 EmitCall (ec, mg.IsBase, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5741 public override void EmitStatement (EmitContext ec)
5746 // Pop the return value if there is one
5748 if (method is MethodInfo){
5749 Type ret = ((MethodInfo)method).ReturnType;
5750 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5751 ec.ig.Emit (OpCodes.Pop);
5756 public class InvocationOrCast : ExpressionStatement
5759 Expression argument;
5761 public InvocationOrCast (Expression expr, Expression argument, Location loc)
5764 this.argument = argument;
5768 public override Expression DoResolve (EmitContext ec)
5771 // First try to resolve it as a cast.
5773 TypeExpr te = expr.ResolveAsTypeStep (ec) as TypeExpr;
5774 if ((te != null) && (te.eclass == ExprClass.Type)) {
5775 Cast cast = new Cast (te, argument, loc);
5776 return cast.Resolve (ec);
5780 // This can either be a type or a delegate invocation.
5781 // Let's just resolve it and see what we'll get.
5783 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5788 // Ok, so it's a Cast.
5790 if (expr.eclass == ExprClass.Type) {
5791 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
5792 return cast.Resolve (ec);
5796 // It's a delegate invocation.
5798 if (!TypeManager.IsDelegateType (expr.Type)) {
5799 Error (149, "Method name expected");
5803 ArrayList args = new ArrayList ();
5804 args.Add (new Argument (argument, Argument.AType.Expression));
5805 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5806 return invocation.Resolve (ec);
5811 Error (201, "Only assignment, call, increment, decrement and new object " +
5812 "expressions can be used as a statement");
5815 public override ExpressionStatement ResolveStatement (EmitContext ec)
5818 // First try to resolve it as a cast.
5820 TypeExpr te = expr.ResolveAsTypeStep (ec) as TypeExpr;
5821 if ((te != null) && (te.eclass == ExprClass.Type)) {
5827 // This can either be a type or a delegate invocation.
5828 // Let's just resolve it and see what we'll get.
5830 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5831 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5837 // It's a delegate invocation.
5839 if (!TypeManager.IsDelegateType (expr.Type)) {
5840 Error (149, "Method name expected");
5844 ArrayList args = new ArrayList ();
5845 args.Add (new Argument (argument, Argument.AType.Expression));
5846 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5847 return invocation.ResolveStatement (ec);
5850 public override void Emit (EmitContext ec)
5852 throw new Exception ("Cannot happen");
5855 public override void EmitStatement (EmitContext ec)
5857 throw new Exception ("Cannot happen");
5862 // This class is used to "disable" the code generation for the
5863 // temporary variable when initializing value types.
5865 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5866 public void AddressOf (EmitContext ec, AddressOp Mode)
5873 /// Implements the new expression
5875 public class New : ExpressionStatement, IMemoryLocation {
5876 public readonly ArrayList Arguments;
5879 // During bootstrap, it contains the RequestedType,
5880 // but if `type' is not null, it *might* contain a NewDelegate
5881 // (because of field multi-initialization)
5883 public Expression RequestedType;
5885 MethodBase method = null;
5888 // If set, the new expression is for a value_target, and
5889 // we will not leave anything on the stack.
5891 Expression value_target;
5892 bool value_target_set = false;
5893 bool is_type_parameter = false;
5895 public New (Expression requested_type, ArrayList arguments, Location l)
5897 RequestedType = requested_type;
5898 Arguments = arguments;
5902 public bool SetValueTypeVariable (Expression value)
5904 value_target = value;
5905 value_target_set = true;
5906 if (!(value_target is IMemoryLocation)){
5907 Error_UnexpectedKind ("variable", loc);
5914 // This function is used to disable the following code sequence for
5915 // value type initialization:
5917 // AddressOf (temporary)
5921 // Instead the provide will have provided us with the address on the
5922 // stack to store the results.
5924 static Expression MyEmptyExpression;
5926 public void DisableTemporaryValueType ()
5928 if (MyEmptyExpression == null)
5929 MyEmptyExpression = new EmptyAddressOf ();
5932 // To enable this, look into:
5933 // test-34 and test-89 and self bootstrapping.
5935 // For instance, we can avoid a copy by using `newobj'
5936 // instead of Call + Push-temp on value types.
5937 // value_target = MyEmptyExpression;
5942 /// Converts complex core type syntax like 'new int ()' to simple constant
5944 Expression Constantify (Type t)
5946 if (t == TypeManager.int32_type)
5947 return new IntConstant (0);
5948 if (t == TypeManager.uint32_type)
5949 return new UIntConstant (0);
5950 if (t == TypeManager.int64_type)
5951 return new LongConstant (0);
5952 if (t == TypeManager.uint64_type)
5953 return new ULongConstant (0);
5954 if (t == TypeManager.float_type)
5955 return new FloatConstant (0);
5956 if (t == TypeManager.double_type)
5957 return new DoubleConstant (0);
5958 if (t == TypeManager.short_type)
5959 return new ShortConstant (0);
5960 if (t == TypeManager.ushort_type)
5961 return new UShortConstant (0);
5962 if (t == TypeManager.sbyte_type)
5963 return new SByteConstant (0);
5964 if (t == TypeManager.byte_type)
5965 return new ByteConstant (0);
5966 if (t == TypeManager.char_type)
5967 return new CharConstant ('\0');
5968 if (t == TypeManager.bool_type)
5969 return new BoolConstant (false);
5970 if (t == TypeManager.decimal_type)
5971 return new DecimalConstant (0);
5976 public override Expression DoResolve (EmitContext ec)
5979 // The New DoResolve might be called twice when initializing field
5980 // expressions (see EmitFieldInitializers, the call to
5981 // GetInitializerExpression will perform a resolve on the expression,
5982 // and later the assign will trigger another resolution
5984 // This leads to bugs (#37014)
5987 if (RequestedType is NewDelegate)
5988 return RequestedType;
5992 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec);
5996 if (Arguments == null) {
5997 Expression c = Constantify (type);
6006 CheckObsoleteAttribute (type);
6008 bool IsDelegate = TypeManager.IsDelegateType (type);
6011 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
6012 if (RequestedType != null)
6013 if (!(RequestedType is DelegateCreation))
6014 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
6015 return RequestedType;
6018 if (type.IsGenericParameter) {
6019 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (type);
6021 if ((gc == null) || (!gc.HasConstructorConstraint && !gc.IsValueType)) {
6022 Error (304, String.Format (
6023 "Cannot create an instance of the " +
6024 "variable type '{0}' because it " +
6025 "doesn't have the new() constraint",
6030 if ((Arguments != null) && (Arguments.Count != 0)) {
6031 Error (417, String.Format (
6032 "`{0}': cannot provide arguments " +
6033 "when creating an instance of a " +
6034 "variable type.", type));
6038 is_type_parameter = true;
6039 eclass = ExprClass.Value;
6043 if (type.IsAbstract && type.IsSealed) {
6044 Report.Error (712, loc, "Cannot create an instance of the static class `{0}'", TypeManager.CSharpName (type));
6048 if (type.IsInterface || type.IsAbstract){
6049 Report.Error (144, loc, "Cannot create an instance of the abstract class or interface `{0}'", TypeManager.CSharpName (type));
6053 bool is_struct = type.IsValueType;
6054 eclass = ExprClass.Value;
6057 // SRE returns a match for .ctor () on structs (the object constructor),
6058 // so we have to manually ignore it.
6060 if (is_struct && Arguments == null)
6064 ml = MemberLookupFinal (ec, type, type, ".ctor",
6065 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
6066 MemberTypes.Constructor,
6067 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
6072 if (! (ml is MethodGroupExpr)){
6074 ml.Error_UnexpectedKind ("method group", loc);
6080 if (Arguments != null){
6081 foreach (Argument a in Arguments){
6082 if (!a.Resolve (ec, loc))
6087 method = Invocation.OverloadResolve (
6088 ec, (MethodGroupExpr) ml, Arguments, true, loc);
6092 if (method == null) {
6093 if (almostMatchedMembers.Count != 0) {
6094 MemberLookupFailed (ec, type, type, ".ctor", null, true, loc);
6098 if (!is_struct || Arguments.Count > 0) {
6099 Invocation.Error_WrongNumArguments (loc, TypeManager.CSharpName (type),
6100 Arguments == null ? 0 : Arguments.Count);
6108 bool DoEmitTypeParameter (EmitContext ec)
6110 ILGenerator ig = ec.ig;
6112 ig.Emit (OpCodes.Ldtoken, type);
6113 ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6114 ig.Emit (OpCodes.Call, TypeManager.activator_create_instance);
6115 ig.Emit (OpCodes.Unbox_Any, type);
6121 // This DoEmit can be invoked in two contexts:
6122 // * As a mechanism that will leave a value on the stack (new object)
6123 // * As one that wont (init struct)
6125 // You can control whether a value is required on the stack by passing
6126 // need_value_on_stack. The code *might* leave a value on the stack
6127 // so it must be popped manually
6129 // If we are dealing with a ValueType, we have a few
6130 // situations to deal with:
6132 // * The target is a ValueType, and we have been provided
6133 // the instance (this is easy, we are being assigned).
6135 // * The target of New is being passed as an argument,
6136 // to a boxing operation or a function that takes a
6139 // In this case, we need to create a temporary variable
6140 // that is the argument of New.
6142 // Returns whether a value is left on the stack
6144 bool DoEmit (EmitContext ec, bool need_value_on_stack)
6146 bool is_value_type = TypeManager.IsValueType (type);
6147 ILGenerator ig = ec.ig;
6152 // Allow DoEmit() to be called multiple times.
6153 // We need to create a new LocalTemporary each time since
6154 // you can't share LocalBuilders among ILGeneators.
6155 if (!value_target_set)
6156 value_target = new LocalTemporary (ec, type);
6158 ml = (IMemoryLocation) value_target;
6159 ml.AddressOf (ec, AddressOp.Store);
6163 Invocation.EmitArguments (ec, method, Arguments, false, null);
6167 ig.Emit (OpCodes.Initobj, type);
6169 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6170 if (need_value_on_stack){
6171 value_target.Emit (ec);
6176 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
6181 public override void Emit (EmitContext ec)
6183 if (is_type_parameter)
6184 DoEmitTypeParameter (ec);
6189 public override void EmitStatement (EmitContext ec)
6191 if (is_type_parameter)
6192 throw new InvalidOperationException ();
6194 if (DoEmit (ec, false))
6195 ec.ig.Emit (OpCodes.Pop);
6198 public void AddressOf (EmitContext ec, AddressOp Mode)
6200 if (is_type_parameter)
6201 throw new InvalidOperationException ();
6203 if (!type.IsValueType){
6205 // We throw an exception. So far, I believe we only need to support
6207 // foreach (int j in new StructType ())
6210 throw new Exception ("AddressOf should not be used for classes");
6213 if (!value_target_set)
6214 value_target = new LocalTemporary (ec, type);
6216 IMemoryLocation ml = (IMemoryLocation) value_target;
6217 ml.AddressOf (ec, AddressOp.Store);
6219 Invocation.EmitArguments (ec, method, Arguments, false, null);
6222 ec.ig.Emit (OpCodes.Initobj, type);
6224 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6226 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
6231 /// 14.5.10.2: Represents an array creation expression.
6235 /// There are two possible scenarios here: one is an array creation
6236 /// expression that specifies the dimensions and optionally the
6237 /// initialization data and the other which does not need dimensions
6238 /// specified but where initialization data is mandatory.
6240 public class ArrayCreation : Expression {
6241 Expression requested_base_type;
6242 ArrayList initializers;
6245 // The list of Argument types.
6246 // This is used to construct the `newarray' or constructor signature
6248 ArrayList arguments;
6251 // Method used to create the array object.
6253 MethodBase new_method = null;
6255 Type array_element_type;
6256 Type underlying_type;
6257 bool is_one_dimensional = false;
6258 bool is_builtin_type = false;
6259 bool expect_initializers = false;
6260 int num_arguments = 0;
6264 ArrayList array_data;
6269 // The number of array initializers that we can handle
6270 // via the InitializeArray method - through EmitStaticInitializers
6272 int num_automatic_initializers;
6274 const int max_automatic_initializers = 6;
6276 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
6278 this.requested_base_type = requested_base_type;
6279 this.initializers = initializers;
6283 arguments = new ArrayList ();
6285 foreach (Expression e in exprs) {
6286 arguments.Add (new Argument (e, Argument.AType.Expression));
6291 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
6293 this.requested_base_type = requested_base_type;
6294 this.initializers = initializers;
6298 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
6300 //string tmp = rank.Substring (rank.LastIndexOf ('['));
6302 //dimensions = tmp.Length - 1;
6303 expect_initializers = true;
6306 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
6308 StringBuilder sb = new StringBuilder (rank);
6311 for (int i = 1; i < idx_count; i++)
6316 return new ComposedCast (base_type, sb.ToString (), loc);
6319 void Error_IncorrectArrayInitializer ()
6321 Error (178, "Invalid rank specifier: expected `,' or `]'");
6324 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
6326 if (specified_dims) {
6327 Argument a = (Argument) arguments [idx];
6329 if (!a.Resolve (ec, loc))
6332 if (!(a.Expr is Constant)) {
6333 Error (150, "A constant value is expected");
6337 int value = (int) ((Constant) a.Expr).GetValue ();
6339 if (value != probe.Count) {
6340 Error_IncorrectArrayInitializer ();
6344 bounds [idx] = value;
6347 int child_bounds = -1;
6348 for (int i = 0; i < probe.Count; ++i) {
6349 object o = probe [i];
6350 if (o is ArrayList) {
6351 ArrayList sub_probe = o as ArrayList;
6352 int current_bounds = sub_probe.Count;
6354 if (child_bounds == -1)
6355 child_bounds = current_bounds;
6357 else if (child_bounds != current_bounds){
6358 Error_IncorrectArrayInitializer ();
6361 if (specified_dims && (idx + 1 >= arguments.Count)){
6362 Error (623, "Array initializers can only be used in a variable or field initializer. Try using a new expression instead");
6366 bool ret = CheckIndices (ec, sub_probe, idx + 1, specified_dims);
6370 if (child_bounds != -1){
6371 Error_IncorrectArrayInitializer ();
6375 Expression tmp = (Expression) o;
6376 tmp = tmp.Resolve (ec);
6381 // Console.WriteLine ("I got: " + tmp);
6382 // Handle initialization from vars, fields etc.
6384 Expression conv = Convert.ImplicitConversionRequired (
6385 ec, tmp, underlying_type, loc);
6390 if (conv is StringConstant || conv is DecimalConstant || conv is NullCast) {
6391 // These are subclasses of Constant that can appear as elements of an
6392 // array that cannot be statically initialized (with num_automatic_initializers
6393 // > max_automatic_initializers), so num_automatic_initializers should be left as zero.
6394 array_data.Add (conv);
6395 } else if (conv is Constant) {
6396 // These are the types of Constant that can appear in arrays that can be
6397 // statically allocated.
6398 array_data.Add (conv);
6399 num_automatic_initializers++;
6401 array_data.Add (conv);
6408 public void UpdateIndices (EmitContext ec)
6411 for (ArrayList probe = initializers; probe != null;) {
6412 if (probe.Count > 0 && probe [0] is ArrayList) {
6413 Expression e = new IntConstant (probe.Count);
6414 arguments.Add (new Argument (e, Argument.AType.Expression));
6416 bounds [i++] = probe.Count;
6418 probe = (ArrayList) probe [0];
6421 Expression e = new IntConstant (probe.Count);
6422 arguments.Add (new Argument (e, Argument.AType.Expression));
6424 bounds [i++] = probe.Count;
6431 public bool ValidateInitializers (EmitContext ec, Type array_type)
6433 if (initializers == null) {
6434 if (expect_initializers)
6440 if (underlying_type == null)
6444 // We use this to store all the date values in the order in which we
6445 // will need to store them in the byte blob later
6447 array_data = new ArrayList ();
6448 bounds = new Hashtable ();
6452 if (arguments != null) {
6453 ret = CheckIndices (ec, initializers, 0, true);
6456 arguments = new ArrayList ();
6458 ret = CheckIndices (ec, initializers, 0, false);
6465 if (arguments.Count != dimensions) {
6466 Error_IncorrectArrayInitializer ();
6475 // Creates the type of the array
6477 bool LookupType (EmitContext ec)
6479 StringBuilder array_qualifier = new StringBuilder (rank);
6482 // `In the first form allocates an array instace of the type that results
6483 // from deleting each of the individual expression from the expression list'
6485 if (num_arguments > 0) {
6486 array_qualifier.Append ("[");
6487 for (int i = num_arguments-1; i > 0; i--)
6488 array_qualifier.Append (",");
6489 array_qualifier.Append ("]");
6495 TypeExpr array_type_expr;
6496 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
6497 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec);
6498 if (array_type_expr == null)
6501 type = array_type_expr.Type;
6503 if (!type.IsArray) {
6504 Error (622, "Can only use array initializer expressions to assign to array types. Try using a new expression instead.");
6507 underlying_type = TypeManager.GetElementType (type);
6508 dimensions = type.GetArrayRank ();
6513 public override Expression DoResolve (EmitContext ec)
6517 if (!LookupType (ec))
6521 // First step is to validate the initializers and fill
6522 // in any missing bits
6524 if (!ValidateInitializers (ec, type))
6527 if (arguments == null)
6530 arg_count = arguments.Count;
6531 foreach (Argument a in arguments){
6532 if (!a.Resolve (ec, loc))
6535 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
6536 if (real_arg == null)
6543 array_element_type = TypeManager.GetElementType (type);
6545 if (array_element_type.IsAbstract && array_element_type.IsSealed) {
6546 Report.Error (719, loc, "`{0}': array elements cannot be of static type", TypeManager.CSharpName (array_element_type));
6550 if (arg_count == 1) {
6551 is_one_dimensional = true;
6552 eclass = ExprClass.Value;
6556 is_builtin_type = TypeManager.IsBuiltinType (type);
6558 if (is_builtin_type) {
6561 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
6562 AllBindingFlags, loc);
6564 if (!(ml is MethodGroupExpr)) {
6565 ml.Error_UnexpectedKind ("method group", loc);
6570 Error (-6, "New invocation: Can not find a constructor for " +
6571 "this argument list");
6575 new_method = Invocation.OverloadResolve (
6576 ec, (MethodGroupExpr) ml, arguments, false, loc);
6578 if (new_method == null) {
6579 Error (-6, "New invocation: Can not find a constructor for " +
6580 "this argument list");
6584 eclass = ExprClass.Value;
6587 ModuleBuilder mb = CodeGen.Module.Builder;
6588 ArrayList args = new ArrayList ();
6590 if (arguments != null) {
6591 for (int i = 0; i < arg_count; i++)
6592 args.Add (TypeManager.int32_type);
6595 Type [] arg_types = null;
6598 arg_types = new Type [args.Count];
6600 args.CopyTo (arg_types, 0);
6602 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
6605 if (new_method == null) {
6606 Error (-6, "New invocation: Can not find a constructor for " +
6607 "this argument list");
6611 eclass = ExprClass.Value;
6616 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
6621 int count = array_data.Count;
6623 if (underlying_type.IsEnum)
6624 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
6626 factor = GetTypeSize (underlying_type);
6628 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
6630 data = new byte [(count * factor + 4) & ~3];
6633 for (int i = 0; i < count; ++i) {
6634 object v = array_data [i];
6636 if (v is EnumConstant)
6637 v = ((EnumConstant) v).Child;
6639 if (v is Constant && !(v is StringConstant))
6640 v = ((Constant) v).GetValue ();
6646 if (underlying_type == TypeManager.int64_type){
6647 if (!(v is Expression)){
6648 long val = (long) v;
6650 for (int j = 0; j < factor; ++j) {
6651 data [idx + j] = (byte) (val & 0xFF);
6655 } else if (underlying_type == TypeManager.uint64_type){
6656 if (!(v is Expression)){
6657 ulong val = (ulong) v;
6659 for (int j = 0; j < factor; ++j) {
6660 data [idx + j] = (byte) (val & 0xFF);
6664 } else if (underlying_type == TypeManager.float_type) {
6665 if (!(v is Expression)){
6666 element = BitConverter.GetBytes ((float) v);
6668 for (int j = 0; j < factor; ++j)
6669 data [idx + j] = element [j];
6671 } else if (underlying_type == TypeManager.double_type) {
6672 if (!(v is Expression)){
6673 element = BitConverter.GetBytes ((double) v);
6675 for (int j = 0; j < factor; ++j)
6676 data [idx + j] = element [j];
6678 } else if (underlying_type == TypeManager.char_type){
6679 if (!(v is Expression)){
6680 int val = (int) ((char) v);
6682 data [idx] = (byte) (val & 0xff);
6683 data [idx+1] = (byte) (val >> 8);
6685 } else if (underlying_type == TypeManager.short_type){
6686 if (!(v is Expression)){
6687 int val = (int) ((short) v);
6689 data [idx] = (byte) (val & 0xff);
6690 data [idx+1] = (byte) (val >> 8);
6692 } else if (underlying_type == TypeManager.ushort_type){
6693 if (!(v is Expression)){
6694 int val = (int) ((ushort) v);
6696 data [idx] = (byte) (val & 0xff);
6697 data [idx+1] = (byte) (val >> 8);
6699 } else if (underlying_type == TypeManager.int32_type) {
6700 if (!(v is Expression)){
6703 data [idx] = (byte) (val & 0xff);
6704 data [idx+1] = (byte) ((val >> 8) & 0xff);
6705 data [idx+2] = (byte) ((val >> 16) & 0xff);
6706 data [idx+3] = (byte) (val >> 24);
6708 } else if (underlying_type == TypeManager.uint32_type) {
6709 if (!(v is Expression)){
6710 uint val = (uint) v;
6712 data [idx] = (byte) (val & 0xff);
6713 data [idx+1] = (byte) ((val >> 8) & 0xff);
6714 data [idx+2] = (byte) ((val >> 16) & 0xff);
6715 data [idx+3] = (byte) (val >> 24);
6717 } else if (underlying_type == TypeManager.sbyte_type) {
6718 if (!(v is Expression)){
6719 sbyte val = (sbyte) v;
6720 data [idx] = (byte) val;
6722 } else if (underlying_type == TypeManager.byte_type) {
6723 if (!(v is Expression)){
6724 byte val = (byte) v;
6725 data [idx] = (byte) val;
6727 } else if (underlying_type == TypeManager.bool_type) {
6728 if (!(v is Expression)){
6729 bool val = (bool) v;
6730 data [idx] = (byte) (val ? 1 : 0);
6732 } else if (underlying_type == TypeManager.decimal_type){
6733 if (!(v is Expression)){
6734 int [] bits = Decimal.GetBits ((decimal) v);
6737 // FIXME: For some reason, this doesn't work on the MS runtime.
6738 int [] nbits = new int [4];
6739 nbits [0] = bits [3];
6740 nbits [1] = bits [2];
6741 nbits [2] = bits [0];
6742 nbits [3] = bits [1];
6744 for (int j = 0; j < 4; j++){
6745 data [p++] = (byte) (nbits [j] & 0xff);
6746 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6747 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6748 data [p++] = (byte) (nbits [j] >> 24);
6752 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6761 // Emits the initializers for the array
6763 void EmitStaticInitializers (EmitContext ec)
6766 // First, the static data
6769 ILGenerator ig = ec.ig;
6771 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6773 fb = RootContext.MakeStaticData (data);
6775 ig.Emit (OpCodes.Dup);
6776 ig.Emit (OpCodes.Ldtoken, fb);
6777 ig.Emit (OpCodes.Call,
6778 TypeManager.void_initializearray_array_fieldhandle);
6782 // Emits pieces of the array that can not be computed at compile
6783 // time (variables and string locations).
6785 // This always expect the top value on the stack to be the array
6787 void EmitDynamicInitializers (EmitContext ec)
6789 ILGenerator ig = ec.ig;
6790 int dims = bounds.Count;
6791 int [] current_pos = new int [dims];
6792 int top = array_data.Count;
6794 MethodInfo set = null;
6798 ModuleBuilder mb = null;
6799 mb = CodeGen.Module.Builder;
6800 args = new Type [dims + 1];
6803 for (j = 0; j < dims; j++)
6804 args [j] = TypeManager.int32_type;
6806 args [j] = array_element_type;
6808 set = mb.GetArrayMethod (
6810 CallingConventions.HasThis | CallingConventions.Standard,
6811 TypeManager.void_type, args);
6814 for (int i = 0; i < top; i++){
6816 Expression e = null;
6818 if (array_data [i] is Expression)
6819 e = (Expression) array_data [i];
6823 // Basically we do this for string literals and
6824 // other non-literal expressions
6826 if (e is EnumConstant){
6827 e = ((EnumConstant) e).Child;
6830 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6831 num_automatic_initializers <= max_automatic_initializers) {
6832 Type etype = e.Type;
6834 ig.Emit (OpCodes.Dup);
6836 for (int idx = 0; idx < dims; idx++)
6837 IntConstant.EmitInt (ig, current_pos [idx]);
6840 // If we are dealing with a struct, get the
6841 // address of it, so we can store it.
6843 if ((dims == 1) && etype.IsValueType &&
6844 (!TypeManager.IsBuiltinOrEnum (etype) ||
6845 etype == TypeManager.decimal_type)) {
6850 // Let new know that we are providing
6851 // the address where to store the results
6853 n.DisableTemporaryValueType ();
6856 ig.Emit (OpCodes.Ldelema, etype);
6862 bool is_stobj, has_type_arg;
6863 OpCode op = ArrayAccess.GetStoreOpcode (
6864 etype, out is_stobj,
6867 ig.Emit (OpCodes.Stobj, etype);
6868 else if (has_type_arg)
6869 ig.Emit (op, etype);
6873 ig.Emit (OpCodes.Call, set);
6880 for (int j = dims - 1; j >= 0; j--){
6882 if (current_pos [j] < (int) bounds [j])
6884 current_pos [j] = 0;
6889 void EmitArrayArguments (EmitContext ec)
6891 ILGenerator ig = ec.ig;
6893 foreach (Argument a in arguments) {
6894 Type atype = a.Type;
6897 if (atype == TypeManager.uint64_type)
6898 ig.Emit (OpCodes.Conv_Ovf_U4);
6899 else if (atype == TypeManager.int64_type)
6900 ig.Emit (OpCodes.Conv_Ovf_I4);
6904 public override void Emit (EmitContext ec)
6906 ILGenerator ig = ec.ig;
6908 EmitArrayArguments (ec);
6909 if (is_one_dimensional)
6910 ig.Emit (OpCodes.Newarr, array_element_type);
6912 if (is_builtin_type)
6913 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6915 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6918 if (initializers != null){
6920 // FIXME: Set this variable correctly.
6922 bool dynamic_initializers = true;
6924 // This will never be true for array types that cannot be statically
6925 // initialized. num_automatic_initializers will always be zero. See
6927 if (num_automatic_initializers > max_automatic_initializers)
6928 EmitStaticInitializers (ec);
6930 if (dynamic_initializers)
6931 EmitDynamicInitializers (ec);
6935 public object EncodeAsAttribute ()
6937 if (!is_one_dimensional){
6938 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6942 if (array_data == null){
6943 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6947 object [] ret = new object [array_data.Count];
6949 foreach (Expression e in array_data){
6952 if (e is NullLiteral)
6955 if (!Attribute.GetAttributeArgumentExpression (e, Location, array_element_type, out v))
6965 /// Represents the `this' construct
6967 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6970 VariableInfo variable_info;
6972 public This (Block block, Location loc)
6978 public This (Location loc)
6983 public VariableInfo VariableInfo {
6984 get { return variable_info; }
6987 public bool VerifyFixed ()
6989 // Treat 'this' as a value parameter for the purpose of fixed variable determination.
6993 public bool ResolveBase (EmitContext ec)
6995 eclass = ExprClass.Variable;
6997 if (ec.TypeContainer.CurrentType != null)
6998 type = ec.TypeContainer.CurrentType;
7000 type = ec.ContainerType;
7003 Error (26, "Keyword `this' is not valid in a static property, static method, or static field initializer");
7007 if ((block != null) && (block.ThisVariable != null))
7008 variable_info = block.ThisVariable.VariableInfo;
7010 if (ec.CurrentAnonymousMethod != null)
7016 public override Expression DoResolve (EmitContext ec)
7018 if (!ResolveBase (ec))
7021 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
7022 Error (188, "The `this' object cannot be used before all of its fields are assigned to");
7023 variable_info.SetAssigned (ec);
7027 if (ec.IsFieldInitializer) {
7028 Error (27, "Keyword `this' is not available in the current context");
7035 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
7037 if (!ResolveBase (ec))
7040 if (variable_info != null)
7041 variable_info.SetAssigned (ec);
7043 if (ec.TypeContainer is Class){
7044 Error (1604, "Cannot assign to 'this' because it is read-only");
7051 public void Emit (EmitContext ec, bool leave_copy)
7055 ec.ig.Emit (OpCodes.Dup);
7058 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
7060 ILGenerator ig = ec.ig;
7062 if (ec.TypeContainer is Struct){
7066 ec.ig.Emit (OpCodes.Dup);
7067 ig.Emit (OpCodes.Stobj, type);
7069 throw new Exception ("how did you get here");
7073 public override void Emit (EmitContext ec)
7075 ILGenerator ig = ec.ig;
7078 if (ec.TypeContainer is Struct)
7079 ig.Emit (OpCodes.Ldobj, type);
7082 public override int GetHashCode()
7084 return block.GetHashCode ();
7087 public override bool Equals (object obj)
7089 This t = obj as This;
7093 return block == t.block;
7096 public void AddressOf (EmitContext ec, AddressOp mode)
7101 // FIGURE OUT WHY LDARG_S does not work
7103 // consider: struct X { int val; int P { set { val = value; }}}
7105 // Yes, this looks very bad. Look at `NOTAS' for
7107 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
7112 /// Represents the `__arglist' construct
7114 public class ArglistAccess : Expression
7116 public ArglistAccess (Location loc)
7121 public bool ResolveBase (EmitContext ec)
7123 eclass = ExprClass.Variable;
7124 type = TypeManager.runtime_argument_handle_type;
7128 public override Expression DoResolve (EmitContext ec)
7130 if (!ResolveBase (ec))
7133 if (ec.IsFieldInitializer || !ec.CurrentBlock.HasVarargs) {
7134 Error (190, "The __arglist construct is valid only within " +
7135 "a variable argument method.");
7142 public override void Emit (EmitContext ec)
7144 ec.ig.Emit (OpCodes.Arglist);
7149 /// Represents the `__arglist (....)' construct
7151 public class Arglist : Expression
7153 public readonly Argument[] Arguments;
7155 public Arglist (Argument[] args, Location l)
7161 public Type[] ArgumentTypes {
7163 Type[] retval = new Type [Arguments.Length];
7164 for (int i = 0; i < Arguments.Length; i++)
7165 retval [i] = Arguments [i].Type;
7170 public override Expression DoResolve (EmitContext ec)
7172 eclass = ExprClass.Variable;
7173 type = TypeManager.runtime_argument_handle_type;
7175 foreach (Argument arg in Arguments) {
7176 if (!arg.Resolve (ec, loc))
7183 public override void Emit (EmitContext ec)
7185 foreach (Argument arg in Arguments)
7191 // This produces the value that renders an instance, used by the iterators code
7193 public class ProxyInstance : Expression, IMemoryLocation {
7194 public override Expression DoResolve (EmitContext ec)
7196 eclass = ExprClass.Variable;
7197 type = ec.ContainerType;
7201 public override void Emit (EmitContext ec)
7203 ec.ig.Emit (OpCodes.Ldarg_0);
7207 public void AddressOf (EmitContext ec, AddressOp mode)
7209 ec.ig.Emit (OpCodes.Ldarg_0);
7214 /// Implements the typeof operator
7216 public class TypeOf : Expression {
7217 public Expression QueriedType;
7218 protected Type typearg;
7220 public TypeOf (Expression queried_type, Location l)
7222 QueriedType = queried_type;
7226 public override Expression DoResolve (EmitContext ec)
7228 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec);
7232 typearg = texpr.Type;
7234 if (typearg == TypeManager.void_type) {
7235 Error (673, "System.Void cannot be used from C#. Use typeof (void) to get the void type object");
7239 if (typearg.IsPointer && !ec.InUnsafe){
7243 CheckObsoleteAttribute (typearg);
7245 type = TypeManager.type_type;
7246 // Even though what is returned is a type object, it's treated as a value by the compiler.
7247 // In particular, 'typeof (Foo).X' is something totally different from 'Foo.X'.
7248 eclass = ExprClass.Value;
7252 public override void Emit (EmitContext ec)
7254 ec.ig.Emit (OpCodes.Ldtoken, typearg);
7255 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
7258 public Type TypeArg {
7259 get { return typearg; }
7264 /// Implements the `typeof (void)' operator
7266 public class TypeOfVoid : TypeOf {
7267 public TypeOfVoid (Location l) : base (null, l)
7272 public override Expression DoResolve (EmitContext ec)
7274 type = TypeManager.type_type;
7275 typearg = TypeManager.void_type;
7276 // See description in TypeOf.
7277 eclass = ExprClass.Value;
7283 /// Implements the sizeof expression
7285 public class SizeOf : Expression {
7286 public Expression QueriedType;
7289 public SizeOf (Expression queried_type, Location l)
7291 this.QueriedType = queried_type;
7295 public override Expression DoResolve (EmitContext ec)
7297 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec);
7301 if (texpr is TypeParameterExpr){
7302 ((TypeParameterExpr)texpr).Error_CannotUseAsUnmanagedType (loc);
7306 type_queried = texpr.Type;
7308 int size_of = GetTypeSize (type_queried);
7310 return new IntConstant (size_of);
7314 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)",
7315 TypeManager.CSharpName (type_queried));
7319 CheckObsoleteAttribute (type_queried);
7321 if (!TypeManager.VerifyUnManaged (type_queried, loc)){
7325 type = TypeManager.int32_type;
7326 eclass = ExprClass.Value;
7330 public override void Emit (EmitContext ec)
7332 int size = GetTypeSize (type_queried);
7335 ec.ig.Emit (OpCodes.Sizeof, type_queried);
7337 IntConstant.EmitInt (ec.ig, size);
7342 /// Implements the member access expression
7344 public class MemberAccess : Expression {
7345 public string Identifier;
7346 protected Expression expr;
7347 protected TypeArguments args;
7349 public MemberAccess (Expression expr, string id, Location l)
7356 public MemberAccess (Expression expr, string id, TypeArguments args,
7358 : this (expr, id, l)
7363 public Expression Expr {
7369 Expression DoResolve (EmitContext ec, Expression right_side)
7372 throw new Exception ();
7375 // Resolve the expression with flow analysis turned off, we'll do the definite
7376 // assignment checks later. This is because we don't know yet what the expression
7377 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7378 // definite assignment check on the actual field and not on the whole struct.
7381 SimpleName original = expr as SimpleName;
7382 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type |
7383 ResolveFlags.Intermediate | ResolveFlags.DisableFlowAnalysis);
7388 if (expr is Namespace) {
7389 Namespace ns = (Namespace) expr;
7390 string lookup_id = MemberName.MakeName (Identifier, args);
7391 FullNamedExpression retval = ns.Lookup (ec.DeclSpace, lookup_id, loc);
7392 if ((retval != null) && (args != null))
7393 retval = new ConstructedType (retval, args, loc).ResolveAsTypeStep (ec);
7395 Report.Error (234, loc, "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
7396 Identifier, ns.FullName);
7401 // TODO: I mailed Ravi about this, and apparently we can get rid
7402 // of this and put it in the right place.
7404 // Handle enums here when they are in transit.
7405 // Note that we cannot afford to hit MemberLookup in this case because
7406 // it will fail to find any members at all
7410 if (expr is TypeExpr){
7411 expr_type = expr.Type;
7413 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
7414 ErrorIsInaccesible (loc, TypeManager.CSharpName (expr_type));
7418 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
7419 Enum en = TypeManager.LookupEnum (expr_type);
7422 object value = en.LookupEnumValue (Identifier, loc);
7425 MemberCore mc = en.GetDefinition (Identifier);
7426 ObsoleteAttribute oa = mc.GetObsoleteAttribute (en);
7428 AttributeTester.Report_ObsoleteMessage (oa, mc.GetSignatureForError (), Location);
7430 oa = en.GetObsoleteAttribute (en);
7432 AttributeTester.Report_ObsoleteMessage (oa, en.GetSignatureForError (), Location);
7435 Constant c = Constantify (value, en.UnderlyingType);
7436 return new EnumConstant (c, expr_type);
7439 CheckObsoleteAttribute (expr_type);
7441 FieldInfo fi = expr_type.GetField (Identifier);
7443 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
7445 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), Location);
7450 expr_type = expr.Type;
7452 if (expr_type.IsPointer){
7453 Error (23, "The `.' operator can not be applied to pointer operands (" +
7454 TypeManager.CSharpName (expr_type) + ")");
7458 Expression member_lookup;
7459 member_lookup = MemberLookup (
7460 ec, expr_type, expr_type, Identifier, loc);
7461 if ((member_lookup == null) && (args != null)) {
7462 string lookup_id = MemberName.MakeName (Identifier, args);
7463 member_lookup = MemberLookup (
7464 ec, expr_type, expr_type, lookup_id, loc);
7466 if (member_lookup == null) {
7467 MemberLookupFailed (
7468 ec, expr_type, expr_type, Identifier, null, true, loc);
7472 if (member_lookup is TypeExpr) {
7473 if (!(expr is TypeExpr) &&
7474 (original == null || !original.IdenticalNameAndTypeName (ec, expr, loc))) {
7475 Report.Error (572, loc, "`{0}': cannot reference a type through an expression; try `{1}' instead",
7476 Identifier, member_lookup.GetSignatureForError ());
7480 ConstructedType ct = expr as ConstructedType;
7483 // When looking up a nested type in a generic instance
7484 // via reflection, we always get a generic type definition
7485 // and not a generic instance - so we have to do this here.
7487 // See gtest-172-lib.cs and gtest-172.cs for an example.
7489 ct = new ConstructedType (
7490 member_lookup.Type, ct.TypeArguments, loc);
7492 return ct.ResolveAsTypeStep (ec);
7495 return member_lookup;
7498 MemberExpr me = (MemberExpr) member_lookup;
7499 member_lookup = me.ResolveMemberAccess (ec, expr, loc, original);
7500 if (member_lookup == null)
7504 MethodGroupExpr mg = member_lookup as MethodGroupExpr;
7506 throw new InternalErrorException ();
7508 return mg.ResolveGeneric (ec, args);
7511 // The following DoResolve/DoResolveLValue will do the definite assignment
7514 if (right_side != null)
7515 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
7517 member_lookup = member_lookup.DoResolve (ec);
7519 return member_lookup;
7522 public override Expression DoResolve (EmitContext ec)
7524 return DoResolve (ec, null);
7527 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7529 return DoResolve (ec, right_side);
7532 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
7534 return ResolveNamespaceOrType (ec, false);
7537 public FullNamedExpression ResolveNamespaceOrType (EmitContext ec, bool silent)
7539 FullNamedExpression new_expr = expr.ResolveAsTypeStep (ec);
7541 if (new_expr == null)
7544 string lookup_id = MemberName.MakeName (Identifier, args);
7546 if (new_expr is Namespace) {
7547 Namespace ns = (Namespace) new_expr;
7548 FullNamedExpression retval = ns.Lookup (ec.DeclSpace, lookup_id, loc);
7549 if ((retval != null) && (args != null))
7550 retval = new ConstructedType (retval, args, loc).ResolveAsTypeStep (ec);
7551 if (!silent && retval == null)
7552 Report.Error (234, loc, "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
7553 Identifier, ns.FullName);
7557 TypeExpr tnew_expr = new_expr.ResolveAsTypeTerminal (ec);
7558 if (tnew_expr == null)
7561 Type expr_type = tnew_expr.Type;
7563 if (expr_type.IsPointer){
7564 Error (23, "The `.' operator can not be applied to pointer operands (" +
7565 TypeManager.CSharpName (expr_type) + ")");
7569 Expression member_lookup = MemberLookup (ec, expr_type, expr_type, lookup_id, loc);
7570 if (member_lookup == null) {
7571 int errors = Report.Errors;
7572 MemberLookupFailed (ec, expr_type, expr_type, lookup_id, null, false, loc);
7574 if (!silent && errors == Report.Errors)
7575 Report.Error (234, loc, "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
7576 lookup_id, new_expr.FullName);
7580 if (!(member_lookup is TypeExpr)) {
7581 Report.Error (118, loc, "`{0}.{1}' denotes a `{2}', where a type was expected",
7582 new_expr.FullName, lookup_id, member_lookup.ExprClassName ());
7586 TypeExpr texpr = member_lookup.ResolveAsTypeTerminal (ec);
7590 TypeArguments the_args = args;
7591 if (TypeManager.HasGenericArguments (expr_type)) {
7592 Type[] decl_args = TypeManager.GetTypeArguments (expr_type);
7594 TypeArguments new_args = new TypeArguments (loc);
7595 foreach (Type decl in decl_args)
7596 new_args.Add (new TypeExpression (decl, loc));
7599 new_args.Add (args);
7601 the_args = new_args;
7604 if (the_args != null) {
7605 ConstructedType ctype = new ConstructedType (texpr.Type, the_args, loc);
7606 return ctype.ResolveAsTypeStep (ec);
7612 public override void Emit (EmitContext ec)
7614 throw new Exception ("Should not happen");
7617 public override string ToString ()
7619 return expr + "." + MemberName.MakeName (Identifier, args);
7624 /// Implements checked expressions
7626 public class CheckedExpr : Expression {
7628 public Expression Expr;
7630 public CheckedExpr (Expression e, Location l)
7636 public override Expression DoResolve (EmitContext ec)
7638 bool last_check = ec.CheckState;
7639 bool last_const_check = ec.ConstantCheckState;
7641 ec.CheckState = true;
7642 ec.ConstantCheckState = true;
7643 Expr = Expr.Resolve (ec);
7644 ec.CheckState = last_check;
7645 ec.ConstantCheckState = last_const_check;
7650 if (Expr is Constant)
7653 eclass = Expr.eclass;
7658 public override void Emit (EmitContext ec)
7660 bool last_check = ec.CheckState;
7661 bool last_const_check = ec.ConstantCheckState;
7663 ec.CheckState = true;
7664 ec.ConstantCheckState = true;
7666 ec.CheckState = last_check;
7667 ec.ConstantCheckState = last_const_check;
7673 /// Implements the unchecked expression
7675 public class UnCheckedExpr : Expression {
7677 public Expression Expr;
7679 public UnCheckedExpr (Expression e, Location l)
7685 public override Expression DoResolve (EmitContext ec)
7687 bool last_check = ec.CheckState;
7688 bool last_const_check = ec.ConstantCheckState;
7690 ec.CheckState = false;
7691 ec.ConstantCheckState = false;
7692 Expr = Expr.Resolve (ec);
7693 ec.CheckState = last_check;
7694 ec.ConstantCheckState = last_const_check;
7699 if (Expr is Constant)
7702 eclass = Expr.eclass;
7707 public override void Emit (EmitContext ec)
7709 bool last_check = ec.CheckState;
7710 bool last_const_check = ec.ConstantCheckState;
7712 ec.CheckState = false;
7713 ec.ConstantCheckState = false;
7715 ec.CheckState = last_check;
7716 ec.ConstantCheckState = last_const_check;
7722 /// An Element Access expression.
7724 /// During semantic analysis these are transformed into
7725 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7727 public class ElementAccess : Expression {
7728 public ArrayList Arguments;
7729 public Expression Expr;
7731 public ElementAccess (Expression e, ArrayList e_list, Location l)
7740 Arguments = new ArrayList ();
7741 foreach (Expression tmp in e_list)
7742 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7746 bool CommonResolve (EmitContext ec)
7748 Expr = Expr.Resolve (ec);
7753 if (Arguments == null)
7756 foreach (Argument a in Arguments){
7757 if (!a.Resolve (ec, loc))
7764 Expression MakePointerAccess (EmitContext ec, Type t)
7766 if (t == TypeManager.void_ptr_type){
7767 Error (242, "The array index operation is not valid on void pointers");
7770 if (Arguments.Count != 1){
7771 Error (196, "A pointer must be indexed by only one value");
7776 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc).Resolve (ec);
7779 return new Indirection (p, loc).Resolve (ec);
7782 public override Expression DoResolve (EmitContext ec)
7784 if (!CommonResolve (ec))
7788 // We perform some simple tests, and then to "split" the emit and store
7789 // code we create an instance of a different class, and return that.
7791 // I am experimenting with this pattern.
7795 if (t == TypeManager.array_type){
7796 Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `System.Array'");
7801 return (new ArrayAccess (this, loc)).Resolve (ec);
7803 return MakePointerAccess (ec, Expr.Type);
7805 FieldExpr fe = Expr as FieldExpr;
7807 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
7809 return MakePointerAccess (ec, ff.ElementType);
7812 return (new IndexerAccess (this, loc)).Resolve (ec);
7815 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7817 if (!CommonResolve (ec))
7822 return (new ArrayAccess (this, loc)).DoResolveLValue (ec, right_side);
7825 return MakePointerAccess (ec, Expr.Type);
7827 FieldExpr fe = Expr as FieldExpr;
7829 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
7831 if (!(fe.InstanceExpression is LocalVariableReference) &&
7832 !(fe.InstanceExpression is This)) {
7833 Report.Error (1708, loc, "Fixed size buffers can only be accessed through locals or fields");
7836 // TODO: not sure whether it is correct
7837 // if (!ec.InFixedInitializer) {
7838 // Error (1666, "You cannot use fixed sized buffers contained in unfixed expressions. Try using the fixed statement");
7841 return MakePointerAccess (ec, ff.ElementType);
7844 return (new IndexerAccess (this, loc)).DoResolveLValue (ec, right_side);
7847 public override void Emit (EmitContext ec)
7849 throw new Exception ("Should never be reached");
7854 /// Implements array access
7856 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7858 // Points to our "data" repository
7862 LocalTemporary temp;
7865 public ArrayAccess (ElementAccess ea_data, Location l)
7868 eclass = ExprClass.Variable;
7872 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7874 return DoResolve (ec);
7877 public override Expression DoResolve (EmitContext ec)
7880 ExprClass eclass = ea.Expr.eclass;
7882 // As long as the type is valid
7883 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7884 eclass == ExprClass.Value)) {
7885 ea.Expr.Error_UnexpectedKind ("variable or value");
7890 Type t = ea.Expr.Type;
7891 if (t.GetArrayRank () != ea.Arguments.Count){
7892 Report.Error (22, ea.Location, "Wrong number of indexes `{0}' inside [], expected `{1}'",
7893 ea.Arguments.Count, t.GetArrayRank ());
7897 type = TypeManager.GetElementType (t);
7898 if (type.IsPointer && !ec.InUnsafe){
7899 UnsafeError (ea.Location);
7903 foreach (Argument a in ea.Arguments){
7904 Type argtype = a.Type;
7906 if (argtype == TypeManager.int32_type ||
7907 argtype == TypeManager.uint32_type ||
7908 argtype == TypeManager.int64_type ||
7909 argtype == TypeManager.uint64_type) {
7910 Constant c = a.Expr as Constant;
7911 if (c != null && c.IsNegative) {
7912 Report.Warning (251, 2, ea.Location, "Indexing an array with a negative index (array indices always start at zero)");
7918 // Mhm. This is strage, because the Argument.Type is not the same as
7919 // Argument.Expr.Type: the value changes depending on the ref/out setting.
7921 // Wonder if I will run into trouble for this.
7923 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
7928 eclass = ExprClass.Variable;
7934 /// Emits the right opcode to load an object of Type `t'
7935 /// from an array of T
7937 static public void EmitLoadOpcode (ILGenerator ig, Type type)
7939 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7940 ig.Emit (OpCodes.Ldelem_U1);
7941 else if (type == TypeManager.sbyte_type)
7942 ig.Emit (OpCodes.Ldelem_I1);
7943 else if (type == TypeManager.short_type)
7944 ig.Emit (OpCodes.Ldelem_I2);
7945 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7946 ig.Emit (OpCodes.Ldelem_U2);
7947 else if (type == TypeManager.int32_type)
7948 ig.Emit (OpCodes.Ldelem_I4);
7949 else if (type == TypeManager.uint32_type)
7950 ig.Emit (OpCodes.Ldelem_U4);
7951 else if (type == TypeManager.uint64_type)
7952 ig.Emit (OpCodes.Ldelem_I8);
7953 else if (type == TypeManager.int64_type)
7954 ig.Emit (OpCodes.Ldelem_I8);
7955 else if (type == TypeManager.float_type)
7956 ig.Emit (OpCodes.Ldelem_R4);
7957 else if (type == TypeManager.double_type)
7958 ig.Emit (OpCodes.Ldelem_R8);
7959 else if (type == TypeManager.intptr_type)
7960 ig.Emit (OpCodes.Ldelem_I);
7961 else if (TypeManager.IsEnumType (type)){
7962 EmitLoadOpcode (ig, TypeManager.EnumToUnderlying (type));
7963 } else if (type.IsValueType){
7964 ig.Emit (OpCodes.Ldelema, type);
7965 ig.Emit (OpCodes.Ldobj, type);
7966 } else if (type.IsGenericParameter)
7967 ig.Emit (OpCodes.Ldelem_Any, type);
7969 ig.Emit (OpCodes.Ldelem_Ref);
7973 /// Returns the right opcode to store an object of Type `t'
7974 /// from an array of T.
7976 static public OpCode GetStoreOpcode (Type t, out bool is_stobj, out bool has_type_arg)
7978 //Console.WriteLine (new System.Diagnostics.StackTrace ());
7979 has_type_arg = false; is_stobj = false;
7980 t = TypeManager.TypeToCoreType (t);
7981 if (TypeManager.IsEnumType (t))
7982 t = TypeManager.EnumToUnderlying (t);
7983 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
7984 t == TypeManager.bool_type)
7985 return OpCodes.Stelem_I1;
7986 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
7987 t == TypeManager.char_type)
7988 return OpCodes.Stelem_I2;
7989 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
7990 return OpCodes.Stelem_I4;
7991 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
7992 return OpCodes.Stelem_I8;
7993 else if (t == TypeManager.float_type)
7994 return OpCodes.Stelem_R4;
7995 else if (t == TypeManager.double_type)
7996 return OpCodes.Stelem_R8;
7997 else if (t == TypeManager.intptr_type) {
7998 has_type_arg = true;
8000 return OpCodes.Stobj;
8001 } else if (t.IsValueType) {
8002 has_type_arg = true;
8004 return OpCodes.Stobj;
8005 } else if (t.IsGenericParameter) {
8006 has_type_arg = true;
8007 return OpCodes.Stelem_Any;
8009 return OpCodes.Stelem_Ref;
8012 MethodInfo FetchGetMethod ()
8014 ModuleBuilder mb = CodeGen.Module.Builder;
8015 int arg_count = ea.Arguments.Count;
8016 Type [] args = new Type [arg_count];
8019 for (int i = 0; i < arg_count; i++){
8020 //args [i++] = a.Type;
8021 args [i] = TypeManager.int32_type;
8024 get = mb.GetArrayMethod (
8025 ea.Expr.Type, "Get",
8026 CallingConventions.HasThis |
8027 CallingConventions.Standard,
8033 MethodInfo FetchAddressMethod ()
8035 ModuleBuilder mb = CodeGen.Module.Builder;
8036 int arg_count = ea.Arguments.Count;
8037 Type [] args = new Type [arg_count];
8041 ret_type = TypeManager.GetReferenceType (type);
8043 for (int i = 0; i < arg_count; i++){
8044 //args [i++] = a.Type;
8045 args [i] = TypeManager.int32_type;
8048 address = mb.GetArrayMethod (
8049 ea.Expr.Type, "Address",
8050 CallingConventions.HasThis |
8051 CallingConventions.Standard,
8058 // Load the array arguments into the stack.
8060 // If we have been requested to cache the values (cached_locations array
8061 // initialized), then load the arguments the first time and store them
8062 // in locals. otherwise load from local variables.
8064 void LoadArrayAndArguments (EmitContext ec)
8066 ILGenerator ig = ec.ig;
8069 foreach (Argument a in ea.Arguments){
8070 Type argtype = a.Expr.Type;
8074 if (argtype == TypeManager.int64_type)
8075 ig.Emit (OpCodes.Conv_Ovf_I);
8076 else if (argtype == TypeManager.uint64_type)
8077 ig.Emit (OpCodes.Conv_Ovf_I_Un);
8081 public void Emit (EmitContext ec, bool leave_copy)
8083 int rank = ea.Expr.Type.GetArrayRank ();
8084 ILGenerator ig = ec.ig;
8087 LoadArrayAndArguments (ec);
8090 EmitLoadOpcode (ig, type);
8094 method = FetchGetMethod ();
8095 ig.Emit (OpCodes.Call, method);
8098 LoadFromPtr (ec.ig, this.type);
8101 ec.ig.Emit (OpCodes.Dup);
8102 temp = new LocalTemporary (ec, this.type);
8107 public override void Emit (EmitContext ec)
8112 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8114 int rank = ea.Expr.Type.GetArrayRank ();
8115 ILGenerator ig = ec.ig;
8116 Type t = source.Type;
8117 prepared = prepare_for_load;
8119 if (prepare_for_load) {
8120 AddressOf (ec, AddressOp.LoadStore);
8121 ec.ig.Emit (OpCodes.Dup);
8124 ec.ig.Emit (OpCodes.Dup);
8125 temp = new LocalTemporary (ec, this.type);
8128 StoreFromPtr (ec.ig, t);
8136 LoadArrayAndArguments (ec);
8139 bool is_stobj, has_type_arg;
8140 OpCode op = GetStoreOpcode (t, out is_stobj, out has_type_arg);
8143 // The stobj opcode used by value types will need
8144 // an address on the stack, not really an array/array
8148 ig.Emit (OpCodes.Ldelema, t);
8152 ec.ig.Emit (OpCodes.Dup);
8153 temp = new LocalTemporary (ec, this.type);
8158 ig.Emit (OpCodes.Stobj, t);
8159 else if (has_type_arg)
8164 ModuleBuilder mb = CodeGen.Module.Builder;
8165 int arg_count = ea.Arguments.Count;
8166 Type [] args = new Type [arg_count + 1];
8171 ec.ig.Emit (OpCodes.Dup);
8172 temp = new LocalTemporary (ec, this.type);
8176 for (int i = 0; i < arg_count; i++){
8177 //args [i++] = a.Type;
8178 args [i] = TypeManager.int32_type;
8181 args [arg_count] = type;
8183 set = mb.GetArrayMethod (
8184 ea.Expr.Type, "Set",
8185 CallingConventions.HasThis |
8186 CallingConventions.Standard,
8187 TypeManager.void_type, args);
8189 ig.Emit (OpCodes.Call, set);
8196 public void AddressOf (EmitContext ec, AddressOp mode)
8198 int rank = ea.Expr.Type.GetArrayRank ();
8199 ILGenerator ig = ec.ig;
8201 LoadArrayAndArguments (ec);
8204 ig.Emit (OpCodes.Ldelema, type);
8206 MethodInfo address = FetchAddressMethod ();
8207 ig.Emit (OpCodes.Call, address);
8211 public void EmitGetLength (EmitContext ec, int dim)
8213 int rank = ea.Expr.Type.GetArrayRank ();
8214 ILGenerator ig = ec.ig;
8218 ig.Emit (OpCodes.Ldlen);
8219 ig.Emit (OpCodes.Conv_I4);
8221 IntLiteral.EmitInt (ig, dim);
8222 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
8228 // note that the ArrayList itself in mutable. We just can't assign to 'Properties' again.
8229 public readonly ArrayList Properties;
8230 static Indexers empty;
8232 public struct Indexer {
8233 public readonly PropertyInfo PropertyInfo;
8234 public readonly MethodInfo Getter, Setter;
8236 public Indexer (PropertyInfo property_info, MethodInfo get, MethodInfo set)
8238 this.PropertyInfo = property_info;
8246 empty = new Indexers (null);
8249 Indexers (ArrayList array)
8254 static void Append (ref Indexers ix, Type caller_type, MemberInfo [] mi)
8259 foreach (PropertyInfo property in mi){
8260 MethodInfo get, set;
8262 get = property.GetGetMethod (true);
8263 set = property.GetSetMethod (true);
8264 if (get != null && !Expression.IsAccessorAccessible (caller_type, get, out dummy))
8266 if (set != null && !Expression.IsAccessorAccessible (caller_type, set, out dummy))
8268 if (get != null || set != null) {
8270 ix = new Indexers (new ArrayList ());
8271 ix.Properties.Add (new Indexer (property, get, set));
8276 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
8278 string p_name = TypeManager.IndexerPropertyName (lookup_type);
8280 return TypeManager.MemberLookup (
8281 caller_type, caller_type, lookup_type, MemberTypes.Property,
8282 BindingFlags.Public | BindingFlags.Instance |
8283 BindingFlags.DeclaredOnly, p_name, null);
8286 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
8288 Indexers ix = empty;
8290 Type copy = lookup_type;
8291 while (copy != TypeManager.object_type && copy != null){
8292 Append (ref ix, caller_type, GetIndexersForTypeOrInterface (caller_type, copy));
8293 copy = copy.BaseType;
8296 if (lookup_type.IsInterface) {
8297 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
8298 if (ifaces != null) {
8299 foreach (Type itype in ifaces)
8300 Append (ref ix, caller_type, GetIndexersForTypeOrInterface (caller_type, itype));
8309 /// Expressions that represent an indexer call.
8311 public class IndexerAccess : Expression, IAssignMethod {
8313 // Points to our "data" repository
8315 MethodInfo get, set;
8316 ArrayList set_arguments;
8317 bool is_base_indexer;
8319 protected Type indexer_type;
8320 protected Type current_type;
8321 protected Expression instance_expr;
8322 protected ArrayList arguments;
8324 public IndexerAccess (ElementAccess ea, Location loc)
8325 : this (ea.Expr, false, loc)
8327 this.arguments = ea.Arguments;
8330 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
8333 this.instance_expr = instance_expr;
8334 this.is_base_indexer = is_base_indexer;
8335 this.eclass = ExprClass.Value;
8339 protected virtual bool CommonResolve (EmitContext ec)
8341 indexer_type = instance_expr.Type;
8342 current_type = ec.ContainerType;
8347 public override Expression DoResolve (EmitContext ec)
8349 ArrayList AllGetters = new ArrayList();
8350 if (!CommonResolve (ec))
8354 // Step 1: Query for all `Item' *properties*. Notice
8355 // that the actual methods are pointed from here.
8357 // This is a group of properties, piles of them.
8359 bool found_any = false, found_any_getters = false;
8360 Type lookup_type = indexer_type;
8362 Indexers ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
8363 if (ilist.Properties != null) {
8365 foreach (Indexers.Indexer ix in ilist.Properties) {
8366 if (ix.Getter != null)
8367 AllGetters.Add (ix.Getter);
8371 if (AllGetters.Count > 0) {
8372 found_any_getters = true;
8373 get = (MethodInfo) Invocation.OverloadResolve (
8374 ec, new MethodGroupExpr (AllGetters, loc),
8375 arguments, false, loc);
8379 Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
8380 TypeManager.CSharpName (indexer_type));
8384 if (!found_any_getters) {
8385 Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
8391 Invocation.Error_WrongNumArguments (loc, "this", arguments.Count);
8396 // Only base will allow this invocation to happen.
8398 if (get.IsAbstract && this is BaseIndexerAccess){
8399 Error_CannotCallAbstractBase (TypeManager.CSharpSignature (get));
8403 type = get.ReturnType;
8404 if (type.IsPointer && !ec.InUnsafe){
8409 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8411 eclass = ExprClass.IndexerAccess;
8415 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8417 ArrayList AllSetters = new ArrayList();
8418 if (!CommonResolve (ec))
8421 bool found_any = false, found_any_setters = false;
8423 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
8424 if (ilist.Properties != null) {
8426 foreach (Indexers.Indexer ix in ilist.Properties) {
8427 if (ix.Setter != null)
8428 AllSetters.Add (ix.Setter);
8431 if (AllSetters.Count > 0) {
8432 found_any_setters = true;
8433 set_arguments = (ArrayList) arguments.Clone ();
8434 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
8435 set = (MethodInfo) Invocation.OverloadResolve (
8436 ec, new MethodGroupExpr (AllSetters, loc),
8437 set_arguments, false, loc);
8441 Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
8442 TypeManager.CSharpName (indexer_type));
8446 if (!found_any_setters) {
8447 Error (154, "indexer can not be used in this context, because " +
8448 "it lacks a `set' accessor");
8453 Invocation.Error_WrongNumArguments (loc, "this", arguments.Count);
8458 // Only base will allow this invocation to happen.
8460 if (set.IsAbstract && this is BaseIndexerAccess){
8461 Error_CannotCallAbstractBase (TypeManager.CSharpSignature (set));
8466 // Now look for the actual match in the list of indexers to set our "return" type
8468 type = TypeManager.void_type; // default value
8469 foreach (Indexers.Indexer ix in ilist.Properties){
8470 if (ix.Setter == set){
8471 type = ix.PropertyInfo.PropertyType;
8476 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8478 eclass = ExprClass.IndexerAccess;
8482 bool prepared = false;
8483 LocalTemporary temp;
8485 public void Emit (EmitContext ec, bool leave_copy)
8487 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc, prepared, false);
8489 ec.ig.Emit (OpCodes.Dup);
8490 temp = new LocalTemporary (ec, Type);
8496 // source is ignored, because we already have a copy of it from the
8497 // LValue resolution and we have already constructed a pre-cached
8498 // version of the arguments (ea.set_arguments);
8500 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8502 prepared = prepare_for_load;
8503 Argument a = (Argument) set_arguments [set_arguments.Count - 1];
8508 ec.ig.Emit (OpCodes.Dup);
8509 temp = new LocalTemporary (ec, Type);
8512 } else if (leave_copy) {
8513 temp = new LocalTemporary (ec, Type);
8519 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc, false, prepared);
8526 public override void Emit (EmitContext ec)
8533 /// The base operator for method names
8535 public class BaseAccess : Expression {
8538 public BaseAccess (string member, Location l)
8540 this.member = member;
8544 public override Expression DoResolve (EmitContext ec)
8546 Expression c = CommonResolve (ec);
8552 // MethodGroups use this opportunity to flag an error on lacking ()
8554 if (!(c is MethodGroupExpr))
8555 return c.Resolve (ec);
8559 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8561 Expression c = CommonResolve (ec);
8567 // MethodGroups use this opportunity to flag an error on lacking ()
8569 if (! (c is MethodGroupExpr))
8570 return c.DoResolveLValue (ec, right_side);
8575 Expression CommonResolve (EmitContext ec)
8577 Expression member_lookup;
8578 Type current_type = ec.ContainerType;
8579 Type base_type = current_type.BaseType;
8582 Error (1511, "Keyword `base' is not available in a static method");
8586 if (ec.IsFieldInitializer){
8587 Error (1512, "Keyword `base' is not available in the current context");
8591 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type,
8592 member, AllMemberTypes, AllBindingFlags,
8594 if (member_lookup == null) {
8595 MemberLookupFailed (ec, base_type, base_type, member, null, true, loc);
8602 left = new TypeExpression (base_type, loc);
8604 left = ec.GetThis (loc);
8606 MemberExpr me = (MemberExpr) member_lookup;
8608 Expression e = me.ResolveMemberAccess (ec, left, loc, null);
8610 if (e is PropertyExpr) {
8611 PropertyExpr pe = (PropertyExpr) e;
8616 if (e is MethodGroupExpr)
8617 ((MethodGroupExpr) e).IsBase = true;
8622 public override void Emit (EmitContext ec)
8624 throw new Exception ("Should never be called");
8629 /// The base indexer operator
8631 public class BaseIndexerAccess : IndexerAccess {
8632 public BaseIndexerAccess (ArrayList args, Location loc)
8633 : base (null, true, loc)
8635 arguments = new ArrayList ();
8636 foreach (Expression tmp in args)
8637 arguments.Add (new Argument (tmp, Argument.AType.Expression));
8640 protected override bool CommonResolve (EmitContext ec)
8642 instance_expr = ec.GetThis (loc);
8644 current_type = ec.ContainerType.BaseType;
8645 indexer_type = current_type;
8647 foreach (Argument a in arguments){
8648 if (!a.Resolve (ec, loc))
8657 /// This class exists solely to pass the Type around and to be a dummy
8658 /// that can be passed to the conversion functions (this is used by
8659 /// foreach implementation to typecast the object return value from
8660 /// get_Current into the proper type. All code has been generated and
8661 /// we only care about the side effect conversions to be performed
8663 /// This is also now used as a placeholder where a no-action expression
8664 /// is needed (the `New' class).
8666 public class EmptyExpression : Expression {
8667 public static readonly EmptyExpression Null = new EmptyExpression ();
8669 static EmptyExpression temp = new EmptyExpression ();
8670 public static EmptyExpression Grab ()
8673 throw new InternalErrorException ("Nested Grab");
8674 EmptyExpression retval = temp;
8679 public static void Release (EmptyExpression e)
8682 throw new InternalErrorException ("Already released");
8686 // TODO: should be protected
8687 public EmptyExpression ()
8689 type = TypeManager.object_type;
8690 eclass = ExprClass.Value;
8691 loc = Location.Null;
8694 public EmptyExpression (Type t)
8697 eclass = ExprClass.Value;
8698 loc = Location.Null;
8701 public override Expression DoResolve (EmitContext ec)
8706 public override void Emit (EmitContext ec)
8708 // nothing, as we only exist to not do anything.
8712 // This is just because we might want to reuse this bad boy
8713 // instead of creating gazillions of EmptyExpressions.
8714 // (CanImplicitConversion uses it)
8716 public void SetType (Type t)
8722 public class UserCast : Expression {
8726 public UserCast (MethodInfo method, Expression source, Location l)
8728 this.method = method;
8729 this.source = source;
8730 type = method.ReturnType;
8731 eclass = ExprClass.Value;
8735 public Expression Source {
8741 public override Expression DoResolve (EmitContext ec)
8744 // We are born fully resolved
8749 public override void Emit (EmitContext ec)
8751 ILGenerator ig = ec.ig;
8755 if (method is MethodInfo)
8756 ig.Emit (OpCodes.Call, (MethodInfo) method);
8758 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
8764 // This class is used to "construct" the type during a typecast
8765 // operation. Since the Type.GetType class in .NET can parse
8766 // the type specification, we just use this to construct the type
8767 // one bit at a time.
8769 public class ComposedCast : TypeExpr {
8773 public ComposedCast (Expression left, string dim, Location l)
8780 public Expression RemoveNullable ()
8782 if (dim.EndsWith ("?")) {
8783 dim = dim.Substring (0, dim.Length - 1);
8791 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
8793 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec);
8797 Type ltype = lexpr.Type;
8799 if ((ltype == TypeManager.void_type) && (dim != "*")) {
8800 Report.Error (1547, Location,
8801 "Keyword 'void' cannot be used in this context");
8805 if ((dim.Length > 0) && (dim [0] == '?')) {
8806 TypeExpr nullable = new NullableType (left, loc);
8808 nullable = new ComposedCast (nullable, dim.Substring (1), loc);
8809 return nullable.ResolveAsTypeTerminal (ec);
8812 if (dim == "*" && !TypeManager.VerifyUnManaged (ltype, loc)) {
8817 type = TypeManager.GetConstructedType (ltype, dim);
8822 throw new InternalErrorException ("Couldn't create computed type " + ltype + dim);
8825 if (!ec.InUnsafe && type.IsPointer){
8830 if (type.IsArray && (type.GetElementType () == TypeManager.arg_iterator_type ||
8831 type.GetElementType () == TypeManager.typed_reference_type)) {
8832 Report.Error (611, loc, "Array elements cannot be of type `{0}'", TypeManager.CSharpName (type.GetElementType ()));
8836 eclass = ExprClass.Type;
8840 public override string Name {
8846 public override string FullName {
8848 return type.FullName;
8853 public class FixedBufferPtr: Expression {
8856 public FixedBufferPtr (Expression array, Type array_type, Location l)
8861 type = TypeManager.GetPointerType (array_type);
8862 eclass = ExprClass.Value;
8865 public override void Emit(EmitContext ec)
8870 public override Expression DoResolve (EmitContext ec)
8873 // We are born fully resolved
8881 // This class is used to represent the address of an array, used
8882 // only by the Fixed statement, this generates "&a [0]" construct
8883 // for fixed (char *pa = a)
8885 public class ArrayPtr : FixedBufferPtr {
8888 public ArrayPtr (Expression array, Type array_type, Location l):
8889 base (array, array_type, l)
8891 this.array_type = array_type;
8894 public override void Emit (EmitContext ec)
8898 ILGenerator ig = ec.ig;
8899 IntLiteral.EmitInt (ig, 0);
8900 ig.Emit (OpCodes.Ldelema, array_type);
8905 // Used by the fixed statement
8907 public class StringPtr : Expression {
8910 public StringPtr (LocalBuilder b, Location l)
8913 eclass = ExprClass.Value;
8914 type = TypeManager.char_ptr_type;
8918 public override Expression DoResolve (EmitContext ec)
8920 // This should never be invoked, we are born in fully
8921 // initialized state.
8926 public override void Emit (EmitContext ec)
8928 ILGenerator ig = ec.ig;
8930 ig.Emit (OpCodes.Ldloc, b);
8931 ig.Emit (OpCodes.Conv_I);
8932 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
8933 ig.Emit (OpCodes.Add);
8938 // Implements the `stackalloc' keyword
8940 public class StackAlloc : Expression {
8945 public StackAlloc (Expression type, Expression count, Location l)
8952 public override Expression DoResolve (EmitContext ec)
8954 count = count.Resolve (ec);
8958 if (count.Type != TypeManager.int32_type){
8959 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8964 Constant c = count as Constant;
8965 if (c != null && c.IsNegative) {
8966 Report.Error (247, loc, "Cannot use a negative size with stackalloc");
8970 if (ec.InCatch || ec.InFinally) {
8971 Error (255, "Cannot use stackalloc in finally or catch");
8975 TypeExpr texpr = t.ResolveAsTypeTerminal (ec);
8981 if (!TypeManager.VerifyUnManaged (otype, loc))
8984 type = TypeManager.GetPointerType (otype);
8985 eclass = ExprClass.Value;
8990 public override void Emit (EmitContext ec)
8992 int size = GetTypeSize (otype);
8993 ILGenerator ig = ec.ig;
8996 ig.Emit (OpCodes.Sizeof, otype);
8998 IntConstant.EmitInt (ig, size);
9000 ig.Emit (OpCodes.Mul);
9001 ig.Emit (OpCodes.Localloc);