2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
8 // (C) 2003, 2004 Novell, Inc.
12 namespace Mono.CSharp {
14 using System.Collections;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// This is just a helper class, it is generated by Unary, UnaryMutator
21 /// when an overloaded method has been found. It just emits the code for a
24 public class StaticCallExpr : ExpressionStatement {
28 public StaticCallExpr (MethodInfo m, ArrayList a, Location l)
34 eclass = ExprClass.Value;
38 public override Expression DoResolve (EmitContext ec)
41 // We are born fully resolved
46 public override void Emit (EmitContext ec)
49 Invocation.EmitArguments (ec, mi, args, false, null);
51 ec.ig.Emit (OpCodes.Call, mi);
55 static public StaticCallExpr MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
56 Expression e, Location loc)
61 args = new ArrayList (1);
62 Argument a = new Argument (e, Argument.AType.Expression);
64 // We need to resolve the arguments before sending them in !
65 if (!a.Resolve (ec, loc))
69 method = Invocation.OverloadResolve (
70 ec, (MethodGroupExpr) mg, args, false, loc);
75 return new StaticCallExpr ((MethodInfo) method, args, loc);
78 public override void EmitStatement (EmitContext ec)
81 if (TypeManager.TypeToCoreType (type) != TypeManager.void_type)
82 ec.ig.Emit (OpCodes.Pop);
85 public MethodInfo Method {
90 public class ParenthesizedExpression : Expression
92 public Expression Expr;
94 public ParenthesizedExpression (Expression expr, Location loc)
100 public override Expression DoResolve (EmitContext ec)
102 Expr = Expr.Resolve (ec);
106 public override void Emit (EmitContext ec)
108 throw new Exception ("Should not happen");
113 /// Unary expressions.
117 /// Unary implements unary expressions. It derives from
118 /// ExpressionStatement becuase the pre/post increment/decrement
119 /// operators can be used in a statement context.
121 public class Unary : Expression {
122 public enum Operator : byte {
123 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
124 Indirection, AddressOf, TOP
127 public Operator Oper;
128 public Expression Expr;
130 public Unary (Operator op, Expression expr, Location loc)
138 /// Returns a stringified representation of the Operator
140 static public string OperName (Operator oper)
143 case Operator.UnaryPlus:
145 case Operator.UnaryNegation:
147 case Operator.LogicalNot:
149 case Operator.OnesComplement:
151 case Operator.AddressOf:
153 case Operator.Indirection:
157 return oper.ToString ();
160 public static readonly string [] oper_names;
164 oper_names = new string [(int)Operator.TOP];
166 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
167 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
168 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
169 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
170 oper_names [(int) Operator.Indirection] = "op_Indirection";
171 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
174 void Error23 (Type t)
177 23, "Operator " + OperName (Oper) +
178 " cannot be applied to operand of type `" +
179 TypeManager.CSharpName (t) + "'");
183 /// The result has been already resolved:
185 /// FIXME: a minus constant -128 sbyte cant be turned into a
188 static Expression TryReduceNegative (Constant expr)
192 if (expr is IntConstant)
193 e = new IntConstant (-((IntConstant) expr).Value);
194 else if (expr is UIntConstant){
195 uint value = ((UIntConstant) expr).Value;
197 if (value < 2147483649)
198 return new IntConstant (-(int)value);
200 e = new LongConstant (-value);
202 else if (expr is LongConstant)
203 e = new LongConstant (-((LongConstant) expr).Value);
204 else if (expr is ULongConstant){
205 ulong value = ((ULongConstant) expr).Value;
207 if (value < 9223372036854775809)
208 return new LongConstant(-(long)value);
210 else if (expr is FloatConstant)
211 e = new FloatConstant (-((FloatConstant) expr).Value);
212 else if (expr is DoubleConstant)
213 e = new DoubleConstant (-((DoubleConstant) expr).Value);
214 else if (expr is DecimalConstant)
215 e = new DecimalConstant (-((DecimalConstant) expr).Value);
216 else if (expr is ShortConstant)
217 e = new IntConstant (-((ShortConstant) expr).Value);
218 else if (expr is UShortConstant)
219 e = new IntConstant (-((UShortConstant) expr).Value);
220 else if (expr is SByteConstant)
221 e = new IntConstant (-((SByteConstant) expr).Value);
222 else if (expr is ByteConstant)
223 e = new IntConstant (-((ByteConstant) expr).Value);
228 // This routine will attempt to simplify the unary expression when the
229 // argument is a constant. The result is returned in `result' and the
230 // function returns true or false depending on whether a reduction
231 // was performed or not
233 bool Reduce (EmitContext ec, Constant e, out Expression result)
235 Type expr_type = e.Type;
238 case Operator.UnaryPlus:
242 case Operator.UnaryNegation:
243 result = TryReduceNegative (e);
244 return result != null;
246 case Operator.LogicalNot:
247 if (expr_type != TypeManager.bool_type) {
253 BoolConstant b = (BoolConstant) e;
254 result = new BoolConstant (!(b.Value));
257 case Operator.OnesComplement:
258 if (!((expr_type == TypeManager.int32_type) ||
259 (expr_type == TypeManager.uint32_type) ||
260 (expr_type == TypeManager.int64_type) ||
261 (expr_type == TypeManager.uint64_type) ||
262 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
265 if (Convert.ImplicitConversionExists (ec, e, TypeManager.int32_type)){
266 result = new Cast (new TypeExpression (TypeManager.int32_type, loc), e, loc);
267 result = result.Resolve (ec);
268 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint32_type)){
269 result = new Cast (new TypeExpression (TypeManager.uint32_type, loc), e, loc);
270 result = result.Resolve (ec);
271 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.int64_type)){
272 result = new Cast (new TypeExpression (TypeManager.int64_type, loc), e, loc);
273 result = result.Resolve (ec);
274 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint64_type)){
275 result = new Cast (new TypeExpression (TypeManager.uint64_type, loc), e, loc);
276 result = result.Resolve (ec);
279 if (result == null || !(result is Constant)){
285 expr_type = result.Type;
286 e = (Constant) result;
289 if (e is EnumConstant){
290 EnumConstant enum_constant = (EnumConstant) e;
293 if (Reduce (ec, enum_constant.Child, out reduced)){
294 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
302 if (expr_type == TypeManager.int32_type){
303 result = new IntConstant (~ ((IntConstant) e).Value);
304 } else if (expr_type == TypeManager.uint32_type){
305 result = new UIntConstant (~ ((UIntConstant) e).Value);
306 } else if (expr_type == TypeManager.int64_type){
307 result = new LongConstant (~ ((LongConstant) e).Value);
308 } else if (expr_type == TypeManager.uint64_type){
309 result = new ULongConstant (~ ((ULongConstant) e).Value);
317 case Operator.AddressOf:
321 case Operator.Indirection:
325 throw new Exception ("Can not constant fold: " + Oper.ToString());
328 Expression ResolveOperator (EmitContext ec)
331 // Step 1: Default operations on CLI native types.
334 // Attempt to use a constant folding operation.
335 if (Expr is Constant){
338 if (Reduce (ec, (Constant) Expr, out result))
343 // Step 2: Perform Operator Overload location
345 Type expr_type = Expr.Type;
349 op_name = oper_names [(int) Oper];
351 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
354 Expression e = StaticCallExpr.MakeSimpleCall (
355 ec, (MethodGroupExpr) mg, Expr, loc);
365 // Only perform numeric promotions on:
368 if (expr_type == null)
372 case Operator.LogicalNot:
373 if (expr_type != TypeManager.bool_type) {
374 Expr = ResolveBoolean (ec, Expr, loc);
381 type = TypeManager.bool_type;
384 case Operator.OnesComplement:
385 if (!((expr_type == TypeManager.int32_type) ||
386 (expr_type == TypeManager.uint32_type) ||
387 (expr_type == TypeManager.int64_type) ||
388 (expr_type == TypeManager.uint64_type) ||
389 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
392 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
394 type = TypeManager.int32_type;
397 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint32_type, loc);
399 type = TypeManager.uint32_type;
402 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
404 type = TypeManager.int64_type;
407 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint64_type, loc);
409 type = TypeManager.uint64_type;
418 case Operator.AddressOf:
419 if (Expr.eclass != ExprClass.Variable){
420 Error (211, "Cannot take the address of non-variables");
429 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
433 IVariable variable = Expr as IVariable;
434 bool is_fixed = variable != null && variable.VerifyFixed (false);
436 if (!ec.InFixedInitializer && !is_fixed) {
437 Error (212, "You can only take the address of an unfixed expression inside " +
438 "of a fixed statement initializer");
442 if (ec.InFixedInitializer && is_fixed) {
443 Error (213, "You can not fix an already fixed expression");
447 LocalVariableReference lr = Expr as LocalVariableReference;
449 if (lr.local_info.IsCaptured){
450 AnonymousMethod.Error_AddressOfCapturedVar (lr.Name, loc);
453 lr.local_info.AddressTaken = true;
454 lr.local_info.Used = true;
457 // According to the specs, a variable is considered definitely assigned if you take
459 if ((variable != null) && (variable.VariableInfo != null))
460 variable.VariableInfo.SetAssigned (ec);
462 type = TypeManager.GetPointerType (Expr.Type);
465 case Operator.Indirection:
471 if (!expr_type.IsPointer){
472 Error (193, "The * or -> operator can only be applied to pointers");
477 // We create an Indirection expression, because
478 // it can implement the IMemoryLocation.
480 return new Indirection (Expr, loc);
482 case Operator.UnaryPlus:
484 // A plus in front of something is just a no-op, so return the child.
488 case Operator.UnaryNegation:
490 // Deals with -literals
491 // int operator- (int x)
492 // long operator- (long x)
493 // float operator- (float f)
494 // double operator- (double d)
495 // decimal operator- (decimal d)
497 Expression expr = null;
500 // transform - - expr into expr
503 Unary unary = (Unary) Expr;
505 if (unary.Oper == Operator.UnaryNegation)
510 // perform numeric promotions to int,
514 // The following is inneficient, because we call
515 // ImplicitConversion too many times.
517 // It is also not clear if we should convert to Float
518 // or Double initially.
520 if (expr_type == TypeManager.uint32_type){
522 // FIXME: handle exception to this rule that
523 // permits the int value -2147483648 (-2^31) to
524 // bt wrote as a decimal interger literal
526 type = TypeManager.int64_type;
527 Expr = Convert.ImplicitConversion (ec, Expr, type, loc);
531 if (expr_type == TypeManager.uint64_type){
533 // FIXME: Handle exception of `long value'
534 // -92233720368547758087 (-2^63) to be wrote as
535 // decimal integer literal.
541 if (expr_type == TypeManager.float_type){
546 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
553 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
560 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.double_type, loc);
571 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
572 TypeManager.CSharpName (expr_type) + "'");
576 public override Expression DoResolve (EmitContext ec)
578 if (Oper == Operator.AddressOf)
579 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
581 Expr = Expr.Resolve (ec);
586 if (TypeManager.IsNullableType (Expr.Type))
587 return new Nullable.LiftedUnaryOperator (Oper, Expr, loc).Resolve (ec);
589 eclass = ExprClass.Value;
590 return ResolveOperator (ec);
593 public override Expression DoResolveLValue (EmitContext ec, Expression right)
595 if (Oper == Operator.Indirection)
596 return base.DoResolveLValue (ec, right);
598 Error (131, "The left-hand side of an assignment must be a " +
599 "variable, property or indexer");
603 public override void Emit (EmitContext ec)
605 ILGenerator ig = ec.ig;
608 case Operator.UnaryPlus:
609 throw new Exception ("This should be caught by Resolve");
611 case Operator.UnaryNegation:
613 ig.Emit (OpCodes.Ldc_I4_0);
614 if (type == TypeManager.int64_type)
615 ig.Emit (OpCodes.Conv_U8);
617 ig.Emit (OpCodes.Sub_Ovf);
620 ig.Emit (OpCodes.Neg);
625 case Operator.LogicalNot:
627 ig.Emit (OpCodes.Ldc_I4_0);
628 ig.Emit (OpCodes.Ceq);
631 case Operator.OnesComplement:
633 ig.Emit (OpCodes.Not);
636 case Operator.AddressOf:
637 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
641 throw new Exception ("This should not happen: Operator = "
646 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
648 if (Oper == Operator.LogicalNot)
649 Expr.EmitBranchable (ec, target, !onTrue);
651 base.EmitBranchable (ec, target, onTrue);
654 public override string ToString ()
656 return "Unary (" + Oper + ", " + Expr + ")";
662 // Unary operators are turned into Indirection expressions
663 // after semantic analysis (this is so we can take the address
664 // of an indirection).
666 public class Indirection : Expression, IMemoryLocation, IAssignMethod, IVariable {
668 LocalTemporary temporary;
671 public Indirection (Expression expr, Location l)
674 type = TypeManager.HasElementType (expr.Type) ? TypeManager.GetElementType (expr.Type) : expr.Type;
675 eclass = ExprClass.Variable;
679 void LoadExprValue (EmitContext ec)
683 public override void Emit (EmitContext ec)
688 LoadFromPtr (ec.ig, Type);
691 public void Emit (EmitContext ec, bool leave_copy)
695 ec.ig.Emit (OpCodes.Dup);
696 temporary = new LocalTemporary (ec, expr.Type);
697 temporary.Store (ec);
701 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
703 prepared = prepare_for_load;
707 if (prepare_for_load)
708 ec.ig.Emit (OpCodes.Dup);
712 ec.ig.Emit (OpCodes.Dup);
713 temporary = new LocalTemporary (ec, expr.Type);
714 temporary.Store (ec);
717 StoreFromPtr (ec.ig, type);
719 if (temporary != null)
723 public void AddressOf (EmitContext ec, AddressOp Mode)
728 public override Expression DoResolve (EmitContext ec)
731 // Born fully resolved
736 public override string ToString ()
738 return "*(" + expr + ")";
741 #region IVariable Members
743 public VariableInfo VariableInfo {
749 public bool VerifyFixed (bool is_expression)
758 /// Unary Mutator expressions (pre and post ++ and --)
762 /// UnaryMutator implements ++ and -- expressions. It derives from
763 /// ExpressionStatement becuase the pre/post increment/decrement
764 /// operators can be used in a statement context.
766 /// FIXME: Idea, we could split this up in two classes, one simpler
767 /// for the common case, and one with the extra fields for more complex
768 /// classes (indexers require temporary access; overloaded require method)
771 public class UnaryMutator : ExpressionStatement {
773 public enum Mode : byte {
780 PreDecrement = IsDecrement,
781 PostIncrement = IsPost,
782 PostDecrement = IsPost | IsDecrement
786 bool is_expr = false;
787 bool recurse = false;
792 // This is expensive for the simplest case.
794 StaticCallExpr method;
796 public UnaryMutator (Mode m, Expression e, Location l)
803 static string OperName (Mode mode)
805 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
809 void Error23 (Type t)
812 23, "Operator " + OperName (mode) +
813 " cannot be applied to operand of type `" +
814 TypeManager.CSharpName (t) + "'");
818 /// Returns whether an object of type `t' can be incremented
819 /// or decremented with add/sub (ie, basically whether we can
820 /// use pre-post incr-decr operations on it, but it is not a
821 /// System.Decimal, which we require operator overloading to catch)
823 static bool IsIncrementableNumber (Type t)
825 return (t == TypeManager.sbyte_type) ||
826 (t == TypeManager.byte_type) ||
827 (t == TypeManager.short_type) ||
828 (t == TypeManager.ushort_type) ||
829 (t == TypeManager.int32_type) ||
830 (t == TypeManager.uint32_type) ||
831 (t == TypeManager.int64_type) ||
832 (t == TypeManager.uint64_type) ||
833 (t == TypeManager.char_type) ||
834 (t.IsSubclassOf (TypeManager.enum_type)) ||
835 (t == TypeManager.float_type) ||
836 (t == TypeManager.double_type) ||
837 (t.IsPointer && t != TypeManager.void_ptr_type);
840 Expression ResolveOperator (EmitContext ec)
842 Type expr_type = expr.Type;
845 // Step 1: Perform Operator Overload location
850 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
851 op_name = "op_Increment";
853 op_name = "op_Decrement";
855 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
857 if (mg == null && expr_type.BaseType != null)
858 mg = MemberLookup (ec, expr_type.BaseType, op_name,
859 MemberTypes.Method, AllBindingFlags, loc);
862 method = StaticCallExpr.MakeSimpleCall (
863 ec, (MethodGroupExpr) mg, expr, loc);
870 // The operand of the prefix/postfix increment decrement operators
871 // should be an expression that is classified as a variable,
872 // a property access or an indexer access
875 if (expr.eclass == ExprClass.Variable){
876 LocalVariableReference var = expr as LocalVariableReference;
877 if ((var != null) && var.IsReadOnly)
878 Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
879 if (IsIncrementableNumber (expr_type) ||
880 expr_type == TypeManager.decimal_type){
883 } else if (expr.eclass == ExprClass.IndexerAccess){
884 IndexerAccess ia = (IndexerAccess) expr;
886 expr = ia.ResolveLValue (ec, this);
891 } else if (expr.eclass == ExprClass.PropertyAccess){
892 PropertyExpr pe = (PropertyExpr) expr;
894 if (pe.VerifyAssignable ())
899 expr.Error_UnexpectedKind ("variable, indexer or property access", loc);
903 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
904 TypeManager.CSharpName (expr_type) + "'");
908 public override Expression DoResolve (EmitContext ec)
910 expr = expr.Resolve (ec);
915 eclass = ExprClass.Value;
917 if (TypeManager.IsNullableType (expr.Type))
918 return new Nullable.LiftedUnaryMutator (mode, expr, loc).Resolve (ec);
920 return ResolveOperator (ec);
923 static int PtrTypeSize (Type t)
925 return GetTypeSize (TypeManager.GetElementType (t));
929 // Loads the proper "1" into the stack based on the type, then it emits the
930 // opcode for the operation requested
932 void LoadOneAndEmitOp (EmitContext ec, Type t)
935 // Measure if getting the typecode and using that is more/less efficient
936 // that comparing types. t.GetTypeCode() is an internal call.
938 ILGenerator ig = ec.ig;
940 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
941 LongConstant.EmitLong (ig, 1);
942 else if (t == TypeManager.double_type)
943 ig.Emit (OpCodes.Ldc_R8, 1.0);
944 else if (t == TypeManager.float_type)
945 ig.Emit (OpCodes.Ldc_R4, 1.0F);
946 else if (t.IsPointer){
947 int n = PtrTypeSize (t);
950 ig.Emit (OpCodes.Sizeof, t);
952 IntConstant.EmitInt (ig, n);
954 ig.Emit (OpCodes.Ldc_I4_1);
957 // Now emit the operation
960 if (t == TypeManager.int32_type ||
961 t == TypeManager.int64_type){
962 if ((mode & Mode.IsDecrement) != 0)
963 ig.Emit (OpCodes.Sub_Ovf);
965 ig.Emit (OpCodes.Add_Ovf);
966 } else if (t == TypeManager.uint32_type ||
967 t == TypeManager.uint64_type){
968 if ((mode & Mode.IsDecrement) != 0)
969 ig.Emit (OpCodes.Sub_Ovf_Un);
971 ig.Emit (OpCodes.Add_Ovf_Un);
973 if ((mode & Mode.IsDecrement) != 0)
974 ig.Emit (OpCodes.Sub_Ovf);
976 ig.Emit (OpCodes.Add_Ovf);
979 if ((mode & Mode.IsDecrement) != 0)
980 ig.Emit (OpCodes.Sub);
982 ig.Emit (OpCodes.Add);
985 if (t == TypeManager.sbyte_type){
987 ig.Emit (OpCodes.Conv_Ovf_I1);
989 ig.Emit (OpCodes.Conv_I1);
990 } else if (t == TypeManager.byte_type){
992 ig.Emit (OpCodes.Conv_Ovf_U1);
994 ig.Emit (OpCodes.Conv_U1);
995 } else if (t == TypeManager.short_type){
997 ig.Emit (OpCodes.Conv_Ovf_I2);
999 ig.Emit (OpCodes.Conv_I2);
1000 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
1002 ig.Emit (OpCodes.Conv_Ovf_U2);
1004 ig.Emit (OpCodes.Conv_U2);
1009 void EmitCode (EmitContext ec, bool is_expr)
1012 this.is_expr = is_expr;
1013 ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
1016 public override void Emit (EmitContext ec)
1019 // We use recurse to allow ourselfs to be the source
1020 // of an assignment. This little hack prevents us from
1021 // having to allocate another expression
1024 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
1026 LoadOneAndEmitOp (ec, expr.Type);
1028 ec.ig.Emit (OpCodes.Call, method.Method);
1033 EmitCode (ec, true);
1036 public override void EmitStatement (EmitContext ec)
1038 EmitCode (ec, false);
1043 /// Base class for the `Is' and `As' classes.
1047 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1050 public abstract class Probe : Expression {
1051 public Expression ProbeType;
1052 protected Expression expr;
1053 protected Type probe_type;
1055 public Probe (Expression expr, Expression probe_type, Location l)
1057 ProbeType = probe_type;
1062 public Expression Expr {
1068 public override Expression DoResolve (EmitContext ec)
1070 TypeExpr texpr = ProbeType.ResolveAsTypeTerminal (ec);
1073 probe_type = texpr.Type;
1075 CheckObsoleteAttribute (probe_type);
1077 expr = expr.Resolve (ec);
1081 if (expr.Type.IsPointer) {
1082 Report.Error (244, loc, "\"is\" or \"as\" are not valid on pointer types");
1090 /// Implementation of the `is' operator.
1092 public class Is : Probe {
1093 public Is (Expression expr, Expression probe_type, Location l)
1094 : base (expr, probe_type, l)
1099 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1104 public override void Emit (EmitContext ec)
1106 ILGenerator ig = ec.ig;
1111 case Action.AlwaysFalse:
1112 ig.Emit (OpCodes.Pop);
1113 IntConstant.EmitInt (ig, 0);
1115 case Action.AlwaysTrue:
1116 ig.Emit (OpCodes.Pop);
1117 IntConstant.EmitInt (ig, 1);
1119 case Action.LeaveOnStack:
1120 // the `e != null' rule.
1121 ig.Emit (OpCodes.Ldnull);
1122 ig.Emit (OpCodes.Ceq);
1123 ig.Emit (OpCodes.Ldc_I4_0);
1124 ig.Emit (OpCodes.Ceq);
1127 ig.Emit (OpCodes.Isinst, probe_type);
1128 ig.Emit (OpCodes.Ldnull);
1129 ig.Emit (OpCodes.Cgt_Un);
1132 throw new Exception ("never reached");
1135 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
1137 ILGenerator ig = ec.ig;
1140 case Action.AlwaysFalse:
1142 ig.Emit (OpCodes.Br, target);
1145 case Action.AlwaysTrue:
1147 ig.Emit (OpCodes.Br, target);
1150 case Action.LeaveOnStack:
1151 // the `e != null' rule.
1153 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1157 ig.Emit (OpCodes.Isinst, probe_type);
1158 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1161 throw new Exception ("never reached");
1164 public override Expression DoResolve (EmitContext ec)
1166 Expression e = base.DoResolve (ec);
1168 if ((e == null) || (expr == null))
1171 Type etype = expr.Type;
1172 bool warning_always_matches = false;
1173 bool warning_never_matches = false;
1175 type = TypeManager.bool_type;
1176 eclass = ExprClass.Value;
1179 // First case, if at compile time, there is an implicit conversion
1180 // then e != null (objects) or true (value types)
1182 e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1185 if (etype.IsValueType)
1186 action = Action.AlwaysTrue;
1188 action = Action.LeaveOnStack;
1190 warning_always_matches = true;
1191 } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1192 if (etype.IsGenericParameter)
1193 expr = new BoxedCast (expr, etype);
1196 // Second case: explicit reference convresion
1198 if (expr is NullLiteral)
1199 action = Action.AlwaysFalse;
1201 action = Action.Probe;
1203 action = Action.AlwaysFalse;
1204 warning_never_matches = true;
1207 if (warning_always_matches)
1208 Warning (183, "The given expression is always of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1209 else if (warning_never_matches){
1210 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1211 Warning (184, "The given expression is never of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1219 /// Implementation of the `as' operator.
1221 public class As : Probe {
1222 public As (Expression expr, Expression probe_type, Location l)
1223 : base (expr, probe_type, l)
1227 bool do_isinst = false;
1229 public override void Emit (EmitContext ec)
1231 ILGenerator ig = ec.ig;
1236 ig.Emit (OpCodes.Isinst, probe_type);
1239 static void Error_CannotConvertType (Type source, Type target, Location loc)
1242 39, loc, "as operator can not convert from `" +
1243 TypeManager.CSharpName (source) + "' to `" +
1244 TypeManager.CSharpName (target) + "'");
1247 public override Expression DoResolve (EmitContext ec)
1249 Expression e = base.DoResolve (ec);
1255 eclass = ExprClass.Value;
1256 Type etype = expr.Type;
1258 if (TypeManager.IsValueType (probe_type)){
1259 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1260 TypeManager.CSharpName (probe_type) + " is a value type)");
1265 e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1272 if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1273 if (etype.IsGenericParameter)
1274 expr = new BoxedCast (expr, etype);
1280 Error_CannotConvertType (etype, probe_type, loc);
1286 /// This represents a typecast in the source language.
1288 /// FIXME: Cast expressions have an unusual set of parsing
1289 /// rules, we need to figure those out.
1291 public class Cast : Expression {
1292 Expression target_type;
1295 public Cast (Expression cast_type, Expression expr, Location loc)
1297 this.target_type = cast_type;
1302 public Expression TargetType {
1308 public Expression Expr {
1317 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1319 if (!ec.ConstantCheckState)
1322 if ((value < min) || (value > max)) {
1323 Error (221, "Constant value `" + value + "' cannot be converted " +
1324 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1325 "syntax to override)");
1332 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1334 if (!ec.ConstantCheckState)
1338 Error (221, "Constant value `" + value + "' cannot be converted " +
1339 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1340 "syntax to override)");
1347 bool CheckUnsigned (EmitContext ec, long value, Type type)
1349 if (!ec.ConstantCheckState)
1353 Error (221, "Constant value `" + value + "' cannot be converted " +
1354 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1355 "syntax to override)");
1363 /// Attempts to do a compile-time folding of a constant cast.
1365 Expression TryReduce (EmitContext ec, Type target_type)
1367 Expression real_expr = expr;
1368 if (real_expr is EnumConstant)
1369 real_expr = ((EnumConstant) real_expr).Child;
1371 if (real_expr is ByteConstant){
1372 byte v = ((ByteConstant) real_expr).Value;
1374 if (target_type == TypeManager.sbyte_type) {
1375 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1377 return new SByteConstant ((sbyte) v);
1379 if (target_type == TypeManager.short_type)
1380 return new ShortConstant ((short) v);
1381 if (target_type == TypeManager.ushort_type)
1382 return new UShortConstant ((ushort) v);
1383 if (target_type == TypeManager.int32_type)
1384 return new IntConstant ((int) v);
1385 if (target_type == TypeManager.uint32_type)
1386 return new UIntConstant ((uint) v);
1387 if (target_type == TypeManager.int64_type)
1388 return new LongConstant ((long) v);
1389 if (target_type == TypeManager.uint64_type)
1390 return new ULongConstant ((ulong) v);
1391 if (target_type == TypeManager.float_type)
1392 return new FloatConstant ((float) v);
1393 if (target_type == TypeManager.double_type)
1394 return new DoubleConstant ((double) v);
1395 if (target_type == TypeManager.char_type)
1396 return new CharConstant ((char) v);
1397 if (target_type == TypeManager.decimal_type)
1398 return new DecimalConstant ((decimal) v);
1400 if (real_expr is SByteConstant){
1401 sbyte v = ((SByteConstant) real_expr).Value;
1403 if (target_type == TypeManager.byte_type) {
1404 if (!CheckUnsigned (ec, v, target_type))
1406 return new ByteConstant ((byte) v);
1408 if (target_type == TypeManager.short_type)
1409 return new ShortConstant ((short) v);
1410 if (target_type == TypeManager.ushort_type) {
1411 if (!CheckUnsigned (ec, v, target_type))
1413 return new UShortConstant ((ushort) v);
1414 } if (target_type == TypeManager.int32_type)
1415 return new IntConstant ((int) v);
1416 if (target_type == TypeManager.uint32_type) {
1417 if (!CheckUnsigned (ec, v, target_type))
1419 return new UIntConstant ((uint) v);
1420 } if (target_type == TypeManager.int64_type)
1421 return new LongConstant ((long) v);
1422 if (target_type == TypeManager.uint64_type) {
1423 if (!CheckUnsigned (ec, v, target_type))
1425 return new ULongConstant ((ulong) v);
1427 if (target_type == TypeManager.float_type)
1428 return new FloatConstant ((float) v);
1429 if (target_type == TypeManager.double_type)
1430 return new DoubleConstant ((double) v);
1431 if (target_type == TypeManager.char_type) {
1432 if (!CheckUnsigned (ec, v, target_type))
1434 return new CharConstant ((char) v);
1436 if (target_type == TypeManager.decimal_type)
1437 return new DecimalConstant ((decimal) v);
1439 if (real_expr is ShortConstant){
1440 short v = ((ShortConstant) real_expr).Value;
1442 if (target_type == TypeManager.byte_type) {
1443 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1445 return new ByteConstant ((byte) v);
1447 if (target_type == TypeManager.sbyte_type) {
1448 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1450 return new SByteConstant ((sbyte) v);
1452 if (target_type == TypeManager.ushort_type) {
1453 if (!CheckUnsigned (ec, v, target_type))
1455 return new UShortConstant ((ushort) v);
1457 if (target_type == TypeManager.int32_type)
1458 return new IntConstant ((int) v);
1459 if (target_type == TypeManager.uint32_type) {
1460 if (!CheckUnsigned (ec, v, target_type))
1462 return new UIntConstant ((uint) v);
1464 if (target_type == TypeManager.int64_type)
1465 return new LongConstant ((long) v);
1466 if (target_type == TypeManager.uint64_type) {
1467 if (!CheckUnsigned (ec, v, target_type))
1469 return new ULongConstant ((ulong) v);
1471 if (target_type == TypeManager.float_type)
1472 return new FloatConstant ((float) v);
1473 if (target_type == TypeManager.double_type)
1474 return new DoubleConstant ((double) v);
1475 if (target_type == TypeManager.char_type) {
1476 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1478 return new CharConstant ((char) v);
1480 if (target_type == TypeManager.decimal_type)
1481 return new DecimalConstant ((decimal) v);
1483 if (real_expr is UShortConstant){
1484 ushort v = ((UShortConstant) real_expr).Value;
1486 if (target_type == TypeManager.byte_type) {
1487 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1489 return new ByteConstant ((byte) v);
1491 if (target_type == TypeManager.sbyte_type) {
1492 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1494 return new SByteConstant ((sbyte) v);
1496 if (target_type == TypeManager.short_type) {
1497 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1499 return new ShortConstant ((short) v);
1501 if (target_type == TypeManager.int32_type)
1502 return new IntConstant ((int) v);
1503 if (target_type == TypeManager.uint32_type)
1504 return new UIntConstant ((uint) v);
1505 if (target_type == TypeManager.int64_type)
1506 return new LongConstant ((long) v);
1507 if (target_type == TypeManager.uint64_type)
1508 return new ULongConstant ((ulong) v);
1509 if (target_type == TypeManager.float_type)
1510 return new FloatConstant ((float) v);
1511 if (target_type == TypeManager.double_type)
1512 return new DoubleConstant ((double) v);
1513 if (target_type == TypeManager.char_type) {
1514 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1516 return new CharConstant ((char) v);
1518 if (target_type == TypeManager.decimal_type)
1519 return new DecimalConstant ((decimal) v);
1521 if (real_expr is IntConstant){
1522 int v = ((IntConstant) real_expr).Value;
1524 if (target_type == TypeManager.byte_type) {
1525 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1527 return new ByteConstant ((byte) v);
1529 if (target_type == TypeManager.sbyte_type) {
1530 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1532 return new SByteConstant ((sbyte) v);
1534 if (target_type == TypeManager.short_type) {
1535 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1537 return new ShortConstant ((short) v);
1539 if (target_type == TypeManager.ushort_type) {
1540 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1542 return new UShortConstant ((ushort) v);
1544 if (target_type == TypeManager.uint32_type) {
1545 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1547 return new UIntConstant ((uint) v);
1549 if (target_type == TypeManager.int64_type)
1550 return new LongConstant ((long) v);
1551 if (target_type == TypeManager.uint64_type) {
1552 if (!CheckUnsigned (ec, v, target_type))
1554 return new ULongConstant ((ulong) v);
1556 if (target_type == TypeManager.float_type)
1557 return new FloatConstant ((float) v);
1558 if (target_type == TypeManager.double_type)
1559 return new DoubleConstant ((double) v);
1560 if (target_type == TypeManager.char_type) {
1561 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1563 return new CharConstant ((char) v);
1565 if (target_type == TypeManager.decimal_type)
1566 return new DecimalConstant ((decimal) v);
1568 if (real_expr is UIntConstant){
1569 uint v = ((UIntConstant) real_expr).Value;
1571 if (target_type == TypeManager.byte_type) {
1572 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1574 return new ByteConstant ((byte) v);
1576 if (target_type == TypeManager.sbyte_type) {
1577 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1579 return new SByteConstant ((sbyte) v);
1581 if (target_type == TypeManager.short_type) {
1582 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1584 return new ShortConstant ((short) v);
1586 if (target_type == TypeManager.ushort_type) {
1587 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1589 return new UShortConstant ((ushort) v);
1591 if (target_type == TypeManager.int32_type) {
1592 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1594 return new IntConstant ((int) v);
1596 if (target_type == TypeManager.int64_type)
1597 return new LongConstant ((long) v);
1598 if (target_type == TypeManager.uint64_type)
1599 return new ULongConstant ((ulong) v);
1600 if (target_type == TypeManager.float_type)
1601 return new FloatConstant ((float) v);
1602 if (target_type == TypeManager.double_type)
1603 return new DoubleConstant ((double) v);
1604 if (target_type == TypeManager.char_type) {
1605 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1607 return new CharConstant ((char) v);
1609 if (target_type == TypeManager.decimal_type)
1610 return new DecimalConstant ((decimal) v);
1612 if (real_expr is LongConstant){
1613 long v = ((LongConstant) real_expr).Value;
1615 if (target_type == TypeManager.byte_type) {
1616 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1618 return new ByteConstant ((byte) v);
1620 if (target_type == TypeManager.sbyte_type) {
1621 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1623 return new SByteConstant ((sbyte) v);
1625 if (target_type == TypeManager.short_type) {
1626 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1628 return new ShortConstant ((short) v);
1630 if (target_type == TypeManager.ushort_type) {
1631 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1633 return new UShortConstant ((ushort) v);
1635 if (target_type == TypeManager.int32_type) {
1636 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1638 return new IntConstant ((int) v);
1640 if (target_type == TypeManager.uint32_type) {
1641 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1643 return new UIntConstant ((uint) v);
1645 if (target_type == TypeManager.uint64_type) {
1646 if (!CheckUnsigned (ec, v, target_type))
1648 return new ULongConstant ((ulong) v);
1650 if (target_type == TypeManager.float_type)
1651 return new FloatConstant ((float) v);
1652 if (target_type == TypeManager.double_type)
1653 return new DoubleConstant ((double) v);
1654 if (target_type == TypeManager.char_type) {
1655 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1657 return new CharConstant ((char) v);
1659 if (target_type == TypeManager.decimal_type)
1660 return new DecimalConstant ((decimal) v);
1662 if (real_expr is ULongConstant){
1663 ulong v = ((ULongConstant) real_expr).Value;
1665 if (target_type == TypeManager.byte_type) {
1666 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1668 return new ByteConstant ((byte) v);
1670 if (target_type == TypeManager.sbyte_type) {
1671 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1673 return new SByteConstant ((sbyte) v);
1675 if (target_type == TypeManager.short_type) {
1676 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1678 return new ShortConstant ((short) v);
1680 if (target_type == TypeManager.ushort_type) {
1681 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1683 return new UShortConstant ((ushort) v);
1685 if (target_type == TypeManager.int32_type) {
1686 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1688 return new IntConstant ((int) v);
1690 if (target_type == TypeManager.uint32_type) {
1691 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1693 return new UIntConstant ((uint) v);
1695 if (target_type == TypeManager.int64_type) {
1696 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1698 return new LongConstant ((long) v);
1700 if (target_type == TypeManager.float_type)
1701 return new FloatConstant ((float) v);
1702 if (target_type == TypeManager.double_type)
1703 return new DoubleConstant ((double) v);
1704 if (target_type == TypeManager.char_type) {
1705 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1707 return new CharConstant ((char) v);
1709 if (target_type == TypeManager.decimal_type)
1710 return new DecimalConstant ((decimal) v);
1712 if (real_expr is FloatConstant){
1713 float v = ((FloatConstant) real_expr).Value;
1715 if (target_type == TypeManager.byte_type)
1716 return new ByteConstant ((byte) v);
1717 if (target_type == TypeManager.sbyte_type)
1718 return new SByteConstant ((sbyte) v);
1719 if (target_type == TypeManager.short_type)
1720 return new ShortConstant ((short) v);
1721 if (target_type == TypeManager.ushort_type)
1722 return new UShortConstant ((ushort) v);
1723 if (target_type == TypeManager.int32_type)
1724 return new IntConstant ((int) v);
1725 if (target_type == TypeManager.uint32_type)
1726 return new UIntConstant ((uint) v);
1727 if (target_type == TypeManager.int64_type)
1728 return new LongConstant ((long) v);
1729 if (target_type == TypeManager.uint64_type)
1730 return new ULongConstant ((ulong) v);
1731 if (target_type == TypeManager.double_type)
1732 return new DoubleConstant ((double) v);
1733 if (target_type == TypeManager.char_type)
1734 return new CharConstant ((char) v);
1735 if (target_type == TypeManager.decimal_type)
1736 return new DecimalConstant ((decimal) v);
1738 if (real_expr is DoubleConstant){
1739 double v = ((DoubleConstant) real_expr).Value;
1741 if (target_type == TypeManager.byte_type){
1742 return new ByteConstant ((byte) v);
1743 } if (target_type == TypeManager.sbyte_type)
1744 return new SByteConstant ((sbyte) v);
1745 if (target_type == TypeManager.short_type)
1746 return new ShortConstant ((short) v);
1747 if (target_type == TypeManager.ushort_type)
1748 return new UShortConstant ((ushort) v);
1749 if (target_type == TypeManager.int32_type)
1750 return new IntConstant ((int) v);
1751 if (target_type == TypeManager.uint32_type)
1752 return new UIntConstant ((uint) v);
1753 if (target_type == TypeManager.int64_type)
1754 return new LongConstant ((long) v);
1755 if (target_type == TypeManager.uint64_type)
1756 return new ULongConstant ((ulong) v);
1757 if (target_type == TypeManager.float_type)
1758 return new FloatConstant ((float) v);
1759 if (target_type == TypeManager.char_type)
1760 return new CharConstant ((char) v);
1761 if (target_type == TypeManager.decimal_type)
1762 return new DecimalConstant ((decimal) v);
1765 if (real_expr is CharConstant){
1766 char v = ((CharConstant) real_expr).Value;
1768 if (target_type == TypeManager.byte_type) {
1769 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1771 return new ByteConstant ((byte) v);
1773 if (target_type == TypeManager.sbyte_type) {
1774 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1776 return new SByteConstant ((sbyte) v);
1778 if (target_type == TypeManager.short_type) {
1779 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1781 return new ShortConstant ((short) v);
1783 if (target_type == TypeManager.int32_type)
1784 return new IntConstant ((int) v);
1785 if (target_type == TypeManager.uint32_type)
1786 return new UIntConstant ((uint) v);
1787 if (target_type == TypeManager.int64_type)
1788 return new LongConstant ((long) v);
1789 if (target_type == TypeManager.uint64_type)
1790 return new ULongConstant ((ulong) v);
1791 if (target_type == TypeManager.float_type)
1792 return new FloatConstant ((float) v);
1793 if (target_type == TypeManager.double_type)
1794 return new DoubleConstant ((double) v);
1795 if (target_type == TypeManager.char_type) {
1796 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1798 return new CharConstant ((char) v);
1800 if (target_type == TypeManager.decimal_type)
1801 return new DecimalConstant ((decimal) v);
1807 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1809 expr = expr.DoResolveLValue (ec, right_side);
1813 return ResolveRest (ec);
1816 public override Expression DoResolve (EmitContext ec)
1818 expr = expr.Resolve (ec);
1822 return ResolveRest (ec);
1825 Expression ResolveRest (EmitContext ec)
1827 TypeExpr target = target_type.ResolveAsTypeTerminal (ec);
1833 CheckObsoleteAttribute (type);
1835 if (type.IsAbstract && type.IsSealed) {
1836 Report.Error (716, loc, "Cannot convert to static type '{0}'", TypeManager.CSharpName (type));
1840 eclass = ExprClass.Value;
1842 if (expr is Constant){
1843 Expression e = TryReduce (ec, type);
1849 if (type.IsPointer && !ec.InUnsafe) {
1853 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1857 public override void Emit (EmitContext ec)
1860 // This one will never happen
1862 throw new Exception ("Should not happen");
1867 /// Binary operators
1869 public class Binary : Expression {
1870 public enum Operator : byte {
1871 Multiply, Division, Modulus,
1872 Addition, Subtraction,
1873 LeftShift, RightShift,
1874 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1875 Equality, Inequality,
1885 Expression left, right;
1887 // This must be kept in sync with Operator!!!
1888 public static readonly string [] oper_names;
1892 oper_names = new string [(int) Operator.TOP];
1894 oper_names [(int) Operator.Multiply] = "op_Multiply";
1895 oper_names [(int) Operator.Division] = "op_Division";
1896 oper_names [(int) Operator.Modulus] = "op_Modulus";
1897 oper_names [(int) Operator.Addition] = "op_Addition";
1898 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1899 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1900 oper_names [(int) Operator.RightShift] = "op_RightShift";
1901 oper_names [(int) Operator.LessThan] = "op_LessThan";
1902 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1903 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1904 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1905 oper_names [(int) Operator.Equality] = "op_Equality";
1906 oper_names [(int) Operator.Inequality] = "op_Inequality";
1907 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1908 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1909 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1910 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1911 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1914 public Binary (Operator oper, Expression left, Expression right, Location loc)
1922 public Operator Oper {
1931 public Expression Left {
1940 public Expression Right {
1951 /// Returns a stringified representation of the Operator
1953 static string OperName (Operator oper)
1956 case Operator.Multiply:
1958 case Operator.Division:
1960 case Operator.Modulus:
1962 case Operator.Addition:
1964 case Operator.Subtraction:
1966 case Operator.LeftShift:
1968 case Operator.RightShift:
1970 case Operator.LessThan:
1972 case Operator.GreaterThan:
1974 case Operator.LessThanOrEqual:
1976 case Operator.GreaterThanOrEqual:
1978 case Operator.Equality:
1980 case Operator.Inequality:
1982 case Operator.BitwiseAnd:
1984 case Operator.BitwiseOr:
1986 case Operator.ExclusiveOr:
1988 case Operator.LogicalOr:
1990 case Operator.LogicalAnd:
1994 return oper.ToString ();
1997 public override string ToString ()
1999 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
2000 right.ToString () + ")";
2003 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
2005 if (expr.Type == target_type)
2008 return Convert.ImplicitConversion (ec, expr, target_type, loc);
2011 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
2014 34, loc, "Operator `" + OperName (oper)
2015 + "' is ambiguous on operands of type `"
2016 + TypeManager.CSharpName (l) + "' "
2017 + "and `" + TypeManager.CSharpName (r)
2021 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
2023 if ((l == t) || (r == t))
2026 if (!check_user_conversions)
2029 if (Convert.ImplicitUserConversionExists (ec, l, t))
2031 else if (Convert.ImplicitUserConversionExists (ec, r, t))
2038 // Note that handling the case l == Decimal || r == Decimal
2039 // is taken care of by the Step 1 Operator Overload resolution.
2041 // If `check_user_conv' is true, we also check whether a user-defined conversion
2042 // exists. Note that we only need to do this if both arguments are of a user-defined
2043 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
2044 // so we don't explicitly check for performance reasons.
2046 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
2048 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
2050 // If either operand is of type double, the other operand is
2051 // conveted to type double.
2053 if (r != TypeManager.double_type)
2054 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
2055 if (l != TypeManager.double_type)
2056 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
2058 type = TypeManager.double_type;
2059 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
2061 // if either operand is of type float, the other operand is
2062 // converted to type float.
2064 if (r != TypeManager.double_type)
2065 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
2066 if (l != TypeManager.double_type)
2067 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
2068 type = TypeManager.float_type;
2069 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2073 // If either operand is of type ulong, the other operand is
2074 // converted to type ulong. or an error ocurrs if the other
2075 // operand is of type sbyte, short, int or long
2077 if (l == TypeManager.uint64_type){
2078 if (r != TypeManager.uint64_type){
2079 if (right is IntConstant){
2080 IntConstant ic = (IntConstant) right;
2082 e = Convert.TryImplicitIntConversion (l, ic);
2085 } else if (right is LongConstant){
2086 long ll = ((LongConstant) right).Value;
2089 right = new ULongConstant ((ulong) ll);
2091 e = Convert.ImplicitNumericConversion (ec, right, l, loc);
2098 if (left is IntConstant){
2099 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
2102 } else if (left is LongConstant){
2103 long ll = ((LongConstant) left).Value;
2106 left = new ULongConstant ((ulong) ll);
2108 e = Convert.ImplicitNumericConversion (ec, left, r, loc);
2115 if ((other == TypeManager.sbyte_type) ||
2116 (other == TypeManager.short_type) ||
2117 (other == TypeManager.int32_type) ||
2118 (other == TypeManager.int64_type))
2119 Error_OperatorAmbiguous (loc, oper, l, r);
2121 left = ForceConversion (ec, left, TypeManager.uint64_type);
2122 right = ForceConversion (ec, right, TypeManager.uint64_type);
2124 type = TypeManager.uint64_type;
2125 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2127 // If either operand is of type long, the other operand is converted
2130 if (l != TypeManager.int64_type)
2131 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
2132 if (r != TypeManager.int64_type)
2133 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
2135 type = TypeManager.int64_type;
2136 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2138 // If either operand is of type uint, and the other
2139 // operand is of type sbyte, short or int, othe operands are
2140 // converted to type long (unless we have an int constant).
2144 if (l == TypeManager.uint32_type){
2145 if (right is IntConstant){
2146 IntConstant ic = (IntConstant) right;
2150 right = new UIntConstant ((uint) val);
2157 } else if (r == TypeManager.uint32_type){
2158 if (left is IntConstant){
2159 IntConstant ic = (IntConstant) left;
2163 left = new UIntConstant ((uint) val);
2172 if ((other == TypeManager.sbyte_type) ||
2173 (other == TypeManager.short_type) ||
2174 (other == TypeManager.int32_type)){
2175 left = ForceConversion (ec, left, TypeManager.int64_type);
2176 right = ForceConversion (ec, right, TypeManager.int64_type);
2177 type = TypeManager.int64_type;
2180 // if either operand is of type uint, the other
2181 // operand is converd to type uint
2183 left = ForceConversion (ec, left, TypeManager.uint32_type);
2184 right = ForceConversion (ec, right, TypeManager.uint32_type);
2185 type = TypeManager.uint32_type;
2187 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2188 if (l != TypeManager.decimal_type)
2189 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
2191 if (r != TypeManager.decimal_type)
2192 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
2193 type = TypeManager.decimal_type;
2195 left = ForceConversion (ec, left, TypeManager.int32_type);
2196 right = ForceConversion (ec, right, TypeManager.int32_type);
2198 type = TypeManager.int32_type;
2201 return (left != null) && (right != null);
2204 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2206 Report.Error (19, loc,
2207 "Operator " + name + " cannot be applied to operands of type `" +
2208 TypeManager.CSharpName (l) + "' and `" +
2209 TypeManager.CSharpName (r) + "'");
2212 void Error_OperatorCannotBeApplied ()
2214 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2217 static bool is_unsigned (Type t)
2219 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2220 t == TypeManager.short_type || t == TypeManager.byte_type);
2223 static bool is_user_defined (Type t)
2225 if (t.IsSubclassOf (TypeManager.value_type) &&
2226 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2232 Expression Make32or64 (EmitContext ec, Expression e)
2236 if (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2237 t == TypeManager.int64_type || t == TypeManager.uint64_type)
2239 Expression ee = Convert.ImplicitConversion (ec, e, TypeManager.int32_type, loc);
2242 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint32_type, loc);
2245 ee = Convert.ImplicitConversion (ec, e, TypeManager.int64_type, loc);
2248 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint64_type, loc);
2254 Expression CheckShiftArguments (EmitContext ec)
2258 e = ForceConversion (ec, right, TypeManager.int32_type);
2260 Error_OperatorCannotBeApplied ();
2265 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
2266 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
2267 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
2268 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
2272 if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
2273 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (31), loc);
2274 right = right.DoResolve (ec);
2276 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (63), loc);
2277 right = right.DoResolve (ec);
2282 Error_OperatorCannotBeApplied ();
2286 Expression ResolveOperator (EmitContext ec)
2289 Type r = right.Type;
2292 // Special cases: string or type parameter comapred to null
2294 if (oper == Operator.Equality || oper == Operator.Inequality){
2295 if ((!TypeManager.IsValueType (l) && r == TypeManager.null_type) ||
2296 (!TypeManager.IsValueType (r) && l == TypeManager.null_type)) {
2297 Type = TypeManager.bool_type;
2302 if (l.IsGenericParameter && (right is NullLiteral)) {
2303 if (l.BaseType == TypeManager.value_type) {
2304 Error_OperatorCannotBeApplied ();
2308 left = new BoxedCast (left);
2309 Type = TypeManager.bool_type;
2313 if (r.IsGenericParameter && (left is NullLiteral)) {
2314 if (r.BaseType == TypeManager.value_type) {
2315 Error_OperatorCannotBeApplied ();
2319 right = new BoxedCast (right);
2320 Type = TypeManager.bool_type;
2325 if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
2326 Type = TypeManager.bool_type;
2333 // Do not perform operator overload resolution when both sides are
2336 if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
2338 // Step 1: Perform Operator Overload location
2340 Expression left_expr, right_expr;
2342 string op = oper_names [(int) oper];
2344 MethodGroupExpr union;
2345 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2347 right_expr = MemberLookup (
2348 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2349 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2351 union = (MethodGroupExpr) left_expr;
2353 if (union != null) {
2354 ArrayList args = new ArrayList (2);
2355 args.Add (new Argument (left, Argument.AType.Expression));
2356 args.Add (new Argument (right, Argument.AType.Expression));
2358 MethodBase method = Invocation.OverloadResolve (
2359 ec, union, args, true, Location.Null);
2361 if (method != null) {
2362 MethodInfo mi = (MethodInfo) method;
2364 return new BinaryMethod (mi.ReturnType, method, args);
2370 // Step 0: String concatenation (because overloading will get this wrong)
2372 if (oper == Operator.Addition){
2374 // If any of the arguments is a string, cast to string
2377 // Simple constant folding
2378 if (left is StringConstant && right is StringConstant)
2379 return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value);
2381 if (l == TypeManager.string_type || r == TypeManager.string_type) {
2383 if (r == TypeManager.void_type || l == TypeManager.void_type) {
2384 Error_OperatorCannotBeApplied ();
2388 // try to fold it in on the left
2389 if (left is StringConcat) {
2392 // We have to test here for not-null, since we can be doubly-resolved
2393 // take care of not appending twice
2396 type = TypeManager.string_type;
2397 ((StringConcat) left).Append (ec, right);
2398 return left.Resolve (ec);
2404 // Otherwise, start a new concat expression
2405 return new StringConcat (ec, loc, left, right).Resolve (ec);
2409 // Transform a + ( - b) into a - b
2411 if (right is Unary){
2412 Unary right_unary = (Unary) right;
2414 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2415 oper = Operator.Subtraction;
2416 right = right_unary.Expr;
2422 if (oper == Operator.Equality || oper == Operator.Inequality){
2423 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2424 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2425 Error_OperatorCannotBeApplied ();
2429 type = TypeManager.bool_type;
2433 bool left_is_null = left is NullLiteral;
2434 bool right_is_null = right is NullLiteral;
2435 if (left_is_null || right_is_null) {
2436 if (oper == Operator.Equality)
2437 return new BoolLiteral (left_is_null == right_is_null);
2439 return new BoolLiteral (left_is_null != right_is_null);
2443 // operator != (object a, object b)
2444 // operator == (object a, object b)
2446 // For this to be used, both arguments have to be reference-types.
2447 // Read the rationale on the spec (14.9.6)
2449 // Also, if at compile time we know that the classes do not inherit
2450 // one from the other, then we catch the error there.
2452 if (!(l.IsValueType || r.IsValueType)){
2453 type = TypeManager.bool_type;
2458 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2462 // Also, a standard conversion must exist from either one
2464 if (!(Convert.ImplicitStandardConversionExists (ec, left, r) ||
2465 Convert.ImplicitStandardConversionExists (ec, right, l))){
2466 Error_OperatorCannotBeApplied ();
2470 // We are going to have to convert to an object to compare
2472 if (l != TypeManager.object_type)
2473 left = new EmptyCast (left, TypeManager.object_type);
2474 if (r != TypeManager.object_type)
2475 right = new EmptyCast (right, TypeManager.object_type);
2478 // FIXME: CSC here catches errors cs254 and cs252
2484 // One of them is a valuetype, but the other one is not.
2486 if (!l.IsValueType || !r.IsValueType) {
2487 Error_OperatorCannotBeApplied ();
2492 // Only perform numeric promotions on:
2493 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2495 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2496 if (TypeManager.IsDelegateType (l)){
2497 if (((right.eclass == ExprClass.MethodGroup) ||
2498 (r == TypeManager.anonymous_method_type))){
2499 if ((RootContext.Version != LanguageVersion.ISO_1)){
2500 Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2508 if (TypeManager.IsDelegateType (r)){
2510 ArrayList args = new ArrayList (2);
2512 args = new ArrayList (2);
2513 args.Add (new Argument (left, Argument.AType.Expression));
2514 args.Add (new Argument (right, Argument.AType.Expression));
2516 if (oper == Operator.Addition)
2517 method = TypeManager.delegate_combine_delegate_delegate;
2519 method = TypeManager.delegate_remove_delegate_delegate;
2521 if (!TypeManager.IsEqual (l, r)) {
2522 Error_OperatorCannotBeApplied ();
2526 return new BinaryDelegate (l, method, args);
2531 // Pointer arithmetic:
2533 // T* operator + (T* x, int y);
2534 // T* operator + (T* x, uint y);
2535 // T* operator + (T* x, long y);
2536 // T* operator + (T* x, ulong y);
2538 // T* operator + (int y, T* x);
2539 // T* operator + (uint y, T *x);
2540 // T* operator + (long y, T *x);
2541 // T* operator + (ulong y, T *x);
2543 // T* operator - (T* x, int y);
2544 // T* operator - (T* x, uint y);
2545 // T* operator - (T* x, long y);
2546 // T* operator - (T* x, ulong y);
2548 // long operator - (T* x, T *y)
2551 if (r.IsPointer && oper == Operator.Subtraction){
2553 return new PointerArithmetic (
2554 false, left, right, TypeManager.int64_type,
2557 Expression t = Make32or64 (ec, right);
2559 return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc).Resolve (ec);
2561 } else if (r.IsPointer && oper == Operator.Addition){
2562 Expression t = Make32or64 (ec, left);
2564 return new PointerArithmetic (true, right, t, r, loc).Resolve (ec);
2569 // Enumeration operators
2571 bool lie = TypeManager.IsEnumType (l);
2572 bool rie = TypeManager.IsEnumType (r);
2576 // U operator - (E e, E f)
2578 if (oper == Operator.Subtraction){
2580 type = TypeManager.EnumToUnderlying (l);
2583 Error_OperatorCannotBeApplied ();
2589 // operator + (E e, U x)
2590 // operator - (E e, U x)
2592 if (oper == Operator.Addition || oper == Operator.Subtraction){
2593 Type enum_type = lie ? l : r;
2594 Type other_type = lie ? r : l;
2595 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2597 if (underlying_type != other_type){
2598 temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
2608 Error_OperatorCannotBeApplied ();
2617 temp = Convert.ImplicitConversion (ec, right, l, loc);
2621 Error_OperatorCannotBeApplied ();
2625 temp = Convert.ImplicitConversion (ec, left, r, loc);
2630 Error_OperatorCannotBeApplied ();
2635 if (oper == Operator.Equality || oper == Operator.Inequality ||
2636 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2637 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2638 if (left.Type != right.Type){
2639 Error_OperatorCannotBeApplied ();
2642 type = TypeManager.bool_type;
2646 if (oper == Operator.BitwiseAnd ||
2647 oper == Operator.BitwiseOr ||
2648 oper == Operator.ExclusiveOr){
2652 Error_OperatorCannotBeApplied ();
2656 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2657 return CheckShiftArguments (ec);
2659 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2660 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2661 type = TypeManager.bool_type;
2666 Error_OperatorCannotBeApplied ();
2670 Expression e = new ConditionalLogicalOperator (
2671 oper == Operator.LogicalAnd, left, right, l, loc);
2672 return e.Resolve (ec);
2676 // operator & (bool x, bool y)
2677 // operator | (bool x, bool y)
2678 // operator ^ (bool x, bool y)
2680 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2681 if (oper == Operator.BitwiseAnd ||
2682 oper == Operator.BitwiseOr ||
2683 oper == Operator.ExclusiveOr){
2690 // Pointer comparison
2692 if (l.IsPointer && r.IsPointer){
2693 if (oper == Operator.Equality || oper == Operator.Inequality ||
2694 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2695 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2696 type = TypeManager.bool_type;
2702 // This will leave left or right set to null if there is an error
2704 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2705 DoNumericPromotions (ec, l, r, check_user_conv);
2706 if (left == null || right == null){
2707 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2712 // reload our cached types if required
2717 if (oper == Operator.BitwiseAnd ||
2718 oper == Operator.BitwiseOr ||
2719 oper == Operator.ExclusiveOr){
2721 if (((l == TypeManager.int32_type) ||
2722 (l == TypeManager.uint32_type) ||
2723 (l == TypeManager.short_type) ||
2724 (l == TypeManager.ushort_type) ||
2725 (l == TypeManager.int64_type) ||
2726 (l == TypeManager.uint64_type))){
2729 Error_OperatorCannotBeApplied ();
2733 Error_OperatorCannotBeApplied ();
2738 if (oper == Operator.Equality ||
2739 oper == Operator.Inequality ||
2740 oper == Operator.LessThanOrEqual ||
2741 oper == Operator.LessThan ||
2742 oper == Operator.GreaterThanOrEqual ||
2743 oper == Operator.GreaterThan){
2744 type = TypeManager.bool_type;
2750 public override Expression DoResolve (EmitContext ec)
2752 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2753 left = ((ParenthesizedExpression) left).Expr;
2754 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2758 if (left.eclass == ExprClass.Type) {
2759 Error (75, "Casting a negative value needs to have the value in parentheses.");
2763 left = left.Resolve (ec);
2768 Constant lc = left as Constant;
2769 if (lc != null && lc.Type == TypeManager.bool_type &&
2770 ((oper == Operator.LogicalAnd && (bool)lc.GetValue () == false) ||
2771 (oper == Operator.LogicalOr && (bool)lc.GetValue () == true))) {
2773 // TODO: make a sense to resolve unreachable expression as we do for statement
2774 Report.Warning (429, 4, loc, "Unreachable expression code detected");
2778 right = right.Resolve (ec);
2782 eclass = ExprClass.Value;
2784 Constant rc = right as Constant;
2785 if (rc != null & lc != null){
2786 Expression e = ConstantFold.BinaryFold (
2787 ec, oper, lc, rc, loc);
2792 if (TypeManager.IsNullableType (left.Type) || TypeManager.IsNullableType (right.Type))
2793 return new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
2795 return ResolveOperator (ec);
2799 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2800 /// context of a conditional bool expression. This function will return
2801 /// false if it is was possible to use EmitBranchable, or true if it was.
2803 /// The expression's code is generated, and we will generate a branch to `target'
2804 /// if the resulting expression value is equal to isTrue
2806 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2808 ILGenerator ig = ec.ig;
2811 // This is more complicated than it looks, but its just to avoid
2812 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2813 // but on top of that we want for == and != to use a special path
2814 // if we are comparing against null
2816 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
2817 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2820 // put the constant on the rhs, for simplicity
2822 if (left is Constant) {
2823 Expression swap = right;
2828 if (((Constant) right).IsZeroInteger) {
2831 ig.Emit (OpCodes.Brtrue, target);
2833 ig.Emit (OpCodes.Brfalse, target);
2836 } else if (right is BoolConstant){
2838 if (my_on_true != ((BoolConstant) right).Value)
2839 ig.Emit (OpCodes.Brtrue, target);
2841 ig.Emit (OpCodes.Brfalse, target);
2846 } else if (oper == Operator.LogicalAnd) {
2849 Label tests_end = ig.DefineLabel ();
2851 left.EmitBranchable (ec, tests_end, false);
2852 right.EmitBranchable (ec, target, true);
2853 ig.MarkLabel (tests_end);
2855 left.EmitBranchable (ec, target, false);
2856 right.EmitBranchable (ec, target, false);
2861 } else if (oper == Operator.LogicalOr){
2863 left.EmitBranchable (ec, target, true);
2864 right.EmitBranchable (ec, target, true);
2867 Label tests_end = ig.DefineLabel ();
2868 left.EmitBranchable (ec, tests_end, true);
2869 right.EmitBranchable (ec, target, false);
2870 ig.MarkLabel (tests_end);
2875 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2876 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2877 oper == Operator.Equality || oper == Operator.Inequality)) {
2878 base.EmitBranchable (ec, target, onTrue);
2886 bool isUnsigned = is_unsigned (t) || t == TypeManager.double_type || t == TypeManager.float_type;
2889 case Operator.Equality:
2891 ig.Emit (OpCodes.Beq, target);
2893 ig.Emit (OpCodes.Bne_Un, target);
2896 case Operator.Inequality:
2898 ig.Emit (OpCodes.Bne_Un, target);
2900 ig.Emit (OpCodes.Beq, target);
2903 case Operator.LessThan:
2906 ig.Emit (OpCodes.Blt_Un, target);
2908 ig.Emit (OpCodes.Blt, target);
2911 ig.Emit (OpCodes.Bge_Un, target);
2913 ig.Emit (OpCodes.Bge, target);
2916 case Operator.GreaterThan:
2919 ig.Emit (OpCodes.Bgt_Un, target);
2921 ig.Emit (OpCodes.Bgt, target);
2924 ig.Emit (OpCodes.Ble_Un, target);
2926 ig.Emit (OpCodes.Ble, target);
2929 case Operator.LessThanOrEqual:
2932 ig.Emit (OpCodes.Ble_Un, target);
2934 ig.Emit (OpCodes.Ble, target);
2937 ig.Emit (OpCodes.Bgt_Un, target);
2939 ig.Emit (OpCodes.Bgt, target);
2943 case Operator.GreaterThanOrEqual:
2946 ig.Emit (OpCodes.Bge_Un, target);
2948 ig.Emit (OpCodes.Bge, target);
2951 ig.Emit (OpCodes.Blt_Un, target);
2953 ig.Emit (OpCodes.Blt, target);
2956 Console.WriteLine (oper);
2957 throw new Exception ("what is THAT");
2961 public override void Emit (EmitContext ec)
2963 ILGenerator ig = ec.ig;
2968 // Handle short-circuit operators differently
2971 if (oper == Operator.LogicalAnd) {
2972 Label load_zero = ig.DefineLabel ();
2973 Label end = ig.DefineLabel ();
2975 left.EmitBranchable (ec, load_zero, false);
2977 ig.Emit (OpCodes.Br, end);
2979 ig.MarkLabel (load_zero);
2980 ig.Emit (OpCodes.Ldc_I4_0);
2983 } else if (oper == Operator.LogicalOr) {
2984 Label load_one = ig.DefineLabel ();
2985 Label end = ig.DefineLabel ();
2987 left.EmitBranchable (ec, load_one, true);
2989 ig.Emit (OpCodes.Br, end);
2991 ig.MarkLabel (load_one);
2992 ig.Emit (OpCodes.Ldc_I4_1);
3000 bool isUnsigned = is_unsigned (left.Type);
3003 case Operator.Multiply:
3005 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3006 opcode = OpCodes.Mul_Ovf;
3007 else if (isUnsigned)
3008 opcode = OpCodes.Mul_Ovf_Un;
3010 opcode = OpCodes.Mul;
3012 opcode = OpCodes.Mul;
3016 case Operator.Division:
3018 opcode = OpCodes.Div_Un;
3020 opcode = OpCodes.Div;
3023 case Operator.Modulus:
3025 opcode = OpCodes.Rem_Un;
3027 opcode = OpCodes.Rem;
3030 case Operator.Addition:
3032 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3033 opcode = OpCodes.Add_Ovf;
3034 else if (isUnsigned)
3035 opcode = OpCodes.Add_Ovf_Un;
3037 opcode = OpCodes.Add;
3039 opcode = OpCodes.Add;
3042 case Operator.Subtraction:
3044 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3045 opcode = OpCodes.Sub_Ovf;
3046 else if (isUnsigned)
3047 opcode = OpCodes.Sub_Ovf_Un;
3049 opcode = OpCodes.Sub;
3051 opcode = OpCodes.Sub;
3054 case Operator.RightShift:
3056 opcode = OpCodes.Shr_Un;
3058 opcode = OpCodes.Shr;
3061 case Operator.LeftShift:
3062 opcode = OpCodes.Shl;
3065 case Operator.Equality:
3066 opcode = OpCodes.Ceq;
3069 case Operator.Inequality:
3070 ig.Emit (OpCodes.Ceq);
3071 ig.Emit (OpCodes.Ldc_I4_0);
3073 opcode = OpCodes.Ceq;
3076 case Operator.LessThan:
3078 opcode = OpCodes.Clt_Un;
3080 opcode = OpCodes.Clt;
3083 case Operator.GreaterThan:
3085 opcode = OpCodes.Cgt_Un;
3087 opcode = OpCodes.Cgt;
3090 case Operator.LessThanOrEqual:
3091 Type lt = left.Type;
3093 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
3094 ig.Emit (OpCodes.Cgt_Un);
3096 ig.Emit (OpCodes.Cgt);
3097 ig.Emit (OpCodes.Ldc_I4_0);
3099 opcode = OpCodes.Ceq;
3102 case Operator.GreaterThanOrEqual:
3103 Type le = left.Type;
3105 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3106 ig.Emit (OpCodes.Clt_Un);
3108 ig.Emit (OpCodes.Clt);
3110 ig.Emit (OpCodes.Ldc_I4_0);
3112 opcode = OpCodes.Ceq;
3115 case Operator.BitwiseOr:
3116 opcode = OpCodes.Or;
3119 case Operator.BitwiseAnd:
3120 opcode = OpCodes.And;
3123 case Operator.ExclusiveOr:
3124 opcode = OpCodes.Xor;
3128 throw new Exception ("This should not happen: Operator = "
3129 + oper.ToString ());
3137 // Object created by Binary when the binary operator uses an method instead of being
3138 // a binary operation that maps to a CIL binary operation.
3140 public class BinaryMethod : Expression {
3141 public MethodBase method;
3142 public ArrayList Arguments;
3144 public BinaryMethod (Type t, MethodBase m, ArrayList args)
3149 eclass = ExprClass.Value;
3152 public override Expression DoResolve (EmitContext ec)
3157 public override void Emit (EmitContext ec)
3159 ILGenerator ig = ec.ig;
3161 if (Arguments != null)
3162 Invocation.EmitArguments (ec, method, Arguments, false, null);
3164 if (method is MethodInfo)
3165 ig.Emit (OpCodes.Call, (MethodInfo) method);
3167 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3172 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3173 // b, c, d... may be strings or objects.
3175 public class StringConcat : Expression {
3177 bool invalid = false;
3178 bool emit_conv_done = false;
3180 // Are we also concating objects?
3182 bool is_strings_only = true;
3184 public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
3187 type = TypeManager.string_type;
3188 eclass = ExprClass.Value;
3190 operands = new ArrayList (2);
3195 public override Expression DoResolve (EmitContext ec)
3203 public void Append (EmitContext ec, Expression operand)
3208 if (operand is StringConstant && operands.Count != 0) {
3209 StringConstant last_operand = operands [operands.Count - 1] as StringConstant;
3210 if (last_operand != null) {
3211 operands [operands.Count - 1] = new StringConstant (last_operand.Value + ((StringConstant) operand).Value);
3217 // Conversion to object
3219 if (operand.Type != TypeManager.string_type) {
3220 Expression no = Convert.ImplicitConversion (ec, operand, TypeManager.object_type, loc);
3223 Binary.Error_OperatorCannotBeApplied (loc, "+", TypeManager.string_type, operand.Type);
3229 operands.Add (operand);
3232 public override void Emit (EmitContext ec)
3234 MethodInfo concat_method = null;
3237 // Do conversion to arguments; check for strings only
3240 // This can get called multiple times, so we have to deal with that.
3241 if (!emit_conv_done) {
3242 emit_conv_done = true;
3243 for (int i = 0; i < operands.Count; i ++) {
3244 Expression e = (Expression) operands [i];
3245 is_strings_only &= e.Type == TypeManager.string_type;
3248 for (int i = 0; i < operands.Count; i ++) {
3249 Expression e = (Expression) operands [i];
3251 if (! is_strings_only && e.Type == TypeManager.string_type) {
3252 // need to make sure this is an object, because the EmitParams
3253 // method might look at the type of this expression, see it is a
3254 // string and emit a string [] when we want an object [];
3256 e = new EmptyCast (e, TypeManager.object_type);
3258 operands [i] = new Argument (e, Argument.AType.Expression);
3263 // Find the right method
3265 switch (operands.Count) {
3268 // This should not be possible, because simple constant folding
3269 // is taken care of in the Binary code.
3271 throw new Exception ("how did you get here?");
3274 concat_method = is_strings_only ?
3275 TypeManager.string_concat_string_string :
3276 TypeManager.string_concat_object_object ;
3279 concat_method = is_strings_only ?
3280 TypeManager.string_concat_string_string_string :
3281 TypeManager.string_concat_object_object_object ;
3285 // There is not a 4 param overlaod for object (the one that there is
3286 // is actually a varargs methods, and is only in corlib because it was
3287 // introduced there before.).
3289 if (!is_strings_only)
3292 concat_method = TypeManager.string_concat_string_string_string_string;
3295 concat_method = is_strings_only ?
3296 TypeManager.string_concat_string_dot_dot_dot :
3297 TypeManager.string_concat_object_dot_dot_dot ;
3301 Invocation.EmitArguments (ec, concat_method, operands, false, null);
3302 ec.ig.Emit (OpCodes.Call, concat_method);
3307 // Object created with +/= on delegates
3309 public class BinaryDelegate : Expression {
3313 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3318 eclass = ExprClass.Value;
3321 public override Expression DoResolve (EmitContext ec)
3326 public override void Emit (EmitContext ec)
3328 ILGenerator ig = ec.ig;
3330 Invocation.EmitArguments (ec, method, args, false, null);
3332 ig.Emit (OpCodes.Call, (MethodInfo) method);
3333 ig.Emit (OpCodes.Castclass, type);
3336 public Expression Right {
3338 Argument arg = (Argument) args [1];
3343 public bool IsAddition {
3345 return method == TypeManager.delegate_combine_delegate_delegate;
3351 // User-defined conditional logical operator
3352 public class ConditionalLogicalOperator : Expression {
3353 Expression left, right;
3356 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3359 eclass = ExprClass.Value;
3363 this.is_and = is_and;
3366 protected void Error19 ()
3368 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3371 protected void Error218 ()
3373 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3374 "declarations of operator true and operator false");
3377 Expression op_true, op_false, op;
3378 LocalTemporary left_temp;
3380 public override Expression DoResolve (EmitContext ec)
3383 Expression operator_group;
3385 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3386 if (operator_group == null) {
3391 left_temp = new LocalTemporary (ec, type);
3393 ArrayList arguments = new ArrayList ();
3394 arguments.Add (new Argument (left_temp, Argument.AType.Expression));
3395 arguments.Add (new Argument (right, Argument.AType.Expression));
3396 method = Invocation.OverloadResolve (
3397 ec, (MethodGroupExpr) operator_group, arguments, false, loc)
3399 if ((method == null) || (method.ReturnType != type)) {
3404 op = new StaticCallExpr (method, arguments, loc);
3406 op_true = GetOperatorTrue (ec, left_temp, loc);
3407 op_false = GetOperatorFalse (ec, left_temp, loc);
3408 if ((op_true == null) || (op_false == null)) {
3416 public override void Emit (EmitContext ec)
3418 ILGenerator ig = ec.ig;
3419 Label false_target = ig.DefineLabel ();
3420 Label end_target = ig.DefineLabel ();
3423 left_temp.Store (ec);
3425 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
3426 left_temp.Emit (ec);
3427 ig.Emit (OpCodes.Br, end_target);
3428 ig.MarkLabel (false_target);
3430 ig.MarkLabel (end_target);
3434 public class PointerArithmetic : Expression {
3435 Expression left, right;
3439 // We assume that `l' is always a pointer
3441 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3447 is_add = is_addition;
3450 public override Expression DoResolve (EmitContext ec)
3452 eclass = ExprClass.Variable;
3454 if (left.Type == TypeManager.void_ptr_type) {
3455 Error (242, "The operation in question is undefined on void pointers");
3462 public override void Emit (EmitContext ec)
3464 Type op_type = left.Type;
3465 ILGenerator ig = ec.ig;
3467 // It must be either array or fixed buffer
3468 Type element = TypeManager.HasElementType (op_type) ?
3469 element = TypeManager.GetElementType (op_type) :
3470 element = AttributeTester.GetFixedBuffer (((FieldExpr)left).FieldInfo).ElementType;
3472 int size = GetTypeSize (element);
3473 Type rtype = right.Type;
3475 if (rtype.IsPointer){
3477 // handle (pointer - pointer)
3481 ig.Emit (OpCodes.Sub);
3485 ig.Emit (OpCodes.Sizeof, element);
3487 IntLiteral.EmitInt (ig, size);
3488 ig.Emit (OpCodes.Div);
3490 ig.Emit (OpCodes.Conv_I8);
3493 // handle + and - on (pointer op int)
3496 ig.Emit (OpCodes.Conv_I);
3498 Constant right_const = right as Constant;
3499 if (right_const != null && size != 0) {
3500 Expression ex = ConstantFold.BinaryFold (ec, Binary.Operator.Multiply, new IntConstant (size), right_const, loc);
3508 ig.Emit (OpCodes.Sizeof, element);
3510 IntLiteral.EmitInt (ig, size);
3511 if (rtype == TypeManager.int64_type)
3512 ig.Emit (OpCodes.Conv_I8);
3513 else if (rtype == TypeManager.uint64_type)
3514 ig.Emit (OpCodes.Conv_U8);
3515 ig.Emit (OpCodes.Mul);
3519 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
3520 ig.Emit (OpCodes.Conv_I);
3523 ig.Emit (OpCodes.Add);
3525 ig.Emit (OpCodes.Sub);
3531 /// Implements the ternary conditional operator (?:)
3533 public class Conditional : Expression {
3534 Expression expr, trueExpr, falseExpr;
3536 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3539 this.trueExpr = trueExpr;
3540 this.falseExpr = falseExpr;
3544 public Expression Expr {
3550 public Expression TrueExpr {
3556 public Expression FalseExpr {
3562 public override Expression DoResolve (EmitContext ec)
3564 expr = expr.Resolve (ec);
3569 if (TypeManager.IsNullableType (expr.Type))
3570 return new Nullable.LiftedConditional (expr, trueExpr, falseExpr, loc).Resolve (ec);
3572 if (expr.Type != TypeManager.bool_type){
3573 expr = Expression.ResolveBoolean (
3580 trueExpr = trueExpr.Resolve (ec);
3581 falseExpr = falseExpr.Resolve (ec);
3583 if (trueExpr == null || falseExpr == null)
3586 eclass = ExprClass.Value;
3587 if (trueExpr.Type == falseExpr.Type)
3588 type = trueExpr.Type;
3591 Type true_type = trueExpr.Type;
3592 Type false_type = falseExpr.Type;
3595 // First, if an implicit conversion exists from trueExpr
3596 // to falseExpr, then the result type is of type falseExpr.Type
3598 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3601 // Check if both can convert implicitl to each other's type
3603 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3605 "Can not compute type of conditional expression " +
3606 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3607 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3608 "' convert implicitly to each other");
3613 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3617 Error (173, "The type of the conditional expression can " +
3618 "not be computed because there is no implicit conversion" +
3619 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3620 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3625 // Dead code optimalization
3626 if (expr is BoolConstant){
3627 BoolConstant bc = (BoolConstant) expr;
3629 Report.Warning (429, 4, bc.Value ? falseExpr.Location : trueExpr.Location, "Unreachable expression code detected");
3630 return bc.Value ? trueExpr : falseExpr;
3636 public override void Emit (EmitContext ec)
3638 ILGenerator ig = ec.ig;
3639 Label false_target = ig.DefineLabel ();
3640 Label end_target = ig.DefineLabel ();
3642 expr.EmitBranchable (ec, false_target, false);
3644 ig.Emit (OpCodes.Br, end_target);
3645 ig.MarkLabel (false_target);
3646 falseExpr.Emit (ec);
3647 ig.MarkLabel (end_target);
3655 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3656 public readonly string Name;
3657 public readonly Block Block;
3658 public LocalInfo local_info;
3661 LocalTemporary temp;
3663 public LocalVariableReference (Block block, string name, Location l)
3668 eclass = ExprClass.Variable;
3672 // Setting `is_readonly' to false will allow you to create a writable
3673 // reference to a read-only variable. This is used by foreach and using.
3675 public LocalVariableReference (Block block, string name, Location l,
3676 LocalInfo local_info, bool is_readonly)
3677 : this (block, name, l)
3679 this.local_info = local_info;
3680 this.is_readonly = is_readonly;
3683 public VariableInfo VariableInfo {
3685 return local_info.VariableInfo;
3689 public bool IsReadOnly {
3695 protected Expression DoResolveBase (EmitContext ec, Expression lvalue_right_side)
3697 if (local_info == null) {
3698 local_info = Block.GetLocalInfo (Name);
3701 if (lvalue_right_side == EmptyExpression.Null)
3702 local_info.Used = true;
3704 is_readonly = local_info.ReadOnly;
3707 type = local_info.VariableType;
3709 VariableInfo variable_info = local_info.VariableInfo;
3710 if (lvalue_right_side != null){
3712 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3716 if (variable_info != null)
3717 variable_info.SetAssigned (ec);
3720 Expression e = Block.GetConstantExpression (Name);
3722 local_info.Used = true;
3723 eclass = ExprClass.Value;
3724 return e.Resolve (ec);
3727 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3730 if (lvalue_right_side == null)
3731 local_info.Used = true;
3733 if (ec.CurrentAnonymousMethod != null){
3735 // If we are referencing a variable from the external block
3736 // flag it for capturing
3738 if (local_info.Block.Toplevel != ec.CurrentBlock.Toplevel){
3739 if (local_info.AddressTaken){
3740 AnonymousMethod.Error_AddressOfCapturedVar (local_info.Name, loc);
3743 ec.CaptureVariable (local_info);
3750 public override Expression DoResolve (EmitContext ec)
3752 return DoResolveBase (ec, null);
3755 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3757 Expression ret = DoResolveBase (ec, right_side);
3759 CheckObsoleteAttribute (ret.Type);
3764 public bool VerifyFixed (bool is_expression)
3766 return !is_expression || local_info.IsFixed;
3769 public override void Emit (EmitContext ec)
3771 ILGenerator ig = ec.ig;
3773 if (local_info.FieldBuilder == null){
3775 // A local variable on the local CLR stack
3777 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3780 // A local variable captured by anonymous methods.
3783 ec.EmitCapturedVariableInstance (local_info);
3785 ig.Emit (OpCodes.Ldfld, local_info.FieldBuilder);
3789 public void Emit (EmitContext ec, bool leave_copy)
3793 ec.ig.Emit (OpCodes.Dup);
3794 if (local_info.FieldBuilder != null){
3795 temp = new LocalTemporary (ec, Type);
3801 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3803 ILGenerator ig = ec.ig;
3804 prepared = prepare_for_load;
3806 if (local_info.FieldBuilder == null){
3808 // A local variable on the local CLR stack
3810 if (local_info.LocalBuilder == null)
3811 throw new Exception ("This should not happen: both Field and Local are null");
3815 ec.ig.Emit (OpCodes.Dup);
3816 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3819 // A local variable captured by anonymous methods or itereators.
3821 ec.EmitCapturedVariableInstance (local_info);
3823 if (prepare_for_load)
3824 ig.Emit (OpCodes.Dup);
3827 ig.Emit (OpCodes.Dup);
3828 temp = new LocalTemporary (ec, Type);
3831 ig.Emit (OpCodes.Stfld, local_info.FieldBuilder);
3837 public void AddressOf (EmitContext ec, AddressOp mode)
3839 ILGenerator ig = ec.ig;
3841 if (local_info.FieldBuilder == null){
3843 // A local variable on the local CLR stack
3845 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3848 // A local variable captured by anonymous methods or iterators
3850 ec.EmitCapturedVariableInstance (local_info);
3851 ig.Emit (OpCodes.Ldflda, local_info.FieldBuilder);
3855 public override string ToString ()
3857 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3862 /// This represents a reference to a parameter in the intermediate
3865 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3871 public Parameter.Modifier mod;
3872 public bool is_ref, is_out, prepared;
3886 LocalTemporary temp;
3888 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3895 eclass = ExprClass.Variable;
3898 public VariableInfo VariableInfo {
3902 public bool VerifyFixed (bool is_expression)
3904 return !is_expression || TypeManager.IsValueType (type);
3907 public bool IsAssigned (EmitContext ec, Location loc)
3909 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsAssigned (vi))
3912 Report.Error (165, loc,
3913 "Use of unassigned parameter `" + name + "'");
3917 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3919 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3922 Report.Error (170, loc,
3923 "Use of possibly unassigned field `" + field_name + "'");
3927 public void SetAssigned (EmitContext ec)
3929 if (is_out && ec.DoFlowAnalysis)
3930 ec.CurrentBranching.SetAssigned (vi);
3933 public void SetFieldAssigned (EmitContext ec, string field_name)
3935 if (is_out && ec.DoFlowAnalysis)
3936 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3939 protected void DoResolveBase (EmitContext ec)
3941 type = pars.GetParameterInfo (ec, idx, out mod);
3942 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3943 is_out = (mod & Parameter.Modifier.OUT) != 0;
3944 eclass = ExprClass.Variable;
3947 vi = block.ParameterMap [idx];
3949 if (ec.CurrentAnonymousMethod != null){
3951 Report.Error (1628, Location,
3952 "Can not reference a ref or out parameter in an anonymous method");
3957 // If we are referencing the parameter from the external block
3958 // flag it for capturing
3960 //Console.WriteLine ("Is parameter `{0}' local? {1}", name, block.IsLocalParameter (name));
3961 if (!block.IsLocalParameter (name)){
3962 ec.CaptureParameter (name, type, idx);
3968 // Notice that for ref/out parameters, the type exposed is not the
3969 // same type exposed externally.
3972 // externally we expose "int&"
3973 // here we expose "int".
3975 // We record this in "is_ref". This means that the type system can treat
3976 // the type as it is expected, but when we generate the code, we generate
3977 // the alternate kind of code.
3979 public override Expression DoResolve (EmitContext ec)
3983 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3986 if (ec.RemapToProxy)
3987 return ec.RemapParameter (idx);
3992 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3998 if (ec.RemapToProxy)
3999 return ec.RemapParameterLValue (idx, right_side);
4004 static public void EmitLdArg (ILGenerator ig, int x)
4008 case 0: ig.Emit (OpCodes.Ldarg_0); break;
4009 case 1: ig.Emit (OpCodes.Ldarg_1); break;
4010 case 2: ig.Emit (OpCodes.Ldarg_2); break;
4011 case 3: ig.Emit (OpCodes.Ldarg_3); break;
4012 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
4015 ig.Emit (OpCodes.Ldarg, x);
4019 // This method is used by parameters that are references, that are
4020 // being passed as references: we only want to pass the pointer (that
4021 // is already stored in the parameter, not the address of the pointer,
4022 // and not the value of the variable).
4024 public void EmitLoad (EmitContext ec)
4026 ILGenerator ig = ec.ig;
4029 if (!ec.MethodIsStatic)
4033 EmitLdArg (ig, arg_idx);
4036 // FIXME: Review for anonymous methods
4040 public override void Emit (EmitContext ec)
4042 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4043 ec.EmitParameter (name);
4050 public void Emit (EmitContext ec, bool leave_copy)
4052 ILGenerator ig = ec.ig;
4055 if (!ec.MethodIsStatic)
4058 EmitLdArg (ig, arg_idx);
4062 ec.ig.Emit (OpCodes.Dup);
4065 // If we are a reference, we loaded on the stack a pointer
4066 // Now lets load the real value
4068 LoadFromPtr (ig, type);
4072 ec.ig.Emit (OpCodes.Dup);
4075 temp = new LocalTemporary (ec, type);
4081 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
4083 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4084 ec.EmitAssignParameter (name, source, leave_copy, prepare_for_load);
4088 ILGenerator ig = ec.ig;
4091 prepared = prepare_for_load;
4093 if (!ec.MethodIsStatic)
4096 if (is_ref && !prepared)
4097 EmitLdArg (ig, arg_idx);
4102 ec.ig.Emit (OpCodes.Dup);
4106 temp = new LocalTemporary (ec, type);
4110 StoreFromPtr (ig, type);
4116 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
4118 ig.Emit (OpCodes.Starg, arg_idx);
4122 public void AddressOf (EmitContext ec, AddressOp mode)
4124 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4125 ec.EmitAddressOfParameter (name);
4131 if (!ec.MethodIsStatic)
4136 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
4138 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
4141 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
4143 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
4150 /// Used for arguments to New(), Invocation()
4152 public class Argument {
4153 public enum AType : byte {
4160 public readonly AType ArgType;
4161 public Expression Expr;
4163 public Argument (Expression expr, AType type)
4166 this.ArgType = type;
4169 public Argument (Expression expr)
4172 this.ArgType = AType.Expression;
4177 if (ArgType == AType.Ref || ArgType == AType.Out)
4178 return TypeManager.GetReferenceType (Expr.Type);
4184 public Parameter.Modifier GetParameterModifier ()
4188 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
4191 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
4194 return Parameter.Modifier.NONE;
4198 public static string FullDesc (Argument a)
4200 if (a.ArgType == AType.ArgList)
4203 return (a.ArgType == AType.Ref ? "ref " :
4204 (a.ArgType == AType.Out ? "out " : "")) +
4205 TypeManager.CSharpName (a.Expr.Type);
4208 public bool ResolveMethodGroup (EmitContext ec, Location loc)
4210 ConstructedType ctype = Expr as ConstructedType;
4212 Expr = ctype.GetSimpleName (ec);
4214 // FIXME: csc doesn't report any error if you try to use `ref' or
4215 // `out' in a delegate creation expression.
4216 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4223 public bool Resolve (EmitContext ec, Location loc)
4225 if (ArgType == AType.Ref) {
4226 Expr = Expr.Resolve (ec);
4230 if (!ec.IsConstructor) {
4231 FieldExpr fe = Expr as FieldExpr;
4232 if (fe != null && fe.FieldInfo.IsInitOnly) {
4233 if (fe.FieldInfo.IsStatic)
4234 Report.Error (199, loc, "A static readonly field cannot be passed ref or out (except in a static constructor)");
4236 Report.Error (192, loc, "A readonly field cannot be passed ref or out (except in a constructor)");
4240 Expr = Expr.ResolveLValue (ec, Expr);
4241 } else if (ArgType == AType.Out)
4242 Expr = Expr.ResolveLValue (ec, EmptyExpression.Null);
4244 Expr = Expr.Resolve (ec);
4249 if (ArgType == AType.Expression)
4253 // Catch errors where fields of a MarshalByRefObject are passed as ref or out
4254 // This is only allowed for `this'
4256 FieldExpr fe = Expr as FieldExpr;
4257 if (fe != null && !fe.IsStatic){
4258 Expression instance = fe.InstanceExpression;
4260 if (instance.GetType () != typeof (This)){
4261 if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
4262 Report.SymbolRelatedToPreviousError (fe.InstanceExpression.Type);
4263 Report.Error (197, loc, "Cannot pass '{0}' as ref or out or take its address because it is a member of a marshal-by-reference class",
4271 if (Expr.eclass != ExprClass.Variable){
4273 // We just probe to match the CSC output
4275 if (Expr.eclass == ExprClass.PropertyAccess ||
4276 Expr.eclass == ExprClass.IndexerAccess){
4279 "A property or indexer can not be passed as an out or ref " +
4284 "An lvalue is required as an argument to out or ref");
4292 public void Emit (EmitContext ec)
4295 // Ref and Out parameters need to have their addresses taken.
4297 // ParameterReferences might already be references, so we want
4298 // to pass just the value
4300 if (ArgType == AType.Ref || ArgType == AType.Out){
4301 AddressOp mode = AddressOp.Store;
4303 if (ArgType == AType.Ref)
4304 mode |= AddressOp.Load;
4306 if (Expr is ParameterReference){
4307 ParameterReference pr = (ParameterReference) Expr;
4313 pr.AddressOf (ec, mode);
4316 if (Expr is IMemoryLocation)
4317 ((IMemoryLocation) Expr).AddressOf (ec, mode);
4320 1510, Expr.Location,
4321 "An lvalue is required as an argument to out or ref");
4331 /// Invocation of methods or delegates.
4333 public class Invocation : ExpressionStatement {
4334 public readonly ArrayList Arguments;
4337 MethodBase method = null;
4340 // arguments is an ArrayList, but we do not want to typecast,
4341 // as it might be null.
4343 // FIXME: only allow expr to be a method invocation or a
4344 // delegate invocation (7.5.5)
4346 public Invocation (Expression expr, ArrayList arguments, Location l)
4349 Arguments = arguments;
4353 public Expression Expr {
4360 /// Determines "better conversion" as specified in 7.4.2.3
4362 /// Returns : p if a->p is better,
4363 /// q if a->q is better,
4364 /// null if neither is better
4366 static Type BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
4368 Type argument_type = TypeManager.TypeToCoreType (a.Type);
4369 Expression argument_expr = a.Expr;
4371 // p = TypeManager.TypeToCoreType (p);
4372 // q = TypeManager.TypeToCoreType (q);
4374 if (argument_type == null)
4375 throw new Exception ("Expression of type " + a.Expr +
4376 " does not resolve its type");
4378 if (p == null || q == null)
4379 throw new InternalErrorException ("BetterConversion Got a null conversion");
4384 if (argument_expr is NullLiteral) {
4386 // If the argument is null and one of the types to compare is 'object' and
4387 // the other is a reference type, we prefer the other.
4389 // This follows from the usual rules:
4390 // * There is an implicit conversion from 'null' to type 'object'
4391 // * There is an implicit conversion from 'null' to any reference type
4392 // * There is an implicit conversion from any reference type to type 'object'
4393 // * There is no implicit conversion from type 'object' to other reference types
4394 // => Conversion of 'null' to a reference type is better than conversion to 'object'
4396 // FIXME: This probably isn't necessary, since the type of a NullLiteral is the
4397 // null type. I think it used to be 'object' and thus needed a special
4398 // case to avoid the immediately following two checks.
4400 if (!p.IsValueType && q == TypeManager.object_type)
4402 if (!q.IsValueType && p == TypeManager.object_type)
4406 if (argument_type == p)
4409 if (argument_type == q)
4412 Expression p_tmp = new EmptyExpression (p);
4413 Expression q_tmp = new EmptyExpression (q);
4415 bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
4416 bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
4418 if (p_to_q && !q_to_p)
4421 if (q_to_p && !p_to_q)
4424 if (p == TypeManager.sbyte_type)
4425 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4426 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4428 if (q == TypeManager.sbyte_type)
4429 if (p == TypeManager.byte_type || p == TypeManager.ushort_type ||
4430 p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4433 if (p == TypeManager.short_type)
4434 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4435 q == TypeManager.uint64_type)
4438 if (q == TypeManager.short_type)
4439 if (p == TypeManager.ushort_type || p == TypeManager.uint32_type ||
4440 p == TypeManager.uint64_type)
4443 if (p == TypeManager.int32_type)
4444 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4447 if (q == TypeManager.int32_type)
4448 if (p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4451 if (p == TypeManager.int64_type)
4452 if (q == TypeManager.uint64_type)
4454 if (q == TypeManager.int64_type)
4455 if (p == TypeManager.uint64_type)
4462 /// Determines "Better function" between candidate
4463 /// and the current best match
4466 /// Returns a boolean indicating :
4467 /// false if candidate ain't better
4468 /// true if candidate is better than the current best match
4470 static bool BetterFunction (EmitContext ec, ArrayList args, int argument_count,
4471 MethodBase candidate, bool candidate_params,
4472 MethodBase best, bool best_params, Location loc)
4474 ParameterData candidate_pd = TypeManager.GetParameterData (candidate);
4475 ParameterData best_pd = TypeManager.GetParameterData (best);
4477 bool better_at_least_one = false;
4479 for (int j = 0; j < argument_count; ++j) {
4480 Argument a = (Argument) args [j];
4482 Type ct = TypeManager.TypeToCoreType (candidate_pd.ParameterType (j));
4483 Type bt = TypeManager.TypeToCoreType (best_pd.ParameterType (j));
4485 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4486 if (candidate_params)
4487 ct = TypeManager.GetElementType (ct);
4489 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4491 bt = TypeManager.GetElementType (bt);
4497 Type better = BetterConversion (ec, a, ct, bt, loc);
4498 // for each argument, the conversion to 'ct' should be no worse than
4499 // the conversion to 'bt'.
4503 // for at least one argument, the conversion to 'ct' should be better than
4504 // the conversion to 'bt'.
4506 better_at_least_one = true;
4509 if (better_at_least_one)
4516 // If two methods have equal parameter types, but
4517 // only one of them is generic, the non-generic one wins.
4519 if (TypeManager.IsGenericMethod (best) && !TypeManager.IsGenericMethod (candidate))
4521 else if (!TypeManager.IsGenericMethod (best) && TypeManager.IsGenericMethod (candidate))
4525 // Note that this is not just an optimization. This handles the case
4527 // Add (float f1, float f2, float f3);
4528 // Add (params decimal [] foo);
4530 // The call Add (3, 4, 5) should be ambiguous. Without this check, the
4531 // first candidate would've chosen as better.
4533 if (candidate_params == best_params) {
4535 // We need to handle the case of a virtual function and its override.
4536 // The override is ignored during 'applicable_type' calculation. However,
4537 // it should be chosen over the base virtual function, especially when handling
4540 return IsAncestralType (best.DeclaringType, candidate.DeclaringType);
4544 // This handles the following cases:
4546 // Trim () is better than Trim (params char[] chars)
4547 // Concat (string s1, string s2, string s3) is better than
4548 // Concat (string s1, params string [] srest)
4550 return !candidate_params && best_params;
4553 public static string FullMethodDesc (MethodBase mb)
4555 string ret_type = "";
4560 if (mb is MethodInfo)
4561 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
4563 StringBuilder sb = new StringBuilder (ret_type);
4565 sb.Append (mb.ReflectedType.ToString ());
4567 sb.Append (mb.Name);
4569 ParameterData pd = TypeManager.GetParameterData (mb);
4571 int count = pd.Count;
4574 for (int i = count; i > 0; ) {
4577 sb.Append (pd.ParameterDesc (count - i - 1));
4583 return sb.ToString ();
4586 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4588 MemberInfo [] miset;
4589 MethodGroupExpr union;
4594 return (MethodGroupExpr) mg2;
4597 return (MethodGroupExpr) mg1;
4600 MethodGroupExpr left_set = null, right_set = null;
4601 int length1 = 0, length2 = 0;
4603 left_set = (MethodGroupExpr) mg1;
4604 length1 = left_set.Methods.Length;
4606 right_set = (MethodGroupExpr) mg2;
4607 length2 = right_set.Methods.Length;
4609 ArrayList common = new ArrayList ();
4611 foreach (MethodBase r in right_set.Methods){
4612 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
4616 miset = new MemberInfo [length1 + length2 - common.Count];
4617 left_set.Methods.CopyTo (miset, 0);
4621 foreach (MethodBase r in right_set.Methods) {
4622 if (!common.Contains (r))
4626 union = new MethodGroupExpr (miset, loc);
4631 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4632 ArrayList arguments, int arg_count,
4633 ref MethodBase candidate)
4635 return IsParamsMethodApplicable (
4636 ec, me, arguments, arg_count, false, ref candidate) ||
4637 IsParamsMethodApplicable (
4638 ec, me, arguments, arg_count, true, ref candidate);
4643 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4644 ArrayList arguments, int arg_count,
4645 bool do_varargs, ref MethodBase candidate)
4647 if (!me.HasTypeArguments &&
4648 !TypeManager.InferParamsTypeArguments (ec, arguments, ref candidate))
4651 return IsParamsMethodApplicable (
4652 ec, arguments, arg_count, candidate, do_varargs);
4656 /// Determines if the candidate method, if a params method, is applicable
4657 /// in its expanded form to the given set of arguments
4659 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
4660 int arg_count, MethodBase candidate,
4663 ParameterData pd = TypeManager.GetParameterData (candidate);
4665 int pd_count = pd.Count;
4670 int count = pd_count - 1;
4672 if (pd.ParameterModifier (count) != Parameter.Modifier.ARGLIST)
4674 if (pd_count != arg_count)
4677 if (pd.ParameterModifier (count) != Parameter.Modifier.PARAMS)
4681 if (count > arg_count)
4684 if (pd_count == 1 && arg_count == 0)
4688 // If we have come this far, the case which
4689 // remains is when the number of parameters is
4690 // less than or equal to the argument count.
4692 for (int i = 0; i < count; ++i) {
4694 Argument a = (Argument) arguments [i];
4696 Parameter.Modifier a_mod = a.GetParameterModifier () &
4697 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4698 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4699 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4701 if (a_mod == p_mod) {
4703 if (a_mod == Parameter.Modifier.NONE)
4704 if (!Convert.ImplicitConversionExists (ec,
4706 pd.ParameterType (i)))
4709 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4710 Type pt = pd.ParameterType (i);
4713 pt = TypeManager.GetReferenceType (pt);
4724 Argument a = (Argument) arguments [count];
4725 if (!(a.Expr is Arglist))
4731 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4733 for (int i = pd_count - 1; i < arg_count; i++) {
4734 Argument a = (Argument) arguments [i];
4736 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4743 static bool IsApplicable (EmitContext ec, MethodGroupExpr me,
4744 ArrayList arguments, int arg_count,
4745 ref MethodBase candidate)
4747 if (!me.HasTypeArguments &&
4748 !TypeManager.InferTypeArguments (ec, arguments, ref candidate))
4751 return IsApplicable (ec, arguments, arg_count, candidate);
4755 /// Determines if the candidate method is applicable (section 14.4.2.1)
4756 /// to the given set of arguments
4758 static bool IsApplicable (EmitContext ec, ArrayList arguments, int arg_count,
4759 MethodBase candidate)
4761 ParameterData pd = TypeManager.GetParameterData (candidate);
4763 if (arg_count != pd.Count)
4766 for (int i = arg_count; i > 0; ) {
4769 Argument a = (Argument) arguments [i];
4771 Parameter.Modifier a_mod = a.GetParameterModifier () &
4772 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4773 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4774 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4777 if (a_mod == p_mod ||
4778 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4779 if (a_mod == Parameter.Modifier.NONE) {
4780 if (!Convert.ImplicitConversionExists (ec,
4782 pd.ParameterType (i)))
4786 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4787 Type pt = pd.ParameterType (i);
4790 pt = TypeManager.GetReferenceType (pt);
4802 static private bool IsAncestralType (Type first_type, Type second_type)
4804 return first_type != second_type &&
4805 (second_type.IsSubclassOf (first_type) ||
4806 TypeManager.ImplementsInterface (second_type, first_type));
4810 /// Find the Applicable Function Members (7.4.2.1)
4812 /// me: Method Group expression with the members to select.
4813 /// it might contain constructors or methods (or anything
4814 /// that maps to a method).
4816 /// Arguments: ArrayList containing resolved Argument objects.
4818 /// loc: The location if we want an error to be reported, or a Null
4819 /// location for "probing" purposes.
4821 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4822 /// that is the best match of me on Arguments.
4825 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4826 ArrayList Arguments, bool may_fail,
4829 MethodBase method = null;
4830 bool method_params = false;
4831 Type applicable_type = null;
4833 ArrayList candidates = new ArrayList ();
4836 // Used to keep a map between the candidate
4837 // and whether it is being considered in its
4838 // normal or expanded form
4840 // false is normal form, true is expanded form
4842 Hashtable candidate_to_form = null;
4844 if (Arguments != null)
4845 arg_count = Arguments.Count;
4847 if ((me.Name == "Invoke") &&
4848 TypeManager.IsDelegateType (me.DeclaringType)) {
4849 Error_InvokeOnDelegate (loc);
4853 MethodBase[] methods = me.Methods;
4856 // First we construct the set of applicable methods
4858 bool is_sorted = true;
4859 for (int i = 0; i < methods.Length; i++){
4860 Type decl_type = methods [i].DeclaringType;
4863 // If we have already found an applicable method
4864 // we eliminate all base types (Section 14.5.5.1)
4866 if ((applicable_type != null) &&
4867 IsAncestralType (decl_type, applicable_type))
4871 // Check if candidate is applicable (section 14.4.2.1)
4872 // Is candidate applicable in normal form?
4874 bool is_applicable = IsApplicable (
4875 ec, me, Arguments, arg_count, ref methods [i]);
4877 if (!is_applicable &&
4878 (IsParamsMethodApplicable (
4879 ec, me, Arguments, arg_count, ref methods [i]))) {
4880 MethodBase candidate = methods [i];
4881 if (candidate_to_form == null)
4882 candidate_to_form = new PtrHashtable ();
4883 candidate_to_form [candidate] = candidate;
4884 // Candidate is applicable in expanded form
4885 is_applicable = true;
4891 candidates.Add (methods [i]);
4894 // Methods marked 'override' don't take part in 'applicable_type'
4898 methods [i].IsVirtual &&
4899 (methods [i].Attributes & MethodAttributes.NewSlot) == 0)
4902 if (applicable_type == null)
4903 applicable_type = decl_type;
4904 else if (applicable_type != decl_type) {
4906 if (IsAncestralType (applicable_type, decl_type))
4907 applicable_type = decl_type;
4911 int candidate_top = candidates.Count;
4913 if (applicable_type == null) {
4915 // Okay so we have failed to find anything so we
4916 // return by providing info about the closest match
4918 for (int i = 0; i < methods.Length; ++i) {
4919 MethodBase c = (MethodBase) methods [i];
4920 ParameterData pd = TypeManager.GetParameterData (c);
4922 if (pd.Count != arg_count)
4925 if (!TypeManager.InferTypeArguments (ec, Arguments, ref c))
4928 VerifyArgumentsCompat (ec, Arguments, arg_count,
4929 c, false, null, may_fail, loc);
4934 string report_name = me.Name;
4935 if (report_name == ".ctor")
4936 report_name = me.DeclaringType.ToString ();
4938 for (int i = 0; i < methods.Length; ++i) {
4939 MethodBase c = methods [i];
4940 ParameterData pd = TypeManager.GetParameterData (c);
4942 if (pd.Count != arg_count)
4945 if (TypeManager.InferTypeArguments (ec, Arguments, ref c))
4949 411, loc, "The type arguments for " +
4950 "method `{0}' cannot be infered from " +
4951 "the usage. Try specifying the type " +
4952 "arguments explicitly.", report_name);
4956 Error_WrongNumArguments (
4957 loc, report_name, arg_count);
4966 // At this point, applicable_type is _one_ of the most derived types
4967 // in the set of types containing the methods in this MethodGroup.
4968 // Filter the candidates so that they only contain methods from the
4969 // most derived types.
4972 int finalized = 0; // Number of finalized candidates
4975 // Invariant: applicable_type is a most derived type
4977 // We'll try to complete Section 14.5.5.1 for 'applicable_type' by
4978 // eliminating all it's base types. At the same time, we'll also move
4979 // every unrelated type to the end of the array, and pick the next
4980 // 'applicable_type'.
4982 Type next_applicable_type = null;
4983 int j = finalized; // where to put the next finalized candidate
4984 int k = finalized; // where to put the next undiscarded candidate
4985 for (int i = finalized; i < candidate_top; ++i) {
4986 MethodBase candidate = (MethodBase) candidates [i];
4987 Type decl_type = candidate.DeclaringType;
4989 if (decl_type == applicable_type) {
4990 candidates [k++] = candidates [j];
4991 candidates [j++] = candidates [i];
4995 if (IsAncestralType (decl_type, applicable_type))
4998 if (next_applicable_type != null &&
4999 IsAncestralType (decl_type, next_applicable_type))
5002 candidates [k++] = candidates [i];
5006 // Methods marked 'override' don't take part in 'applicable_type'
5010 candidate.IsVirtual &&
5011 (candidate.Attributes & MethodAttributes.NewSlot) == 0)
5015 if (next_applicable_type == null ||
5016 IsAncestralType (next_applicable_type, decl_type))
5017 next_applicable_type = decl_type;
5020 applicable_type = next_applicable_type;
5023 } while (applicable_type != null);
5027 // Now we actually find the best method
5030 method = (MethodBase) candidates [0];
5031 method_params = candidate_to_form != null && candidate_to_form.Contains (method);
5032 for (int ix = 1; ix < candidate_top; ix++){
5033 MethodBase candidate = (MethodBase) candidates [ix];
5035 if (candidate == method)
5038 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
5040 if (BetterFunction (ec, Arguments, arg_count,
5041 candidate, cand_params,
5042 method, method_params, loc)) {
5044 method_params = cand_params;
5049 // Now check that there are no ambiguities i.e the selected method
5050 // should be better than all the others
5052 bool ambiguous = false;
5053 for (int ix = 0; ix < candidate_top; ix++){
5054 MethodBase candidate = (MethodBase) candidates [ix];
5056 if (candidate == method)
5059 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
5060 if (!BetterFunction (ec, Arguments, arg_count,
5061 method, method_params,
5062 candidate, cand_params,
5064 Report.SymbolRelatedToPreviousError (candidate);
5070 Report.SymbolRelatedToPreviousError (method);
5071 Report.Error (121, loc, "Ambiguous call when selecting function due to implicit casts");
5076 // And now check if the arguments are all
5077 // compatible, perform conversions if
5078 // necessary etc. and return if everything is
5081 if (!VerifyArgumentsCompat (ec, Arguments, arg_count, method,
5082 method_params, null, may_fail, loc))
5088 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
5090 Report.Error (1501, loc,
5091 "No overload for method `" + name + "' takes `" +
5092 arg_count + "' arguments");
5095 static void Error_InvokeOnDelegate (Location loc)
5097 Report.Error (1533, loc,
5098 "Invoke cannot be called directly on a delegate");
5101 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
5102 Type delegate_type, string arg_sig, string par_desc)
5104 if (delegate_type == null)
5105 Report.Error (1502, loc,
5106 "The best overloaded match for method '" +
5107 FullMethodDesc (method) +
5108 "' has some invalid arguments");
5110 Report.Error (1594, loc,
5111 "Delegate '" + delegate_type.ToString () +
5112 "' has some invalid arguments.");
5113 Report.Error (1503, loc,
5114 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
5115 idx, arg_sig, par_desc));
5118 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
5119 int arg_count, MethodBase method,
5120 bool chose_params_expanded,
5121 Type delegate_type, bool may_fail,
5124 ParameterData pd = TypeManager.GetParameterData (method);
5125 int pd_count = pd.Count;
5127 for (int j = 0; j < arg_count; j++) {
5128 Argument a = (Argument) Arguments [j];
5129 Expression a_expr = a.Expr;
5130 Type parameter_type = pd.ParameterType (j);
5131 Parameter.Modifier pm = pd.ParameterModifier (j);
5133 if (pm == Parameter.Modifier.PARAMS){
5134 if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
5136 Error_InvalidArguments (
5137 loc, j, method, delegate_type,
5138 Argument.FullDesc (a), pd.ParameterDesc (j));
5142 if (chose_params_expanded)
5143 parameter_type = TypeManager.GetElementType (parameter_type);
5144 } else if (pm == Parameter.Modifier.ARGLIST){
5150 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
5152 Error_InvalidArguments (
5153 loc, j, method, delegate_type,
5154 Argument.FullDesc (a), pd.ParameterDesc (j));
5162 if (!TypeManager.IsEqual (a.Type, parameter_type)){
5165 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
5169 Error_InvalidArguments (
5170 loc, j, method, delegate_type,
5171 Argument.FullDesc (a), pd.ParameterDesc (j));
5176 // Update the argument with the implicit conversion
5182 if (parameter_type.IsPointer){
5189 Parameter.Modifier a_mod = a.GetParameterModifier () &
5190 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5191 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
5192 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5194 if (a_mod != p_mod &&
5195 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
5197 Report.Error (1502, loc,
5198 "The best overloaded match for method '" + FullMethodDesc (method)+
5199 "' has some invalid arguments");
5200 Report.Error (1503, loc,
5201 "Argument " + (j+1) +
5202 ": Cannot convert from '" + Argument.FullDesc (a)
5203 + "' to '" + pd.ParameterDesc (j) + "'");
5213 public override Expression DoResolve (EmitContext ec)
5216 // First, resolve the expression that is used to
5217 // trigger the invocation
5219 if (expr is ConstructedType)
5220 expr = ((ConstructedType) expr).GetSimpleName (ec);
5222 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
5226 if (!(expr is MethodGroupExpr)) {
5227 Type expr_type = expr.Type;
5229 if (expr_type != null){
5230 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
5232 return (new DelegateInvocation (
5233 this.expr, Arguments, loc)).Resolve (ec);
5237 if (!(expr is MethodGroupExpr)){
5238 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup, loc);
5243 // Next, evaluate all the expressions in the argument list
5245 if (Arguments != null){
5246 foreach (Argument a in Arguments){
5247 if (!a.Resolve (ec, loc))
5252 MethodGroupExpr mg = (MethodGroupExpr) expr;
5253 method = OverloadResolve (ec, mg, Arguments, false, loc);
5258 MethodInfo mi = method as MethodInfo;
5260 type = TypeManager.TypeToCoreType (mi.ReturnType);
5261 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null)) {
5262 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
5266 Expression iexpr = mg.InstanceExpression;
5267 if (mi.IsStatic && (iexpr != null) && !(iexpr is This)) {
5268 if (mg.IdenticalTypeName)
5269 mg.InstanceExpression = null;
5271 MemberAccess.error176 (loc, mi.Name);
5277 if (type.IsPointer){
5285 // Only base will allow this invocation to happen.
5287 if (mg.IsBase && method.IsAbstract){
5288 Report.Error (205, loc, "Cannot call an abstract base member: " +
5289 FullMethodDesc (method));
5293 if (method.Name == "Finalize" && Arguments == null) {
5295 Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
5297 Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
5301 if ((method.Attributes & MethodAttributes.SpecialName) != 0){
5302 if (TypeManager.LookupDeclSpace (method.DeclaringType) != null || TypeManager.IsSpecialMethod (method)) {
5303 Report.Error (571, loc, TypeManager.CSharpSignature (method) + ": can not call operator or accessor");
5308 if (mg.InstanceExpression != null)
5309 mg.InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
5311 eclass = ExprClass.Value;
5316 // Emits the list of arguments as an array
5318 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
5320 ILGenerator ig = ec.ig;
5321 int count = arguments.Count - idx;
5322 Argument a = (Argument) arguments [idx];
5323 Type t = a.Expr.Type;
5325 IntConstant.EmitInt (ig, count);
5326 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
5328 int top = arguments.Count;
5329 for (int j = idx; j < top; j++){
5330 a = (Argument) arguments [j];
5332 ig.Emit (OpCodes.Dup);
5333 IntConstant.EmitInt (ig, j - idx);
5335 bool is_stobj, has_type_arg;
5336 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj, out has_type_arg);
5338 ig.Emit (OpCodes.Ldelema, t);
5350 /// Emits a list of resolved Arguments that are in the arguments
5353 /// The MethodBase argument might be null if the
5354 /// emission of the arguments is known not to contain
5355 /// a `params' field (for example in constructors or other routines
5356 /// that keep their arguments in this structure)
5358 /// if `dup_args' is true, a copy of the arguments will be left
5359 /// on the stack. If `dup_args' is true, you can specify `this_arg'
5360 /// which will be duplicated before any other args. Only EmitCall
5361 /// should be using this interface.
5363 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments, bool dup_args, LocalTemporary this_arg)
5367 pd = TypeManager.GetParameterData (mb);
5371 LocalTemporary [] temps = null;
5374 temps = new LocalTemporary [arguments.Count];
5377 // If we are calling a params method with no arguments, special case it
5379 if (arguments == null){
5380 if (pd != null && pd.Count > 0 &&
5381 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
5382 ILGenerator ig = ec.ig;
5384 IntConstant.EmitInt (ig, 0);
5385 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
5391 int top = arguments.Count;
5393 for (int i = 0; i < top; i++){
5394 Argument a = (Argument) arguments [i];
5397 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
5399 // Special case if we are passing the same data as the
5400 // params argument, do not put it in an array.
5402 if (pd.ParameterType (i) == a.Type)
5405 EmitParams (ec, i, arguments);
5412 ec.ig.Emit (OpCodes.Dup);
5413 (temps [i] = new LocalTemporary (ec, a.Type)).Store (ec);
5418 if (this_arg != null)
5421 for (int i = 0; i < top; i ++)
5422 temps [i].Emit (ec);
5425 if (pd != null && pd.Count > top &&
5426 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
5427 ILGenerator ig = ec.ig;
5429 IntConstant.EmitInt (ig, 0);
5430 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
5434 static Type[] GetVarargsTypes (EmitContext ec, MethodBase mb,
5435 ArrayList arguments)
5437 ParameterData pd = TypeManager.GetParameterData (mb);
5439 if (arguments == null)
5440 return new Type [0];
5442 Argument a = (Argument) arguments [pd.Count - 1];
5443 Arglist list = (Arglist) a.Expr;
5445 return list.ArgumentTypes;
5449 /// This checks the ConditionalAttribute on the method
5451 static bool IsMethodExcluded (MethodBase method, EmitContext ec)
5453 if (method.IsConstructor)
5456 IMethodData md = TypeManager.GetMethod (method);
5458 return md.IsExcluded (ec);
5460 // For some methods (generated by delegate class) GetMethod returns null
5461 // because they are not included in builder_to_method table
5462 if (method.DeclaringType is TypeBuilder)
5465 return AttributeTester.IsConditionalMethodExcluded (method);
5469 /// is_base tells whether we want to force the use of the `call'
5470 /// opcode instead of using callvirt. Call is required to call
5471 /// a specific method, while callvirt will always use the most
5472 /// recent method in the vtable.
5474 /// is_static tells whether this is an invocation on a static method
5476 /// instance_expr is an expression that represents the instance
5477 /// it must be non-null if is_static is false.
5479 /// method is the method to invoke.
5481 /// Arguments is the list of arguments to pass to the method or constructor.
5483 public static void EmitCall (EmitContext ec, bool is_base,
5484 bool is_static, Expression instance_expr,
5485 MethodBase method, ArrayList Arguments, Location loc)
5487 EmitCall (ec, is_base, is_static, instance_expr, method, Arguments, loc, false, false);
5490 // `dup_args' leaves an extra copy of the arguments on the stack
5491 // `omit_args' does not leave any arguments at all.
5492 // So, basically, you could make one call with `dup_args' set to true,
5493 // and then another with `omit_args' set to true, and the two calls
5494 // would have the same set of arguments. However, each argument would
5495 // only have been evaluated once.
5496 public static void EmitCall (EmitContext ec, bool is_base,
5497 bool is_static, Expression instance_expr,
5498 MethodBase method, ArrayList Arguments, Location loc,
5499 bool dup_args, bool omit_args)
5501 ILGenerator ig = ec.ig;
5502 bool struct_call = false;
5503 bool this_call = false;
5504 LocalTemporary this_arg = null;
5506 Type decl_type = method.DeclaringType;
5508 if (!RootContext.StdLib) {
5509 // Replace any calls to the system's System.Array type with calls to
5510 // the newly created one.
5511 if (method == TypeManager.system_int_array_get_length)
5512 method = TypeManager.int_array_get_length;
5513 else if (method == TypeManager.system_int_array_get_rank)
5514 method = TypeManager.int_array_get_rank;
5515 else if (method == TypeManager.system_object_array_clone)
5516 method = TypeManager.object_array_clone;
5517 else if (method == TypeManager.system_int_array_get_length_int)
5518 method = TypeManager.int_array_get_length_int;
5519 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5520 method = TypeManager.int_array_get_lower_bound_int;
5521 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5522 method = TypeManager.int_array_get_upper_bound_int;
5523 else if (method == TypeManager.system_void_array_copyto_array_int)
5524 method = TypeManager.void_array_copyto_array_int;
5527 if (ec.TestObsoleteMethodUsage) {
5529 // This checks ObsoleteAttribute on the method and on the declaring type
5531 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
5533 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
5535 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
5537 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
5541 if (IsMethodExcluded (method, ec))
5545 this_call = instance_expr == null;
5546 if (decl_type.IsValueType || (!this_call && instance_expr.Type.IsValueType))
5550 // If this is ourselves, push "this"
5555 ig.Emit (OpCodes.Ldarg_0);
5558 Type iexpr_type = instance_expr.Type;
5561 // Push the instance expression
5563 if (TypeManager.IsValueType (iexpr_type)) {
5565 // Special case: calls to a function declared in a
5566 // reference-type with a value-type argument need
5567 // to have their value boxed.
5568 if (decl_type.IsValueType ||
5569 iexpr_type.IsGenericParameter) {
5571 // If the expression implements IMemoryLocation, then
5572 // we can optimize and use AddressOf on the
5575 // If not we have to use some temporary storage for
5577 if (instance_expr is IMemoryLocation) {
5578 ((IMemoryLocation)instance_expr).
5579 AddressOf (ec, AddressOp.LoadStore);
5581 LocalTemporary temp = new LocalTemporary (ec, iexpr_type);
5582 instance_expr.Emit (ec);
5584 temp.AddressOf (ec, AddressOp.Load);
5587 // avoid the overhead of doing this all the time.
5589 t = TypeManager.GetReferenceType (iexpr_type);
5591 instance_expr.Emit (ec);
5592 ig.Emit (OpCodes.Box, instance_expr.Type);
5593 t = TypeManager.object_type;
5596 instance_expr.Emit (ec);
5597 t = instance_expr.Type;
5602 this_arg = new LocalTemporary (ec, t);
5603 ig.Emit (OpCodes.Dup);
5604 this_arg.Store (ec);
5610 EmitArguments (ec, method, Arguments, dup_args, this_arg);
5612 if ((instance_expr != null) && (instance_expr.Type.IsGenericParameter))
5613 ig.Emit (OpCodes.Constrained, instance_expr.Type);
5616 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
5617 call_op = OpCodes.Call;
5619 call_op = OpCodes.Callvirt;
5621 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
5622 Type[] varargs_types = GetVarargsTypes (ec, method, Arguments);
5623 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
5630 // and DoFoo is not virtual, you can omit the callvirt,
5631 // because you don't need the null checking behavior.
5633 if (method is MethodInfo)
5634 ig.Emit (call_op, (MethodInfo) method);
5636 ig.Emit (call_op, (ConstructorInfo) method);
5639 public override void Emit (EmitContext ec)
5641 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5643 EmitCall (ec, mg.IsBase, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5646 public override void EmitStatement (EmitContext ec)
5651 // Pop the return value if there is one
5653 if (method is MethodInfo){
5654 Type ret = ((MethodInfo)method).ReturnType;
5655 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5656 ec.ig.Emit (OpCodes.Pop);
5661 public class InvocationOrCast : ExpressionStatement
5664 Expression argument;
5666 public InvocationOrCast (Expression expr, Expression argument, Location loc)
5669 this.argument = argument;
5673 public override Expression DoResolve (EmitContext ec)
5676 // First try to resolve it as a cast.
5678 TypeExpr te = expr.ResolveAsTypeStep (ec) as TypeExpr;
5679 if ((te != null) && (te.eclass == ExprClass.Type)) {
5680 Cast cast = new Cast (te, argument, loc);
5681 return cast.Resolve (ec);
5685 // This can either be a type or a delegate invocation.
5686 // Let's just resolve it and see what we'll get.
5688 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5693 // Ok, so it's a Cast.
5695 if (expr.eclass == ExprClass.Type) {
5696 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
5697 return cast.Resolve (ec);
5701 // It's a delegate invocation.
5703 if (!TypeManager.IsDelegateType (expr.Type)) {
5704 Error (149, "Method name expected");
5708 ArrayList args = new ArrayList ();
5709 args.Add (new Argument (argument, Argument.AType.Expression));
5710 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5711 return invocation.Resolve (ec);
5716 Error (201, "Only assignment, call, increment, decrement and new object " +
5717 "expressions can be used as a statement");
5720 public override ExpressionStatement ResolveStatement (EmitContext ec)
5723 // First try to resolve it as a cast.
5725 TypeExpr te = expr.ResolveAsTypeStep (ec) as TypeExpr;
5726 if ((te != null) && (te.eclass == ExprClass.Type)) {
5732 // This can either be a type or a delegate invocation.
5733 // Let's just resolve it and see what we'll get.
5735 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5736 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5742 // It's a delegate invocation.
5744 if (!TypeManager.IsDelegateType (expr.Type)) {
5745 Error (149, "Method name expected");
5749 ArrayList args = new ArrayList ();
5750 args.Add (new Argument (argument, Argument.AType.Expression));
5751 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5752 return invocation.ResolveStatement (ec);
5755 public override void Emit (EmitContext ec)
5757 throw new Exception ("Cannot happen");
5760 public override void EmitStatement (EmitContext ec)
5762 throw new Exception ("Cannot happen");
5767 // This class is used to "disable" the code generation for the
5768 // temporary variable when initializing value types.
5770 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5771 public void AddressOf (EmitContext ec, AddressOp Mode)
5778 /// Implements the new expression
5780 public class New : ExpressionStatement, IMemoryLocation {
5781 public readonly ArrayList Arguments;
5784 // During bootstrap, it contains the RequestedType,
5785 // but if `type' is not null, it *might* contain a NewDelegate
5786 // (because of field multi-initialization)
5788 public Expression RequestedType;
5790 MethodBase method = null;
5793 // If set, the new expression is for a value_target, and
5794 // we will not leave anything on the stack.
5796 Expression value_target;
5797 bool value_target_set = false;
5798 bool is_type_parameter = false;
5800 public New (Expression requested_type, ArrayList arguments, Location l)
5802 RequestedType = requested_type;
5803 Arguments = arguments;
5807 public bool SetValueTypeVariable (Expression value)
5809 value_target = value;
5810 value_target_set = true;
5811 if (!(value_target is IMemoryLocation)){
5812 Error_UnexpectedKind ("variable", loc);
5819 // This function is used to disable the following code sequence for
5820 // value type initialization:
5822 // AddressOf (temporary)
5826 // Instead the provide will have provided us with the address on the
5827 // stack to store the results.
5829 static Expression MyEmptyExpression;
5831 public void DisableTemporaryValueType ()
5833 if (MyEmptyExpression == null)
5834 MyEmptyExpression = new EmptyAddressOf ();
5837 // To enable this, look into:
5838 // test-34 and test-89 and self bootstrapping.
5840 // For instance, we can avoid a copy by using `newobj'
5841 // instead of Call + Push-temp on value types.
5842 // value_target = MyEmptyExpression;
5847 /// Converts complex core type syntax like 'new int ()' to simple constant
5849 Expression Constantify (Type t)
5851 if (t == TypeManager.int32_type)
5852 return new IntConstant (0);
5853 if (t == TypeManager.uint32_type)
5854 return new UIntConstant (0);
5855 if (t == TypeManager.int64_type)
5856 return new LongConstant (0);
5857 if (t == TypeManager.uint64_type)
5858 return new ULongConstant (0);
5859 if (t == TypeManager.float_type)
5860 return new FloatConstant (0);
5861 if (t == TypeManager.double_type)
5862 return new DoubleConstant (0);
5863 if (t == TypeManager.short_type)
5864 return new ShortConstant (0);
5865 if (t == TypeManager.ushort_type)
5866 return new UShortConstant (0);
5867 if (t == TypeManager.sbyte_type)
5868 return new SByteConstant (0);
5869 if (t == TypeManager.byte_type)
5870 return new ByteConstant (0);
5871 if (t == TypeManager.char_type)
5872 return new CharConstant ('\0');
5873 if (t == TypeManager.bool_type)
5874 return new BoolConstant (false);
5875 if (t == TypeManager.decimal_type)
5876 return new DecimalConstant (0);
5881 public override Expression DoResolve (EmitContext ec)
5884 // The New DoResolve might be called twice when initializing field
5885 // expressions (see EmitFieldInitializers, the call to
5886 // GetInitializerExpression will perform a resolve on the expression,
5887 // and later the assign will trigger another resolution
5889 // This leads to bugs (#37014)
5892 if (RequestedType is NewDelegate)
5893 return RequestedType;
5897 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec);
5901 if (Arguments == null) {
5902 Expression c = Constantify (type);
5911 CheckObsoleteAttribute (type);
5913 bool IsDelegate = TypeManager.IsDelegateType (type);
5916 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5917 if (RequestedType != null)
5918 if (!(RequestedType is DelegateCreation))
5919 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
5920 return RequestedType;
5923 if (type.IsGenericParameter) {
5924 if (!TypeManager.HasConstructorConstraint (type)) {
5925 Error (304, String.Format (
5926 "Cannot create an instance of the " +
5927 "variable type '{0}' because it " +
5928 "doesn't have the new() constraint",
5933 if ((Arguments != null) && (Arguments.Count != 0)) {
5934 Error (417, String.Format (
5935 "`{0}': cannot provide arguments " +
5936 "when creating an instance of a " +
5937 "variable type.", type));
5941 is_type_parameter = true;
5942 eclass = ExprClass.Value;
5946 if (type.IsInterface || type.IsAbstract){
5947 Error (144, "It is not possible to create instances of interfaces or abstract classes");
5951 if (type.IsAbstract && type.IsSealed) {
5952 Report.Error (712, loc, "Cannot create an instance of the static class '{0}'", TypeManager.CSharpName (type));
5956 bool is_struct = type.IsValueType;
5957 eclass = ExprClass.Value;
5960 // SRE returns a match for .ctor () on structs (the object constructor),
5961 // so we have to manually ignore it.
5963 if (is_struct && Arguments == null)
5967 ml = MemberLookupFinal (ec, type, type, ".ctor",
5968 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
5969 MemberTypes.Constructor,
5970 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5975 if (! (ml is MethodGroupExpr)){
5977 ml.Error_UnexpectedKind ("method group", loc);
5983 if (Arguments != null){
5984 foreach (Argument a in Arguments){
5985 if (!a.Resolve (ec, loc))
5990 method = Invocation.OverloadResolve (
5991 ec, (MethodGroupExpr) ml, Arguments, true, loc);
5995 if (method == null) {
5996 if (almostMatchedMembers.Count != 0) {
5997 MemberLookupFailed (ec, type, type, ".ctor", null, loc);
6001 if (!is_struct || Arguments.Count > 0) {
6002 Error (1501, String.Format (
6003 "New invocation: Can not find a constructor in `{0}' for this argument list",
6004 TypeManager.CSharpName (type)));
6012 bool DoEmitTypeParameter (EmitContext ec)
6014 ILGenerator ig = ec.ig;
6016 ig.Emit (OpCodes.Ldtoken, type);
6017 ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6018 ig.Emit (OpCodes.Call, TypeManager.activator_create_instance);
6019 ig.Emit (OpCodes.Unbox_Any, type);
6025 // This DoEmit can be invoked in two contexts:
6026 // * As a mechanism that will leave a value on the stack (new object)
6027 // * As one that wont (init struct)
6029 // You can control whether a value is required on the stack by passing
6030 // need_value_on_stack. The code *might* leave a value on the stack
6031 // so it must be popped manually
6033 // If we are dealing with a ValueType, we have a few
6034 // situations to deal with:
6036 // * The target is a ValueType, and we have been provided
6037 // the instance (this is easy, we are being assigned).
6039 // * The target of New is being passed as an argument,
6040 // to a boxing operation or a function that takes a
6043 // In this case, we need to create a temporary variable
6044 // that is the argument of New.
6046 // Returns whether a value is left on the stack
6048 bool DoEmit (EmitContext ec, bool need_value_on_stack)
6050 bool is_value_type = TypeManager.IsValueType (type);
6051 ILGenerator ig = ec.ig;
6056 // Allow DoEmit() to be called multiple times.
6057 // We need to create a new LocalTemporary each time since
6058 // you can't share LocalBuilders among ILGeneators.
6059 if (!value_target_set)
6060 value_target = new LocalTemporary (ec, type);
6062 ml = (IMemoryLocation) value_target;
6063 ml.AddressOf (ec, AddressOp.Store);
6067 Invocation.EmitArguments (ec, method, Arguments, false, null);
6071 ig.Emit (OpCodes.Initobj, type);
6073 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6074 if (need_value_on_stack){
6075 value_target.Emit (ec);
6080 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
6085 public override void Emit (EmitContext ec)
6087 if (is_type_parameter)
6088 DoEmitTypeParameter (ec);
6093 public override void EmitStatement (EmitContext ec)
6095 if (is_type_parameter)
6096 throw new InvalidOperationException ();
6098 if (DoEmit (ec, false))
6099 ec.ig.Emit (OpCodes.Pop);
6102 public void AddressOf (EmitContext ec, AddressOp Mode)
6104 if (is_type_parameter)
6105 throw new InvalidOperationException ();
6107 if (!type.IsValueType){
6109 // We throw an exception. So far, I believe we only need to support
6111 // foreach (int j in new StructType ())
6114 throw new Exception ("AddressOf should not be used for classes");
6117 if (!value_target_set)
6118 value_target = new LocalTemporary (ec, type);
6120 IMemoryLocation ml = (IMemoryLocation) value_target;
6121 ml.AddressOf (ec, AddressOp.Store);
6123 Invocation.EmitArguments (ec, method, Arguments, false, null);
6126 ec.ig.Emit (OpCodes.Initobj, type);
6128 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6130 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
6135 /// 14.5.10.2: Represents an array creation expression.
6139 /// There are two possible scenarios here: one is an array creation
6140 /// expression that specifies the dimensions and optionally the
6141 /// initialization data and the other which does not need dimensions
6142 /// specified but where initialization data is mandatory.
6144 public class ArrayCreation : Expression {
6145 Expression requested_base_type;
6146 ArrayList initializers;
6149 // The list of Argument types.
6150 // This is used to construct the `newarray' or constructor signature
6152 ArrayList arguments;
6155 // Method used to create the array object.
6157 MethodBase new_method = null;
6159 Type array_element_type;
6160 Type underlying_type;
6161 bool is_one_dimensional = false;
6162 bool is_builtin_type = false;
6163 bool expect_initializers = false;
6164 int num_arguments = 0;
6168 ArrayList array_data;
6173 // The number of array initializers that we can handle
6174 // via the InitializeArray method - through EmitStaticInitializers
6176 int num_automatic_initializers;
6178 const int max_automatic_initializers = 6;
6180 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
6182 this.requested_base_type = requested_base_type;
6183 this.initializers = initializers;
6187 arguments = new ArrayList ();
6189 foreach (Expression e in exprs) {
6190 arguments.Add (new Argument (e, Argument.AType.Expression));
6195 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
6197 this.requested_base_type = requested_base_type;
6198 this.initializers = initializers;
6202 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
6204 //string tmp = rank.Substring (rank.LastIndexOf ('['));
6206 //dimensions = tmp.Length - 1;
6207 expect_initializers = true;
6210 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
6212 StringBuilder sb = new StringBuilder (rank);
6215 for (int i = 1; i < idx_count; i++)
6220 return new ComposedCast (base_type, sb.ToString (), loc);
6223 void Error_IncorrectArrayInitializer ()
6225 Error (178, "Incorrectly structured array initializer");
6228 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
6230 if (specified_dims) {
6231 Argument a = (Argument) arguments [idx];
6233 if (!a.Resolve (ec, loc))
6236 if (!(a.Expr is Constant)) {
6237 Error (150, "A constant value is expected");
6241 int value = (int) ((Constant) a.Expr).GetValue ();
6243 if (value != probe.Count) {
6244 Error_IncorrectArrayInitializer ();
6248 bounds [idx] = value;
6251 int child_bounds = -1;
6252 foreach (object o in probe) {
6253 if (o is ArrayList) {
6254 int current_bounds = ((ArrayList) o).Count;
6256 if (child_bounds == -1)
6257 child_bounds = current_bounds;
6259 else if (child_bounds != current_bounds){
6260 Error_IncorrectArrayInitializer ();
6263 if (specified_dims && (idx + 1 >= arguments.Count)){
6264 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
6268 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
6272 if (child_bounds != -1){
6273 Error_IncorrectArrayInitializer ();
6277 Expression tmp = (Expression) o;
6278 tmp = tmp.Resolve (ec);
6282 // Console.WriteLine ("I got: " + tmp);
6283 // Handle initialization from vars, fields etc.
6285 Expression conv = Convert.ImplicitConversionRequired (
6286 ec, tmp, underlying_type, loc);
6291 if (conv is StringConstant || conv is DecimalConstant || conv is NullCast) {
6292 // These are subclasses of Constant that can appear as elements of an
6293 // array that cannot be statically initialized (with num_automatic_initializers
6294 // > max_automatic_initializers), so num_automatic_initializers should be left as zero.
6295 array_data.Add (conv);
6296 } else if (conv is Constant) {
6297 // These are the types of Constant that can appear in arrays that can be
6298 // statically allocated.
6299 array_data.Add (conv);
6300 num_automatic_initializers++;
6302 array_data.Add (conv);
6309 public void UpdateIndices (EmitContext ec)
6312 for (ArrayList probe = initializers; probe != null;) {
6313 if (probe.Count > 0 && probe [0] is ArrayList) {
6314 Expression e = new IntConstant (probe.Count);
6315 arguments.Add (new Argument (e, Argument.AType.Expression));
6317 bounds [i++] = probe.Count;
6319 probe = (ArrayList) probe [0];
6322 Expression e = new IntConstant (probe.Count);
6323 arguments.Add (new Argument (e, Argument.AType.Expression));
6325 bounds [i++] = probe.Count;
6332 public bool ValidateInitializers (EmitContext ec, Type array_type)
6334 if (initializers == null) {
6335 if (expect_initializers)
6341 if (underlying_type == null)
6345 // We use this to store all the date values in the order in which we
6346 // will need to store them in the byte blob later
6348 array_data = new ArrayList ();
6349 bounds = new Hashtable ();
6353 if (arguments != null) {
6354 ret = CheckIndices (ec, initializers, 0, true);
6357 arguments = new ArrayList ();
6359 ret = CheckIndices (ec, initializers, 0, false);
6366 if (arguments.Count != dimensions) {
6367 Error_IncorrectArrayInitializer ();
6376 // Converts `source' to an int, uint, long or ulong.
6378 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
6382 bool old_checked = ec.CheckState;
6383 ec.CheckState = true;
6385 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
6386 if (target == null){
6387 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
6388 if (target == null){
6389 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
6390 if (target == null){
6391 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
6393 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
6397 ec.CheckState = old_checked;
6400 // Only positive constants are allowed at compile time
6402 if (target is Constant){
6403 if (target is IntConstant){
6404 if (((IntConstant) target).Value < 0){
6405 Expression.Error_NegativeArrayIndex (loc);
6410 if (target is LongConstant){
6411 if (((LongConstant) target).Value < 0){
6412 Expression.Error_NegativeArrayIndex (loc);
6423 // Creates the type of the array
6425 bool LookupType (EmitContext ec)
6427 StringBuilder array_qualifier = new StringBuilder (rank);
6430 // `In the first form allocates an array instace of the type that results
6431 // from deleting each of the individual expression from the expression list'
6433 if (num_arguments > 0) {
6434 array_qualifier.Append ("[");
6435 for (int i = num_arguments-1; i > 0; i--)
6436 array_qualifier.Append (",");
6437 array_qualifier.Append ("]");
6443 TypeExpr array_type_expr;
6444 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
6445 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec);
6446 if (array_type_expr == null)
6449 type = array_type_expr.Type;
6451 if (!type.IsArray) {
6452 Error (622, "Can only use array initializer expressions to assign to array types. Try using a new expression instead.");
6455 underlying_type = TypeManager.GetElementType (type);
6456 dimensions = type.GetArrayRank ();
6461 public override Expression DoResolve (EmitContext ec)
6465 if (!LookupType (ec))
6469 // First step is to validate the initializers and fill
6470 // in any missing bits
6472 if (!ValidateInitializers (ec, type))
6475 if (arguments == null)
6478 arg_count = arguments.Count;
6479 foreach (Argument a in arguments){
6480 if (!a.Resolve (ec, loc))
6483 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
6484 if (real_arg == null)
6491 array_element_type = TypeManager.GetElementType (type);
6493 if (array_element_type.IsAbstract && array_element_type.IsSealed) {
6494 Report.Error (719, loc, "'{0}': array elements cannot be of static type", TypeManager.CSharpName (array_element_type));
6498 if (arg_count == 1) {
6499 is_one_dimensional = true;
6500 eclass = ExprClass.Value;
6504 is_builtin_type = TypeManager.IsBuiltinType (type);
6506 if (is_builtin_type) {
6509 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
6510 AllBindingFlags, loc);
6512 if (!(ml is MethodGroupExpr)) {
6513 ml.Error_UnexpectedKind ("method group", loc);
6518 Error (-6, "New invocation: Can not find a constructor for " +
6519 "this argument list");
6523 new_method = Invocation.OverloadResolve (
6524 ec, (MethodGroupExpr) ml, arguments, false, loc);
6526 if (new_method == null) {
6527 Error (-6, "New invocation: Can not find a constructor for " +
6528 "this argument list");
6532 eclass = ExprClass.Value;
6535 ModuleBuilder mb = CodeGen.Module.Builder;
6536 ArrayList args = new ArrayList ();
6538 if (arguments != null) {
6539 for (int i = 0; i < arg_count; i++)
6540 args.Add (TypeManager.int32_type);
6543 Type [] arg_types = null;
6546 arg_types = new Type [args.Count];
6548 args.CopyTo (arg_types, 0);
6550 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
6553 if (new_method == null) {
6554 Error (-6, "New invocation: Can not find a constructor for " +
6555 "this argument list");
6559 eclass = ExprClass.Value;
6564 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
6569 int count = array_data.Count;
6571 if (underlying_type.IsEnum)
6572 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
6574 factor = GetTypeSize (underlying_type);
6576 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
6578 data = new byte [(count * factor + 4) & ~3];
6581 for (int i = 0; i < count; ++i) {
6582 object v = array_data [i];
6584 if (v is EnumConstant)
6585 v = ((EnumConstant) v).Child;
6587 if (v is Constant && !(v is StringConstant))
6588 v = ((Constant) v).GetValue ();
6594 if (underlying_type == TypeManager.int64_type){
6595 if (!(v is Expression)){
6596 long val = (long) v;
6598 for (int j = 0; j < factor; ++j) {
6599 data [idx + j] = (byte) (val & 0xFF);
6603 } else if (underlying_type == TypeManager.uint64_type){
6604 if (!(v is Expression)){
6605 ulong val = (ulong) v;
6607 for (int j = 0; j < factor; ++j) {
6608 data [idx + j] = (byte) (val & 0xFF);
6612 } else if (underlying_type == TypeManager.float_type) {
6613 if (!(v is Expression)){
6614 element = BitConverter.GetBytes ((float) v);
6616 for (int j = 0; j < factor; ++j)
6617 data [idx + j] = element [j];
6619 } else if (underlying_type == TypeManager.double_type) {
6620 if (!(v is Expression)){
6621 element = BitConverter.GetBytes ((double) v);
6623 for (int j = 0; j < factor; ++j)
6624 data [idx + j] = element [j];
6626 } else if (underlying_type == TypeManager.char_type){
6627 if (!(v is Expression)){
6628 int val = (int) ((char) v);
6630 data [idx] = (byte) (val & 0xff);
6631 data [idx+1] = (byte) (val >> 8);
6633 } else if (underlying_type == TypeManager.short_type){
6634 if (!(v is Expression)){
6635 int val = (int) ((short) v);
6637 data [idx] = (byte) (val & 0xff);
6638 data [idx+1] = (byte) (val >> 8);
6640 } else if (underlying_type == TypeManager.ushort_type){
6641 if (!(v is Expression)){
6642 int val = (int) ((ushort) v);
6644 data [idx] = (byte) (val & 0xff);
6645 data [idx+1] = (byte) (val >> 8);
6647 } else if (underlying_type == TypeManager.int32_type) {
6648 if (!(v is Expression)){
6651 data [idx] = (byte) (val & 0xff);
6652 data [idx+1] = (byte) ((val >> 8) & 0xff);
6653 data [idx+2] = (byte) ((val >> 16) & 0xff);
6654 data [idx+3] = (byte) (val >> 24);
6656 } else if (underlying_type == TypeManager.uint32_type) {
6657 if (!(v is Expression)){
6658 uint val = (uint) v;
6660 data [idx] = (byte) (val & 0xff);
6661 data [idx+1] = (byte) ((val >> 8) & 0xff);
6662 data [idx+2] = (byte) ((val >> 16) & 0xff);
6663 data [idx+3] = (byte) (val >> 24);
6665 } else if (underlying_type == TypeManager.sbyte_type) {
6666 if (!(v is Expression)){
6667 sbyte val = (sbyte) v;
6668 data [idx] = (byte) val;
6670 } else if (underlying_type == TypeManager.byte_type) {
6671 if (!(v is Expression)){
6672 byte val = (byte) v;
6673 data [idx] = (byte) val;
6675 } else if (underlying_type == TypeManager.bool_type) {
6676 if (!(v is Expression)){
6677 bool val = (bool) v;
6678 data [idx] = (byte) (val ? 1 : 0);
6680 } else if (underlying_type == TypeManager.decimal_type){
6681 if (!(v is Expression)){
6682 int [] bits = Decimal.GetBits ((decimal) v);
6685 // FIXME: For some reason, this doesn't work on the MS runtime.
6686 int [] nbits = new int [4];
6687 nbits [0] = bits [3];
6688 nbits [1] = bits [2];
6689 nbits [2] = bits [0];
6690 nbits [3] = bits [1];
6692 for (int j = 0; j < 4; j++){
6693 data [p++] = (byte) (nbits [j] & 0xff);
6694 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6695 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6696 data [p++] = (byte) (nbits [j] >> 24);
6700 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6709 // Emits the initializers for the array
6711 void EmitStaticInitializers (EmitContext ec)
6714 // First, the static data
6717 ILGenerator ig = ec.ig;
6719 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6721 fb = RootContext.MakeStaticData (data);
6723 ig.Emit (OpCodes.Dup);
6724 ig.Emit (OpCodes.Ldtoken, fb);
6725 ig.Emit (OpCodes.Call,
6726 TypeManager.void_initializearray_array_fieldhandle);
6730 // Emits pieces of the array that can not be computed at compile
6731 // time (variables and string locations).
6733 // This always expect the top value on the stack to be the array
6735 void EmitDynamicInitializers (EmitContext ec)
6737 ILGenerator ig = ec.ig;
6738 int dims = bounds.Count;
6739 int [] current_pos = new int [dims];
6740 int top = array_data.Count;
6742 MethodInfo set = null;
6746 ModuleBuilder mb = null;
6747 mb = CodeGen.Module.Builder;
6748 args = new Type [dims + 1];
6751 for (j = 0; j < dims; j++)
6752 args [j] = TypeManager.int32_type;
6754 args [j] = array_element_type;
6756 set = mb.GetArrayMethod (
6758 CallingConventions.HasThis | CallingConventions.Standard,
6759 TypeManager.void_type, args);
6762 for (int i = 0; i < top; i++){
6764 Expression e = null;
6766 if (array_data [i] is Expression)
6767 e = (Expression) array_data [i];
6771 // Basically we do this for string literals and
6772 // other non-literal expressions
6774 if (e is EnumConstant){
6775 e = ((EnumConstant) e).Child;
6778 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6779 num_automatic_initializers <= max_automatic_initializers) {
6780 Type etype = e.Type;
6782 ig.Emit (OpCodes.Dup);
6784 for (int idx = 0; idx < dims; idx++)
6785 IntConstant.EmitInt (ig, current_pos [idx]);
6788 // If we are dealing with a struct, get the
6789 // address of it, so we can store it.
6791 if ((dims == 1) && etype.IsValueType &&
6792 (!TypeManager.IsBuiltinOrEnum (etype) ||
6793 etype == TypeManager.decimal_type)) {
6798 // Let new know that we are providing
6799 // the address where to store the results
6801 n.DisableTemporaryValueType ();
6804 ig.Emit (OpCodes.Ldelema, etype);
6810 bool is_stobj, has_type_arg;
6811 OpCode op = ArrayAccess.GetStoreOpcode (
6812 etype, out is_stobj,
6815 ig.Emit (OpCodes.Stobj, etype);
6816 else if (has_type_arg)
6817 ig.Emit (op, etype);
6821 ig.Emit (OpCodes.Call, set);
6828 for (int j = dims - 1; j >= 0; j--){
6830 if (current_pos [j] < (int) bounds [j])
6832 current_pos [j] = 0;
6837 void EmitArrayArguments (EmitContext ec)
6839 ILGenerator ig = ec.ig;
6841 foreach (Argument a in arguments) {
6842 Type atype = a.Type;
6845 if (atype == TypeManager.uint64_type)
6846 ig.Emit (OpCodes.Conv_Ovf_U4);
6847 else if (atype == TypeManager.int64_type)
6848 ig.Emit (OpCodes.Conv_Ovf_I4);
6852 public override void Emit (EmitContext ec)
6854 ILGenerator ig = ec.ig;
6856 EmitArrayArguments (ec);
6857 if (is_one_dimensional)
6858 ig.Emit (OpCodes.Newarr, array_element_type);
6860 if (is_builtin_type)
6861 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6863 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6866 if (initializers != null){
6868 // FIXME: Set this variable correctly.
6870 bool dynamic_initializers = true;
6872 // This will never be true for array types that cannot be statically
6873 // initialized. num_automatic_initializers will always be zero. See
6875 if (num_automatic_initializers > max_automatic_initializers)
6876 EmitStaticInitializers (ec);
6878 if (dynamic_initializers)
6879 EmitDynamicInitializers (ec);
6883 public object EncodeAsAttribute ()
6885 if (!is_one_dimensional){
6886 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6890 if (array_data == null){
6891 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6895 object [] ret = new object [array_data.Count];
6897 foreach (Expression e in array_data){
6900 if (e is NullLiteral)
6903 if (!Attribute.GetAttributeArgumentExpression (e, Location, array_element_type, out v))
6913 /// Represents the `this' construct
6915 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6918 VariableInfo variable_info;
6920 public This (Block block, Location loc)
6926 public This (Location loc)
6931 public VariableInfo VariableInfo {
6932 get { return variable_info; }
6935 public bool VerifyFixed (bool is_expression)
6937 if ((variable_info == null) || (variable_info.LocalInfo == null))
6940 return variable_info.LocalInfo.IsFixed;
6943 public bool ResolveBase (EmitContext ec)
6945 eclass = ExprClass.Variable;
6947 if (ec.TypeContainer.CurrentType != null)
6948 type = ec.TypeContainer.CurrentType;
6950 type = ec.ContainerType;
6953 Error (26, "Keyword this not valid in static code");
6957 if ((block != null) && (block.ThisVariable != null))
6958 variable_info = block.ThisVariable.VariableInfo;
6960 if (ec.CurrentAnonymousMethod != null)
6966 public override Expression DoResolve (EmitContext ec)
6968 if (!ResolveBase (ec))
6971 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
6972 Error (188, "The this object cannot be used before all " +
6973 "of its fields are assigned to");
6974 variable_info.SetAssigned (ec);
6978 if (ec.IsFieldInitializer) {
6979 Error (27, "Keyword `this' can't be used outside a constructor, " +
6980 "a method or a property.");
6987 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6989 if (!ResolveBase (ec))
6992 if (variable_info != null)
6993 variable_info.SetAssigned (ec);
6995 if (ec.TypeContainer is Class){
6996 Error (1604, "Cannot assign to `this'");
7003 public void Emit (EmitContext ec, bool leave_copy)
7007 ec.ig.Emit (OpCodes.Dup);
7010 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
7012 ILGenerator ig = ec.ig;
7014 if (ec.TypeContainer is Struct){
7018 ec.ig.Emit (OpCodes.Dup);
7019 ig.Emit (OpCodes.Stobj, type);
7021 throw new Exception ("how did you get here");
7025 public override void Emit (EmitContext ec)
7027 ILGenerator ig = ec.ig;
7030 if (ec.TypeContainer is Struct)
7031 ig.Emit (OpCodes.Ldobj, type);
7034 public void AddressOf (EmitContext ec, AddressOp mode)
7039 // FIGURE OUT WHY LDARG_S does not work
7041 // consider: struct X { int val; int P { set { val = value; }}}
7043 // Yes, this looks very bad. Look at `NOTAS' for
7045 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
7050 /// Represents the `__arglist' construct
7052 public class ArglistAccess : Expression
7054 public ArglistAccess (Location loc)
7059 public bool ResolveBase (EmitContext ec)
7061 eclass = ExprClass.Variable;
7062 type = TypeManager.runtime_argument_handle_type;
7066 public override Expression DoResolve (EmitContext ec)
7068 if (!ResolveBase (ec))
7071 if (ec.IsFieldInitializer || !ec.CurrentBlock.HasVarargs) {
7072 Error (190, "The __arglist construct is valid only within " +
7073 "a variable argument method.");
7080 public override void Emit (EmitContext ec)
7082 ec.ig.Emit (OpCodes.Arglist);
7087 /// Represents the `__arglist (....)' construct
7089 public class Arglist : Expression
7091 public readonly Argument[] Arguments;
7093 public Arglist (Argument[] args, Location l)
7099 public Type[] ArgumentTypes {
7101 Type[] retval = new Type [Arguments.Length];
7102 for (int i = 0; i < Arguments.Length; i++)
7103 retval [i] = Arguments [i].Type;
7108 public override Expression DoResolve (EmitContext ec)
7110 eclass = ExprClass.Variable;
7111 type = TypeManager.runtime_argument_handle_type;
7113 foreach (Argument arg in Arguments) {
7114 if (!arg.Resolve (ec, loc))
7121 public override void Emit (EmitContext ec)
7123 foreach (Argument arg in Arguments)
7129 // This produces the value that renders an instance, used by the iterators code
7131 public class ProxyInstance : Expression, IMemoryLocation {
7132 public override Expression DoResolve (EmitContext ec)
7134 eclass = ExprClass.Variable;
7135 type = ec.ContainerType;
7139 public override void Emit (EmitContext ec)
7141 ec.ig.Emit (OpCodes.Ldarg_0);
7145 public void AddressOf (EmitContext ec, AddressOp mode)
7147 ec.ig.Emit (OpCodes.Ldarg_0);
7152 /// Implements the typeof operator
7154 public class TypeOf : Expression {
7155 public Expression QueriedType;
7156 protected Type typearg;
7158 public TypeOf (Expression queried_type, Location l)
7160 QueriedType = queried_type;
7164 public override Expression DoResolve (EmitContext ec)
7166 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec);
7170 typearg = texpr.Type;
7172 if (typearg == TypeManager.void_type) {
7173 Error (673, "System.Void cannot be used from C# - " +
7174 "use typeof (void) to get the void type object");
7178 if (typearg.IsPointer && !ec.InUnsafe){
7182 CheckObsoleteAttribute (typearg);
7184 type = TypeManager.type_type;
7185 eclass = ExprClass.Type;
7189 public override void Emit (EmitContext ec)
7191 ec.ig.Emit (OpCodes.Ldtoken, typearg);
7192 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
7195 public Type TypeArg {
7196 get { return typearg; }
7201 /// Implements the `typeof (void)' operator
7203 public class TypeOfVoid : TypeOf {
7204 public TypeOfVoid (Location l) : base (null, l)
7209 public override Expression DoResolve (EmitContext ec)
7211 type = TypeManager.type_type;
7212 typearg = TypeManager.void_type;
7213 eclass = ExprClass.Type;
7219 /// Implements the sizeof expression
7221 public class SizeOf : Expression {
7222 public Expression QueriedType;
7225 public SizeOf (Expression queried_type, Location l)
7227 this.QueriedType = queried_type;
7231 public override Expression DoResolve (EmitContext ec)
7235 233, loc, "Sizeof may only be used in an unsafe context " +
7236 "(consider using System.Runtime.InteropServices.Marshal.SizeOf");
7240 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec);
7244 if (texpr is TypeParameterExpr){
7245 ((TypeParameterExpr)texpr).Error_CannotUseAsUnmanagedType (loc);
7249 type_queried = texpr.Type;
7251 CheckObsoleteAttribute (type_queried);
7253 if (!TypeManager.IsUnmanagedType (type_queried)){
7254 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
7258 type = TypeManager.int32_type;
7259 eclass = ExprClass.Value;
7263 public override void Emit (EmitContext ec)
7265 int size = GetTypeSize (type_queried);
7268 ec.ig.Emit (OpCodes.Sizeof, type_queried);
7270 IntConstant.EmitInt (ec.ig, size);
7275 /// Implements the member access expression
7277 public class MemberAccess : Expression {
7278 public string Identifier;
7279 protected Expression expr;
7280 protected TypeArguments args;
7282 public MemberAccess (Expression expr, string id, Location l)
7289 public MemberAccess (Expression expr, string id, TypeArguments args,
7291 : this (expr, id, l)
7296 public Expression Expr {
7302 public static void error176 (Location loc, string name)
7304 Report.Error (176, loc, "Static member `" +
7305 name + "' cannot be accessed " +
7306 "with an instance reference, qualify with a " +
7307 "type name instead");
7310 public static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Expression left, Location loc)
7312 SimpleName sn = left_original as SimpleName;
7313 if (sn == null || left == null || left.Type.Name != sn.Name)
7316 return ec.DeclSpace.LookupType (sn.Name, true, loc) != null;
7319 // TODO: possible optimalization
7320 // Cache resolved constant result in FieldBuilder <-> expresion map
7321 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
7322 Expression left, Location loc,
7323 Expression left_original)
7325 bool left_is_type, left_is_explicit;
7327 // If `left' is null, then we're called from SimpleNameResolve and this is
7328 // a member in the currently defining class.
7330 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
7331 left_is_explicit = false;
7333 // Implicitly default to `this' unless we're static.
7334 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
7335 left = ec.GetThis (loc);
7337 left_is_type = left is TypeExpr;
7338 left_is_explicit = true;
7341 if (member_lookup is FieldExpr){
7342 FieldExpr fe = (FieldExpr) member_lookup;
7343 FieldInfo fi = fe.FieldInfo.Mono_GetGenericFieldDefinition ();
7344 Type decl_type = fi.DeclaringType;
7346 bool is_emitted = fi is FieldBuilder;
7347 Type t = fi.FieldType;
7350 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
7354 if (!c.LookupConstantValue (out o))
7357 object real_value = ((Constant) c.Expr).GetValue ();
7359 Expression exp = Constantify (real_value, t);
7361 if (left_is_explicit && !left_is_type && !IdenticalNameAndTypeName (ec, left_original, left, loc)) {
7362 Report.SymbolRelatedToPreviousError (c);
7363 error176 (loc, c.GetSignatureForError ());
7371 // IsInitOnly is because of MS compatibility, I don't know why but they emit decimal constant as InitOnly
7372 if (fi.IsInitOnly && !is_emitted && t == TypeManager.decimal_type) {
7373 object[] attrs = fi.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
7374 if (attrs.Length == 1)
7375 return new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
7382 o = TypeManager.GetValue ((FieldBuilder) fi);
7384 o = fi.GetValue (fi);
7386 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
7387 if (left_is_explicit && !left_is_type &&
7388 !IdenticalNameAndTypeName (ec, left_original, member_lookup, loc)) {
7389 error176 (loc, fe.FieldInfo.Name);
7393 Expression enum_member = MemberLookup (
7394 ec, decl_type, "value__", MemberTypes.Field,
7395 AllBindingFlags, loc);
7397 Enum en = TypeManager.LookupEnum (decl_type);
7401 c = Constantify (o, en.UnderlyingType);
7403 c = Constantify (o, enum_member.Type);
7405 return new EnumConstant (c, decl_type);
7408 Expression exp = Constantify (o, t);
7410 if (left_is_explicit && !left_is_type) {
7411 error176 (loc, fe.FieldInfo.Name);
7418 if (t.IsPointer && !ec.InUnsafe){
7424 if (member_lookup is EventExpr) {
7425 EventExpr ee = (EventExpr) member_lookup;
7428 // If the event is local to this class, we transform ourselves into
7432 if (ee.EventInfo.DeclaringType == ec.ContainerType ||
7433 TypeManager.IsNestedChildOf(ec.ContainerType, ee.EventInfo.DeclaringType)) {
7434 MemberInfo mi = GetFieldFromEvent (ee);
7438 // If this happens, then we have an event with its own
7439 // accessors and private field etc so there's no need
7440 // to transform ourselves.
7442 ee.InstanceExpression = left;
7446 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
7449 Report.Error (-200, loc, "Internal error!!");
7453 if (!left_is_explicit)
7456 ee.InstanceExpression = left;
7458 return ResolveMemberAccess (ec, ml, left, loc, left_original);
7462 if (member_lookup is IMemberExpr) {
7463 IMemberExpr me = (IMemberExpr) member_lookup;
7464 MethodGroupExpr mg = me as MethodGroupExpr;
7467 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
7468 mg.IsExplicitImpl = left_is_explicit;
7471 if ((ec.IsFieldInitializer || ec.IsStatic) &&
7472 IdenticalNameAndTypeName (ec, left_original, member_lookup, loc))
7473 return member_lookup;
7475 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
7480 if (!me.IsInstance){
7481 if (IdenticalNameAndTypeName (ec, left_original, left, loc))
7482 return member_lookup;
7484 if (left_is_explicit) {
7485 error176 (loc, me.Name);
7491 // Since we can not check for instance objects in SimpleName,
7492 // becaue of the rule that allows types and variables to share
7493 // the name (as long as they can be de-ambiguated later, see
7494 // IdenticalNameAndTypeName), we have to check whether left
7495 // is an instance variable in a static context
7497 // However, if the left-hand value is explicitly given, then
7498 // it is already our instance expression, so we aren't in
7502 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
7503 IMemberExpr mexp = (IMemberExpr) left;
7505 if (!mexp.IsStatic){
7506 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
7511 if ((mg != null) && IdenticalNameAndTypeName (ec, left_original, left, loc))
7512 mg.IdenticalTypeName = true;
7514 me.InstanceExpression = left;
7517 return member_lookup;
7520 Console.WriteLine ("Left is: " + left);
7521 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
7522 Environment.Exit (1);
7526 public virtual Expression DoResolve (EmitContext ec, Expression right_side,
7530 throw new Exception ();
7533 // Resolve the expression with flow analysis turned off, we'll do the definite
7534 // assignment checks later. This is because we don't know yet what the expression
7535 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7536 // definite assignment check on the actual field and not on the whole struct.
7539 Expression original = expr;
7540 expr = expr.Resolve (ec, flags | ResolveFlags.Intermediate | ResolveFlags.DisableFlowAnalysis);
7544 if (expr is Namespace) {
7545 Namespace ns = (Namespace) expr;
7546 string lookup_id = MemberName.MakeName (Identifier, args);
7547 FullNamedExpression retval = ns.Lookup (ec.DeclSpace, lookup_id, loc);
7548 if ((retval != null) && (args != null))
7549 retval = new ConstructedType (retval, args, loc).ResolveAsTypeStep (ec);
7551 Report.Error (234, loc, "The type or namespace name `{0}' could not be found in namespace `{1}'", Identifier, ns.FullName);
7556 // TODO: I mailed Ravi about this, and apparently we can get rid
7557 // of this and put it in the right place.
7559 // Handle enums here when they are in transit.
7560 // Note that we cannot afford to hit MemberLookup in this case because
7561 // it will fail to find any members at all
7565 if (expr is TypeExpr){
7566 expr_type = expr.Type;
7568 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
7569 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", expr_type);
7573 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
7574 Enum en = TypeManager.LookupEnum (expr_type);
7577 object value = en.LookupEnumValue (ec, Identifier, loc);
7580 MemberCore mc = en.GetDefinition (Identifier);
7581 ObsoleteAttribute oa = mc.GetObsoleteAttribute (en);
7583 AttributeTester.Report_ObsoleteMessage (oa, mc.GetSignatureForError (), Location);
7585 oa = en.GetObsoleteAttribute (en);
7587 AttributeTester.Report_ObsoleteMessage (oa, en.GetSignatureForError (), Location);
7590 Constant c = Constantify (value, en.UnderlyingType);
7591 return new EnumConstant (c, expr_type);
7594 CheckObsoleteAttribute (expr_type);
7596 FieldInfo fi = expr_type.GetField (Identifier);
7598 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
7600 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), Location);
7605 expr_type = expr.Type;
7607 if (expr_type.IsPointer){
7608 Error (23, "The `.' operator can not be applied to pointer operands (" +
7609 TypeManager.CSharpName (expr_type) + ")");
7613 Expression member_lookup;
7614 member_lookup = MemberLookup (
7615 ec, expr_type, expr_type, Identifier, loc);
7616 if ((member_lookup == null) && (args != null)) {
7617 string lookup_id = MemberName.MakeName (Identifier, args);
7618 member_lookup = MemberLookup (
7619 ec, expr_type, expr_type, lookup_id, loc);
7621 if (member_lookup == null) {
7622 MemberLookupFailed (
7623 ec, expr_type, expr_type, Identifier, null, loc);
7627 if (member_lookup is TypeExpr) {
7628 if (!(expr is TypeExpr) &&
7629 !IdenticalNameAndTypeName (ec, original, expr, loc)) {
7630 Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
7631 member_lookup.Type + "' instead");
7635 return member_lookup;
7639 string full_name = expr_type + "." + Identifier;
7641 if (member_lookup is FieldExpr) {
7642 Report.Error (307, loc, "The field `{0}' cannot " +
7643 "be used with type arguments", full_name);
7645 } else if (member_lookup is EventExpr) {
7646 Report.Error (307, loc, "The event `{0}' cannot " +
7647 "be used with type arguments", full_name);
7649 } else if (member_lookup is PropertyExpr) {
7650 Report.Error (307, loc, "The property `{0}' cannot " +
7651 "be used with type arguments", full_name);
7656 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
7657 if (member_lookup == null)
7661 MethodGroupExpr mg = member_lookup as MethodGroupExpr;
7663 throw new InternalErrorException ();
7665 return mg.ResolveGeneric (ec, args);
7668 // The following DoResolve/DoResolveLValue will do the definite assignment
7671 if (right_side != null)
7672 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
7674 member_lookup = member_lookup.DoResolve (ec);
7676 return member_lookup;
7679 public override Expression DoResolve (EmitContext ec)
7681 return DoResolve (ec, null, ResolveFlags.VariableOrValue | ResolveFlags.Type);
7684 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7686 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue | ResolveFlags.Type);
7689 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
7691 return ResolveNamespaceOrType (ec, false);
7694 public FullNamedExpression ResolveNamespaceOrType (EmitContext ec, bool silent)
7696 FullNamedExpression new_expr = expr.ResolveAsTypeStep (ec);
7698 if (new_expr == null)
7701 string lookup_id = MemberName.MakeName (Identifier, args);
7703 if (new_expr is Namespace) {
7704 Namespace ns = (Namespace) new_expr;
7705 FullNamedExpression retval = ns.Lookup (ec.DeclSpace, lookup_id, loc);
7706 if ((retval != null) && (args != null))
7707 retval = new ConstructedType (retval, args, loc).ResolveAsTypeStep (ec);
7708 if (!silent && retval == null)
7709 Report.Error (234, loc, "The type or namespace name `{0}' could not be found in namespace `{1}'", Identifier, ns.FullName);
7713 TypeExpr tnew_expr = new_expr.ResolveAsTypeTerminal (ec);
7714 if (tnew_expr == null)
7717 Type expr_type = tnew_expr.Type;
7719 if (expr_type.IsPointer){
7720 Error (23, "The `.' operator can not be applied to pointer operands (" +
7721 TypeManager.CSharpName (expr_type) + ")");
7725 Expression member_lookup;
7726 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, lookup_id, loc);
7727 if (!silent && member_lookup == null) {
7728 Report.Error (234, loc, "The type name `{0}' could not be found in type `{1}'",
7729 Identifier, new_expr.FullName);
7733 if (!(member_lookup is TypeExpr)) {
7734 Report.Error (118, loc, "'{0}.{1}' denotes a '{2}', where a type was expected",
7735 new_expr.FullName, Identifier, member_lookup.ExprClassName ());
7739 TypeExpr texpr = member_lookup.ResolveAsTypeTerminal (ec);
7743 TypeArguments the_args = args;
7744 if (TypeManager.HasGenericArguments (expr_type)) {
7745 Type[] decl_args = TypeManager.GetTypeArguments (expr_type);
7747 TypeArguments new_args = new TypeArguments (loc);
7748 foreach (Type decl in decl_args)
7749 new_args.Add (new TypeExpression (decl, loc));
7752 new_args.Add (args);
7754 the_args = new_args;
7757 if (the_args != null) {
7758 ConstructedType ctype = new ConstructedType (texpr.Type, the_args, loc);
7759 return ctype.ResolveAsTypeStep (ec);
7765 public override void Emit (EmitContext ec)
7767 throw new Exception ("Should not happen");
7770 public override string ToString ()
7772 return expr + "." + MemberName.MakeName (Identifier, args);
7777 /// Implements checked expressions
7779 public class CheckedExpr : Expression {
7781 public Expression Expr;
7783 public CheckedExpr (Expression e, Location l)
7789 public override Expression DoResolve (EmitContext ec)
7791 bool last_check = ec.CheckState;
7792 bool last_const_check = ec.ConstantCheckState;
7794 ec.CheckState = true;
7795 ec.ConstantCheckState = true;
7796 Expr = Expr.Resolve (ec);
7797 ec.CheckState = last_check;
7798 ec.ConstantCheckState = last_const_check;
7803 if (Expr is Constant)
7806 eclass = Expr.eclass;
7811 public override void Emit (EmitContext ec)
7813 bool last_check = ec.CheckState;
7814 bool last_const_check = ec.ConstantCheckState;
7816 ec.CheckState = true;
7817 ec.ConstantCheckState = true;
7819 ec.CheckState = last_check;
7820 ec.ConstantCheckState = last_const_check;
7826 /// Implements the unchecked expression
7828 public class UnCheckedExpr : Expression {
7830 public Expression Expr;
7832 public UnCheckedExpr (Expression e, Location l)
7838 public override Expression DoResolve (EmitContext ec)
7840 bool last_check = ec.CheckState;
7841 bool last_const_check = ec.ConstantCheckState;
7843 ec.CheckState = false;
7844 ec.ConstantCheckState = false;
7845 Expr = Expr.Resolve (ec);
7846 ec.CheckState = last_check;
7847 ec.ConstantCheckState = last_const_check;
7852 if (Expr is Constant)
7855 eclass = Expr.eclass;
7860 public override void Emit (EmitContext ec)
7862 bool last_check = ec.CheckState;
7863 bool last_const_check = ec.ConstantCheckState;
7865 ec.CheckState = false;
7866 ec.ConstantCheckState = false;
7868 ec.CheckState = last_check;
7869 ec.ConstantCheckState = last_const_check;
7875 /// An Element Access expression.
7877 /// During semantic analysis these are transformed into
7878 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7880 public class ElementAccess : Expression {
7881 public ArrayList Arguments;
7882 public Expression Expr;
7884 public ElementAccess (Expression e, ArrayList e_list, Location l)
7893 Arguments = new ArrayList ();
7894 foreach (Expression tmp in e_list)
7895 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7899 bool CommonResolve (EmitContext ec)
7901 Expr = Expr.Resolve (ec);
7906 if (Arguments == null)
7909 foreach (Argument a in Arguments){
7910 if (!a.Resolve (ec, loc))
7917 Expression MakePointerAccess (EmitContext ec, Type t)
7919 if (t == TypeManager.void_ptr_type){
7920 Error (242, "The array index operation is not valid for void pointers");
7923 if (Arguments.Count != 1){
7924 Error (196, "A pointer must be indexed by a single value");
7929 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc).Resolve (ec);
7932 return new Indirection (p, loc).Resolve (ec);
7935 public override Expression DoResolve (EmitContext ec)
7937 if (!CommonResolve (ec))
7941 // We perform some simple tests, and then to "split" the emit and store
7942 // code we create an instance of a different class, and return that.
7944 // I am experimenting with this pattern.
7948 if (t == TypeManager.array_type){
7949 Report.Error (21, loc, "Cannot use indexer on System.Array");
7954 return (new ArrayAccess (this, loc)).Resolve (ec);
7956 return MakePointerAccess (ec, Expr.Type);
7958 FieldExpr fe = Expr as FieldExpr;
7960 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
7962 return MakePointerAccess (ec, ff.ElementType);
7965 return (new IndexerAccess (this, loc)).Resolve (ec);
7968 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7970 if (!CommonResolve (ec))
7975 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
7978 return MakePointerAccess (ec, Expr.Type);
7980 FieldExpr fe = Expr as FieldExpr;
7982 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
7984 // TODO: not sure whether it is correct
7985 // if (!ec.InFixedInitializer) {
7986 // if (!ec.InFixedInitializer) {
7987 // Error (1666, "You cannot use fixed sized buffers contained in unfixed expressions. Try using the fixed statement.");
7990 return MakePointerAccess (ec, ff.ElementType);
7993 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
7996 public override void Emit (EmitContext ec)
7998 throw new Exception ("Should never be reached");
8003 /// Implements array access
8005 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
8007 // Points to our "data" repository
8011 LocalTemporary temp;
8014 public ArrayAccess (ElementAccess ea_data, Location l)
8017 eclass = ExprClass.Variable;
8021 public override Expression DoResolve (EmitContext ec)
8024 ExprClass eclass = ea.Expr.eclass;
8026 // As long as the type is valid
8027 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
8028 eclass == ExprClass.Value)) {
8029 ea.Expr.Error_UnexpectedKind ("variable or value");
8034 Type t = ea.Expr.Type;
8035 if (t.GetArrayRank () != ea.Arguments.Count){
8037 "Incorrect number of indexes for array " +
8038 " expected: " + t.GetArrayRank () + " got: " +
8039 ea.Arguments.Count);
8043 type = TypeManager.GetElementType (t);
8044 if (type.IsPointer && !ec.InUnsafe){
8045 UnsafeError (ea.Location);
8049 foreach (Argument a in ea.Arguments){
8050 Type argtype = a.Type;
8052 if (argtype == TypeManager.int32_type ||
8053 argtype == TypeManager.uint32_type ||
8054 argtype == TypeManager.int64_type ||
8055 argtype == TypeManager.uint64_type) {
8056 Constant c = a.Expr as Constant;
8057 if (c != null && c.IsNegative) {
8058 Report.Warning (251, 2, a.Expr.Location, "Indexing an array with a negative index (array indices always start at zero)");
8064 // Mhm. This is strage, because the Argument.Type is not the same as
8065 // Argument.Expr.Type: the value changes depending on the ref/out setting.
8067 // Wonder if I will run into trouble for this.
8069 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
8074 eclass = ExprClass.Variable;
8080 /// Emits the right opcode to load an object of Type `t'
8081 /// from an array of T
8083 static public void EmitLoadOpcode (ILGenerator ig, Type type)
8085 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
8086 ig.Emit (OpCodes.Ldelem_U1);
8087 else if (type == TypeManager.sbyte_type)
8088 ig.Emit (OpCodes.Ldelem_I1);
8089 else if (type == TypeManager.short_type)
8090 ig.Emit (OpCodes.Ldelem_I2);
8091 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
8092 ig.Emit (OpCodes.Ldelem_U2);
8093 else if (type == TypeManager.int32_type)
8094 ig.Emit (OpCodes.Ldelem_I4);
8095 else if (type == TypeManager.uint32_type)
8096 ig.Emit (OpCodes.Ldelem_U4);
8097 else if (type == TypeManager.uint64_type)
8098 ig.Emit (OpCodes.Ldelem_I8);
8099 else if (type == TypeManager.int64_type)
8100 ig.Emit (OpCodes.Ldelem_I8);
8101 else if (type == TypeManager.float_type)
8102 ig.Emit (OpCodes.Ldelem_R4);
8103 else if (type == TypeManager.double_type)
8104 ig.Emit (OpCodes.Ldelem_R8);
8105 else if (type == TypeManager.intptr_type)
8106 ig.Emit (OpCodes.Ldelem_I);
8107 else if (TypeManager.IsEnumType (type)){
8108 EmitLoadOpcode (ig, TypeManager.EnumToUnderlying (type));
8109 } else if (type.IsValueType){
8110 ig.Emit (OpCodes.Ldelema, type);
8111 ig.Emit (OpCodes.Ldobj, type);
8112 } else if (type.IsGenericParameter)
8113 ig.Emit (OpCodes.Ldelem_Any, type);
8115 ig.Emit (OpCodes.Ldelem_Ref);
8119 /// Returns the right opcode to store an object of Type `t'
8120 /// from an array of T.
8122 static public OpCode GetStoreOpcode (Type t, out bool is_stobj, out bool has_type_arg)
8124 //Console.WriteLine (new System.Diagnostics.StackTrace ());
8125 has_type_arg = false; is_stobj = false;
8126 t = TypeManager.TypeToCoreType (t);
8127 if (TypeManager.IsEnumType (t))
8128 t = TypeManager.EnumToUnderlying (t);
8129 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
8130 t == TypeManager.bool_type)
8131 return OpCodes.Stelem_I1;
8132 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
8133 t == TypeManager.char_type)
8134 return OpCodes.Stelem_I2;
8135 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
8136 return OpCodes.Stelem_I4;
8137 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
8138 return OpCodes.Stelem_I8;
8139 else if (t == TypeManager.float_type)
8140 return OpCodes.Stelem_R4;
8141 else if (t == TypeManager.double_type)
8142 return OpCodes.Stelem_R8;
8143 else if (t == TypeManager.intptr_type) {
8144 has_type_arg = true;
8146 return OpCodes.Stobj;
8147 } else if (t.IsValueType) {
8148 has_type_arg = true;
8150 return OpCodes.Stobj;
8151 } else if (t.IsGenericParameter) {
8152 has_type_arg = true;
8153 return OpCodes.Stelem_Any;
8155 return OpCodes.Stelem_Ref;
8158 MethodInfo FetchGetMethod ()
8160 ModuleBuilder mb = CodeGen.Module.Builder;
8161 int arg_count = ea.Arguments.Count;
8162 Type [] args = new Type [arg_count];
8165 for (int i = 0; i < arg_count; i++){
8166 //args [i++] = a.Type;
8167 args [i] = TypeManager.int32_type;
8170 get = mb.GetArrayMethod (
8171 ea.Expr.Type, "Get",
8172 CallingConventions.HasThis |
8173 CallingConventions.Standard,
8179 MethodInfo FetchAddressMethod ()
8181 ModuleBuilder mb = CodeGen.Module.Builder;
8182 int arg_count = ea.Arguments.Count;
8183 Type [] args = new Type [arg_count];
8187 ret_type = TypeManager.GetReferenceType (type);
8189 for (int i = 0; i < arg_count; i++){
8190 //args [i++] = a.Type;
8191 args [i] = TypeManager.int32_type;
8194 address = mb.GetArrayMethod (
8195 ea.Expr.Type, "Address",
8196 CallingConventions.HasThis |
8197 CallingConventions.Standard,
8204 // Load the array arguments into the stack.
8206 // If we have been requested to cache the values (cached_locations array
8207 // initialized), then load the arguments the first time and store them
8208 // in locals. otherwise load from local variables.
8210 void LoadArrayAndArguments (EmitContext ec)
8212 ILGenerator ig = ec.ig;
8215 foreach (Argument a in ea.Arguments){
8216 Type argtype = a.Expr.Type;
8220 if (argtype == TypeManager.int64_type)
8221 ig.Emit (OpCodes.Conv_Ovf_I);
8222 else if (argtype == TypeManager.uint64_type)
8223 ig.Emit (OpCodes.Conv_Ovf_I_Un);
8227 public void Emit (EmitContext ec, bool leave_copy)
8229 int rank = ea.Expr.Type.GetArrayRank ();
8230 ILGenerator ig = ec.ig;
8233 LoadArrayAndArguments (ec);
8236 EmitLoadOpcode (ig, type);
8240 method = FetchGetMethod ();
8241 ig.Emit (OpCodes.Call, method);
8244 LoadFromPtr (ec.ig, this.type);
8247 ec.ig.Emit (OpCodes.Dup);
8248 temp = new LocalTemporary (ec, this.type);
8253 public override void Emit (EmitContext ec)
8258 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8260 int rank = ea.Expr.Type.GetArrayRank ();
8261 ILGenerator ig = ec.ig;
8262 Type t = source.Type;
8263 prepared = prepare_for_load;
8265 if (prepare_for_load) {
8266 AddressOf (ec, AddressOp.LoadStore);
8267 ec.ig.Emit (OpCodes.Dup);
8270 ec.ig.Emit (OpCodes.Dup);
8271 temp = new LocalTemporary (ec, this.type);
8274 StoreFromPtr (ec.ig, t);
8282 LoadArrayAndArguments (ec);
8285 bool is_stobj, has_type_arg;
8286 OpCode op = GetStoreOpcode (t, out is_stobj, out has_type_arg);
8289 // The stobj opcode used by value types will need
8290 // an address on the stack, not really an array/array
8294 ig.Emit (OpCodes.Ldelema, t);
8298 ec.ig.Emit (OpCodes.Dup);
8299 temp = new LocalTemporary (ec, this.type);
8304 ig.Emit (OpCodes.Stobj, t);
8305 else if (has_type_arg)
8310 ModuleBuilder mb = CodeGen.Module.Builder;
8311 int arg_count = ea.Arguments.Count;
8312 Type [] args = new Type [arg_count + 1];
8317 ec.ig.Emit (OpCodes.Dup);
8318 temp = new LocalTemporary (ec, this.type);
8322 for (int i = 0; i < arg_count; i++){
8323 //args [i++] = a.Type;
8324 args [i] = TypeManager.int32_type;
8327 args [arg_count] = type;
8329 set = mb.GetArrayMethod (
8330 ea.Expr.Type, "Set",
8331 CallingConventions.HasThis |
8332 CallingConventions.Standard,
8333 TypeManager.void_type, args);
8335 ig.Emit (OpCodes.Call, set);
8342 public void AddressOf (EmitContext ec, AddressOp mode)
8344 int rank = ea.Expr.Type.GetArrayRank ();
8345 ILGenerator ig = ec.ig;
8347 LoadArrayAndArguments (ec);
8350 ig.Emit (OpCodes.Ldelema, type);
8352 MethodInfo address = FetchAddressMethod ();
8353 ig.Emit (OpCodes.Call, address);
8360 public ArrayList Properties;
8361 static Hashtable map;
8363 public struct Indexer {
8364 public readonly Type Type;
8365 public readonly MethodInfo Getter, Setter;
8367 public Indexer (Type type, MethodInfo get, MethodInfo set)
8377 map = new Hashtable ();
8382 Properties = new ArrayList ();
8385 void Append (MemberInfo [] mi)
8387 foreach (PropertyInfo property in mi){
8388 MethodInfo get, set;
8390 get = property.GetGetMethod (true);
8391 set = property.GetSetMethod (true);
8392 Properties.Add (new Indexer (property.PropertyType, get, set));
8396 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
8398 string p_name = TypeManager.IndexerPropertyName (lookup_type);
8400 MemberInfo [] mi = TypeManager.MemberLookup (
8401 caller_type, caller_type, lookup_type, MemberTypes.Property,
8402 BindingFlags.Public | BindingFlags.Instance |
8403 BindingFlags.DeclaredOnly, p_name, null);
8405 if (mi == null || mi.Length == 0)
8411 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
8413 Indexers ix = (Indexers) map [lookup_type];
8418 Type copy = lookup_type;
8419 while (copy != TypeManager.object_type && copy != null){
8420 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
8424 ix = new Indexers ();
8429 copy = copy.BaseType;
8432 if (!lookup_type.IsInterface)
8435 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
8436 if (ifaces != null) {
8437 foreach (Type itype in ifaces) {
8438 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
8441 ix = new Indexers ();
8453 /// Expressions that represent an indexer call.
8455 public class IndexerAccess : Expression, IAssignMethod {
8457 // Points to our "data" repository
8459 MethodInfo get, set;
8460 ArrayList set_arguments;
8461 bool is_base_indexer;
8463 protected Type indexer_type;
8464 protected Type current_type;
8465 protected Expression instance_expr;
8466 protected ArrayList arguments;
8468 public IndexerAccess (ElementAccess ea, Location loc)
8469 : this (ea.Expr, false, loc)
8471 this.arguments = ea.Arguments;
8474 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
8477 this.instance_expr = instance_expr;
8478 this.is_base_indexer = is_base_indexer;
8479 this.eclass = ExprClass.Value;
8483 protected virtual bool CommonResolve (EmitContext ec)
8485 indexer_type = instance_expr.Type;
8486 current_type = ec.ContainerType;
8491 public override Expression DoResolve (EmitContext ec)
8493 ArrayList AllGetters = new ArrayList();
8494 if (!CommonResolve (ec))
8498 // Step 1: Query for all `Item' *properties*. Notice
8499 // that the actual methods are pointed from here.
8501 // This is a group of properties, piles of them.
8503 bool found_any = false, found_any_getters = false;
8504 Type lookup_type = indexer_type;
8507 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
8508 if (ilist != null) {
8510 if (ilist.Properties != null) {
8511 foreach (Indexers.Indexer ix in ilist.Properties) {
8512 if (ix.Getter != null)
8513 AllGetters.Add(ix.Getter);
8518 if (AllGetters.Count > 0) {
8519 found_any_getters = true;
8520 get = (MethodInfo) Invocation.OverloadResolve (
8521 ec, new MethodGroupExpr (AllGetters, loc),
8522 arguments, false, loc);
8526 Report.Error (21, loc,
8527 "Type `" + TypeManager.CSharpName (indexer_type) +
8528 "' does not have any indexers defined");
8532 if (!found_any_getters) {
8533 Error (154, "indexer can not be used in this context, because " +
8534 "it lacks a `get' accessor");
8539 Error (1501, "No Overload for method `this' takes `" +
8540 arguments.Count + "' arguments");
8545 // Only base will allow this invocation to happen.
8547 if (get.IsAbstract && this is BaseIndexerAccess){
8548 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
8552 type = get.ReturnType;
8553 if (type.IsPointer && !ec.InUnsafe){
8558 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8560 eclass = ExprClass.IndexerAccess;
8564 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8566 ArrayList AllSetters = new ArrayList();
8567 if (!CommonResolve (ec))
8570 bool found_any = false, found_any_setters = false;
8572 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
8573 if (ilist != null) {
8575 if (ilist.Properties != null) {
8576 foreach (Indexers.Indexer ix in ilist.Properties) {
8577 if (ix.Setter != null)
8578 AllSetters.Add(ix.Setter);
8582 if (AllSetters.Count > 0) {
8583 found_any_setters = true;
8584 set_arguments = (ArrayList) arguments.Clone ();
8585 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
8586 set = (MethodInfo) Invocation.OverloadResolve (
8587 ec, new MethodGroupExpr (AllSetters, loc),
8588 set_arguments, false, loc);
8592 Report.Error (21, loc,
8593 "Type `" + TypeManager.CSharpName (indexer_type) +
8594 "' does not have any indexers defined");
8598 if (!found_any_setters) {
8599 Error (154, "indexer can not be used in this context, because " +
8600 "it lacks a `set' accessor");
8605 Error (1501, "No Overload for method `this' takes `" +
8606 arguments.Count + "' arguments");
8611 // Only base will allow this invocation to happen.
8613 if (set.IsAbstract && this is BaseIndexerAccess){
8614 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
8619 // Now look for the actual match in the list of indexers to set our "return" type
8621 type = TypeManager.void_type; // default value
8622 foreach (Indexers.Indexer ix in ilist.Properties){
8623 if (ix.Setter == set){
8629 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8631 eclass = ExprClass.IndexerAccess;
8635 bool prepared = false;
8636 LocalTemporary temp;
8638 public void Emit (EmitContext ec, bool leave_copy)
8640 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc, prepared, false);
8642 ec.ig.Emit (OpCodes.Dup);
8643 temp = new LocalTemporary (ec, Type);
8649 // source is ignored, because we already have a copy of it from the
8650 // LValue resolution and we have already constructed a pre-cached
8651 // version of the arguments (ea.set_arguments);
8653 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8655 prepared = prepare_for_load;
8656 Argument a = (Argument) set_arguments [set_arguments.Count - 1];
8661 ec.ig.Emit (OpCodes.Dup);
8662 temp = new LocalTemporary (ec, Type);
8665 } else if (leave_copy) {
8666 temp = new LocalTemporary (ec, Type);
8672 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc, false, prepared);
8679 public override void Emit (EmitContext ec)
8686 /// The base operator for method names
8688 public class BaseAccess : Expression {
8691 public BaseAccess (string member, Location l)
8693 this.member = member;
8697 public override Expression DoResolve (EmitContext ec)
8699 Expression c = CommonResolve (ec);
8705 // MethodGroups use this opportunity to flag an error on lacking ()
8707 if (!(c is MethodGroupExpr))
8708 return c.Resolve (ec);
8712 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8714 Expression c = CommonResolve (ec);
8720 // MethodGroups use this opportunity to flag an error on lacking ()
8722 if (! (c is MethodGroupExpr))
8723 return c.DoResolveLValue (ec, right_side);
8728 Expression CommonResolve (EmitContext ec)
8730 Expression member_lookup;
8731 Type current_type = ec.ContainerType;
8732 Type base_type = current_type.BaseType;
8736 Error (1511, "Keyword base is not allowed in static method");
8740 if (ec.IsFieldInitializer){
8741 Error (1512, "Keyword base is not available in the current context");
8745 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type,
8746 member, AllMemberTypes, AllBindingFlags,
8748 if (member_lookup == null) {
8749 MemberLookupFailed (
8750 ec, base_type, base_type, member, null, loc);
8757 left = new TypeExpression (base_type, loc);
8759 left = ec.GetThis (loc);
8761 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
8763 if (e is PropertyExpr){
8764 PropertyExpr pe = (PropertyExpr) e;
8769 if (e is MethodGroupExpr)
8770 ((MethodGroupExpr) e).IsBase = true;
8775 public override void Emit (EmitContext ec)
8777 throw new Exception ("Should never be called");
8782 /// The base indexer operator
8784 public class BaseIndexerAccess : IndexerAccess {
8785 public BaseIndexerAccess (ArrayList args, Location loc)
8786 : base (null, true, loc)
8788 arguments = new ArrayList ();
8789 foreach (Expression tmp in args)
8790 arguments.Add (new Argument (tmp, Argument.AType.Expression));
8793 protected override bool CommonResolve (EmitContext ec)
8795 instance_expr = ec.GetThis (loc);
8797 current_type = ec.ContainerType.BaseType;
8798 indexer_type = current_type;
8800 foreach (Argument a in arguments){
8801 if (!a.Resolve (ec, loc))
8810 /// This class exists solely to pass the Type around and to be a dummy
8811 /// that can be passed to the conversion functions (this is used by
8812 /// foreach implementation to typecast the object return value from
8813 /// get_Current into the proper type. All code has been generated and
8814 /// we only care about the side effect conversions to be performed
8816 /// This is also now used as a placeholder where a no-action expression
8817 /// is needed (the `New' class).
8819 public class EmptyExpression : Expression {
8820 public static readonly EmptyExpression Null = new EmptyExpression ();
8822 // TODO: should be protected
8823 public EmptyExpression ()
8825 type = TypeManager.object_type;
8826 eclass = ExprClass.Value;
8827 loc = Location.Null;
8830 public EmptyExpression (Type t)
8833 eclass = ExprClass.Value;
8834 loc = Location.Null;
8837 public override Expression DoResolve (EmitContext ec)
8842 public override void Emit (EmitContext ec)
8844 // nothing, as we only exist to not do anything.
8848 // This is just because we might want to reuse this bad boy
8849 // instead of creating gazillions of EmptyExpressions.
8850 // (CanImplicitConversion uses it)
8852 public void SetType (Type t)
8858 public class UserCast : Expression {
8862 public UserCast (MethodInfo method, Expression source, Location l)
8864 this.method = method;
8865 this.source = source;
8866 type = method.ReturnType;
8867 eclass = ExprClass.Value;
8871 public Expression Source {
8877 public override Expression DoResolve (EmitContext ec)
8880 // We are born fully resolved
8885 public override void Emit (EmitContext ec)
8887 ILGenerator ig = ec.ig;
8891 if (method is MethodInfo)
8892 ig.Emit (OpCodes.Call, (MethodInfo) method);
8894 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
8900 // This class is used to "construct" the type during a typecast
8901 // operation. Since the Type.GetType class in .NET can parse
8902 // the type specification, we just use this to construct the type
8903 // one bit at a time.
8905 public class ComposedCast : TypeExpr {
8909 public ComposedCast (Expression left, string dim, Location l)
8916 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
8918 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec);
8922 Type ltype = lexpr.Type;
8924 if ((ltype == TypeManager.void_type) && (dim != "*")) {
8925 Report.Error (1547, Location,
8926 "Keyword 'void' cannot be used in this context");
8930 if ((dim.Length > 0) && (dim [0] == '?')) {
8931 TypeExpr nullable = new NullableType (left, loc);
8933 nullable = new ComposedCast (nullable, dim.Substring (1), loc);
8934 return nullable.ResolveAsTypeTerminal (ec);
8938 while ((pos < dim.Length) && (dim [pos] == '[')) {
8941 if (dim [pos] == ']') {
8942 ltype = ltype.MakeArrayType ();
8945 if (pos < dim.Length)
8949 eclass = ExprClass.Type;
8954 while (dim [pos] == ',') {
8958 if ((dim [pos] != ']') || (pos != dim.Length-1))
8961 type = ltype.MakeArrayType (rank + 1);
8962 eclass = ExprClass.Type;
8968 // ltype.Fullname is already fully qualified, so we can skip
8969 // a lot of probes, and go directly to TypeManager.LookupType
8971 string fname = ltype.FullName != null ? ltype.FullName : ltype.Name;
8972 string cname = fname + dim;
8973 type = TypeManager.LookupTypeDirect (cname);
8976 // For arrays of enumerations we are having a problem
8977 // with the direct lookup. Need to investigate.
8979 // For now, fall back to the full lookup in that case.
8981 FullNamedExpression e = ec.DeclSpace.LookupType (cname, false, loc);
8983 type = ((TypeExpr) e).ResolveType (ec);
8991 if (!ec.InUnsafe && type.IsPointer){
8996 if (type.IsArray && (type.GetElementType () == TypeManager.arg_iterator_type ||
8997 type.GetElementType () == TypeManager.typed_reference_type)) {
8998 Report.Error (611, loc, "Array elements cannot be of type '{0}'", TypeManager.CSharpName (type.GetElementType ()));
9002 eclass = ExprClass.Type;
9006 public override string Name {
9012 public override string FullName {
9014 return type.FullName;
9019 public class FixedBufferPtr: Expression {
9022 public FixedBufferPtr (Expression array, Type array_type, Location l)
9027 type = TypeManager.GetPointerType (array_type);
9028 eclass = ExprClass.Value;
9031 public override void Emit(EmitContext ec)
9036 public override Expression DoResolve (EmitContext ec)
9039 // We are born fully resolved
9047 // This class is used to represent the address of an array, used
9048 // only by the Fixed statement, this generates "&a [0]" construct
9049 // for fixed (char *pa = a)
9051 public class ArrayPtr : FixedBufferPtr {
9054 public ArrayPtr (Expression array, Type array_type, Location l):
9055 base (array, array_type, l)
9057 this.array_type = array_type;
9060 public override void Emit (EmitContext ec)
9064 ILGenerator ig = ec.ig;
9065 IntLiteral.EmitInt (ig, 0);
9066 ig.Emit (OpCodes.Ldelema, array_type);
9071 // Used by the fixed statement
9073 public class StringPtr : Expression {
9076 public StringPtr (LocalBuilder b, Location l)
9079 eclass = ExprClass.Value;
9080 type = TypeManager.char_ptr_type;
9084 public override Expression DoResolve (EmitContext ec)
9086 // This should never be invoked, we are born in fully
9087 // initialized state.
9092 public override void Emit (EmitContext ec)
9094 ILGenerator ig = ec.ig;
9096 ig.Emit (OpCodes.Ldloc, b);
9097 ig.Emit (OpCodes.Conv_I);
9098 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
9099 ig.Emit (OpCodes.Add);
9104 // Implements the `stackalloc' keyword
9106 public class StackAlloc : Expression {
9111 public StackAlloc (Expression type, Expression count, Location l)
9118 public override Expression DoResolve (EmitContext ec)
9120 count = count.Resolve (ec);
9124 if (count.Type != TypeManager.int32_type){
9125 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
9130 Constant c = count as Constant;
9131 if (c != null && c.IsNegative) {
9132 Report.Error (247, loc, "Cannot use a negative size with stackalloc");
9136 if (ec.CurrentBranching.InCatch () ||
9137 ec.CurrentBranching.InFinally (true)) {
9139 "stackalloc can not be used in a catch or finally block");
9143 TypeExpr texpr = t.ResolveAsTypeTerminal (ec);
9149 if (!TypeManager.VerifyUnManaged (otype, loc))
9152 type = TypeManager.GetPointerType (otype);
9153 eclass = ExprClass.Value;
9158 public override void Emit (EmitContext ec)
9160 int size = GetTypeSize (otype);
9161 ILGenerator ig = ec.ig;
9164 ig.Emit (OpCodes.Sizeof, otype);
9166 IntConstant.EmitInt (ig, size);
9168 ig.Emit (OpCodes.Mul);
9169 ig.Emit (OpCodes.Localloc);