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);
224 // This routine will attempt to simplify the unary expression when the
225 // argument is a constant. The result is returned in `result' and the
226 // function returns true or false depending on whether a reduction
227 // was performed or not
229 bool Reduce (EmitContext ec, Constant e, out Expression result)
231 Type expr_type = e.Type;
234 case Operator.UnaryPlus:
238 case Operator.UnaryNegation:
239 result = TryReduceNegative (e);
242 case Operator.LogicalNot:
243 if (expr_type != TypeManager.bool_type) {
249 BoolConstant b = (BoolConstant) e;
250 result = new BoolConstant (!(b.Value));
253 case Operator.OnesComplement:
254 if (!((expr_type == TypeManager.int32_type) ||
255 (expr_type == TypeManager.uint32_type) ||
256 (expr_type == TypeManager.int64_type) ||
257 (expr_type == TypeManager.uint64_type) ||
258 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
261 if (Convert.ImplicitConversionExists (ec, e, TypeManager.int32_type)){
262 result = new Cast (new TypeExpression (TypeManager.int32_type, loc), e, loc);
263 result = result.Resolve (ec);
264 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint32_type)){
265 result = new Cast (new TypeExpression (TypeManager.uint32_type, loc), e, loc);
266 result = result.Resolve (ec);
267 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.int64_type)){
268 result = new Cast (new TypeExpression (TypeManager.int64_type, loc), e, loc);
269 result = result.Resolve (ec);
270 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint64_type)){
271 result = new Cast (new TypeExpression (TypeManager.uint64_type, loc), e, loc);
272 result = result.Resolve (ec);
275 if (result == null || !(result is Constant)){
281 expr_type = result.Type;
282 e = (Constant) result;
285 if (e is EnumConstant){
286 EnumConstant enum_constant = (EnumConstant) e;
289 if (Reduce (ec, enum_constant.Child, out reduced)){
290 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
298 if (expr_type == TypeManager.int32_type){
299 result = new IntConstant (~ ((IntConstant) e).Value);
300 } else if (expr_type == TypeManager.uint32_type){
301 result = new UIntConstant (~ ((UIntConstant) e).Value);
302 } else if (expr_type == TypeManager.int64_type){
303 result = new LongConstant (~ ((LongConstant) e).Value);
304 } else if (expr_type == TypeManager.uint64_type){
305 result = new ULongConstant (~ ((ULongConstant) e).Value);
313 case Operator.AddressOf:
317 case Operator.Indirection:
321 throw new Exception ("Can not constant fold: " + Oper.ToString());
324 Expression ResolveOperator (EmitContext ec)
327 // Step 1: Default operations on CLI native types.
330 // Attempt to use a constant folding operation.
331 if (Expr is Constant){
334 if (Reduce (ec, (Constant) Expr, out result))
339 // Step 2: Perform Operator Overload location
341 Type expr_type = Expr.Type;
345 op_name = oper_names [(int) Oper];
347 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
350 Expression e = StaticCallExpr.MakeSimpleCall (
351 ec, (MethodGroupExpr) mg, Expr, loc);
361 // Only perform numeric promotions on:
364 if (expr_type == null)
368 case Operator.LogicalNot:
369 if (expr_type != TypeManager.bool_type) {
370 Expr = ResolveBoolean (ec, Expr, loc);
377 type = TypeManager.bool_type;
380 case Operator.OnesComplement:
381 if (!((expr_type == TypeManager.int32_type) ||
382 (expr_type == TypeManager.uint32_type) ||
383 (expr_type == TypeManager.int64_type) ||
384 (expr_type == TypeManager.uint64_type) ||
385 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
388 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
390 type = TypeManager.int32_type;
393 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint32_type, loc);
395 type = TypeManager.uint32_type;
398 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
400 type = TypeManager.int64_type;
403 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint64_type, loc);
405 type = TypeManager.uint64_type;
414 case Operator.AddressOf:
415 if (Expr.eclass != ExprClass.Variable){
416 Error (211, "Cannot take the address of non-variables");
425 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
429 IVariable variable = Expr as IVariable;
430 if (!ec.InFixedInitializer && ((variable == null) || !variable.VerifyFixed (false))) {
431 Error (212, "You can only take the address of an unfixed expression inside " +
432 "of a fixed statement initializer");
436 if (ec.InFixedInitializer && ((variable != null) && variable.VerifyFixed (false))) {
437 Error (213, "You can not fix an already fixed expression");
441 LocalVariableReference lr = Expr as LocalVariableReference;
443 if (lr.local_info.IsCaptured){
444 AnonymousMethod.Error_AddressOfCapturedVar (lr.Name, loc);
447 lr.local_info.AddressTaken = true;
448 lr.local_info.Used = true;
451 // According to the specs, a variable is considered definitely assigned if you take
453 if ((variable != null) && (variable.VariableInfo != null)){
454 variable.VariableInfo.SetAssigned (ec);
457 type = TypeManager.GetPointerType (Expr.Type);
460 case Operator.Indirection:
466 if (!expr_type.IsPointer){
467 Error (193, "The * or -> operator can only be applied to pointers");
472 // We create an Indirection expression, because
473 // it can implement the IMemoryLocation.
475 return new Indirection (Expr, loc);
477 case Operator.UnaryPlus:
479 // A plus in front of something is just a no-op, so return the child.
483 case Operator.UnaryNegation:
485 // Deals with -literals
486 // int operator- (int x)
487 // long operator- (long x)
488 // float operator- (float f)
489 // double operator- (double d)
490 // decimal operator- (decimal d)
492 Expression expr = null;
495 // transform - - expr into expr
498 Unary unary = (Unary) Expr;
500 if (unary.Oper == Operator.UnaryNegation)
505 // perform numeric promotions to int,
509 // The following is inneficient, because we call
510 // ImplicitConversion too many times.
512 // It is also not clear if we should convert to Float
513 // or Double initially.
515 if (expr_type == TypeManager.uint32_type){
517 // FIXME: handle exception to this rule that
518 // permits the int value -2147483648 (-2^31) to
519 // bt wrote as a decimal interger literal
521 type = TypeManager.int64_type;
522 Expr = Convert.ImplicitConversion (ec, Expr, type, loc);
526 if (expr_type == TypeManager.uint64_type){
528 // FIXME: Handle exception of `long value'
529 // -92233720368547758087 (-2^63) to be wrote as
530 // decimal integer literal.
536 if (expr_type == TypeManager.float_type){
541 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
548 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
555 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.double_type, loc);
566 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
567 TypeManager.CSharpName (expr_type) + "'");
571 public override Expression DoResolve (EmitContext ec)
573 if (Oper == Operator.AddressOf)
574 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
576 Expr = Expr.Resolve (ec);
581 eclass = ExprClass.Value;
582 return ResolveOperator (ec);
585 public override Expression DoResolveLValue (EmitContext ec, Expression right)
587 if (Oper == Operator.Indirection)
588 return base.DoResolveLValue (ec, right);
590 Error (131, "The left-hand side of an assignment must be a " +
591 "variable, property or indexer");
595 public override void Emit (EmitContext ec)
597 ILGenerator ig = ec.ig;
600 case Operator.UnaryPlus:
601 throw new Exception ("This should be caught by Resolve");
603 case Operator.UnaryNegation:
605 ig.Emit (OpCodes.Ldc_I4_0);
606 if (type == TypeManager.int64_type)
607 ig.Emit (OpCodes.Conv_U8);
609 ig.Emit (OpCodes.Sub_Ovf);
612 ig.Emit (OpCodes.Neg);
617 case Operator.LogicalNot:
619 ig.Emit (OpCodes.Ldc_I4_0);
620 ig.Emit (OpCodes.Ceq);
623 case Operator.OnesComplement:
625 ig.Emit (OpCodes.Not);
628 case Operator.AddressOf:
629 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
633 throw new Exception ("This should not happen: Operator = "
638 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
640 if (Oper == Operator.LogicalNot)
641 Expr.EmitBranchable (ec, target, !onTrue);
643 base.EmitBranchable (ec, target, onTrue);
646 public override string ToString ()
648 return "Unary (" + Oper + ", " + Expr + ")";
654 // Unary operators are turned into Indirection expressions
655 // after semantic analysis (this is so we can take the address
656 // of an indirection).
658 public class Indirection : Expression, IMemoryLocation, IAssignMethod {
660 LocalTemporary temporary;
663 public Indirection (Expression expr, Location l)
666 this.type = TypeManager.GetElementType (expr.Type);
667 eclass = ExprClass.Variable;
671 void LoadExprValue (EmitContext ec)
675 public override void Emit (EmitContext ec)
680 LoadFromPtr (ec.ig, Type);
683 public void Emit (EmitContext ec, bool leave_copy)
687 ec.ig.Emit (OpCodes.Dup);
688 temporary = new LocalTemporary (ec, expr.Type);
689 temporary.Store (ec);
693 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
695 prepared = prepare_for_load;
699 if (prepare_for_load)
700 ec.ig.Emit (OpCodes.Dup);
704 ec.ig.Emit (OpCodes.Dup);
705 temporary = new LocalTemporary (ec, expr.Type);
706 temporary.Store (ec);
709 StoreFromPtr (ec.ig, type);
711 if (temporary != null)
715 public void AddressOf (EmitContext ec, AddressOp Mode)
720 public override Expression DoResolve (EmitContext ec)
723 // Born fully resolved
728 public override string ToString ()
730 return "*(" + expr + ")";
735 /// Unary Mutator expressions (pre and post ++ and --)
739 /// UnaryMutator implements ++ and -- expressions. It derives from
740 /// ExpressionStatement becuase the pre/post increment/decrement
741 /// operators can be used in a statement context.
743 /// FIXME: Idea, we could split this up in two classes, one simpler
744 /// for the common case, and one with the extra fields for more complex
745 /// classes (indexers require temporary access; overloaded require method)
748 public class UnaryMutator : ExpressionStatement {
750 public enum Mode : byte {
757 PreDecrement = IsDecrement,
758 PostIncrement = IsPost,
759 PostDecrement = IsPost | IsDecrement
763 bool is_expr = false;
764 bool recurse = false;
769 // This is expensive for the simplest case.
771 StaticCallExpr method;
773 public UnaryMutator (Mode m, Expression e, Location l)
780 static string OperName (Mode mode)
782 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
786 void Error23 (Type t)
789 23, "Operator " + OperName (mode) +
790 " cannot be applied to operand of type `" +
791 TypeManager.CSharpName (t) + "'");
795 /// Returns whether an object of type `t' can be incremented
796 /// or decremented with add/sub (ie, basically whether we can
797 /// use pre-post incr-decr operations on it, but it is not a
798 /// System.Decimal, which we require operator overloading to catch)
800 static bool IsIncrementableNumber (Type t)
802 return (t == TypeManager.sbyte_type) ||
803 (t == TypeManager.byte_type) ||
804 (t == TypeManager.short_type) ||
805 (t == TypeManager.ushort_type) ||
806 (t == TypeManager.int32_type) ||
807 (t == TypeManager.uint32_type) ||
808 (t == TypeManager.int64_type) ||
809 (t == TypeManager.uint64_type) ||
810 (t == TypeManager.char_type) ||
811 (t.IsSubclassOf (TypeManager.enum_type)) ||
812 (t == TypeManager.float_type) ||
813 (t == TypeManager.double_type) ||
814 (t.IsPointer && t != TypeManager.void_ptr_type);
817 Expression ResolveOperator (EmitContext ec)
819 Type expr_type = expr.Type;
822 // Step 1: Perform Operator Overload location
827 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
828 op_name = "op_Increment";
830 op_name = "op_Decrement";
832 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
834 if (mg == null && expr_type.BaseType != null)
835 mg = MemberLookup (ec, expr_type.BaseType, op_name,
836 MemberTypes.Method, AllBindingFlags, loc);
839 method = StaticCallExpr.MakeSimpleCall (
840 ec, (MethodGroupExpr) mg, expr, loc);
847 // The operand of the prefix/postfix increment decrement operators
848 // should be an expression that is classified as a variable,
849 // a property access or an indexer access
852 if (expr.eclass == ExprClass.Variable){
853 LocalVariableReference var = expr as LocalVariableReference;
854 if ((var != null) && var.IsReadOnly)
855 Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
856 if (IsIncrementableNumber (expr_type) ||
857 expr_type == TypeManager.decimal_type){
860 } else if (expr.eclass == ExprClass.IndexerAccess){
861 IndexerAccess ia = (IndexerAccess) expr;
863 expr = ia.ResolveLValue (ec, this);
868 } else if (expr.eclass == ExprClass.PropertyAccess){
869 PropertyExpr pe = (PropertyExpr) expr;
871 if (pe.VerifyAssignable ())
876 expr.Error_UnexpectedKind ("variable, indexer or property access", loc);
880 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
881 TypeManager.CSharpName (expr_type) + "'");
885 public override Expression DoResolve (EmitContext ec)
887 expr = expr.Resolve (ec);
892 eclass = ExprClass.Value;
893 return ResolveOperator (ec);
896 static int PtrTypeSize (Type t)
898 return GetTypeSize (TypeManager.GetElementType (t));
902 // Loads the proper "1" into the stack based on the type, then it emits the
903 // opcode for the operation requested
905 void LoadOneAndEmitOp (EmitContext ec, Type t)
908 // Measure if getting the typecode and using that is more/less efficient
909 // that comparing types. t.GetTypeCode() is an internal call.
911 ILGenerator ig = ec.ig;
913 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
914 LongConstant.EmitLong (ig, 1);
915 else if (t == TypeManager.double_type)
916 ig.Emit (OpCodes.Ldc_R8, 1.0);
917 else if (t == TypeManager.float_type)
918 ig.Emit (OpCodes.Ldc_R4, 1.0F);
919 else if (t.IsPointer){
920 int n = PtrTypeSize (t);
923 ig.Emit (OpCodes.Sizeof, t);
925 IntConstant.EmitInt (ig, n);
927 ig.Emit (OpCodes.Ldc_I4_1);
930 // Now emit the operation
933 if (t == TypeManager.int32_type ||
934 t == TypeManager.int64_type){
935 if ((mode & Mode.IsDecrement) != 0)
936 ig.Emit (OpCodes.Sub_Ovf);
938 ig.Emit (OpCodes.Add_Ovf);
939 } else if (t == TypeManager.uint32_type ||
940 t == TypeManager.uint64_type){
941 if ((mode & Mode.IsDecrement) != 0)
942 ig.Emit (OpCodes.Sub_Ovf_Un);
944 ig.Emit (OpCodes.Add_Ovf_Un);
946 if ((mode & Mode.IsDecrement) != 0)
947 ig.Emit (OpCodes.Sub_Ovf);
949 ig.Emit (OpCodes.Add_Ovf);
952 if ((mode & Mode.IsDecrement) != 0)
953 ig.Emit (OpCodes.Sub);
955 ig.Emit (OpCodes.Add);
958 if (t == TypeManager.sbyte_type){
960 ig.Emit (OpCodes.Conv_Ovf_I1);
962 ig.Emit (OpCodes.Conv_I1);
963 } else if (t == TypeManager.byte_type){
965 ig.Emit (OpCodes.Conv_Ovf_U1);
967 ig.Emit (OpCodes.Conv_U1);
968 } else if (t == TypeManager.short_type){
970 ig.Emit (OpCodes.Conv_Ovf_I2);
972 ig.Emit (OpCodes.Conv_I2);
973 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
975 ig.Emit (OpCodes.Conv_Ovf_U2);
977 ig.Emit (OpCodes.Conv_U2);
982 void EmitCode (EmitContext ec, bool is_expr)
985 this.is_expr = is_expr;
986 ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
990 public override void Emit (EmitContext ec)
993 // We use recurse to allow ourselfs to be the source
994 // of an assignment. This little hack prevents us from
995 // having to allocate another expression
998 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
1000 LoadOneAndEmitOp (ec, expr.Type);
1002 ec.ig.Emit (OpCodes.Call, method.Method);
1007 EmitCode (ec, true);
1010 public override void EmitStatement (EmitContext ec)
1012 EmitCode (ec, false);
1017 /// Base class for the `Is' and `As' classes.
1021 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1024 public abstract class Probe : Expression {
1025 public Expression ProbeType;
1026 protected Expression expr;
1027 protected Type probe_type;
1029 public Probe (Expression expr, Expression probe_type, Location l)
1031 ProbeType = probe_type;
1036 public Expression Expr {
1042 public override Expression DoResolve (EmitContext ec)
1044 TypeExpr texpr = ProbeType.ResolveAsTypeTerminal (ec, false);
1047 probe_type = texpr.ResolveType (ec);
1049 CheckObsoleteAttribute (probe_type);
1051 expr = expr.Resolve (ec);
1055 if (expr.Type.IsPointer) {
1056 Report.Error (244, loc, "\"is\" or \"as\" are not valid on pointer types");
1064 /// Implementation of the `is' operator.
1066 public class Is : Probe {
1067 public Is (Expression expr, Expression probe_type, Location l)
1068 : base (expr, probe_type, l)
1073 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1078 public override void Emit (EmitContext ec)
1080 ILGenerator ig = ec.ig;
1085 case Action.AlwaysFalse:
1086 ig.Emit (OpCodes.Pop);
1087 IntConstant.EmitInt (ig, 0);
1089 case Action.AlwaysTrue:
1090 ig.Emit (OpCodes.Pop);
1091 IntConstant.EmitInt (ig, 1);
1093 case Action.LeaveOnStack:
1094 // the `e != null' rule.
1095 ig.Emit (OpCodes.Ldnull);
1096 ig.Emit (OpCodes.Ceq);
1097 ig.Emit (OpCodes.Ldc_I4_0);
1098 ig.Emit (OpCodes.Ceq);
1101 ig.Emit (OpCodes.Isinst, probe_type);
1102 ig.Emit (OpCodes.Ldnull);
1103 ig.Emit (OpCodes.Cgt_Un);
1106 throw new Exception ("never reached");
1109 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
1111 ILGenerator ig = ec.ig;
1114 case Action.AlwaysFalse:
1116 ig.Emit (OpCodes.Br, target);
1119 case Action.AlwaysTrue:
1121 ig.Emit (OpCodes.Br, target);
1124 case Action.LeaveOnStack:
1125 // the `e != null' rule.
1127 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1131 ig.Emit (OpCodes.Isinst, probe_type);
1132 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1135 throw new Exception ("never reached");
1138 public override Expression DoResolve (EmitContext ec)
1140 Expression e = base.DoResolve (ec);
1142 if ((e == null) || (expr == null))
1145 Type etype = expr.Type;
1146 bool warning_always_matches = false;
1147 bool warning_never_matches = false;
1149 type = TypeManager.bool_type;
1150 eclass = ExprClass.Value;
1153 // First case, if at compile time, there is an implicit conversion
1154 // then e != null (objects) or true (value types)
1156 e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1159 if (etype.IsValueType)
1160 action = Action.AlwaysTrue;
1162 action = Action.LeaveOnStack;
1164 warning_always_matches = true;
1165 } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1167 // Second case: explicit reference convresion
1169 if (expr is NullLiteral)
1170 action = Action.AlwaysFalse;
1172 action = Action.Probe;
1174 action = Action.AlwaysFalse;
1175 warning_never_matches = true;
1178 if (warning_always_matches)
1179 Warning (183, "The given expression is always of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1180 else if (warning_never_matches){
1181 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1182 Warning (184, "The given expression is never of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1190 /// Implementation of the `as' operator.
1192 public class As : Probe {
1193 public As (Expression expr, Expression probe_type, Location l)
1194 : base (expr, probe_type, l)
1198 bool do_isinst = false;
1200 public override void Emit (EmitContext ec)
1202 ILGenerator ig = ec.ig;
1207 ig.Emit (OpCodes.Isinst, probe_type);
1210 static void Error_CannotConvertType (Type source, Type target, Location loc)
1213 39, loc, "as operator can not convert from `" +
1214 TypeManager.CSharpName (source) + "' to `" +
1215 TypeManager.CSharpName (target) + "'");
1218 public override Expression DoResolve (EmitContext ec)
1220 Expression e = base.DoResolve (ec);
1226 eclass = ExprClass.Value;
1227 Type etype = expr.Type;
1229 if (TypeManager.IsValueType (probe_type)){
1230 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1231 TypeManager.CSharpName (probe_type) + " is a value type)");
1236 e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1243 if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1248 Error_CannotConvertType (etype, probe_type, loc);
1254 /// This represents a typecast in the source language.
1256 /// FIXME: Cast expressions have an unusual set of parsing
1257 /// rules, we need to figure those out.
1259 public class Cast : Expression {
1260 Expression target_type;
1263 public Cast (Expression cast_type, Expression expr, Location loc)
1265 this.target_type = cast_type;
1270 public Expression TargetType {
1276 public Expression Expr {
1285 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1287 if (!ec.ConstantCheckState)
1290 if ((value < min) || (value > max)) {
1291 Error (221, "Constant value `" + value + "' cannot be converted " +
1292 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1293 "syntax to override)");
1300 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1302 if (!ec.ConstantCheckState)
1306 Error (221, "Constant value `" + value + "' cannot be converted " +
1307 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1308 "syntax to override)");
1315 bool CheckUnsigned (EmitContext ec, long value, Type type)
1317 if (!ec.ConstantCheckState)
1321 Error (221, "Constant value `" + value + "' cannot be converted " +
1322 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1323 "syntax to override)");
1331 /// Attempts to do a compile-time folding of a constant cast.
1333 Expression TryReduce (EmitContext ec, Type target_type)
1335 Expression real_expr = expr;
1336 if (real_expr is EnumConstant)
1337 real_expr = ((EnumConstant) real_expr).Child;
1339 if (real_expr is ByteConstant){
1340 byte v = ((ByteConstant) real_expr).Value;
1342 if (target_type == TypeManager.sbyte_type) {
1343 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1345 return new SByteConstant ((sbyte) v);
1347 if (target_type == TypeManager.short_type)
1348 return new ShortConstant ((short) v);
1349 if (target_type == TypeManager.ushort_type)
1350 return new UShortConstant ((ushort) v);
1351 if (target_type == TypeManager.int32_type)
1352 return new IntConstant ((int) v);
1353 if (target_type == TypeManager.uint32_type)
1354 return new UIntConstant ((uint) v);
1355 if (target_type == TypeManager.int64_type)
1356 return new LongConstant ((long) v);
1357 if (target_type == TypeManager.uint64_type)
1358 return new ULongConstant ((ulong) v);
1359 if (target_type == TypeManager.float_type)
1360 return new FloatConstant ((float) v);
1361 if (target_type == TypeManager.double_type)
1362 return new DoubleConstant ((double) v);
1363 if (target_type == TypeManager.char_type)
1364 return new CharConstant ((char) v);
1365 if (target_type == TypeManager.decimal_type)
1366 return new DecimalConstant ((decimal) v);
1368 if (real_expr is SByteConstant){
1369 sbyte v = ((SByteConstant) real_expr).Value;
1371 if (target_type == TypeManager.byte_type) {
1372 if (!CheckUnsigned (ec, v, target_type))
1374 return new ByteConstant ((byte) v);
1376 if (target_type == TypeManager.short_type)
1377 return new ShortConstant ((short) v);
1378 if (target_type == TypeManager.ushort_type) {
1379 if (!CheckUnsigned (ec, v, target_type))
1381 return new UShortConstant ((ushort) v);
1382 } if (target_type == TypeManager.int32_type)
1383 return new IntConstant ((int) v);
1384 if (target_type == TypeManager.uint32_type) {
1385 if (!CheckUnsigned (ec, v, target_type))
1387 return new UIntConstant ((uint) v);
1388 } if (target_type == TypeManager.int64_type)
1389 return new LongConstant ((long) v);
1390 if (target_type == TypeManager.uint64_type) {
1391 if (!CheckUnsigned (ec, v, target_type))
1393 return new ULongConstant ((ulong) v);
1395 if (target_type == TypeManager.float_type)
1396 return new FloatConstant ((float) v);
1397 if (target_type == TypeManager.double_type)
1398 return new DoubleConstant ((double) v);
1399 if (target_type == TypeManager.char_type) {
1400 if (!CheckUnsigned (ec, v, target_type))
1402 return new CharConstant ((char) v);
1404 if (target_type == TypeManager.decimal_type)
1405 return new DecimalConstant ((decimal) v);
1407 if (real_expr is ShortConstant){
1408 short v = ((ShortConstant) real_expr).Value;
1410 if (target_type == TypeManager.byte_type) {
1411 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1413 return new ByteConstant ((byte) v);
1415 if (target_type == TypeManager.sbyte_type) {
1416 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1418 return new SByteConstant ((sbyte) v);
1420 if (target_type == TypeManager.ushort_type) {
1421 if (!CheckUnsigned (ec, v, target_type))
1423 return new UShortConstant ((ushort) v);
1425 if (target_type == TypeManager.int32_type)
1426 return new IntConstant ((int) v);
1427 if (target_type == TypeManager.uint32_type) {
1428 if (!CheckUnsigned (ec, v, target_type))
1430 return new UIntConstant ((uint) v);
1432 if (target_type == TypeManager.int64_type)
1433 return new LongConstant ((long) v);
1434 if (target_type == TypeManager.uint64_type) {
1435 if (!CheckUnsigned (ec, v, target_type))
1437 return new ULongConstant ((ulong) v);
1439 if (target_type == TypeManager.float_type)
1440 return new FloatConstant ((float) v);
1441 if (target_type == TypeManager.double_type)
1442 return new DoubleConstant ((double) v);
1443 if (target_type == TypeManager.char_type) {
1444 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1446 return new CharConstant ((char) v);
1448 if (target_type == TypeManager.decimal_type)
1449 return new DecimalConstant ((decimal) v);
1451 if (real_expr is UShortConstant){
1452 ushort v = ((UShortConstant) real_expr).Value;
1454 if (target_type == TypeManager.byte_type) {
1455 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1457 return new ByteConstant ((byte) v);
1459 if (target_type == TypeManager.sbyte_type) {
1460 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1462 return new SByteConstant ((sbyte) v);
1464 if (target_type == TypeManager.short_type) {
1465 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1467 return new ShortConstant ((short) v);
1469 if (target_type == TypeManager.int32_type)
1470 return new IntConstant ((int) v);
1471 if (target_type == TypeManager.uint32_type)
1472 return new UIntConstant ((uint) v);
1473 if (target_type == TypeManager.int64_type)
1474 return new LongConstant ((long) v);
1475 if (target_type == TypeManager.uint64_type)
1476 return new ULongConstant ((ulong) v);
1477 if (target_type == TypeManager.float_type)
1478 return new FloatConstant ((float) v);
1479 if (target_type == TypeManager.double_type)
1480 return new DoubleConstant ((double) v);
1481 if (target_type == TypeManager.char_type) {
1482 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1484 return new CharConstant ((char) v);
1486 if (target_type == TypeManager.decimal_type)
1487 return new DecimalConstant ((decimal) v);
1489 if (real_expr is IntConstant){
1490 int v = ((IntConstant) real_expr).Value;
1492 if (target_type == TypeManager.byte_type) {
1493 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1495 return new ByteConstant ((byte) v);
1497 if (target_type == TypeManager.sbyte_type) {
1498 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1500 return new SByteConstant ((sbyte) v);
1502 if (target_type == TypeManager.short_type) {
1503 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1505 return new ShortConstant ((short) v);
1507 if (target_type == TypeManager.ushort_type) {
1508 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1510 return new UShortConstant ((ushort) v);
1512 if (target_type == TypeManager.uint32_type) {
1513 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1515 return new UIntConstant ((uint) v);
1517 if (target_type == TypeManager.int64_type)
1518 return new LongConstant ((long) v);
1519 if (target_type == TypeManager.uint64_type) {
1520 if (!CheckUnsigned (ec, v, target_type))
1522 return new ULongConstant ((ulong) v);
1524 if (target_type == TypeManager.float_type)
1525 return new FloatConstant ((float) v);
1526 if (target_type == TypeManager.double_type)
1527 return new DoubleConstant ((double) v);
1528 if (target_type == TypeManager.char_type) {
1529 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1531 return new CharConstant ((char) v);
1533 if (target_type == TypeManager.decimal_type)
1534 return new DecimalConstant ((decimal) v);
1536 if (real_expr is UIntConstant){
1537 uint v = ((UIntConstant) real_expr).Value;
1539 if (target_type == TypeManager.byte_type) {
1540 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1542 return new ByteConstant ((byte) v);
1544 if (target_type == TypeManager.sbyte_type) {
1545 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1547 return new SByteConstant ((sbyte) v);
1549 if (target_type == TypeManager.short_type) {
1550 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1552 return new ShortConstant ((short) v);
1554 if (target_type == TypeManager.ushort_type) {
1555 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1557 return new UShortConstant ((ushort) v);
1559 if (target_type == TypeManager.int32_type) {
1560 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1562 return new IntConstant ((int) v);
1564 if (target_type == TypeManager.int64_type)
1565 return new LongConstant ((long) v);
1566 if (target_type == TypeManager.uint64_type)
1567 return new ULongConstant ((ulong) v);
1568 if (target_type == TypeManager.float_type)
1569 return new FloatConstant ((float) v);
1570 if (target_type == TypeManager.double_type)
1571 return new DoubleConstant ((double) v);
1572 if (target_type == TypeManager.char_type) {
1573 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1575 return new CharConstant ((char) v);
1577 if (target_type == TypeManager.decimal_type)
1578 return new DecimalConstant ((decimal) v);
1580 if (real_expr is LongConstant){
1581 long v = ((LongConstant) real_expr).Value;
1583 if (target_type == TypeManager.byte_type) {
1584 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1586 return new ByteConstant ((byte) v);
1588 if (target_type == TypeManager.sbyte_type) {
1589 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1591 return new SByteConstant ((sbyte) v);
1593 if (target_type == TypeManager.short_type) {
1594 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1596 return new ShortConstant ((short) v);
1598 if (target_type == TypeManager.ushort_type) {
1599 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1601 return new UShortConstant ((ushort) v);
1603 if (target_type == TypeManager.int32_type) {
1604 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1606 return new IntConstant ((int) v);
1608 if (target_type == TypeManager.uint32_type) {
1609 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1611 return new UIntConstant ((uint) v);
1613 if (target_type == TypeManager.uint64_type) {
1614 if (!CheckUnsigned (ec, v, target_type))
1616 return new ULongConstant ((ulong) v);
1618 if (target_type == TypeManager.float_type)
1619 return new FloatConstant ((float) v);
1620 if (target_type == TypeManager.double_type)
1621 return new DoubleConstant ((double) v);
1622 if (target_type == TypeManager.char_type) {
1623 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1625 return new CharConstant ((char) v);
1627 if (target_type == TypeManager.decimal_type)
1628 return new DecimalConstant ((decimal) v);
1630 if (real_expr is ULongConstant){
1631 ulong v = ((ULongConstant) real_expr).Value;
1633 if (target_type == TypeManager.byte_type) {
1634 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1636 return new ByteConstant ((byte) v);
1638 if (target_type == TypeManager.sbyte_type) {
1639 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1641 return new SByteConstant ((sbyte) v);
1643 if (target_type == TypeManager.short_type) {
1644 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1646 return new ShortConstant ((short) v);
1648 if (target_type == TypeManager.ushort_type) {
1649 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1651 return new UShortConstant ((ushort) v);
1653 if (target_type == TypeManager.int32_type) {
1654 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1656 return new IntConstant ((int) v);
1658 if (target_type == TypeManager.uint32_type) {
1659 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1661 return new UIntConstant ((uint) v);
1663 if (target_type == TypeManager.int64_type) {
1664 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1666 return new LongConstant ((long) v);
1668 if (target_type == TypeManager.float_type)
1669 return new FloatConstant ((float) v);
1670 if (target_type == TypeManager.double_type)
1671 return new DoubleConstant ((double) v);
1672 if (target_type == TypeManager.char_type) {
1673 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1675 return new CharConstant ((char) v);
1677 if (target_type == TypeManager.decimal_type)
1678 return new DecimalConstant ((decimal) v);
1680 if (real_expr is FloatConstant){
1681 float v = ((FloatConstant) real_expr).Value;
1683 if (target_type == TypeManager.byte_type)
1684 return new ByteConstant ((byte) v);
1685 if (target_type == TypeManager.sbyte_type)
1686 return new SByteConstant ((sbyte) v);
1687 if (target_type == TypeManager.short_type)
1688 return new ShortConstant ((short) v);
1689 if (target_type == TypeManager.ushort_type)
1690 return new UShortConstant ((ushort) v);
1691 if (target_type == TypeManager.int32_type)
1692 return new IntConstant ((int) v);
1693 if (target_type == TypeManager.uint32_type)
1694 return new UIntConstant ((uint) v);
1695 if (target_type == TypeManager.int64_type)
1696 return new LongConstant ((long) v);
1697 if (target_type == TypeManager.uint64_type)
1698 return new ULongConstant ((ulong) v);
1699 if (target_type == TypeManager.double_type)
1700 return new DoubleConstant ((double) v);
1701 if (target_type == TypeManager.char_type)
1702 return new CharConstant ((char) v);
1703 if (target_type == TypeManager.decimal_type)
1704 return new DecimalConstant ((decimal) v);
1706 if (real_expr is DoubleConstant){
1707 double v = ((DoubleConstant) real_expr).Value;
1709 if (target_type == TypeManager.byte_type){
1710 return new ByteConstant ((byte) v);
1711 } if (target_type == TypeManager.sbyte_type)
1712 return new SByteConstant ((sbyte) v);
1713 if (target_type == TypeManager.short_type)
1714 return new ShortConstant ((short) v);
1715 if (target_type == TypeManager.ushort_type)
1716 return new UShortConstant ((ushort) v);
1717 if (target_type == TypeManager.int32_type)
1718 return new IntConstant ((int) v);
1719 if (target_type == TypeManager.uint32_type)
1720 return new UIntConstant ((uint) v);
1721 if (target_type == TypeManager.int64_type)
1722 return new LongConstant ((long) v);
1723 if (target_type == TypeManager.uint64_type)
1724 return new ULongConstant ((ulong) v);
1725 if (target_type == TypeManager.float_type)
1726 return new FloatConstant ((float) v);
1727 if (target_type == TypeManager.char_type)
1728 return new CharConstant ((char) v);
1729 if (target_type == TypeManager.decimal_type)
1730 return new DecimalConstant ((decimal) v);
1733 if (real_expr is CharConstant){
1734 char v = ((CharConstant) real_expr).Value;
1736 if (target_type == TypeManager.byte_type) {
1737 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1739 return new ByteConstant ((byte) v);
1741 if (target_type == TypeManager.sbyte_type) {
1742 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1744 return new SByteConstant ((sbyte) v);
1746 if (target_type == TypeManager.short_type) {
1747 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1749 return new ShortConstant ((short) v);
1751 if (target_type == TypeManager.int32_type)
1752 return new IntConstant ((int) v);
1753 if (target_type == TypeManager.uint32_type)
1754 return new UIntConstant ((uint) v);
1755 if (target_type == TypeManager.int64_type)
1756 return new LongConstant ((long) v);
1757 if (target_type == TypeManager.uint64_type)
1758 return new ULongConstant ((ulong) v);
1759 if (target_type == TypeManager.float_type)
1760 return new FloatConstant ((float) v);
1761 if (target_type == TypeManager.double_type)
1762 return new DoubleConstant ((double) v);
1763 if (target_type == TypeManager.char_type) {
1764 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1766 return new CharConstant ((char) v);
1768 if (target_type == TypeManager.decimal_type)
1769 return new DecimalConstant ((decimal) v);
1775 public override Expression DoResolve (EmitContext ec)
1777 expr = expr.Resolve (ec);
1781 TypeExpr target = target_type.ResolveAsTypeTerminal (ec, false);
1785 type = target.ResolveType (ec);
1787 CheckObsoleteAttribute (type);
1789 if (type.IsAbstract && type.IsSealed) {
1790 Report.Error (716, loc, "Cannot convert to static type '{0}'", TypeManager.CSharpName (type));
1794 eclass = ExprClass.Value;
1796 if (expr is Constant){
1797 Expression e = TryReduce (ec, type);
1803 if (type.IsPointer && !ec.InUnsafe) {
1807 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1811 public override void Emit (EmitContext ec)
1814 // This one will never happen
1816 throw new Exception ("Should not happen");
1821 /// Binary operators
1823 public class Binary : Expression {
1824 public enum Operator : byte {
1825 Multiply, Division, Modulus,
1826 Addition, Subtraction,
1827 LeftShift, RightShift,
1828 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1829 Equality, Inequality,
1839 Expression left, right;
1841 // This must be kept in sync with Operator!!!
1842 public static readonly string [] oper_names;
1846 oper_names = new string [(int) Operator.TOP];
1848 oper_names [(int) Operator.Multiply] = "op_Multiply";
1849 oper_names [(int) Operator.Division] = "op_Division";
1850 oper_names [(int) Operator.Modulus] = "op_Modulus";
1851 oper_names [(int) Operator.Addition] = "op_Addition";
1852 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1853 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1854 oper_names [(int) Operator.RightShift] = "op_RightShift";
1855 oper_names [(int) Operator.LessThan] = "op_LessThan";
1856 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1857 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1858 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1859 oper_names [(int) Operator.Equality] = "op_Equality";
1860 oper_names [(int) Operator.Inequality] = "op_Inequality";
1861 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1862 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1863 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1864 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1865 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1868 public Binary (Operator oper, Expression left, Expression right, Location loc)
1876 public Operator Oper {
1885 public Expression Left {
1894 public Expression Right {
1905 /// Returns a stringified representation of the Operator
1907 static string OperName (Operator oper)
1910 case Operator.Multiply:
1912 case Operator.Division:
1914 case Operator.Modulus:
1916 case Operator.Addition:
1918 case Operator.Subtraction:
1920 case Operator.LeftShift:
1922 case Operator.RightShift:
1924 case Operator.LessThan:
1926 case Operator.GreaterThan:
1928 case Operator.LessThanOrEqual:
1930 case Operator.GreaterThanOrEqual:
1932 case Operator.Equality:
1934 case Operator.Inequality:
1936 case Operator.BitwiseAnd:
1938 case Operator.BitwiseOr:
1940 case Operator.ExclusiveOr:
1942 case Operator.LogicalOr:
1944 case Operator.LogicalAnd:
1948 return oper.ToString ();
1951 public override string ToString ()
1953 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1954 right.ToString () + ")";
1957 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1959 if (expr.Type == target_type)
1962 return Convert.ImplicitConversion (ec, expr, target_type, loc);
1965 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1968 34, loc, "Operator `" + OperName (oper)
1969 + "' is ambiguous on operands of type `"
1970 + TypeManager.CSharpName (l) + "' "
1971 + "and `" + TypeManager.CSharpName (r)
1975 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
1977 if ((l == t) || (r == t))
1980 if (!check_user_conversions)
1983 if (Convert.ImplicitUserConversionExists (ec, l, t))
1985 else if (Convert.ImplicitUserConversionExists (ec, r, t))
1992 // Note that handling the case l == Decimal || r == Decimal
1993 // is taken care of by the Step 1 Operator Overload resolution.
1995 // If `check_user_conv' is true, we also check whether a user-defined conversion
1996 // exists. Note that we only need to do this if both arguments are of a user-defined
1997 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
1998 // so we don't explicitly check for performance reasons.
2000 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
2002 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
2004 // If either operand is of type double, the other operand is
2005 // conveted to type double.
2007 if (r != TypeManager.double_type)
2008 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
2009 if (l != TypeManager.double_type)
2010 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
2012 type = TypeManager.double_type;
2013 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
2015 // if either operand is of type float, the other operand is
2016 // converted to type float.
2018 if (r != TypeManager.double_type)
2019 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
2020 if (l != TypeManager.double_type)
2021 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
2022 type = TypeManager.float_type;
2023 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2027 // If either operand is of type ulong, the other operand is
2028 // converted to type ulong. or an error ocurrs if the other
2029 // operand is of type sbyte, short, int or long
2031 if (l == TypeManager.uint64_type){
2032 if (r != TypeManager.uint64_type){
2033 if (right is IntConstant){
2034 IntConstant ic = (IntConstant) right;
2036 e = Convert.TryImplicitIntConversion (l, ic);
2039 } else if (right is LongConstant){
2040 long ll = ((LongConstant) right).Value;
2043 right = new ULongConstant ((ulong) ll);
2045 e = Convert.ImplicitNumericConversion (ec, right, l, loc);
2052 if (left is IntConstant){
2053 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
2056 } else if (left is LongConstant){
2057 long ll = ((LongConstant) left).Value;
2060 left = new ULongConstant ((ulong) ll);
2062 e = Convert.ImplicitNumericConversion (ec, left, r, loc);
2069 if ((other == TypeManager.sbyte_type) ||
2070 (other == TypeManager.short_type) ||
2071 (other == TypeManager.int32_type) ||
2072 (other == TypeManager.int64_type))
2073 Error_OperatorAmbiguous (loc, oper, l, r);
2075 left = ForceConversion (ec, left, TypeManager.uint64_type);
2076 right = ForceConversion (ec, right, TypeManager.uint64_type);
2078 type = TypeManager.uint64_type;
2079 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2081 // If either operand is of type long, the other operand is converted
2084 if (l != TypeManager.int64_type)
2085 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
2086 if (r != TypeManager.int64_type)
2087 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
2089 type = TypeManager.int64_type;
2090 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2092 // If either operand is of type uint, and the other
2093 // operand is of type sbyte, short or int, othe operands are
2094 // converted to type long (unless we have an int constant).
2098 if (l == TypeManager.uint32_type){
2099 if (right is IntConstant){
2100 IntConstant ic = (IntConstant) right;
2104 right = new UIntConstant ((uint) val);
2111 } else if (r == TypeManager.uint32_type){
2112 if (left is IntConstant){
2113 IntConstant ic = (IntConstant) left;
2117 left = new UIntConstant ((uint) val);
2126 if ((other == TypeManager.sbyte_type) ||
2127 (other == TypeManager.short_type) ||
2128 (other == TypeManager.int32_type)){
2129 left = ForceConversion (ec, left, TypeManager.int64_type);
2130 right = ForceConversion (ec, right, TypeManager.int64_type);
2131 type = TypeManager.int64_type;
2134 // if either operand is of type uint, the other
2135 // operand is converd to type uint
2137 left = ForceConversion (ec, left, TypeManager.uint32_type);
2138 right = ForceConversion (ec, right, TypeManager.uint32_type);
2139 type = TypeManager.uint32_type;
2141 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2142 if (l != TypeManager.decimal_type)
2143 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
2145 if (r != TypeManager.decimal_type)
2146 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
2147 type = TypeManager.decimal_type;
2149 left = ForceConversion (ec, left, TypeManager.int32_type);
2150 right = ForceConversion (ec, right, TypeManager.int32_type);
2152 type = TypeManager.int32_type;
2155 return (left != null) && (right != null);
2158 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2160 Report.Error (19, loc,
2161 "Operator " + name + " cannot be applied to operands of type `" +
2162 TypeManager.CSharpName (l) + "' and `" +
2163 TypeManager.CSharpName (r) + "'");
2166 void Error_OperatorCannotBeApplied ()
2168 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2171 static bool is_unsigned (Type t)
2173 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2174 t == TypeManager.short_type || t == TypeManager.byte_type);
2177 static bool is_user_defined (Type t)
2179 if (t.IsSubclassOf (TypeManager.value_type) &&
2180 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2186 Expression Make32or64 (EmitContext ec, Expression e)
2190 if (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2191 t == TypeManager.int64_type || t == TypeManager.uint64_type)
2193 Expression ee = Convert.ImplicitConversion (ec, e, TypeManager.int32_type, loc);
2196 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint32_type, loc);
2199 ee = Convert.ImplicitConversion (ec, e, TypeManager.int64_type, loc);
2202 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint64_type, loc);
2208 Expression CheckShiftArguments (EmitContext ec)
2212 e = ForceConversion (ec, right, TypeManager.int32_type);
2214 Error_OperatorCannotBeApplied ();
2219 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
2220 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
2221 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
2222 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
2226 if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
2227 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (31), loc);
2228 right = right.DoResolve (ec);
2230 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (63), loc);
2231 right = right.DoResolve (ec);
2236 Error_OperatorCannotBeApplied ();
2240 Expression ResolveOperator (EmitContext ec)
2243 Type r = right.Type;
2246 // Special cases: string comapred to null
2248 if (oper == Operator.Equality || oper == Operator.Inequality){
2249 if ((!TypeManager.IsValueType (l) && r == TypeManager.null_type) ||
2250 (!TypeManager.IsValueType (r) && l == TypeManager.null_type)) {
2251 Type = TypeManager.bool_type;
2257 if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
2258 Type = TypeManager.bool_type;
2265 // Do not perform operator overload resolution when both sides are
2268 if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
2270 // Step 1: Perform Operator Overload location
2272 Expression left_expr, right_expr;
2274 string op = oper_names [(int) oper];
2276 MethodGroupExpr union;
2277 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2279 right_expr = MemberLookup (
2280 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2281 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2283 union = (MethodGroupExpr) left_expr;
2285 if (union != null) {
2286 ArrayList args = new ArrayList (2);
2287 args.Add (new Argument (left, Argument.AType.Expression));
2288 args.Add (new Argument (right, Argument.AType.Expression));
2290 MethodBase method = Invocation.OverloadResolve (
2291 ec, union, args, true, Location.Null);
2293 if (method != null) {
2294 MethodInfo mi = (MethodInfo) method;
2296 return new BinaryMethod (mi.ReturnType, method, args);
2302 // Step 0: String concatenation (because overloading will get this wrong)
2304 if (oper == Operator.Addition){
2306 // If any of the arguments is a string, cast to string
2309 // Simple constant folding
2310 if (left is StringConstant && right is StringConstant)
2311 return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value);
2313 if (l == TypeManager.string_type || r == TypeManager.string_type) {
2315 if (r == TypeManager.void_type || l == TypeManager.void_type) {
2316 Error_OperatorCannotBeApplied ();
2320 // try to fold it in on the left
2321 if (left is StringConcat) {
2324 // We have to test here for not-null, since we can be doubly-resolved
2325 // take care of not appending twice
2328 type = TypeManager.string_type;
2329 ((StringConcat) left).Append (ec, right);
2330 return left.Resolve (ec);
2336 // Otherwise, start a new concat expression
2337 return new StringConcat (ec, loc, left, right).Resolve (ec);
2341 // Transform a + ( - b) into a - b
2343 if (right is Unary){
2344 Unary right_unary = (Unary) right;
2346 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2347 oper = Operator.Subtraction;
2348 right = right_unary.Expr;
2354 if (oper == Operator.Equality || oper == Operator.Inequality){
2355 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2356 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2357 Error_OperatorCannotBeApplied ();
2361 type = TypeManager.bool_type;
2366 // operator != (object a, object b)
2367 // operator == (object a, object b)
2369 // For this to be used, both arguments have to be reference-types.
2370 // Read the rationale on the spec (14.9.6)
2372 // Also, if at compile time we know that the classes do not inherit
2373 // one from the other, then we catch the error there.
2375 if (!(l.IsValueType || r.IsValueType)){
2376 type = TypeManager.bool_type;
2381 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2385 // Also, a standard conversion must exist from either one
2387 if (!(Convert.ImplicitStandardConversionExists (ec, left, r) ||
2388 Convert.ImplicitStandardConversionExists (ec, right, l))){
2389 Error_OperatorCannotBeApplied ();
2393 // We are going to have to convert to an object to compare
2395 if (l != TypeManager.object_type)
2396 left = new EmptyCast (left, TypeManager.object_type);
2397 if (r != TypeManager.object_type)
2398 right = new EmptyCast (right, TypeManager.object_type);
2401 // FIXME: CSC here catches errors cs254 and cs252
2407 // One of them is a valuetype, but the other one is not.
2409 if (!l.IsValueType || !r.IsValueType) {
2410 Error_OperatorCannotBeApplied ();
2415 // Only perform numeric promotions on:
2416 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2418 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2419 if (l.IsSubclassOf (TypeManager.delegate_type)){
2420 if (((right.eclass == ExprClass.MethodGroup) ||
2421 (r == TypeManager.anonymous_method_type))){
2422 if ((RootContext.Version != LanguageVersion.ISO_1)){
2423 Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2431 if (r.IsSubclassOf (TypeManager.delegate_type)){
2433 ArrayList args = new ArrayList (2);
2435 args = new ArrayList (2);
2436 args.Add (new Argument (left, Argument.AType.Expression));
2437 args.Add (new Argument (right, Argument.AType.Expression));
2439 if (oper == Operator.Addition)
2440 method = TypeManager.delegate_combine_delegate_delegate;
2442 method = TypeManager.delegate_remove_delegate_delegate;
2445 Error_OperatorCannotBeApplied ();
2449 return new BinaryDelegate (l, method, args);
2454 // Pointer arithmetic:
2456 // T* operator + (T* x, int y);
2457 // T* operator + (T* x, uint y);
2458 // T* operator + (T* x, long y);
2459 // T* operator + (T* x, ulong y);
2461 // T* operator + (int y, T* x);
2462 // T* operator + (uint y, T *x);
2463 // T* operator + (long y, T *x);
2464 // T* operator + (ulong y, T *x);
2466 // T* operator - (T* x, int y);
2467 // T* operator - (T* x, uint y);
2468 // T* operator - (T* x, long y);
2469 // T* operator - (T* x, ulong y);
2471 // long operator - (T* x, T *y)
2474 if (r.IsPointer && oper == Operator.Subtraction){
2476 return new PointerArithmetic (
2477 false, left, right, TypeManager.int64_type,
2480 Expression t = Make32or64 (ec, right);
2482 return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc).Resolve (ec);
2484 } else if (r.IsPointer && oper == Operator.Addition){
2485 Expression t = Make32or64 (ec, left);
2487 return new PointerArithmetic (true, right, t, r, loc).Resolve (ec);
2492 // Enumeration operators
2494 bool lie = TypeManager.IsEnumType (l);
2495 bool rie = TypeManager.IsEnumType (r);
2499 // U operator - (E e, E f)
2501 if (oper == Operator.Subtraction){
2503 type = TypeManager.EnumToUnderlying (l);
2506 Error_OperatorCannotBeApplied ();
2512 // operator + (E e, U x)
2513 // operator - (E e, U x)
2515 if (oper == Operator.Addition || oper == Operator.Subtraction){
2516 Type enum_type = lie ? l : r;
2517 Type other_type = lie ? r : l;
2518 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2520 if (underlying_type != other_type){
2521 temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
2531 Error_OperatorCannotBeApplied ();
2540 temp = Convert.ImplicitConversion (ec, right, l, loc);
2544 Error_OperatorCannotBeApplied ();
2548 temp = Convert.ImplicitConversion (ec, left, r, loc);
2553 Error_OperatorCannotBeApplied ();
2558 if (oper == Operator.Equality || oper == Operator.Inequality ||
2559 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2560 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2561 if (left.Type != right.Type){
2562 Error_OperatorCannotBeApplied ();
2565 type = TypeManager.bool_type;
2569 if (oper == Operator.BitwiseAnd ||
2570 oper == Operator.BitwiseOr ||
2571 oper == Operator.ExclusiveOr){
2575 Error_OperatorCannotBeApplied ();
2579 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2580 return CheckShiftArguments (ec);
2582 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2583 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2584 type = TypeManager.bool_type;
2589 Error_OperatorCannotBeApplied ();
2593 Expression e = new ConditionalLogicalOperator (
2594 oper == Operator.LogicalAnd, left, right, l, loc);
2595 return e.Resolve (ec);
2599 // operator & (bool x, bool y)
2600 // operator | (bool x, bool y)
2601 // operator ^ (bool x, bool y)
2603 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2604 if (oper == Operator.BitwiseAnd ||
2605 oper == Operator.BitwiseOr ||
2606 oper == Operator.ExclusiveOr){
2613 // Pointer comparison
2615 if (l.IsPointer && r.IsPointer){
2616 if (oper == Operator.Equality || oper == Operator.Inequality ||
2617 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2618 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2619 type = TypeManager.bool_type;
2625 // This will leave left or right set to null if there is an error
2627 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2628 DoNumericPromotions (ec, l, r, check_user_conv);
2629 if (left == null || right == null){
2630 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2635 // reload our cached types if required
2640 if (oper == Operator.BitwiseAnd ||
2641 oper == Operator.BitwiseOr ||
2642 oper == Operator.ExclusiveOr){
2644 if (((l == TypeManager.int32_type) ||
2645 (l == TypeManager.uint32_type) ||
2646 (l == TypeManager.short_type) ||
2647 (l == TypeManager.ushort_type) ||
2648 (l == TypeManager.int64_type) ||
2649 (l == TypeManager.uint64_type))){
2652 Error_OperatorCannotBeApplied ();
2656 Error_OperatorCannotBeApplied ();
2661 if (oper == Operator.Equality ||
2662 oper == Operator.Inequality ||
2663 oper == Operator.LessThanOrEqual ||
2664 oper == Operator.LessThan ||
2665 oper == Operator.GreaterThanOrEqual ||
2666 oper == Operator.GreaterThan){
2667 type = TypeManager.bool_type;
2673 public override Expression DoResolve (EmitContext ec)
2675 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2676 left = ((ParenthesizedExpression) left).Expr;
2677 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2681 if (left.eclass == ExprClass.Type) {
2682 Error (75, "Casting a negative value needs to have the value in parentheses.");
2686 left = left.Resolve (ec);
2691 Constant lc = left as Constant;
2692 if (lc != null && lc.Type == TypeManager.bool_type &&
2693 ((oper == Operator.LogicalAnd && (bool)lc.GetValue () == false) ||
2694 (oper == Operator.LogicalOr && (bool)lc.GetValue () == true))) {
2696 // TODO: make a sence to resolve unreachable expression as we do for statement
2697 Report.Warning (429, 4, loc, "Unreachable expression code detected");
2701 right = right.Resolve (ec);
2705 eclass = ExprClass.Value;
2707 Constant rc = right as Constant;
2708 if (rc != null & lc != null){
2709 Expression e = ConstantFold.BinaryFold (
2710 ec, oper, lc, rc, loc);
2715 return ResolveOperator (ec);
2719 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2720 /// context of a conditional bool expression. This function will return
2721 /// false if it is was possible to use EmitBranchable, or true if it was.
2723 /// The expression's code is generated, and we will generate a branch to `target'
2724 /// if the resulting expression value is equal to isTrue
2726 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2728 ILGenerator ig = ec.ig;
2731 // This is more complicated than it looks, but its just to avoid
2732 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2733 // but on top of that we want for == and != to use a special path
2734 // if we are comparing against null
2736 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
2737 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2740 // put the constant on the rhs, for simplicity
2742 if (left is Constant) {
2743 Expression swap = right;
2748 if (((Constant) right).IsZeroInteger) {
2751 ig.Emit (OpCodes.Brtrue, target);
2753 ig.Emit (OpCodes.Brfalse, target);
2756 } else if (right is BoolConstant) {
2758 if (my_on_true != ((BoolConstant) right).Value)
2759 ig.Emit (OpCodes.Brtrue, target);
2761 ig.Emit (OpCodes.Brfalse, target);
2766 } else if (oper == Operator.LogicalAnd) {
2769 Label tests_end = ig.DefineLabel ();
2771 left.EmitBranchable (ec, tests_end, false);
2772 right.EmitBranchable (ec, target, true);
2773 ig.MarkLabel (tests_end);
2775 left.EmitBranchable (ec, target, false);
2776 right.EmitBranchable (ec, target, false);
2781 } else if (oper == Operator.LogicalOr){
2783 left.EmitBranchable (ec, target, true);
2784 right.EmitBranchable (ec, target, true);
2787 Label tests_end = ig.DefineLabel ();
2788 left.EmitBranchable (ec, tests_end, true);
2789 right.EmitBranchable (ec, target, false);
2790 ig.MarkLabel (tests_end);
2795 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2796 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2797 oper == Operator.Equality || oper == Operator.Inequality)) {
2798 base.EmitBranchable (ec, target, onTrue);
2806 bool isUnsigned = is_unsigned (t) || t == TypeManager.double_type || t == TypeManager.float_type;
2809 case Operator.Equality:
2811 ig.Emit (OpCodes.Beq, target);
2813 ig.Emit (OpCodes.Bne_Un, target);
2816 case Operator.Inequality:
2818 ig.Emit (OpCodes.Bne_Un, target);
2820 ig.Emit (OpCodes.Beq, target);
2823 case Operator.LessThan:
2826 ig.Emit (OpCodes.Blt_Un, target);
2828 ig.Emit (OpCodes.Blt, target);
2831 ig.Emit (OpCodes.Bge_Un, target);
2833 ig.Emit (OpCodes.Bge, target);
2836 case Operator.GreaterThan:
2839 ig.Emit (OpCodes.Bgt_Un, target);
2841 ig.Emit (OpCodes.Bgt, target);
2844 ig.Emit (OpCodes.Ble_Un, target);
2846 ig.Emit (OpCodes.Ble, target);
2849 case Operator.LessThanOrEqual:
2852 ig.Emit (OpCodes.Ble_Un, target);
2854 ig.Emit (OpCodes.Ble, target);
2857 ig.Emit (OpCodes.Bgt_Un, target);
2859 ig.Emit (OpCodes.Bgt, target);
2863 case Operator.GreaterThanOrEqual:
2866 ig.Emit (OpCodes.Bge_Un, target);
2868 ig.Emit (OpCodes.Bge, target);
2871 ig.Emit (OpCodes.Blt_Un, target);
2873 ig.Emit (OpCodes.Blt, target);
2876 Console.WriteLine (oper);
2877 throw new Exception ("what is THAT");
2881 public override void Emit (EmitContext ec)
2883 ILGenerator ig = ec.ig;
2888 // Handle short-circuit operators differently
2891 if (oper == Operator.LogicalAnd) {
2892 Label load_zero = ig.DefineLabel ();
2893 Label end = ig.DefineLabel ();
2895 left.EmitBranchable (ec, load_zero, false);
2897 ig.Emit (OpCodes.Br, end);
2899 ig.MarkLabel (load_zero);
2900 ig.Emit (OpCodes.Ldc_I4_0);
2903 } else if (oper == Operator.LogicalOr) {
2904 Label load_one = ig.DefineLabel ();
2905 Label end = ig.DefineLabel ();
2907 left.EmitBranchable (ec, load_one, true);
2909 ig.Emit (OpCodes.Br, end);
2911 ig.MarkLabel (load_one);
2912 ig.Emit (OpCodes.Ldc_I4_1);
2920 bool isUnsigned = is_unsigned (left.Type);
2923 case Operator.Multiply:
2925 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2926 opcode = OpCodes.Mul_Ovf;
2927 else if (isUnsigned)
2928 opcode = OpCodes.Mul_Ovf_Un;
2930 opcode = OpCodes.Mul;
2932 opcode = OpCodes.Mul;
2936 case Operator.Division:
2938 opcode = OpCodes.Div_Un;
2940 opcode = OpCodes.Div;
2943 case Operator.Modulus:
2945 opcode = OpCodes.Rem_Un;
2947 opcode = OpCodes.Rem;
2950 case Operator.Addition:
2952 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2953 opcode = OpCodes.Add_Ovf;
2954 else if (isUnsigned)
2955 opcode = OpCodes.Add_Ovf_Un;
2957 opcode = OpCodes.Add;
2959 opcode = OpCodes.Add;
2962 case Operator.Subtraction:
2964 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2965 opcode = OpCodes.Sub_Ovf;
2966 else if (isUnsigned)
2967 opcode = OpCodes.Sub_Ovf_Un;
2969 opcode = OpCodes.Sub;
2971 opcode = OpCodes.Sub;
2974 case Operator.RightShift:
2976 opcode = OpCodes.Shr_Un;
2978 opcode = OpCodes.Shr;
2981 case Operator.LeftShift:
2982 opcode = OpCodes.Shl;
2985 case Operator.Equality:
2986 opcode = OpCodes.Ceq;
2989 case Operator.Inequality:
2990 ig.Emit (OpCodes.Ceq);
2991 ig.Emit (OpCodes.Ldc_I4_0);
2993 opcode = OpCodes.Ceq;
2996 case Operator.LessThan:
2998 opcode = OpCodes.Clt_Un;
3000 opcode = OpCodes.Clt;
3003 case Operator.GreaterThan:
3005 opcode = OpCodes.Cgt_Un;
3007 opcode = OpCodes.Cgt;
3010 case Operator.LessThanOrEqual:
3011 Type lt = left.Type;
3013 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
3014 ig.Emit (OpCodes.Cgt_Un);
3016 ig.Emit (OpCodes.Cgt);
3017 ig.Emit (OpCodes.Ldc_I4_0);
3019 opcode = OpCodes.Ceq;
3022 case Operator.GreaterThanOrEqual:
3023 Type le = left.Type;
3025 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3026 ig.Emit (OpCodes.Clt_Un);
3028 ig.Emit (OpCodes.Clt);
3030 ig.Emit (OpCodes.Ldc_I4_0);
3032 opcode = OpCodes.Ceq;
3035 case Operator.BitwiseOr:
3036 opcode = OpCodes.Or;
3039 case Operator.BitwiseAnd:
3040 opcode = OpCodes.And;
3043 case Operator.ExclusiveOr:
3044 opcode = OpCodes.Xor;
3048 throw new Exception ("This should not happen: Operator = "
3049 + oper.ToString ());
3057 // Object created by Binary when the binary operator uses an method instead of being
3058 // a binary operation that maps to a CIL binary operation.
3060 public class BinaryMethod : Expression {
3061 public MethodBase method;
3062 public ArrayList Arguments;
3064 public BinaryMethod (Type t, MethodBase m, ArrayList args)
3069 eclass = ExprClass.Value;
3072 public override Expression DoResolve (EmitContext ec)
3077 public override void Emit (EmitContext ec)
3079 ILGenerator ig = ec.ig;
3081 if (Arguments != null)
3082 Invocation.EmitArguments (ec, method, Arguments, false, null);
3084 if (method is MethodInfo)
3085 ig.Emit (OpCodes.Call, (MethodInfo) method);
3087 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3092 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3093 // b, c, d... may be strings or objects.
3095 public class StringConcat : Expression {
3097 bool invalid = false;
3098 bool emit_conv_done = false;
3100 // Are we also concating objects?
3102 bool is_strings_only = true;
3104 public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
3107 type = TypeManager.string_type;
3108 eclass = ExprClass.Value;
3110 operands = new ArrayList (2);
3115 public override Expression DoResolve (EmitContext ec)
3123 public void Append (EmitContext ec, Expression operand)
3128 if (operand is StringConstant && operands.Count != 0) {
3129 StringConstant last_operand = operands [operands.Count - 1] as StringConstant;
3130 if (last_operand != null) {
3131 operands [operands.Count - 1] = new StringConstant (last_operand.Value + ((StringConstant) operand).Value);
3137 // Conversion to object
3139 if (operand.Type != TypeManager.string_type) {
3140 Expression no = Convert.ImplicitConversion (ec, operand, TypeManager.object_type, loc);
3143 Binary.Error_OperatorCannotBeApplied (loc, "+", TypeManager.string_type, operand.Type);
3149 operands.Add (operand);
3152 public override void Emit (EmitContext ec)
3154 MethodInfo concat_method = null;
3157 // Do conversion to arguments; check for strings only
3160 // This can get called multiple times, so we have to deal with that.
3161 if (!emit_conv_done) {
3162 emit_conv_done = true;
3163 for (int i = 0; i < operands.Count; i ++) {
3164 Expression e = (Expression) operands [i];
3165 is_strings_only &= e.Type == TypeManager.string_type;
3168 for (int i = 0; i < operands.Count; i ++) {
3169 Expression e = (Expression) operands [i];
3171 if (! is_strings_only && e.Type == TypeManager.string_type) {
3172 // need to make sure this is an object, because the EmitParams
3173 // method might look at the type of this expression, see it is a
3174 // string and emit a string [] when we want an object [];
3176 e = new EmptyCast (e, TypeManager.object_type);
3178 operands [i] = new Argument (e, Argument.AType.Expression);
3183 // Find the right method
3185 switch (operands.Count) {
3188 // This should not be possible, because simple constant folding
3189 // is taken care of in the Binary code.
3191 throw new Exception ("how did you get here?");
3194 concat_method = is_strings_only ?
3195 TypeManager.string_concat_string_string :
3196 TypeManager.string_concat_object_object ;
3199 concat_method = is_strings_only ?
3200 TypeManager.string_concat_string_string_string :
3201 TypeManager.string_concat_object_object_object ;
3205 // There is not a 4 param overlaod for object (the one that there is
3206 // is actually a varargs methods, and is only in corlib because it was
3207 // introduced there before.).
3209 if (!is_strings_only)
3212 concat_method = TypeManager.string_concat_string_string_string_string;
3215 concat_method = is_strings_only ?
3216 TypeManager.string_concat_string_dot_dot_dot :
3217 TypeManager.string_concat_object_dot_dot_dot ;
3221 Invocation.EmitArguments (ec, concat_method, operands, false, null);
3222 ec.ig.Emit (OpCodes.Call, concat_method);
3227 // Object created with +/= on delegates
3229 public class BinaryDelegate : Expression {
3233 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3238 eclass = ExprClass.Value;
3241 public override Expression DoResolve (EmitContext ec)
3246 public override void Emit (EmitContext ec)
3248 ILGenerator ig = ec.ig;
3250 Invocation.EmitArguments (ec, method, args, false, null);
3252 ig.Emit (OpCodes.Call, (MethodInfo) method);
3253 ig.Emit (OpCodes.Castclass, type);
3256 public Expression Right {
3258 Argument arg = (Argument) args [1];
3263 public bool IsAddition {
3265 return method == TypeManager.delegate_combine_delegate_delegate;
3271 // User-defined conditional logical operator
3272 public class ConditionalLogicalOperator : Expression {
3273 Expression left, right;
3276 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3279 eclass = ExprClass.Value;
3283 this.is_and = is_and;
3286 protected void Error19 ()
3288 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3291 protected void Error218 ()
3293 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3294 "declarations of operator true and operator false");
3297 Expression op_true, op_false, op;
3298 LocalTemporary left_temp;
3300 public override Expression DoResolve (EmitContext ec)
3303 Expression operator_group;
3305 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3306 if (operator_group == null) {
3311 left_temp = new LocalTemporary (ec, type);
3313 ArrayList arguments = new ArrayList ();
3314 arguments.Add (new Argument (left_temp, Argument.AType.Expression));
3315 arguments.Add (new Argument (right, Argument.AType.Expression));
3316 method = Invocation.OverloadResolve (
3317 ec, (MethodGroupExpr) operator_group, arguments, false, loc)
3319 if ((method == null) || (method.ReturnType != type)) {
3324 op = new StaticCallExpr (method, arguments, loc);
3326 op_true = GetOperatorTrue (ec, left_temp, loc);
3327 op_false = GetOperatorFalse (ec, left_temp, loc);
3328 if ((op_true == null) || (op_false == null)) {
3336 public override void Emit (EmitContext ec)
3338 ILGenerator ig = ec.ig;
3339 Label false_target = ig.DefineLabel ();
3340 Label end_target = ig.DefineLabel ();
3343 left_temp.Store (ec);
3345 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
3346 left_temp.Emit (ec);
3347 ig.Emit (OpCodes.Br, end_target);
3348 ig.MarkLabel (false_target);
3350 ig.MarkLabel (end_target);
3354 public class PointerArithmetic : Expression {
3355 Expression left, right;
3359 // We assume that `l' is always a pointer
3361 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3367 is_add = is_addition;
3370 public override Expression DoResolve (EmitContext ec)
3372 eclass = ExprClass.Variable;
3374 if (left.Type == TypeManager.void_ptr_type) {
3375 Error (242, "The operation in question is undefined on void pointers");
3382 public override void Emit (EmitContext ec)
3384 Type op_type = left.Type;
3385 ILGenerator ig = ec.ig;
3386 Type element = TypeManager.GetElementType (op_type);
3387 int size = GetTypeSize (element);
3388 Type rtype = right.Type;
3390 if (rtype.IsPointer){
3392 // handle (pointer - pointer)
3396 ig.Emit (OpCodes.Sub);
3400 ig.Emit (OpCodes.Sizeof, element);
3402 IntLiteral.EmitInt (ig, size);
3403 ig.Emit (OpCodes.Div);
3405 ig.Emit (OpCodes.Conv_I8);
3408 // handle + and - on (pointer op int)
3411 ig.Emit (OpCodes.Conv_I);
3415 ig.Emit (OpCodes.Sizeof, element);
3417 IntLiteral.EmitInt (ig, size);
3418 if (rtype == TypeManager.int64_type)
3419 ig.Emit (OpCodes.Conv_I8);
3420 else if (rtype == TypeManager.uint64_type)
3421 ig.Emit (OpCodes.Conv_U8);
3422 ig.Emit (OpCodes.Mul);
3425 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
3426 ig.Emit (OpCodes.Conv_I);
3429 ig.Emit (OpCodes.Add);
3431 ig.Emit (OpCodes.Sub);
3437 /// Implements the ternary conditional operator (?:)
3439 public class Conditional : Expression {
3440 Expression expr, trueExpr, falseExpr;
3442 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3445 this.trueExpr = trueExpr;
3446 this.falseExpr = falseExpr;
3450 public Expression Expr {
3456 public Expression TrueExpr {
3462 public Expression FalseExpr {
3468 public override Expression DoResolve (EmitContext ec)
3470 expr = expr.Resolve (ec);
3475 if (expr.Type != TypeManager.bool_type){
3476 expr = Expression.ResolveBoolean (
3483 trueExpr = trueExpr.Resolve (ec);
3484 falseExpr = falseExpr.Resolve (ec);
3486 if (trueExpr == null || falseExpr == null)
3489 eclass = ExprClass.Value;
3490 if (trueExpr.Type == falseExpr.Type)
3491 type = trueExpr.Type;
3494 Type true_type = trueExpr.Type;
3495 Type false_type = falseExpr.Type;
3498 // First, if an implicit conversion exists from trueExpr
3499 // to falseExpr, then the result type is of type falseExpr.Type
3501 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3504 // Check if both can convert implicitl to each other's type
3506 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3508 "Can not compute type of conditional expression " +
3509 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3510 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3511 "' convert implicitly to each other");
3516 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3520 Error (173, "The type of the conditional expression can " +
3521 "not be computed because there is no implicit conversion" +
3522 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3523 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3528 if (expr is BoolConstant){
3529 BoolConstant bc = (BoolConstant) expr;
3540 public override void Emit (EmitContext ec)
3542 ILGenerator ig = ec.ig;
3543 Label false_target = ig.DefineLabel ();
3544 Label end_target = ig.DefineLabel ();
3546 expr.EmitBranchable (ec, false_target, false);
3548 ig.Emit (OpCodes.Br, end_target);
3549 ig.MarkLabel (false_target);
3550 falseExpr.Emit (ec);
3551 ig.MarkLabel (end_target);
3559 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3560 public readonly string Name;
3561 public readonly Block Block;
3562 public LocalInfo local_info;
3565 LocalTemporary temp;
3567 public LocalVariableReference (Block block, string name, Location l)
3572 eclass = ExprClass.Variable;
3576 // Setting `is_readonly' to false will allow you to create a writable
3577 // reference to a read-only variable. This is used by foreach and using.
3579 public LocalVariableReference (Block block, string name, Location l,
3580 LocalInfo local_info, bool is_readonly)
3581 : this (block, name, l)
3583 this.local_info = local_info;
3584 this.is_readonly = is_readonly;
3587 public VariableInfo VariableInfo {
3589 return local_info.VariableInfo;
3593 public bool IsReadOnly {
3599 protected Expression DoResolveBase (EmitContext ec, Expression lvalue_right_side)
3601 if (local_info == null) {
3602 local_info = Block.GetLocalInfo (Name);
3605 if (lvalue_right_side == EmptyExpression.Null)
3606 local_info.Used = true;
3608 is_readonly = local_info.ReadOnly;
3611 type = local_info.VariableType;
3613 VariableInfo variable_info = local_info.VariableInfo;
3614 if (lvalue_right_side != null){
3616 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3620 if (variable_info != null)
3621 variable_info.SetAssigned (ec);
3624 Expression e = Block.GetConstantExpression (Name);
3626 local_info.Used = true;
3627 eclass = ExprClass.Value;
3628 return e.Resolve (ec);
3631 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3634 if (lvalue_right_side == null)
3635 local_info.Used = true;
3637 if (ec.CurrentAnonymousMethod != null){
3639 // If we are referencing a variable from the external block
3640 // flag it for capturing
3642 if (local_info.Block.Toplevel != ec.CurrentBlock.Toplevel){
3643 if (local_info.AddressTaken){
3644 AnonymousMethod.Error_AddressOfCapturedVar (local_info.Name, loc);
3647 ec.CaptureVariable (local_info);
3654 public override Expression DoResolve (EmitContext ec)
3656 return DoResolveBase (ec, null);
3659 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3661 Expression ret = DoResolveBase (ec, right_side);
3663 CheckObsoleteAttribute (ret.Type);
3668 public bool VerifyFixed (bool is_expression)
3670 return !is_expression || local_info.IsFixed;
3673 public override void Emit (EmitContext ec)
3675 ILGenerator ig = ec.ig;
3677 if (local_info.FieldBuilder == null){
3679 // A local variable on the local CLR stack
3681 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3684 // A local variable captured by anonymous methods.
3687 ec.EmitCapturedVariableInstance (local_info);
3689 ig.Emit (OpCodes.Ldfld, local_info.FieldBuilder);
3693 public void Emit (EmitContext ec, bool leave_copy)
3697 ec.ig.Emit (OpCodes.Dup);
3698 if (local_info.FieldBuilder != null){
3699 temp = new LocalTemporary (ec, Type);
3705 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3707 ILGenerator ig = ec.ig;
3708 prepared = prepare_for_load;
3710 if (local_info.FieldBuilder == null){
3712 // A local variable on the local CLR stack
3714 if (local_info.LocalBuilder == null)
3715 throw new Exception ("This should not happen: both Field and Local are null");
3719 ec.ig.Emit (OpCodes.Dup);
3720 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3723 // A local variable captured by anonymous methods or itereators.
3725 ec.EmitCapturedVariableInstance (local_info);
3727 if (prepare_for_load)
3728 ig.Emit (OpCodes.Dup);
3731 ig.Emit (OpCodes.Dup);
3732 temp = new LocalTemporary (ec, Type);
3735 ig.Emit (OpCodes.Stfld, local_info.FieldBuilder);
3741 public void AddressOf (EmitContext ec, AddressOp mode)
3743 ILGenerator ig = ec.ig;
3745 if (local_info.FieldBuilder == null){
3747 // A local variable on the local CLR stack
3749 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3752 // A local variable captured by anonymous methods or iterators
3754 ec.EmitCapturedVariableInstance (local_info);
3755 ig.Emit (OpCodes.Ldflda, local_info.FieldBuilder);
3759 public override string ToString ()
3761 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3766 /// This represents a reference to a parameter in the intermediate
3769 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3775 public Parameter.Modifier mod;
3776 public bool is_ref, is_out, prepared;
3790 LocalTemporary temp;
3792 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3799 eclass = ExprClass.Variable;
3802 public VariableInfo VariableInfo {
3806 public bool VerifyFixed (bool is_expression)
3808 return !is_expression || TypeManager.IsValueType (type);
3811 public bool IsAssigned (EmitContext ec, Location loc)
3813 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsAssigned (vi))
3816 Report.Error (165, loc,
3817 "Use of unassigned parameter `" + name + "'");
3821 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3823 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3826 Report.Error (170, loc,
3827 "Use of possibly unassigned field `" + field_name + "'");
3831 public void SetAssigned (EmitContext ec)
3833 if (is_out && ec.DoFlowAnalysis)
3834 ec.CurrentBranching.SetAssigned (vi);
3837 public void SetFieldAssigned (EmitContext ec, string field_name)
3839 if (is_out && ec.DoFlowAnalysis)
3840 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3843 protected void DoResolveBase (EmitContext ec)
3845 type = pars.GetParameterInfo (ec, idx, out mod);
3846 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3847 is_out = (mod & Parameter.Modifier.OUT) != 0;
3848 eclass = ExprClass.Variable;
3851 vi = block.ParameterMap [idx];
3853 if (ec.CurrentAnonymousMethod != null){
3855 Report.Error (1628, Location,
3856 "Can not reference a ref or out parameter in an anonymous method");
3861 // If we are referencing the parameter from the external block
3862 // flag it for capturing
3864 //Console.WriteLine ("Is parameter `{0}' local? {1}", name, block.IsLocalParameter (name));
3865 if (!block.IsLocalParameter (name)){
3866 ec.CaptureParameter (name, type, idx);
3872 // Notice that for ref/out parameters, the type exposed is not the
3873 // same type exposed externally.
3876 // externally we expose "int&"
3877 // here we expose "int".
3879 // We record this in "is_ref". This means that the type system can treat
3880 // the type as it is expected, but when we generate the code, we generate
3881 // the alternate kind of code.
3883 public override Expression DoResolve (EmitContext ec)
3887 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3890 if (ec.RemapToProxy)
3891 return ec.RemapParameter (idx);
3896 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3902 if (ec.RemapToProxy)
3903 return ec.RemapParameterLValue (idx, right_side);
3908 static public void EmitLdArg (ILGenerator ig, int x)
3912 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3913 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3914 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3915 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3916 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3919 ig.Emit (OpCodes.Ldarg, x);
3923 // This method is used by parameters that are references, that are
3924 // being passed as references: we only want to pass the pointer (that
3925 // is already stored in the parameter, not the address of the pointer,
3926 // and not the value of the variable).
3928 public void EmitLoad (EmitContext ec)
3930 ILGenerator ig = ec.ig;
3936 EmitLdArg (ig, arg_idx);
3939 // FIXME: Review for anonymous methods
3943 public override void Emit (EmitContext ec)
3945 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
3946 ec.EmitParameter (name);
3953 public void Emit (EmitContext ec, bool leave_copy)
3955 ILGenerator ig = ec.ig;
3961 EmitLdArg (ig, arg_idx);
3965 ec.ig.Emit (OpCodes.Dup);
3968 // If we are a reference, we loaded on the stack a pointer
3969 // Now lets load the real value
3971 LoadFromPtr (ig, type);
3975 ec.ig.Emit (OpCodes.Dup);
3978 temp = new LocalTemporary (ec, type);
3984 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3986 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
3987 ec.EmitAssignParameter (name, source, leave_copy, prepare_for_load);
3991 ILGenerator ig = ec.ig;
3994 prepared = prepare_for_load;
3999 if (is_ref && !prepared)
4000 EmitLdArg (ig, arg_idx);
4005 ec.ig.Emit (OpCodes.Dup);
4009 temp = new LocalTemporary (ec, type);
4013 StoreFromPtr (ig, type);
4019 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
4021 ig.Emit (OpCodes.Starg, arg_idx);
4025 public void AddressOf (EmitContext ec, AddressOp mode)
4027 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4028 ec.EmitAddressOfParameter (name);
4039 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
4041 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
4044 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
4046 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
4053 /// Used for arguments to New(), Invocation()
4055 public class Argument {
4056 public enum AType : byte {
4063 public readonly AType ArgType;
4064 public Expression Expr;
4066 public Argument (Expression expr, AType type)
4069 this.ArgType = type;
4072 public Argument (Expression expr)
4075 this.ArgType = AType.Expression;
4080 if (ArgType == AType.Ref || ArgType == AType.Out)
4081 return TypeManager.GetReferenceType (Expr.Type);
4087 public Parameter.Modifier GetParameterModifier ()
4091 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
4094 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
4097 return Parameter.Modifier.NONE;
4101 public static string FullDesc (Argument a)
4103 if (a.ArgType == AType.ArgList)
4106 return (a.ArgType == AType.Ref ? "ref " :
4107 (a.ArgType == AType.Out ? "out " : "")) +
4108 TypeManager.CSharpName (a.Expr.Type);
4111 public bool ResolveMethodGroup (EmitContext ec, Location loc)
4113 // FIXME: csc doesn't report any error if you try to use `ref' or
4114 // `out' in a delegate creation expression.
4115 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4122 public bool Resolve (EmitContext ec, Location loc)
4124 if (ArgType == AType.Ref) {
4125 Expr = Expr.Resolve (ec);
4129 if (!ec.IsConstructor) {
4130 FieldExpr fe = Expr as FieldExpr;
4131 if (fe != null && fe.FieldInfo.IsInitOnly) {
4132 if (fe.FieldInfo.IsStatic)
4133 Report.Error (199, loc, "A static readonly field cannot be passed ref or out (except in a static constructor)");
4135 Report.Error (192, loc, "A readonly field cannot be passed ref or out (except in a constructor)");
4139 Expr = Expr.ResolveLValue (ec, Expr);
4140 } else if (ArgType == AType.Out)
4141 Expr = Expr.ResolveLValue (ec, EmptyExpression.Null);
4143 Expr = Expr.Resolve (ec);
4148 if (ArgType == AType.Expression)
4152 // Catch errors where fields of a MarshalByRefObject are passed as ref or out
4153 // This is only allowed for `this'
4155 FieldExpr fe = Expr as FieldExpr;
4156 if (fe != null && !fe.IsStatic){
4157 Expression instance = fe.InstanceExpression;
4159 if (instance.GetType () != typeof (This)){
4160 if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
4161 Report.SymbolRelatedToPreviousError (fe.InstanceExpression.Type);
4162 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",
4170 if (Expr.eclass != ExprClass.Variable){
4172 // We just probe to match the CSC output
4174 if (Expr.eclass == ExprClass.PropertyAccess ||
4175 Expr.eclass == ExprClass.IndexerAccess){
4178 "A property or indexer can not be passed as an out or ref " +
4183 "An lvalue is required as an argument to out or ref");
4191 public void Emit (EmitContext ec)
4194 // Ref and Out parameters need to have their addresses taken.
4196 // ParameterReferences might already be references, so we want
4197 // to pass just the value
4199 if (ArgType == AType.Ref || ArgType == AType.Out){
4200 AddressOp mode = AddressOp.Store;
4202 if (ArgType == AType.Ref)
4203 mode |= AddressOp.Load;
4205 if (Expr is ParameterReference){
4206 ParameterReference pr = (ParameterReference) Expr;
4212 pr.AddressOf (ec, mode);
4215 ((IMemoryLocation)Expr).AddressOf (ec, mode);
4223 /// Invocation of methods or delegates.
4225 public class Invocation : ExpressionStatement {
4226 public readonly ArrayList Arguments;
4229 MethodBase method = null;
4231 static Hashtable method_parameter_cache;
4233 static Invocation ()
4235 method_parameter_cache = new PtrHashtable ();
4239 // arguments is an ArrayList, but we do not want to typecast,
4240 // as it might be null.
4242 // FIXME: only allow expr to be a method invocation or a
4243 // delegate invocation (7.5.5)
4245 public Invocation (Expression expr, ArrayList arguments, Location l)
4248 Arguments = arguments;
4252 public Expression Expr {
4259 /// Returns the Parameters (a ParameterData interface) for the
4262 public static ParameterData GetParameterData (MethodBase mb)
4264 object pd = method_parameter_cache [mb];
4268 return (ParameterData) pd;
4271 ip = TypeManager.LookupParametersByBuilder (mb);
4273 method_parameter_cache [mb] = ip;
4275 return (ParameterData) ip;
4277 ReflectionParameters rp = new ReflectionParameters (mb);
4278 method_parameter_cache [mb] = rp;
4280 return (ParameterData) rp;
4285 /// Determines "better conversion" as specified in 7.4.2.3
4287 /// Returns : p if a->p is better,
4288 /// q if a->q is better,
4289 /// null if neither is better
4291 static Type BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
4293 Type argument_type = a.Type;
4294 Expression argument_expr = a.Expr;
4296 if (argument_type == null)
4297 throw new Exception ("Expression of type " + a.Expr +
4298 " does not resolve its type");
4300 if (p == null || q == null)
4301 throw new InternalErrorException ("BetterConversion Got a null conversion");
4306 if (argument_expr is NullLiteral) {
4308 // If the argument is null and one of the types to compare is 'object' and
4309 // the other is a reference type, we prefer the other.
4311 // This follows from the usual rules:
4312 // * There is an implicit conversion from 'null' to type 'object'
4313 // * There is an implicit conversion from 'null' to any reference type
4314 // * There is an implicit conversion from any reference type to type 'object'
4315 // * There is no implicit conversion from type 'object' to other reference types
4316 // => Conversion of 'null' to a reference type is better than conversion to 'object'
4318 // FIXME: This probably isn't necessary, since the type of a NullLiteral is the
4319 // null type. I think it used to be 'object' and thus needed a special
4320 // case to avoid the immediately following two checks.
4322 if (!p.IsValueType && q == TypeManager.object_type)
4324 if (!q.IsValueType && p == TypeManager.object_type)
4328 if (argument_type == p)
4331 if (argument_type == q)
4334 Expression p_tmp = new EmptyExpression (p);
4335 Expression q_tmp = new EmptyExpression (q);
4337 bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
4338 bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
4340 if (p_to_q && !q_to_p)
4343 if (q_to_p && !p_to_q)
4346 if (p == TypeManager.sbyte_type)
4347 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4348 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4350 if (q == TypeManager.sbyte_type)
4351 if (p == TypeManager.byte_type || p == TypeManager.ushort_type ||
4352 p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4355 if (p == TypeManager.short_type)
4356 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4357 q == TypeManager.uint64_type)
4359 if (q == TypeManager.short_type)
4360 if (p == TypeManager.ushort_type || p == TypeManager.uint32_type ||
4361 p == TypeManager.uint64_type)
4364 if (p == TypeManager.int32_type)
4365 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4367 if (q == TypeManager.int32_type)
4368 if (p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4371 if (p == TypeManager.int64_type)
4372 if (q == TypeManager.uint64_type)
4374 if (q == TypeManager.int64_type)
4375 if (p == TypeManager.uint64_type)
4382 /// Determines "Better function" between candidate
4383 /// and the current best match
4386 /// Returns an integer indicating :
4387 /// false if candidate ain't better
4388 /// true if candidate is better than the current best match
4390 static bool BetterFunction (EmitContext ec, ArrayList args, int argument_count,
4391 MethodBase candidate, bool candidate_params,
4392 MethodBase best, bool best_params, Location loc)
4394 ParameterData candidate_pd = GetParameterData (candidate);
4395 ParameterData best_pd = GetParameterData (best);
4397 int cand_count = candidate_pd.Count;
4400 // If there is no best method, than this one
4401 // is better, however, if we already found a
4402 // best method, we cant tell. This happens
4413 // interface IFooBar : IFoo, IBar {}
4415 // We cant tell if IFoo.DoIt is better than IBar.DoIt
4417 // However, we have to consider that
4418 // Trim (); is better than Trim (params char[] chars);
4420 if (cand_count == 0 && argument_count == 0)
4421 return !candidate_params && best_params;
4423 if ((candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS) &&
4424 (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.ARGLIST))
4425 if (cand_count != argument_count)
4428 bool better_at_least_one = false;
4429 for (int j = 0; j < argument_count; ++j) {
4430 Argument a = (Argument) args [j];
4432 Type ct = TypeManager.TypeToCoreType (candidate_pd.ParameterType (j));
4433 Type bt = TypeManager.TypeToCoreType (best_pd.ParameterType (j));
4435 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4436 if (candidate_params)
4437 ct = TypeManager.GetElementType (ct);
4439 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4441 bt = TypeManager.GetElementType (bt);
4443 Type better = BetterConversion (ec, a, ct, bt, loc);
4445 // for each argument, the conversion to 'ct' should be no worse than
4446 // the conversion to 'bt'.
4450 // for at least one argument, the conversion to 'ct' should be better than
4451 // the conversion to 'bt'.
4453 better_at_least_one = true;
4457 // If a method (in the normal form) with the
4458 // same signature as the expanded form of the
4459 // current best params method already exists,
4460 // the expanded form is not applicable so we
4461 // force it to select the candidate
4463 if (!candidate_params && best_params && cand_count == argument_count)
4466 return better_at_least_one;
4469 public static string FullMethodDesc (MethodBase mb)
4471 string ret_type = "";
4476 if (mb is MethodInfo)
4477 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
4479 StringBuilder sb = new StringBuilder (ret_type);
4481 sb.Append (mb.ReflectedType.ToString ());
4483 sb.Append (mb.Name);
4485 ParameterData pd = GetParameterData (mb);
4487 int count = pd.Count;
4490 for (int i = count; i > 0; ) {
4493 sb.Append (pd.ParameterDesc (count - i - 1));
4499 return sb.ToString ();
4502 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4504 MemberInfo [] miset;
4505 MethodGroupExpr union;
4510 return (MethodGroupExpr) mg2;
4513 return (MethodGroupExpr) mg1;
4516 MethodGroupExpr left_set = null, right_set = null;
4517 int length1 = 0, length2 = 0;
4519 left_set = (MethodGroupExpr) mg1;
4520 length1 = left_set.Methods.Length;
4522 right_set = (MethodGroupExpr) mg2;
4523 length2 = right_set.Methods.Length;
4525 ArrayList common = new ArrayList ();
4527 foreach (MethodBase r in right_set.Methods){
4528 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
4532 miset = new MemberInfo [length1 + length2 - common.Count];
4533 left_set.Methods.CopyTo (miset, 0);
4537 foreach (MethodBase r in right_set.Methods) {
4538 if (!common.Contains (r))
4542 union = new MethodGroupExpr (miset, loc);
4547 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4548 ArrayList arguments, int arg_count,
4549 ref MethodBase candidate)
4551 return IsParamsMethodApplicable (
4552 ec, me, arguments, arg_count, false, ref candidate) ||
4553 IsParamsMethodApplicable (
4554 ec, me, arguments, arg_count, true, ref candidate);
4559 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4560 ArrayList arguments, int arg_count,
4561 bool do_varargs, ref MethodBase candidate)
4563 return IsParamsMethodApplicable (
4564 ec, arguments, arg_count, candidate, do_varargs);
4568 /// Determines if the candidate method, if a params method, is applicable
4569 /// in its expanded form to the given set of arguments
4571 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
4572 int arg_count, MethodBase candidate,
4575 ParameterData pd = GetParameterData (candidate);
4577 int pd_count = pd.Count;
4581 int count = pd_count - 1;
4583 if (pd.ParameterModifier (count) != Parameter.Modifier.ARGLIST)
4585 if (pd_count != arg_count)
4588 if (pd.ParameterModifier (count) != Parameter.Modifier.PARAMS)
4592 if (count > arg_count)
4595 if (pd_count == 1 && arg_count == 0)
4599 // If we have come this far, the case which
4600 // remains is when the number of parameters is
4601 // less than or equal to the argument count.
4603 for (int i = 0; i < count; ++i) {
4605 Argument a = (Argument) arguments [i];
4607 Parameter.Modifier a_mod = a.GetParameterModifier () &
4608 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4609 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4610 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4612 if (a_mod == p_mod) {
4614 if (a_mod == Parameter.Modifier.NONE)
4615 if (!Convert.ImplicitConversionExists (ec,
4617 pd.ParameterType (i)))
4620 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4621 Type pt = pd.ParameterType (i);
4624 pt = TypeManager.GetReferenceType (pt);
4635 Argument a = (Argument) arguments [count];
4636 if (!(a.Expr is Arglist))
4642 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4644 for (int i = pd_count - 1; i < arg_count; i++) {
4645 Argument a = (Argument) arguments [i];
4647 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4654 static bool IsApplicable (EmitContext ec, MethodGroupExpr me,
4655 ArrayList arguments, int arg_count,
4656 ref MethodBase candidate)
4658 return IsApplicable (ec, arguments, arg_count, candidate);
4662 /// Determines if the candidate method is applicable (section 14.4.2.1)
4663 /// to the given set of arguments
4665 static bool IsApplicable (EmitContext ec, ArrayList arguments, int arg_count,
4666 MethodBase candidate)
4668 ParameterData pd = GetParameterData (candidate);
4670 if (arg_count != pd.Count)
4673 for (int i = arg_count; i > 0; ) {
4676 Argument a = (Argument) arguments [i];
4678 Parameter.Modifier a_mod = a.GetParameterModifier () &
4679 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4680 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4681 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4684 if (a_mod == p_mod ||
4685 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4686 if (a_mod == Parameter.Modifier.NONE) {
4687 if (!Convert.ImplicitConversionExists (ec,
4689 pd.ParameterType (i)))
4693 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4694 Type pt = pd.ParameterType (i);
4697 pt = TypeManager.GetReferenceType (pt);
4709 static private bool IsAncestralType (Type first_type, Type second_type)
4711 return first_type != second_type &&
4712 (second_type.IsSubclassOf (first_type) ||
4713 TypeManager.ImplementsInterface (second_type, first_type));
4717 /// Find the Applicable Function Members (7.4.2.1)
4719 /// me: Method Group expression with the members to select.
4720 /// it might contain constructors or methods (or anything
4721 /// that maps to a method).
4723 /// Arguments: ArrayList containing resolved Argument objects.
4725 /// loc: The location if we want an error to be reported, or a Null
4726 /// location for "probing" purposes.
4728 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4729 /// that is the best match of me on Arguments.
4732 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4733 ArrayList Arguments, bool may_fail,
4736 MethodBase method = null;
4737 bool method_params = false;
4738 Type applicable_type = null;
4740 ArrayList candidates = new ArrayList ();
4743 // Used to keep a map between the candidate
4744 // and whether it is being considered in its
4745 // normal or expanded form
4747 // false is normal form, true is expanded form
4749 Hashtable candidate_to_form = null;
4751 if (Arguments != null)
4752 arg_count = Arguments.Count;
4754 if ((me.Name == "Invoke") &&
4755 TypeManager.IsDelegateType (me.DeclaringType)) {
4756 Error_InvokeOnDelegate (loc);
4760 MethodBase[] methods = me.Methods;
4763 // First we construct the set of applicable methods
4765 bool is_sorted = true;
4766 for (int i = 0; i < methods.Length; i++){
4767 Type decl_type = methods [i].DeclaringType;
4770 // If we have already found an applicable method
4771 // we eliminate all base types (Section 14.5.5.1)
4773 if ((applicable_type != null) &&
4774 IsAncestralType (decl_type, applicable_type))
4778 // Check if candidate is applicable (section 14.4.2.1)
4779 // Is candidate applicable in normal form?
4781 bool is_applicable = IsApplicable (
4782 ec, me, Arguments, arg_count, ref methods [i]);
4784 if (!is_applicable &&
4785 (IsParamsMethodApplicable (
4786 ec, me, Arguments, arg_count, ref methods [i]))) {
4787 MethodBase candidate = methods [i];
4788 if (candidate_to_form == null)
4789 candidate_to_form = new PtrHashtable ();
4790 candidate_to_form [candidate] = candidate;
4791 // Candidate is applicable in expanded form
4792 is_applicable = true;
4798 candidates.Add (methods [i]);
4800 if (applicable_type == null)
4801 applicable_type = decl_type;
4802 else if (applicable_type != decl_type) {
4804 if (IsAncestralType (applicable_type, decl_type))
4805 applicable_type = decl_type;
4809 int candidate_top = candidates.Count;
4811 if (candidate_top == 0) {
4813 // Okay so we have failed to find anything so we
4814 // return by providing info about the closest match
4816 for (int i = 0; i < methods.Length; ++i) {
4817 MethodBase c = (MethodBase) methods [i];
4818 ParameterData pd = GetParameterData (c);
4820 if (pd.Count != arg_count)
4823 VerifyArgumentsCompat (ec, Arguments, arg_count,
4824 c, false, null, may_fail, loc);
4829 string report_name = me.Name;
4830 if (report_name == ".ctor")
4831 report_name = me.DeclaringType.ToString ();
4833 Error_WrongNumArguments (
4834 loc, report_name, arg_count);
4843 // At this point, applicable_type is _one_ of the most derived types
4844 // in the set of types containing the methods in this MethodGroup.
4845 // Filter the candidates so that they only contain methods from the
4846 // most derived types.
4849 int finalized = 0; // Number of finalized candidates
4852 // Invariant: applicable_type is a most derived type
4854 // We'll try to complete Section 14.5.5.1 for 'applicable_type' by
4855 // eliminating all it's base types. At the same time, we'll also move
4856 // every unrelated type to the end of the array, and pick the next
4857 // 'applicable_type'.
4859 Type next_applicable_type = null;
4860 int j = finalized; // where to put the next finalized candidate
4861 int k = finalized; // where to put the next undiscarded candidate
4862 for (int i = finalized; i < candidate_top; ++i) {
4863 Type decl_type = ((MethodBase) candidates[i]).DeclaringType;
4865 if (decl_type == applicable_type) {
4866 candidates[k++] = candidates[j];
4867 candidates[j++] = candidates[i];
4871 if (IsAncestralType (decl_type, applicable_type))
4874 if (next_applicable_type != null &&
4875 IsAncestralType (decl_type, next_applicable_type))
4878 candidates[k++] = candidates[i];
4880 if (next_applicable_type == null ||
4881 IsAncestralType (next_applicable_type, decl_type))
4882 next_applicable_type = decl_type;
4885 applicable_type = next_applicable_type;
4888 } while (applicable_type != null);
4892 // Now we actually find the best method
4895 method = (MethodBase) candidates[0];
4896 method_params = candidate_to_form != null && candidate_to_form.Contains (method);
4897 for (int ix = 1; ix < candidate_top; ix++){
4898 MethodBase candidate = (MethodBase) candidates [ix];
4899 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4901 if (BetterFunction (ec, Arguments, arg_count,
4902 candidate, cand_params,
4903 method, method_params, loc)) {
4905 method_params = cand_params;
4910 // Now check that there are no ambiguities i.e the selected method
4911 // should be better than all the others
4913 bool ambiguous = false;
4914 for (int ix = 0; ix < candidate_top; ix++){
4915 MethodBase candidate = (MethodBase) candidates [ix];
4917 if (candidate == method)
4920 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4921 if (!BetterFunction (ec, Arguments, arg_count,
4922 method, method_params,
4923 candidate, cand_params,
4925 Report.SymbolRelatedToPreviousError (candidate);
4931 Report.SymbolRelatedToPreviousError (method);
4932 Report.Error (121, loc, "Ambiguous call when selecting function due to implicit casts");
4938 // And now check if the arguments are all
4939 // compatible, perform conversions if
4940 // necessary etc. and return if everything is
4943 if (!VerifyArgumentsCompat (ec, Arguments, arg_count, method,
4944 method_params, null, may_fail, loc))
4950 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
4952 Report.Error (1501, loc,
4953 "No overload for method `" + name + "' takes `" +
4954 arg_count + "' arguments");
4957 static void Error_InvokeOnDelegate (Location loc)
4959 Report.Error (1533, loc,
4960 "Invoke cannot be called directly on a delegate");
4963 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
4964 Type delegate_type, string arg_sig, string par_desc)
4966 if (delegate_type == null)
4967 Report.Error (1502, loc,
4968 "The best overloaded match for method '" +
4969 FullMethodDesc (method) +
4970 "' has some invalid arguments");
4972 Report.Error (1594, loc,
4973 "Delegate '" + delegate_type.ToString () +
4974 "' has some invalid arguments.");
4975 Report.Error (1503, loc,
4976 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
4977 idx, arg_sig, par_desc));
4980 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
4981 int arg_count, MethodBase method,
4982 bool chose_params_expanded,
4983 Type delegate_type, bool may_fail,
4986 ParameterData pd = GetParameterData (method);
4987 int pd_count = pd.Count;
4989 for (int j = 0; j < arg_count; j++) {
4990 Argument a = (Argument) Arguments [j];
4991 Expression a_expr = a.Expr;
4992 Type parameter_type = pd.ParameterType (j);
4993 Parameter.Modifier pm = pd.ParameterModifier (j);
4995 if (pm == Parameter.Modifier.PARAMS){
4996 if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
4998 Error_InvalidArguments (
4999 loc, j, method, delegate_type,
5000 Argument.FullDesc (a), pd.ParameterDesc (j));
5004 if (chose_params_expanded)
5005 parameter_type = TypeManager.GetElementType (parameter_type);
5006 } else if (pm == Parameter.Modifier.ARGLIST){
5012 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
5014 Error_InvalidArguments (
5015 loc, j, method, delegate_type,
5016 Argument.FullDesc (a), pd.ParameterDesc (j));
5024 if (!a.Type.Equals (parameter_type)){
5027 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
5031 Error_InvalidArguments (
5032 loc, j, method, delegate_type,
5033 Argument.FullDesc (a), pd.ParameterDesc (j));
5038 // Update the argument with the implicit conversion
5044 if (parameter_type.IsPointer){
5051 Parameter.Modifier a_mod = a.GetParameterModifier () &
5052 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5053 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
5054 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5056 if (a_mod != p_mod &&
5057 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
5059 Report.Error (1502, loc,
5060 "The best overloaded match for method '" + FullMethodDesc (method)+
5061 "' has some invalid arguments");
5062 Report.Error (1503, loc,
5063 "Argument " + (j+1) +
5064 ": Cannot convert from '" + Argument.FullDesc (a)
5065 + "' to '" + pd.ParameterDesc (j) + "'");
5075 public override Expression DoResolve (EmitContext ec)
5078 // First, resolve the expression that is used to
5079 // trigger the invocation
5081 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
5085 if (!(expr is MethodGroupExpr)) {
5086 Type expr_type = expr.Type;
5088 if (expr_type != null){
5089 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
5091 return (new DelegateInvocation (
5092 this.expr, Arguments, loc)).Resolve (ec);
5096 if (!(expr is MethodGroupExpr)){
5097 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup, loc);
5102 // Next, evaluate all the expressions in the argument list
5104 if (Arguments != null){
5105 foreach (Argument a in Arguments){
5106 if (!a.Resolve (ec, loc))
5111 MethodGroupExpr mg = (MethodGroupExpr) expr;
5112 method = OverloadResolve (ec, mg, Arguments, false, loc);
5117 MethodInfo mi = method as MethodInfo;
5119 type = TypeManager.TypeToCoreType (mi.ReturnType);
5120 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null)) {
5121 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
5125 Expression iexpr = mg.InstanceExpression;
5126 if (mi.IsStatic && (iexpr != null) && !(iexpr is This)) {
5127 if (mg.IdenticalTypeName)
5128 mg.InstanceExpression = null;
5130 MemberAccess.error176 (loc, mi.Name);
5136 if (type.IsPointer){
5144 // Only base will allow this invocation to happen.
5146 if (mg.IsBase && method.IsAbstract){
5147 Report.Error (205, loc, "Cannot call an abstract base member: " +
5148 FullMethodDesc (method));
5152 if (method.Name == "Finalize" && Arguments == null) {
5154 Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
5156 Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
5160 if ((method.Attributes & MethodAttributes.SpecialName) != 0) {
5161 if (TypeManager.LookupDeclSpace (method.DeclaringType) != null || TypeManager.IsSpecialMethod (method)) {
5162 Report.Error (571, loc, TypeManager.CSharpSignature (method) + ": can not call operator or accessor");
5167 if (mg.InstanceExpression != null)
5168 mg.InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
5170 eclass = ExprClass.Value;
5175 // Emits the list of arguments as an array
5177 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
5179 ILGenerator ig = ec.ig;
5180 int count = arguments.Count - idx;
5181 Argument a = (Argument) arguments [idx];
5182 Type t = a.Expr.Type;
5184 IntConstant.EmitInt (ig, count);
5185 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
5187 int top = arguments.Count;
5188 for (int j = idx; j < top; j++){
5189 a = (Argument) arguments [j];
5191 ig.Emit (OpCodes.Dup);
5192 IntConstant.EmitInt (ig, j - idx);
5195 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj);
5197 ig.Emit (OpCodes.Ldelema, t);
5202 ig.Emit (OpCodes.Stobj, t);
5209 /// Emits a list of resolved Arguments that are in the arguments
5212 /// The MethodBase argument might be null if the
5213 /// emission of the arguments is known not to contain
5214 /// a `params' field (for example in constructors or other routines
5215 /// that keep their arguments in this structure)
5217 /// if `dup_args' is true, a copy of the arguments will be left
5218 /// on the stack. If `dup_args' is true, you can specify `this_arg'
5219 /// which will be duplicated before any other args. Only EmitCall
5220 /// should be using this interface.
5222 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments, bool dup_args, LocalTemporary this_arg)
5226 pd = GetParameterData (mb);
5230 LocalTemporary [] temps = null;
5233 temps = new LocalTemporary [arguments.Count];
5236 // If we are calling a params method with no arguments, special case it
5238 if (arguments == null){
5239 if (pd != null && pd.Count > 0 &&
5240 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
5241 ILGenerator ig = ec.ig;
5243 IntConstant.EmitInt (ig, 0);
5244 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
5250 int top = arguments.Count;
5252 for (int i = 0; i < top; i++){
5253 Argument a = (Argument) arguments [i];
5256 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
5258 // Special case if we are passing the same data as the
5259 // params argument, do not put it in an array.
5261 if (pd.ParameterType (i) == a.Type)
5264 EmitParams (ec, i, arguments);
5271 ec.ig.Emit (OpCodes.Dup);
5272 (temps [i] = new LocalTemporary (ec, a.Type)).Store (ec);
5277 if (this_arg != null)
5280 for (int i = 0; i < top; i ++)
5281 temps [i].Emit (ec);
5284 if (pd != null && pd.Count > top &&
5285 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
5286 ILGenerator ig = ec.ig;
5288 IntConstant.EmitInt (ig, 0);
5289 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
5293 static Type[] GetVarargsTypes (EmitContext ec, MethodBase mb,
5294 ArrayList arguments)
5296 ParameterData pd = GetParameterData (mb);
5298 if (arguments == null)
5299 return new Type [0];
5301 Argument a = (Argument) arguments [pd.Count - 1];
5302 Arglist list = (Arglist) a.Expr;
5304 return list.ArgumentTypes;
5308 /// This checks the ConditionalAttribute on the method
5310 static bool IsMethodExcluded (MethodBase method, EmitContext ec)
5312 if (method.IsConstructor)
5315 IMethodData md = TypeManager.GetMethod (method);
5317 return md.IsExcluded (ec);
5319 // For some methods (generated by delegate class) GetMethod returns null
5320 // because they are not included in builder_to_method table
5321 if (method.DeclaringType is TypeBuilder)
5324 return AttributeTester.IsConditionalMethodExcluded (method);
5328 /// is_base tells whether we want to force the use of the `call'
5329 /// opcode instead of using callvirt. Call is required to call
5330 /// a specific method, while callvirt will always use the most
5331 /// recent method in the vtable.
5333 /// is_static tells whether this is an invocation on a static method
5335 /// instance_expr is an expression that represents the instance
5336 /// it must be non-null if is_static is false.
5338 /// method is the method to invoke.
5340 /// Arguments is the list of arguments to pass to the method or constructor.
5342 public static void EmitCall (EmitContext ec, bool is_base,
5343 bool is_static, Expression instance_expr,
5344 MethodBase method, ArrayList Arguments, Location loc)
5346 EmitCall (ec, is_base, is_static, instance_expr, method, Arguments, loc, false, false);
5349 // `dup_args' leaves an extra copy of the arguments on the stack
5350 // `omit_args' does not leave any arguments at all.
5351 // So, basically, you could make one call with `dup_args' set to true,
5352 // and then another with `omit_args' set to true, and the two calls
5353 // would have the same set of arguments. However, each argument would
5354 // only have been evaluated once.
5355 public static void EmitCall (EmitContext ec, bool is_base,
5356 bool is_static, Expression instance_expr,
5357 MethodBase method, ArrayList Arguments, Location loc,
5358 bool dup_args, bool omit_args)
5360 ILGenerator ig = ec.ig;
5361 bool struct_call = false;
5362 bool this_call = false;
5363 LocalTemporary this_arg = null;
5365 Type decl_type = method.DeclaringType;
5367 if (!RootContext.StdLib) {
5368 // Replace any calls to the system's System.Array type with calls to
5369 // the newly created one.
5370 if (method == TypeManager.system_int_array_get_length)
5371 method = TypeManager.int_array_get_length;
5372 else if (method == TypeManager.system_int_array_get_rank)
5373 method = TypeManager.int_array_get_rank;
5374 else if (method == TypeManager.system_object_array_clone)
5375 method = TypeManager.object_array_clone;
5376 else if (method == TypeManager.system_int_array_get_length_int)
5377 method = TypeManager.int_array_get_length_int;
5378 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5379 method = TypeManager.int_array_get_lower_bound_int;
5380 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5381 method = TypeManager.int_array_get_upper_bound_int;
5382 else if (method == TypeManager.system_void_array_copyto_array_int)
5383 method = TypeManager.void_array_copyto_array_int;
5386 if (ec.TestObsoleteMethodUsage) {
5388 // This checks ObsoleteAttribute on the method and on the declaring type
5390 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
5392 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
5395 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
5397 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
5401 if (IsMethodExcluded (method, ec))
5405 this_call = instance_expr == null;
5406 if (decl_type.IsValueType || (!this_call && instance_expr.Type.IsValueType))
5410 // If this is ourselves, push "this"
5415 ig.Emit (OpCodes.Ldarg_0);
5419 // Push the instance expression
5421 if (instance_expr.Type.IsValueType) {
5423 // Special case: calls to a function declared in a
5424 // reference-type with a value-type argument need
5425 // to have their value boxed.
5426 if (decl_type.IsValueType) {
5428 // If the expression implements IMemoryLocation, then
5429 // we can optimize and use AddressOf on the
5432 // If not we have to use some temporary storage for
5434 if (instance_expr is IMemoryLocation) {
5435 ((IMemoryLocation)instance_expr).
5436 AddressOf (ec, AddressOp.LoadStore);
5438 LocalTemporary temp = new LocalTemporary (ec, instance_expr.Type);
5439 instance_expr.Emit (ec);
5441 temp.AddressOf (ec, AddressOp.Load);
5444 // avoid the overhead of doing this all the time.
5446 t = TypeManager.GetReferenceType (instance_expr.Type);
5448 instance_expr.Emit (ec);
5449 ig.Emit (OpCodes.Box, instance_expr.Type);
5450 t = TypeManager.object_type;
5453 instance_expr.Emit (ec);
5454 t = instance_expr.Type;
5459 this_arg = new LocalTemporary (ec, t);
5460 ig.Emit (OpCodes.Dup);
5461 this_arg.Store (ec);
5467 EmitArguments (ec, method, Arguments, dup_args, this_arg);
5470 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
5471 call_op = OpCodes.Call;
5473 call_op = OpCodes.Callvirt;
5475 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
5476 Type[] varargs_types = GetVarargsTypes (ec, method, Arguments);
5477 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
5484 // and DoFoo is not virtual, you can omit the callvirt,
5485 // because you don't need the null checking behavior.
5487 if (method is MethodInfo)
5488 ig.Emit (call_op, (MethodInfo) method);
5490 ig.Emit (call_op, (ConstructorInfo) method);
5493 public override void Emit (EmitContext ec)
5495 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5497 EmitCall (ec, mg.IsBase, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5500 public override void EmitStatement (EmitContext ec)
5505 // Pop the return value if there is one
5507 if (method is MethodInfo){
5508 Type ret = ((MethodInfo)method).ReturnType;
5509 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5510 ec.ig.Emit (OpCodes.Pop);
5515 public class InvocationOrCast : ExpressionStatement
5518 Expression argument;
5520 public InvocationOrCast (Expression expr, Expression argument, Location loc)
5523 this.argument = argument;
5527 public override Expression DoResolve (EmitContext ec)
5530 // First try to resolve it as a cast.
5532 TypeExpr te = expr.ResolveAsTypeTerminal (ec, true);
5534 Cast cast = new Cast (te, argument, loc);
5535 return cast.Resolve (ec);
5539 // This can either be a type or a delegate invocation.
5540 // Let's just resolve it and see what we'll get.
5542 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5547 // Ok, so it's a Cast.
5549 if (expr.eclass == ExprClass.Type) {
5550 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
5551 return cast.Resolve (ec);
5555 // It's a delegate invocation.
5557 if (!TypeManager.IsDelegateType (expr.Type)) {
5558 Error (149, "Method name expected");
5562 ArrayList args = new ArrayList ();
5563 args.Add (new Argument (argument, Argument.AType.Expression));
5564 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5565 return invocation.Resolve (ec);
5570 Error (201, "Only assignment, call, increment, decrement and new object " +
5571 "expressions can be used as a statement");
5574 public override ExpressionStatement ResolveStatement (EmitContext ec)
5577 // First try to resolve it as a cast.
5579 TypeExpr te = expr.ResolveAsTypeTerminal (ec, true);
5586 // This can either be a type or a delegate invocation.
5587 // Let's just resolve it and see what we'll get.
5589 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5590 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5596 // It's a delegate invocation.
5598 if (!TypeManager.IsDelegateType (expr.Type)) {
5599 Error (149, "Method name expected");
5603 ArrayList args = new ArrayList ();
5604 args.Add (new Argument (argument, Argument.AType.Expression));
5605 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5606 return invocation.ResolveStatement (ec);
5609 public override void Emit (EmitContext ec)
5611 throw new Exception ("Cannot happen");
5614 public override void EmitStatement (EmitContext ec)
5616 throw new Exception ("Cannot happen");
5621 // This class is used to "disable" the code generation for the
5622 // temporary variable when initializing value types.
5624 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5625 public void AddressOf (EmitContext ec, AddressOp Mode)
5632 /// Implements the new expression
5634 public class New : ExpressionStatement, IMemoryLocation {
5635 public readonly ArrayList Arguments;
5638 // During bootstrap, it contains the RequestedType,
5639 // but if `type' is not null, it *might* contain a NewDelegate
5640 // (because of field multi-initialization)
5642 public Expression RequestedType;
5644 MethodBase method = null;
5647 // If set, the new expression is for a value_target, and
5648 // we will not leave anything on the stack.
5650 Expression value_target;
5651 bool value_target_set = false;
5653 public New (Expression requested_type, ArrayList arguments, Location l)
5655 RequestedType = requested_type;
5656 Arguments = arguments;
5660 public bool SetValueTypeVariable (Expression value)
5662 value_target = value;
5663 value_target_set = true;
5664 if (!(value_target is IMemoryLocation)){
5665 Error_UnexpectedKind ("variable", loc);
5672 // This function is used to disable the following code sequence for
5673 // value type initialization:
5675 // AddressOf (temporary)
5679 // Instead the provide will have provided us with the address on the
5680 // stack to store the results.
5682 static Expression MyEmptyExpression;
5684 public void DisableTemporaryValueType ()
5686 if (MyEmptyExpression == null)
5687 MyEmptyExpression = new EmptyAddressOf ();
5690 // To enable this, look into:
5691 // test-34 and test-89 and self bootstrapping.
5693 // For instance, we can avoid a copy by using `newobj'
5694 // instead of Call + Push-temp on value types.
5695 // value_target = MyEmptyExpression;
5698 public override Expression DoResolve (EmitContext ec)
5701 // The New DoResolve might be called twice when initializing field
5702 // expressions (see EmitFieldInitializers, the call to
5703 // GetInitializerExpression will perform a resolve on the expression,
5704 // and later the assign will trigger another resolution
5706 // This leads to bugs (#37014)
5709 if (RequestedType is NewDelegate)
5710 return RequestedType;
5714 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec, false);
5718 type = texpr.ResolveType (ec);
5720 CheckObsoleteAttribute (type);
5722 bool IsDelegate = TypeManager.IsDelegateType (type);
5725 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5726 if (RequestedType != null)
5727 if (!(RequestedType is DelegateCreation))
5728 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
5729 return RequestedType;
5732 if (type.IsAbstract && type.IsSealed) {
5733 Report.Error (712, loc, "Cannot create an instance of the static class '{0}'", TypeManager.CSharpName (type));
5737 if (type.IsInterface || type.IsAbstract){
5738 Error (144, "It is not possible to create instances of interfaces or abstract classes");
5742 bool is_struct = type.IsValueType;
5743 eclass = ExprClass.Value;
5746 // SRE returns a match for .ctor () on structs (the object constructor),
5747 // so we have to manually ignore it.
5749 if (is_struct && Arguments == null)
5753 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
5754 ml = MemberLookupFinal (ec, type, type, ".ctor",
5755 MemberTypes.Constructor,
5756 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5761 if (! (ml is MethodGroupExpr)){
5763 ml.Error_UnexpectedKind ("method group", loc);
5769 if (Arguments != null){
5770 foreach (Argument a in Arguments){
5771 if (!a.Resolve (ec, loc))
5776 method = Invocation.OverloadResolve (
5777 ec, (MethodGroupExpr) ml, Arguments, false, loc);
5781 if (method == null) {
5782 if (!is_struct || Arguments.Count > 0) {
5783 Error (1501, String.Format (
5784 "New invocation: Can not find a constructor in `{0}' for this argument list",
5785 TypeManager.CSharpName (type)));
5794 // This DoEmit can be invoked in two contexts:
5795 // * As a mechanism that will leave a value on the stack (new object)
5796 // * As one that wont (init struct)
5798 // You can control whether a value is required on the stack by passing
5799 // need_value_on_stack. The code *might* leave a value on the stack
5800 // so it must be popped manually
5802 // If we are dealing with a ValueType, we have a few
5803 // situations to deal with:
5805 // * The target is a ValueType, and we have been provided
5806 // the instance (this is easy, we are being assigned).
5808 // * The target of New is being passed as an argument,
5809 // to a boxing operation or a function that takes a
5812 // In this case, we need to create a temporary variable
5813 // that is the argument of New.
5815 // Returns whether a value is left on the stack
5817 bool DoEmit (EmitContext ec, bool need_value_on_stack)
5819 bool is_value_type = type.IsValueType;
5820 ILGenerator ig = ec.ig;
5825 // Allow DoEmit() to be called multiple times.
5826 // We need to create a new LocalTemporary each time since
5827 // you can't share LocalBuilders among ILGeneators.
5828 if (!value_target_set)
5829 value_target = new LocalTemporary (ec, type);
5831 ml = (IMemoryLocation) value_target;
5832 ml.AddressOf (ec, AddressOp.Store);
5836 Invocation.EmitArguments (ec, method, Arguments, false, null);
5840 ig.Emit (OpCodes.Initobj, type);
5842 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5843 if (need_value_on_stack){
5844 value_target.Emit (ec);
5849 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
5854 public override void Emit (EmitContext ec)
5859 public override void EmitStatement (EmitContext ec)
5861 if (DoEmit (ec, false))
5862 ec.ig.Emit (OpCodes.Pop);
5865 public void AddressOf (EmitContext ec, AddressOp Mode)
5867 if (!type.IsValueType){
5869 // We throw an exception. So far, I believe we only need to support
5871 // foreach (int j in new StructType ())
5874 throw new Exception ("AddressOf should not be used for classes");
5877 if (!value_target_set)
5878 value_target = new LocalTemporary (ec, type);
5880 IMemoryLocation ml = (IMemoryLocation) value_target;
5881 ml.AddressOf (ec, AddressOp.Store);
5883 Invocation.EmitArguments (ec, method, Arguments, false, null);
5886 ec.ig.Emit (OpCodes.Initobj, type);
5888 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5890 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
5895 /// 14.5.10.2: Represents an array creation expression.
5899 /// There are two possible scenarios here: one is an array creation
5900 /// expression that specifies the dimensions and optionally the
5901 /// initialization data and the other which does not need dimensions
5902 /// specified but where initialization data is mandatory.
5904 public class ArrayCreation : Expression {
5905 Expression requested_base_type;
5906 ArrayList initializers;
5909 // The list of Argument types.
5910 // This is used to construct the `newarray' or constructor signature
5912 ArrayList arguments;
5915 // Method used to create the array object.
5917 MethodBase new_method = null;
5919 Type array_element_type;
5920 Type underlying_type;
5921 bool is_one_dimensional = false;
5922 bool is_builtin_type = false;
5923 bool expect_initializers = false;
5924 int num_arguments = 0;
5928 ArrayList array_data;
5933 // The number of array initializers that we can handle
5934 // via the InitializeArray method - through EmitStaticInitializers
5936 int num_automatic_initializers;
5938 const int max_automatic_initializers = 6;
5940 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
5942 this.requested_base_type = requested_base_type;
5943 this.initializers = initializers;
5947 arguments = new ArrayList ();
5949 foreach (Expression e in exprs) {
5950 arguments.Add (new Argument (e, Argument.AType.Expression));
5955 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
5957 this.requested_base_type = requested_base_type;
5958 this.initializers = initializers;
5962 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
5964 //string tmp = rank.Substring (rank.LastIndexOf ('['));
5966 //dimensions = tmp.Length - 1;
5967 expect_initializers = true;
5970 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
5972 StringBuilder sb = new StringBuilder (rank);
5975 for (int i = 1; i < idx_count; i++)
5980 return new ComposedCast (base_type, sb.ToString (), loc);
5983 void Error_IncorrectArrayInitializer ()
5985 Error (178, "Incorrectly structured array initializer");
5988 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
5990 if (specified_dims) {
5991 Argument a = (Argument) arguments [idx];
5993 if (!a.Resolve (ec, loc))
5996 if (!(a.Expr is Constant)) {
5997 Error (150, "A constant value is expected");
6001 int value = (int) ((Constant) a.Expr).GetValue ();
6003 if (value != probe.Count) {
6004 Error_IncorrectArrayInitializer ();
6008 bounds [idx] = value;
6011 int child_bounds = -1;
6012 foreach (object o in probe) {
6013 if (o is ArrayList) {
6014 int current_bounds = ((ArrayList) o).Count;
6016 if (child_bounds == -1)
6017 child_bounds = current_bounds;
6019 else if (child_bounds != current_bounds){
6020 Error_IncorrectArrayInitializer ();
6023 if (specified_dims && (idx + 1 >= arguments.Count)){
6024 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
6028 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
6032 if (child_bounds != -1){
6033 Error_IncorrectArrayInitializer ();
6037 Expression tmp = (Expression) o;
6038 tmp = tmp.Resolve (ec);
6042 // Console.WriteLine ("I got: " + tmp);
6043 // Handle initialization from vars, fields etc.
6045 Expression conv = Convert.ImplicitConversionRequired (
6046 ec, tmp, underlying_type, loc);
6051 if (conv is StringConstant || conv is DecimalConstant || conv is NullCast) {
6052 // These are subclasses of Constant that can appear as elements of an
6053 // array that cannot be statically initialized (with num_automatic_initializers
6054 // > max_automatic_initializers), so num_automatic_initializers should be left as zero.
6055 array_data.Add (conv);
6056 } else if (conv is Constant) {
6057 // These are the types of Constant that can appear in arrays that can be
6058 // statically allocated.
6059 array_data.Add (conv);
6060 num_automatic_initializers++;
6062 array_data.Add (conv);
6069 public void UpdateIndices (EmitContext ec)
6072 for (ArrayList probe = initializers; probe != null;) {
6073 if (probe.Count > 0 && probe [0] is ArrayList) {
6074 Expression e = new IntConstant (probe.Count);
6075 arguments.Add (new Argument (e, Argument.AType.Expression));
6077 bounds [i++] = probe.Count;
6079 probe = (ArrayList) probe [0];
6082 Expression e = new IntConstant (probe.Count);
6083 arguments.Add (new Argument (e, Argument.AType.Expression));
6085 bounds [i++] = probe.Count;
6092 public bool ValidateInitializers (EmitContext ec, Type array_type)
6094 if (initializers == null) {
6095 if (expect_initializers)
6101 if (underlying_type == null)
6105 // We use this to store all the date values in the order in which we
6106 // will need to store them in the byte blob later
6108 array_data = new ArrayList ();
6109 bounds = new Hashtable ();
6113 if (arguments != null) {
6114 ret = CheckIndices (ec, initializers, 0, true);
6117 arguments = new ArrayList ();
6119 ret = CheckIndices (ec, initializers, 0, false);
6126 if (arguments.Count != dimensions) {
6127 Error_IncorrectArrayInitializer ();
6136 // Converts `source' to an int, uint, long or ulong.
6138 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
6142 bool old_checked = ec.CheckState;
6143 ec.CheckState = true;
6145 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
6146 if (target == null){
6147 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
6148 if (target == null){
6149 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
6150 if (target == null){
6151 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
6153 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
6157 ec.CheckState = old_checked;
6160 // Only positive constants are allowed at compile time
6162 if (target is Constant){
6163 if (target is IntConstant){
6164 if (((IntConstant) target).Value < 0){
6165 Expression.Error_NegativeArrayIndex (loc);
6170 if (target is LongConstant){
6171 if (((LongConstant) target).Value < 0){
6172 Expression.Error_NegativeArrayIndex (loc);
6183 // Creates the type of the array
6185 bool LookupType (EmitContext ec)
6187 StringBuilder array_qualifier = new StringBuilder (rank);
6190 // `In the first form allocates an array instace of the type that results
6191 // from deleting each of the individual expression from the expression list'
6193 if (num_arguments > 0) {
6194 array_qualifier.Append ("[");
6195 for (int i = num_arguments-1; i > 0; i--)
6196 array_qualifier.Append (",");
6197 array_qualifier.Append ("]");
6203 TypeExpr array_type_expr;
6204 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
6205 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec, false);
6206 if (array_type_expr == null)
6209 type = array_type_expr.ResolveType (ec);
6211 if (!type.IsArray) {
6212 Error (622, "Can only use array initializer expressions to assign to array types. Try using a new expression instead.");
6215 underlying_type = TypeManager.GetElementType (type);
6216 dimensions = type.GetArrayRank ();
6221 public override Expression DoResolve (EmitContext ec)
6225 if (!LookupType (ec))
6229 // First step is to validate the initializers and fill
6230 // in any missing bits
6232 if (!ValidateInitializers (ec, type))
6235 if (arguments == null)
6238 arg_count = arguments.Count;
6239 foreach (Argument a in arguments){
6240 if (!a.Resolve (ec, loc))
6243 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
6244 if (real_arg == null)
6251 array_element_type = TypeManager.GetElementType (type);
6253 if (array_element_type.IsAbstract && array_element_type.IsSealed) {
6254 Report.Error (719, loc, "'{0}': array elements cannot be of static type", TypeManager.CSharpName (array_element_type));
6258 if (arg_count == 1) {
6259 is_one_dimensional = true;
6260 eclass = ExprClass.Value;
6264 is_builtin_type = TypeManager.IsBuiltinType (type);
6266 if (is_builtin_type) {
6269 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
6270 AllBindingFlags, loc);
6272 if (!(ml is MethodGroupExpr)) {
6273 ml.Error_UnexpectedKind ("method group", loc);
6278 Error (-6, "New invocation: Can not find a constructor for " +
6279 "this argument list");
6283 new_method = Invocation.OverloadResolve (
6284 ec, (MethodGroupExpr) ml, arguments, false, loc);
6286 if (new_method == null) {
6287 Error (-6, "New invocation: Can not find a constructor for " +
6288 "this argument list");
6292 eclass = ExprClass.Value;
6295 ModuleBuilder mb = CodeGen.Module.Builder;
6296 ArrayList args = new ArrayList ();
6298 if (arguments != null) {
6299 for (int i = 0; i < arg_count; i++)
6300 args.Add (TypeManager.int32_type);
6303 Type [] arg_types = null;
6306 arg_types = new Type [args.Count];
6308 args.CopyTo (arg_types, 0);
6310 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
6313 if (new_method == null) {
6314 Error (-6, "New invocation: Can not find a constructor for " +
6315 "this argument list");
6319 eclass = ExprClass.Value;
6324 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
6329 int count = array_data.Count;
6331 if (underlying_type.IsEnum)
6332 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
6334 factor = GetTypeSize (underlying_type);
6336 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
6338 data = new byte [(count * factor + 4) & ~3];
6341 for (int i = 0; i < count; ++i) {
6342 object v = array_data [i];
6344 if (v is EnumConstant)
6345 v = ((EnumConstant) v).Child;
6347 if (v is Constant && !(v is StringConstant))
6348 v = ((Constant) v).GetValue ();
6354 if (underlying_type == TypeManager.int64_type){
6355 if (!(v is Expression)){
6356 long val = (long) v;
6358 for (int j = 0; j < factor; ++j) {
6359 data [idx + j] = (byte) (val & 0xFF);
6363 } else if (underlying_type == TypeManager.uint64_type){
6364 if (!(v is Expression)){
6365 ulong val = (ulong) v;
6367 for (int j = 0; j < factor; ++j) {
6368 data [idx + j] = (byte) (val & 0xFF);
6372 } else if (underlying_type == TypeManager.float_type) {
6373 if (!(v is Expression)){
6374 element = BitConverter.GetBytes ((float) v);
6376 for (int j = 0; j < factor; ++j)
6377 data [idx + j] = element [j];
6379 } else if (underlying_type == TypeManager.double_type) {
6380 if (!(v is Expression)){
6381 element = BitConverter.GetBytes ((double) v);
6383 for (int j = 0; j < factor; ++j)
6384 data [idx + j] = element [j];
6386 } else if (underlying_type == TypeManager.char_type){
6387 if (!(v is Expression)){
6388 int val = (int) ((char) v);
6390 data [idx] = (byte) (val & 0xff);
6391 data [idx+1] = (byte) (val >> 8);
6393 } else if (underlying_type == TypeManager.short_type){
6394 if (!(v is Expression)){
6395 int val = (int) ((short) v);
6397 data [idx] = (byte) (val & 0xff);
6398 data [idx+1] = (byte) (val >> 8);
6400 } else if (underlying_type == TypeManager.ushort_type){
6401 if (!(v is Expression)){
6402 int val = (int) ((ushort) v);
6404 data [idx] = (byte) (val & 0xff);
6405 data [idx+1] = (byte) (val >> 8);
6407 } else if (underlying_type == TypeManager.int32_type) {
6408 if (!(v is Expression)){
6411 data [idx] = (byte) (val & 0xff);
6412 data [idx+1] = (byte) ((val >> 8) & 0xff);
6413 data [idx+2] = (byte) ((val >> 16) & 0xff);
6414 data [idx+3] = (byte) (val >> 24);
6416 } else if (underlying_type == TypeManager.uint32_type) {
6417 if (!(v is Expression)){
6418 uint val = (uint) v;
6420 data [idx] = (byte) (val & 0xff);
6421 data [idx+1] = (byte) ((val >> 8) & 0xff);
6422 data [idx+2] = (byte) ((val >> 16) & 0xff);
6423 data [idx+3] = (byte) (val >> 24);
6425 } else if (underlying_type == TypeManager.sbyte_type) {
6426 if (!(v is Expression)){
6427 sbyte val = (sbyte) v;
6428 data [idx] = (byte) val;
6430 } else if (underlying_type == TypeManager.byte_type) {
6431 if (!(v is Expression)){
6432 byte val = (byte) v;
6433 data [idx] = (byte) val;
6435 } else if (underlying_type == TypeManager.bool_type) {
6436 if (!(v is Expression)){
6437 bool val = (bool) v;
6438 data [idx] = (byte) (val ? 1 : 0);
6440 } else if (underlying_type == TypeManager.decimal_type){
6441 if (!(v is Expression)){
6442 int [] bits = Decimal.GetBits ((decimal) v);
6445 // FIXME: For some reason, this doesn't work on the MS runtime.
6446 int [] nbits = new int [4];
6447 nbits [0] = bits [3];
6448 nbits [1] = bits [2];
6449 nbits [2] = bits [0];
6450 nbits [3] = bits [1];
6452 for (int j = 0; j < 4; j++){
6453 data [p++] = (byte) (nbits [j] & 0xff);
6454 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6455 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6456 data [p++] = (byte) (nbits [j] >> 24);
6460 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6469 // Emits the initializers for the array
6471 void EmitStaticInitializers (EmitContext ec)
6474 // First, the static data
6477 ILGenerator ig = ec.ig;
6479 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6481 fb = RootContext.MakeStaticData (data);
6483 ig.Emit (OpCodes.Dup);
6484 ig.Emit (OpCodes.Ldtoken, fb);
6485 ig.Emit (OpCodes.Call,
6486 TypeManager.void_initializearray_array_fieldhandle);
6490 // Emits pieces of the array that can not be computed at compile
6491 // time (variables and string locations).
6493 // This always expect the top value on the stack to be the array
6495 void EmitDynamicInitializers (EmitContext ec)
6497 ILGenerator ig = ec.ig;
6498 int dims = bounds.Count;
6499 int [] current_pos = new int [dims];
6500 int top = array_data.Count;
6502 MethodInfo set = null;
6506 ModuleBuilder mb = null;
6507 mb = CodeGen.Module.Builder;
6508 args = new Type [dims + 1];
6511 for (j = 0; j < dims; j++)
6512 args [j] = TypeManager.int32_type;
6514 args [j] = array_element_type;
6516 set = mb.GetArrayMethod (
6518 CallingConventions.HasThis | CallingConventions.Standard,
6519 TypeManager.void_type, args);
6522 for (int i = 0; i < top; i++){
6524 Expression e = null;
6526 if (array_data [i] is Expression)
6527 e = (Expression) array_data [i];
6531 // Basically we do this for string literals and
6532 // other non-literal expressions
6534 if (e is EnumConstant){
6535 e = ((EnumConstant) e).Child;
6538 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6539 num_automatic_initializers <= max_automatic_initializers) {
6540 Type etype = e.Type;
6542 ig.Emit (OpCodes.Dup);
6544 for (int idx = 0; idx < dims; idx++)
6545 IntConstant.EmitInt (ig, current_pos [idx]);
6548 // If we are dealing with a struct, get the
6549 // address of it, so we can store it.
6552 etype.IsSubclassOf (TypeManager.value_type) &&
6553 (!TypeManager.IsBuiltinOrEnum (etype) ||
6554 etype == TypeManager.decimal_type)) {
6559 // Let new know that we are providing
6560 // the address where to store the results
6562 n.DisableTemporaryValueType ();
6565 ig.Emit (OpCodes.Ldelema, etype);
6572 OpCode op = ArrayAccess.GetStoreOpcode (etype, out is_stobj);
6574 ig.Emit (OpCodes.Stobj, etype);
6578 ig.Emit (OpCodes.Call, set);
6586 for (int j = dims - 1; j >= 0; j--){
6588 if (current_pos [j] < (int) bounds [j])
6590 current_pos [j] = 0;
6595 void EmitArrayArguments (EmitContext ec)
6597 ILGenerator ig = ec.ig;
6599 foreach (Argument a in arguments) {
6600 Type atype = a.Type;
6603 if (atype == TypeManager.uint64_type)
6604 ig.Emit (OpCodes.Conv_Ovf_U4);
6605 else if (atype == TypeManager.int64_type)
6606 ig.Emit (OpCodes.Conv_Ovf_I4);
6610 public override void Emit (EmitContext ec)
6612 ILGenerator ig = ec.ig;
6614 EmitArrayArguments (ec);
6615 if (is_one_dimensional)
6616 ig.Emit (OpCodes.Newarr, array_element_type);
6618 if (is_builtin_type)
6619 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6621 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6624 if (initializers != null){
6626 // FIXME: Set this variable correctly.
6628 bool dynamic_initializers = true;
6630 // This will never be true for array types that cannot be statically
6631 // initialized. num_automatic_initializers will always be zero. See
6633 if (num_automatic_initializers > max_automatic_initializers)
6634 EmitStaticInitializers (ec);
6636 if (dynamic_initializers)
6637 EmitDynamicInitializers (ec);
6641 public object EncodeAsAttribute ()
6643 if (!is_one_dimensional){
6644 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6648 if (array_data == null){
6649 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6653 object [] ret = new object [array_data.Count];
6655 foreach (Expression e in array_data){
6658 if (e is NullLiteral)
6661 if (!Attribute.GetAttributeArgumentExpression (e, Location, array_element_type, out v))
6671 /// Represents the `this' construct
6673 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6676 VariableInfo variable_info;
6678 public This (Block block, Location loc)
6684 public This (Location loc)
6689 public VariableInfo VariableInfo {
6690 get { return variable_info; }
6693 public bool VerifyFixed (bool is_expression)
6695 if ((variable_info == null) || (variable_info.LocalInfo == null))
6698 return variable_info.LocalInfo.IsFixed;
6701 public bool ResolveBase (EmitContext ec)
6703 eclass = ExprClass.Variable;
6704 type = ec.ContainerType;
6707 Error (26, "Keyword this not valid in static code");
6711 if ((block != null) && (block.ThisVariable != null))
6712 variable_info = block.ThisVariable.VariableInfo;
6717 public override Expression DoResolve (EmitContext ec)
6719 if (!ResolveBase (ec))
6722 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
6723 Error (188, "The this object cannot be used before all " +
6724 "of its fields are assigned to");
6725 variable_info.SetAssigned (ec);
6729 if (ec.IsFieldInitializer) {
6730 Error (27, "Keyword `this' can't be used outside a constructor, " +
6731 "a method or a property.");
6738 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6740 if (!ResolveBase (ec))
6743 if (variable_info != null)
6744 variable_info.SetAssigned (ec);
6746 if (ec.TypeContainer is Class){
6747 Error (1604, "Cannot assign to `this'");
6754 public void Emit (EmitContext ec, bool leave_copy)
6758 ec.ig.Emit (OpCodes.Dup);
6761 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
6763 ILGenerator ig = ec.ig;
6765 if (ec.TypeContainer is Struct){
6769 ec.ig.Emit (OpCodes.Dup);
6770 ig.Emit (OpCodes.Stobj, type);
6772 throw new Exception ("how did you get here");
6776 public override void Emit (EmitContext ec)
6778 ILGenerator ig = ec.ig;
6781 if (ec.TypeContainer is Struct)
6782 ig.Emit (OpCodes.Ldobj, type);
6785 public void AddressOf (EmitContext ec, AddressOp mode)
6790 // FIGURE OUT WHY LDARG_S does not work
6792 // consider: struct X { int val; int P { set { val = value; }}}
6794 // Yes, this looks very bad. Look at `NOTAS' for
6796 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
6801 /// Represents the `__arglist' construct
6803 public class ArglistAccess : Expression
6805 public ArglistAccess (Location loc)
6810 public bool ResolveBase (EmitContext ec)
6812 eclass = ExprClass.Variable;
6813 type = TypeManager.runtime_argument_handle_type;
6817 public override Expression DoResolve (EmitContext ec)
6819 if (!ResolveBase (ec))
6822 if (ec.IsFieldInitializer || !ec.CurrentBlock.HasVarargs) {
6823 Error (190, "The __arglist construct is valid only within " +
6824 "a variable argument method.");
6831 public override void Emit (EmitContext ec)
6833 ec.ig.Emit (OpCodes.Arglist);
6838 /// Represents the `__arglist (....)' construct
6840 public class Arglist : Expression
6842 public readonly Argument[] Arguments;
6844 public Arglist (Argument[] args, Location l)
6850 public Type[] ArgumentTypes {
6852 Type[] retval = new Type [Arguments.Length];
6853 for (int i = 0; i < Arguments.Length; i++)
6854 retval [i] = Arguments [i].Type;
6859 public override Expression DoResolve (EmitContext ec)
6861 eclass = ExprClass.Variable;
6862 type = TypeManager.runtime_argument_handle_type;
6864 foreach (Argument arg in Arguments) {
6865 if (!arg.Resolve (ec, loc))
6872 public override void Emit (EmitContext ec)
6874 foreach (Argument arg in Arguments)
6880 // This produces the value that renders an instance, used by the iterators code
6882 public class ProxyInstance : Expression, IMemoryLocation {
6883 public override Expression DoResolve (EmitContext ec)
6885 eclass = ExprClass.Variable;
6886 type = ec.ContainerType;
6890 public override void Emit (EmitContext ec)
6892 ec.ig.Emit (OpCodes.Ldarg_0);
6896 public void AddressOf (EmitContext ec, AddressOp mode)
6898 ec.ig.Emit (OpCodes.Ldarg_0);
6903 /// Implements the typeof operator
6905 public class TypeOf : Expression {
6906 public Expression QueriedType;
6907 protected Type typearg;
6909 public TypeOf (Expression queried_type, Location l)
6911 QueriedType = queried_type;
6915 public override Expression DoResolve (EmitContext ec)
6917 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
6921 typearg = texpr.ResolveType (ec);
6923 if (typearg == TypeManager.void_type) {
6924 Error (673, "System.Void cannot be used from C# - " +
6925 "use typeof (void) to get the void type object");
6929 if (typearg.IsPointer && !ec.InUnsafe){
6933 CheckObsoleteAttribute (typearg);
6935 type = TypeManager.type_type;
6936 eclass = ExprClass.Type;
6940 public override void Emit (EmitContext ec)
6942 ec.ig.Emit (OpCodes.Ldtoken, typearg);
6943 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6946 public Type TypeArg {
6947 get { return typearg; }
6952 /// Implements the `typeof (void)' operator
6954 public class TypeOfVoid : TypeOf {
6955 public TypeOfVoid (Location l) : base (null, l)
6960 public override Expression DoResolve (EmitContext ec)
6962 type = TypeManager.type_type;
6963 typearg = TypeManager.void_type;
6964 eclass = ExprClass.Type;
6970 /// Implements the sizeof expression
6972 public class SizeOf : Expression {
6973 public Expression QueriedType;
6976 public SizeOf (Expression queried_type, Location l)
6978 this.QueriedType = queried_type;
6982 public override Expression DoResolve (EmitContext ec)
6986 233, loc, "Sizeof may only be used in an unsafe context " +
6987 "(consider using System.Runtime.InteropServices.Marshal.SizeOf");
6991 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
6995 type_queried = texpr.ResolveType (ec);
6997 CheckObsoleteAttribute (type_queried);
6999 if (!TypeManager.IsUnmanagedType (type_queried)){
7000 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
7004 type = TypeManager.int32_type;
7005 eclass = ExprClass.Value;
7009 public override void Emit (EmitContext ec)
7011 int size = GetTypeSize (type_queried);
7014 ec.ig.Emit (OpCodes.Sizeof, type_queried);
7016 IntConstant.EmitInt (ec.ig, size);
7021 /// Implements the member access expression
7023 public class MemberAccess : Expression {
7024 public readonly string Identifier;
7027 public MemberAccess (Expression expr, string id, Location l)
7034 public Expression Expr {
7040 public static void error176 (Location loc, string name)
7042 Report.Error (176, loc, "Static member `" +
7043 name + "' cannot be accessed " +
7044 "with an instance reference, qualify with a " +
7045 "type name instead");
7048 public static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Expression left, Location loc)
7050 SimpleName sn = left_original as SimpleName;
7051 if (sn == null || left == null || left.Type.Name != sn.Name)
7054 return RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc) != null;
7057 // TODO: possible optimalization
7058 // Cache resolved constant result in FieldBuilder <-> expresion map
7059 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
7060 Expression left, Location loc,
7061 Expression left_original)
7063 bool left_is_type, left_is_explicit;
7065 // If `left' is null, then we're called from SimpleNameResolve and this is
7066 // a member in the currently defining class.
7068 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
7069 left_is_explicit = false;
7071 // Implicitly default to `this' unless we're static.
7072 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
7073 left = ec.GetThis (loc);
7075 left_is_type = left is TypeExpr;
7076 left_is_explicit = true;
7079 if (member_lookup is FieldExpr){
7080 FieldExpr fe = (FieldExpr) member_lookup;
7081 FieldInfo fi = fe.FieldInfo;
7082 Type decl_type = fi.DeclaringType;
7084 bool is_emitted = fi is FieldBuilder;
7085 Type t = fi.FieldType;
7088 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
7092 if (!c.LookupConstantValue (out o))
7095 object real_value = ((Constant) c.Expr).GetValue ();
7097 return Constantify (real_value, t);
7101 // IsInitOnly is because of MS compatibility, I don't know why but they emit decimal constant as InitOnly
7102 if (fi.IsInitOnly && !is_emitted && t == TypeManager.decimal_type) {
7103 object[] attrs = fi.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
7104 if (attrs.Length == 1)
7105 return new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
7112 o = TypeManager.GetValue ((FieldBuilder) fi);
7114 o = fi.GetValue (fi);
7116 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
7117 if (left_is_explicit && !left_is_type &&
7118 !IdenticalNameAndTypeName (ec, left_original, member_lookup, loc)) {
7119 error176 (loc, fe.FieldInfo.Name);
7123 Expression enum_member = MemberLookup (
7124 ec, decl_type, "value__", MemberTypes.Field,
7125 AllBindingFlags, loc);
7127 Enum en = TypeManager.LookupEnum (decl_type);
7131 c = Constantify (o, en.UnderlyingType);
7133 c = Constantify (o, enum_member.Type);
7135 return new EnumConstant (c, decl_type);
7138 Expression exp = Constantify (o, t);
7140 if (left_is_explicit && !left_is_type) {
7141 error176 (loc, fe.FieldInfo.Name);
7148 if (t.IsPointer && !ec.InUnsafe){
7154 if (member_lookup is EventExpr) {
7155 EventExpr ee = (EventExpr) member_lookup;
7158 // If the event is local to this class, we transform ourselves into
7162 if (ee.EventInfo.DeclaringType == ec.ContainerType ||
7163 TypeManager.IsNestedChildOf(ec.ContainerType, ee.EventInfo.DeclaringType)) {
7164 MemberInfo mi = GetFieldFromEvent (ee);
7168 // If this happens, then we have an event with its own
7169 // accessors and private field etc so there's no need
7170 // to transform ourselves.
7172 ee.InstanceExpression = left;
7176 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
7179 Report.Error (-200, loc, "Internal error!!");
7183 if (!left_is_explicit)
7186 ee.InstanceExpression = left;
7188 return ResolveMemberAccess (ec, ml, left, loc, left_original);
7192 if (member_lookup is IMemberExpr) {
7193 IMemberExpr me = (IMemberExpr) member_lookup;
7194 MethodGroupExpr mg = me as MethodGroupExpr;
7197 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
7198 mg.IsExplicitImpl = left_is_explicit;
7201 if ((ec.IsFieldInitializer || ec.IsStatic) &&
7202 IdenticalNameAndTypeName (ec, left_original, member_lookup, loc))
7203 return member_lookup;
7205 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
7210 if (!me.IsInstance) {
7211 if (IdenticalNameAndTypeName (ec, left_original, left, loc))
7212 return member_lookup;
7214 if (left_is_explicit) {
7215 error176 (loc, me.Name);
7221 // Since we can not check for instance objects in SimpleName,
7222 // becaue of the rule that allows types and variables to share
7223 // the name (as long as they can be de-ambiguated later, see
7224 // IdenticalNameAndTypeName), we have to check whether left
7225 // is an instance variable in a static context
7227 // However, if the left-hand value is explicitly given, then
7228 // it is already our instance expression, so we aren't in
7232 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
7233 IMemberExpr mexp = (IMemberExpr) left;
7235 if (!mexp.IsStatic){
7236 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
7241 if ((mg != null) && IdenticalNameAndTypeName (ec, left_original, left, loc))
7242 mg.IdenticalTypeName = true;
7244 me.InstanceExpression = left;
7247 return member_lookup;
7250 Console.WriteLine ("Left is: " + left);
7251 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
7252 Environment.Exit (1);
7256 public Expression DoResolve (EmitContext ec, Expression right_side, ResolveFlags flags)
7259 throw new Exception ();
7262 // Resolve the expression with flow analysis turned off, we'll do the definite
7263 // assignment checks later. This is because we don't know yet what the expression
7264 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7265 // definite assignment check on the actual field and not on the whole struct.
7268 Expression original = expr;
7269 expr = expr.Resolve (ec, flags | ResolveFlags.Intermediate | ResolveFlags.DisableFlowAnalysis);
7273 if (expr is SimpleName){
7274 SimpleName child_expr = (SimpleName) expr;
7276 Expression new_expr = new SimpleName (child_expr.Name, Identifier, loc);
7278 return new_expr.Resolve (ec, flags);
7282 // TODO: I mailed Ravi about this, and apparently we can get rid
7283 // of this and put it in the right place.
7285 // Handle enums here when they are in transit.
7286 // Note that we cannot afford to hit MemberLookup in this case because
7287 // it will fail to find any members at all
7290 Type expr_type = expr.Type;
7291 if (expr is TypeExpr){
7292 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
7293 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", expr_type);
7297 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
7298 Enum en = TypeManager.LookupEnum (expr_type);
7301 object value = en.LookupEnumValue (ec, Identifier, loc);
7304 MemberCore mc = en.GetDefinition (Identifier);
7305 ObsoleteAttribute oa = mc.GetObsoleteAttribute (en);
7307 AttributeTester.Report_ObsoleteMessage (oa, mc.GetSignatureForError (), Location);
7309 oa = en.GetObsoleteAttribute (en);
7311 AttributeTester.Report_ObsoleteMessage (oa, en.GetSignatureForError (), Location);
7314 Constant c = Constantify (value, en.UnderlyingType);
7315 return new EnumConstant (c, expr_type);
7318 CheckObsoleteAttribute (expr_type);
7320 FieldInfo fi = expr_type.GetField (Identifier);
7322 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
7324 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), Location);
7330 if (expr_type.IsPointer){
7331 Error (23, "The `.' operator can not be applied to pointer operands (" +
7332 TypeManager.CSharpName (expr_type) + ")");
7336 Expression member_lookup;
7337 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
7338 if (member_lookup == null)
7341 if (member_lookup is TypeExpr) {
7342 if (!(expr is TypeExpr) && !(expr is SimpleName)) {
7343 Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
7344 member_lookup.Type + "' instead");
7348 return member_lookup;
7351 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
7352 if (member_lookup == null)
7355 // The following DoResolve/DoResolveLValue will do the definite assignment
7358 if (right_side != null)
7359 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
7361 member_lookup = member_lookup.DoResolve (ec);
7363 return member_lookup;
7366 public override Expression DoResolve (EmitContext ec)
7368 return DoResolve (ec, null, ResolveFlags.VariableOrValue |
7369 ResolveFlags.SimpleName | ResolveFlags.Type);
7372 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7374 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
7375 ResolveFlags.SimpleName | ResolveFlags.Type);
7378 public override Expression ResolveAsTypeStep (EmitContext ec)
7380 string fname = null;
7381 MemberAccess full_expr = this;
7382 while (full_expr != null) {
7384 fname = String.Concat (full_expr.Identifier, ".", fname);
7386 fname = full_expr.Identifier;
7388 if (full_expr.Expr is SimpleName) {
7389 string full_name = String.Concat (((SimpleName) full_expr.Expr).Name, ".", fname);
7390 Type fully_qualified = ec.DeclSpace.FindType (loc, full_name);
7391 if (fully_qualified != null)
7392 return new TypeExpression (fully_qualified, loc);
7395 full_expr = full_expr.Expr as MemberAccess;
7398 Expression new_expr = expr.ResolveAsTypeStep (ec);
7400 if (new_expr == null)
7403 if (new_expr is SimpleName){
7404 SimpleName child_expr = (SimpleName) new_expr;
7406 new_expr = new SimpleName (child_expr.Name, Identifier, loc);
7408 return new_expr.ResolveAsTypeStep (ec);
7411 Type expr_type = new_expr.Type;
7413 if (expr_type.IsPointer){
7414 Error (23, "The `.' operator can not be applied to pointer operands (" +
7415 TypeManager.CSharpName (expr_type) + ")");
7419 Expression member_lookup;
7420 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
7421 if (member_lookup == null)
7424 if (member_lookup is TypeExpr){
7425 member_lookup.Resolve (ec, ResolveFlags.Type);
7426 return member_lookup;
7432 public override void Emit (EmitContext ec)
7434 throw new Exception ("Should not happen");
7437 public override string ToString ()
7439 return expr + "." + Identifier;
7444 /// Implements checked expressions
7446 public class CheckedExpr : Expression {
7448 public Expression Expr;
7450 public CheckedExpr (Expression e, Location l)
7456 public override Expression DoResolve (EmitContext ec)
7458 bool last_check = ec.CheckState;
7459 bool last_const_check = ec.ConstantCheckState;
7461 ec.CheckState = true;
7462 ec.ConstantCheckState = true;
7463 Expr = Expr.Resolve (ec);
7464 ec.CheckState = last_check;
7465 ec.ConstantCheckState = last_const_check;
7470 if (Expr is Constant)
7473 eclass = Expr.eclass;
7478 public override void Emit (EmitContext ec)
7480 bool last_check = ec.CheckState;
7481 bool last_const_check = ec.ConstantCheckState;
7483 ec.CheckState = true;
7484 ec.ConstantCheckState = true;
7486 ec.CheckState = last_check;
7487 ec.ConstantCheckState = last_const_check;
7493 /// Implements the unchecked expression
7495 public class UnCheckedExpr : Expression {
7497 public Expression Expr;
7499 public UnCheckedExpr (Expression e, Location l)
7505 public override Expression DoResolve (EmitContext ec)
7507 bool last_check = ec.CheckState;
7508 bool last_const_check = ec.ConstantCheckState;
7510 ec.CheckState = false;
7511 ec.ConstantCheckState = false;
7512 Expr = Expr.Resolve (ec);
7513 ec.CheckState = last_check;
7514 ec.ConstantCheckState = last_const_check;
7519 if (Expr is Constant)
7522 eclass = Expr.eclass;
7527 public override void Emit (EmitContext ec)
7529 bool last_check = ec.CheckState;
7530 bool last_const_check = ec.ConstantCheckState;
7532 ec.CheckState = false;
7533 ec.ConstantCheckState = false;
7535 ec.CheckState = last_check;
7536 ec.ConstantCheckState = last_const_check;
7542 /// An Element Access expression.
7544 /// During semantic analysis these are transformed into
7545 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7547 public class ElementAccess : Expression {
7548 public ArrayList Arguments;
7549 public Expression Expr;
7551 public ElementAccess (Expression e, ArrayList e_list, Location l)
7560 Arguments = new ArrayList ();
7561 foreach (Expression tmp in e_list)
7562 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7566 bool CommonResolve (EmitContext ec)
7568 Expr = Expr.Resolve (ec);
7573 if (Arguments == null)
7576 foreach (Argument a in Arguments){
7577 if (!a.Resolve (ec, loc))
7584 Expression MakePointerAccess (EmitContext ec)
7588 if (t == TypeManager.void_ptr_type){
7589 Error (242, "The array index operation is not valid for void pointers");
7592 if (Arguments.Count != 1){
7593 Error (196, "A pointer must be indexed by a single value");
7598 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc).Resolve (ec);
7601 return new Indirection (p, loc).Resolve (ec);
7604 public override Expression DoResolve (EmitContext ec)
7606 if (!CommonResolve (ec))
7610 // We perform some simple tests, and then to "split" the emit and store
7611 // code we create an instance of a different class, and return that.
7613 // I am experimenting with this pattern.
7617 if (t == TypeManager.array_type){
7618 Report.Error (21, loc, "Cannot use indexer on System.Array");
7623 return (new ArrayAccess (this, loc)).Resolve (ec);
7624 else if (t.IsPointer)
7625 return MakePointerAccess (ec);
7627 return (new IndexerAccess (this, loc)).Resolve (ec);
7630 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7632 if (!CommonResolve (ec))
7637 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
7638 else if (t.IsPointer)
7639 return MakePointerAccess (ec);
7641 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
7644 public override void Emit (EmitContext ec)
7646 throw new Exception ("Should never be reached");
7651 /// Implements array access
7653 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7655 // Points to our "data" repository
7659 LocalTemporary temp;
7662 public ArrayAccess (ElementAccess ea_data, Location l)
7665 eclass = ExprClass.Variable;
7669 public override Expression DoResolve (EmitContext ec)
7672 ExprClass eclass = ea.Expr.eclass;
7674 // As long as the type is valid
7675 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7676 eclass == ExprClass.Value)) {
7677 ea.Expr.Error_UnexpectedKind ("variable or value");
7682 Type t = ea.Expr.Type;
7683 if (t.GetArrayRank () != ea.Arguments.Count){
7685 "Incorrect number of indexes for array " +
7686 " expected: " + t.GetArrayRank () + " got: " +
7687 ea.Arguments.Count);
7691 type = TypeManager.GetElementType (t);
7692 if (type.IsPointer && !ec.InUnsafe){
7693 UnsafeError (ea.Location);
7697 foreach (Argument a in ea.Arguments){
7698 Type argtype = a.Type;
7700 if (argtype == TypeManager.int32_type ||
7701 argtype == TypeManager.uint32_type ||
7702 argtype == TypeManager.int64_type ||
7703 argtype == TypeManager.uint64_type) {
7704 Constant c = a.Expr as Constant;
7705 if (c != null && c.IsNegative) {
7706 Report.Warning (251, 2, a.Expr.Location, "Indexing an array with a negative index (array indices always start at zero)");
7712 // Mhm. This is strage, because the Argument.Type is not the same as
7713 // Argument.Expr.Type: the value changes depending on the ref/out setting.
7715 // Wonder if I will run into trouble for this.
7717 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
7722 eclass = ExprClass.Variable;
7728 /// Emits the right opcode to load an object of Type `t'
7729 /// from an array of T
7731 static public void EmitLoadOpcode (ILGenerator ig, Type type)
7733 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7734 ig.Emit (OpCodes.Ldelem_U1);
7735 else if (type == TypeManager.sbyte_type)
7736 ig.Emit (OpCodes.Ldelem_I1);
7737 else if (type == TypeManager.short_type)
7738 ig.Emit (OpCodes.Ldelem_I2);
7739 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7740 ig.Emit (OpCodes.Ldelem_U2);
7741 else if (type == TypeManager.int32_type)
7742 ig.Emit (OpCodes.Ldelem_I4);
7743 else if (type == TypeManager.uint32_type)
7744 ig.Emit (OpCodes.Ldelem_U4);
7745 else if (type == TypeManager.uint64_type)
7746 ig.Emit (OpCodes.Ldelem_I8);
7747 else if (type == TypeManager.int64_type)
7748 ig.Emit (OpCodes.Ldelem_I8);
7749 else if (type == TypeManager.float_type)
7750 ig.Emit (OpCodes.Ldelem_R4);
7751 else if (type == TypeManager.double_type)
7752 ig.Emit (OpCodes.Ldelem_R8);
7753 else if (type == TypeManager.intptr_type)
7754 ig.Emit (OpCodes.Ldelem_I);
7755 else if (TypeManager.IsEnumType (type)){
7756 EmitLoadOpcode (ig, TypeManager.EnumToUnderlying (type));
7757 } else if (type.IsValueType){
7758 ig.Emit (OpCodes.Ldelema, type);
7759 ig.Emit (OpCodes.Ldobj, type);
7761 ig.Emit (OpCodes.Ldelem_Ref);
7765 /// Returns the right opcode to store an object of Type `t'
7766 /// from an array of T.
7768 static public OpCode GetStoreOpcode (Type t, out bool is_stobj)
7770 //Console.WriteLine (new System.Diagnostics.StackTrace ());
7772 t = TypeManager.TypeToCoreType (t);
7773 if (TypeManager.IsEnumType (t))
7774 t = TypeManager.EnumToUnderlying (t);
7775 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
7776 t == TypeManager.bool_type)
7777 return OpCodes.Stelem_I1;
7778 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
7779 t == TypeManager.char_type)
7780 return OpCodes.Stelem_I2;
7781 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
7782 return OpCodes.Stelem_I4;
7783 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
7784 return OpCodes.Stelem_I8;
7785 else if (t == TypeManager.float_type)
7786 return OpCodes.Stelem_R4;
7787 else if (t == TypeManager.double_type)
7788 return OpCodes.Stelem_R8;
7789 else if (t == TypeManager.intptr_type) {
7791 return OpCodes.Stobj;
7792 } else if (t.IsValueType) {
7794 return OpCodes.Stobj;
7796 return OpCodes.Stelem_Ref;
7799 MethodInfo FetchGetMethod ()
7801 ModuleBuilder mb = CodeGen.Module.Builder;
7802 int arg_count = ea.Arguments.Count;
7803 Type [] args = new Type [arg_count];
7806 for (int i = 0; i < arg_count; i++){
7807 //args [i++] = a.Type;
7808 args [i] = TypeManager.int32_type;
7811 get = mb.GetArrayMethod (
7812 ea.Expr.Type, "Get",
7813 CallingConventions.HasThis |
7814 CallingConventions.Standard,
7820 MethodInfo FetchAddressMethod ()
7822 ModuleBuilder mb = CodeGen.Module.Builder;
7823 int arg_count = ea.Arguments.Count;
7824 Type [] args = new Type [arg_count];
7828 ret_type = TypeManager.GetReferenceType (type);
7830 for (int i = 0; i < arg_count; i++){
7831 //args [i++] = a.Type;
7832 args [i] = TypeManager.int32_type;
7835 address = mb.GetArrayMethod (
7836 ea.Expr.Type, "Address",
7837 CallingConventions.HasThis |
7838 CallingConventions.Standard,
7845 // Load the array arguments into the stack.
7847 // If we have been requested to cache the values (cached_locations array
7848 // initialized), then load the arguments the first time and store them
7849 // in locals. otherwise load from local variables.
7851 void LoadArrayAndArguments (EmitContext ec)
7853 ILGenerator ig = ec.ig;
7856 foreach (Argument a in ea.Arguments){
7857 Type argtype = a.Expr.Type;
7861 if (argtype == TypeManager.int64_type)
7862 ig.Emit (OpCodes.Conv_Ovf_I);
7863 else if (argtype == TypeManager.uint64_type)
7864 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7868 public void Emit (EmitContext ec, bool leave_copy)
7870 int rank = ea.Expr.Type.GetArrayRank ();
7871 ILGenerator ig = ec.ig;
7874 LoadArrayAndArguments (ec);
7877 EmitLoadOpcode (ig, type);
7881 method = FetchGetMethod ();
7882 ig.Emit (OpCodes.Call, method);
7885 LoadFromPtr (ec.ig, this.type);
7888 ec.ig.Emit (OpCodes.Dup);
7889 temp = new LocalTemporary (ec, this.type);
7894 public override void Emit (EmitContext ec)
7899 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
7901 int rank = ea.Expr.Type.GetArrayRank ();
7902 ILGenerator ig = ec.ig;
7903 Type t = source.Type;
7904 prepared = prepare_for_load;
7906 if (prepare_for_load) {
7907 AddressOf (ec, AddressOp.LoadStore);
7908 ec.ig.Emit (OpCodes.Dup);
7911 ec.ig.Emit (OpCodes.Dup);
7912 temp = new LocalTemporary (ec, this.type);
7915 StoreFromPtr (ec.ig, t);
7923 LoadArrayAndArguments (ec);
7927 OpCode op = GetStoreOpcode (t, out is_stobj);
7929 // The stobj opcode used by value types will need
7930 // an address on the stack, not really an array/array
7934 ig.Emit (OpCodes.Ldelema, t);
7938 ec.ig.Emit (OpCodes.Dup);
7939 temp = new LocalTemporary (ec, this.type);
7944 ig.Emit (OpCodes.Stobj, t);
7948 ModuleBuilder mb = CodeGen.Module.Builder;
7949 int arg_count = ea.Arguments.Count;
7950 Type [] args = new Type [arg_count + 1];
7955 ec.ig.Emit (OpCodes.Dup);
7956 temp = new LocalTemporary (ec, this.type);
7960 for (int i = 0; i < arg_count; i++){
7961 //args [i++] = a.Type;
7962 args [i] = TypeManager.int32_type;
7965 args [arg_count] = type;
7967 set = mb.GetArrayMethod (
7968 ea.Expr.Type, "Set",
7969 CallingConventions.HasThis |
7970 CallingConventions.Standard,
7971 TypeManager.void_type, args);
7973 ig.Emit (OpCodes.Call, set);
7980 public void AddressOf (EmitContext ec, AddressOp mode)
7982 int rank = ea.Expr.Type.GetArrayRank ();
7983 ILGenerator ig = ec.ig;
7985 LoadArrayAndArguments (ec);
7988 ig.Emit (OpCodes.Ldelema, type);
7990 MethodInfo address = FetchAddressMethod ();
7991 ig.Emit (OpCodes.Call, address);
7998 public ArrayList Properties;
7999 static Hashtable map;
8001 public struct Indexer {
8002 public readonly Type Type;
8003 public readonly MethodInfo Getter, Setter;
8005 public Indexer (Type type, MethodInfo get, MethodInfo set)
8015 map = new Hashtable ();
8020 Properties = new ArrayList ();
8023 void Append (MemberInfo [] mi)
8025 foreach (PropertyInfo property in mi){
8026 MethodInfo get, set;
8028 get = property.GetGetMethod (true);
8029 set = property.GetSetMethod (true);
8030 Properties.Add (new Indexer (property.PropertyType, get, set));
8034 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
8036 string p_name = TypeManager.IndexerPropertyName (lookup_type);
8038 MemberInfo [] mi = TypeManager.MemberLookup (
8039 caller_type, caller_type, lookup_type, MemberTypes.Property,
8040 BindingFlags.Public | BindingFlags.Instance |
8041 BindingFlags.DeclaredOnly, p_name, null);
8043 if (mi == null || mi.Length == 0)
8049 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
8051 Indexers ix = (Indexers) map [lookup_type];
8056 Type copy = lookup_type;
8057 while (copy != TypeManager.object_type && copy != null){
8058 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
8062 ix = new Indexers ();
8067 copy = copy.BaseType;
8070 if (!lookup_type.IsInterface)
8073 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
8074 if (ifaces != null) {
8075 foreach (Type itype in ifaces) {
8076 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
8079 ix = new Indexers ();
8091 /// Expressions that represent an indexer call.
8093 public class IndexerAccess : Expression, IAssignMethod {
8095 // Points to our "data" repository
8097 MethodInfo get, set;
8098 ArrayList set_arguments;
8099 bool is_base_indexer;
8101 protected Type indexer_type;
8102 protected Type current_type;
8103 protected Expression instance_expr;
8104 protected ArrayList arguments;
8106 public IndexerAccess (ElementAccess ea, Location loc)
8107 : this (ea.Expr, false, loc)
8109 this.arguments = ea.Arguments;
8112 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
8115 this.instance_expr = instance_expr;
8116 this.is_base_indexer = is_base_indexer;
8117 this.eclass = ExprClass.Value;
8121 protected virtual bool CommonResolve (EmitContext ec)
8123 indexer_type = instance_expr.Type;
8124 current_type = ec.ContainerType;
8129 public override Expression DoResolve (EmitContext ec)
8131 ArrayList AllGetters = new ArrayList();
8132 if (!CommonResolve (ec))
8136 // Step 1: Query for all `Item' *properties*. Notice
8137 // that the actual methods are pointed from here.
8139 // This is a group of properties, piles of them.
8141 bool found_any = false, found_any_getters = false;
8142 Type lookup_type = indexer_type;
8145 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
8146 if (ilist != null) {
8148 if (ilist.Properties != null) {
8149 foreach (Indexers.Indexer ix in ilist.Properties) {
8150 if (ix.Getter != null)
8151 AllGetters.Add(ix.Getter);
8156 if (AllGetters.Count > 0) {
8157 found_any_getters = true;
8158 get = (MethodInfo) Invocation.OverloadResolve (
8159 ec, new MethodGroupExpr (AllGetters, loc),
8160 arguments, false, loc);
8164 Report.Error (21, loc,
8165 "Type `" + TypeManager.CSharpName (indexer_type) +
8166 "' does not have any indexers defined");
8170 if (!found_any_getters) {
8171 Error (154, "indexer can not be used in this context, because " +
8172 "it lacks a `get' accessor");
8177 Error (1501, "No Overload for method `this' takes `" +
8178 arguments.Count + "' arguments");
8183 // Only base will allow this invocation to happen.
8185 if (get.IsAbstract && this is BaseIndexerAccess){
8186 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
8190 type = get.ReturnType;
8191 if (type.IsPointer && !ec.InUnsafe){
8196 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8198 eclass = ExprClass.IndexerAccess;
8202 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8204 ArrayList AllSetters = new ArrayList();
8205 if (!CommonResolve (ec))
8208 bool found_any = false, found_any_setters = false;
8210 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
8211 if (ilist != null) {
8213 if (ilist.Properties != null) {
8214 foreach (Indexers.Indexer ix in ilist.Properties) {
8215 if (ix.Setter != null)
8216 AllSetters.Add(ix.Setter);
8220 if (AllSetters.Count > 0) {
8221 found_any_setters = true;
8222 set_arguments = (ArrayList) arguments.Clone ();
8223 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
8224 set = (MethodInfo) Invocation.OverloadResolve (
8225 ec, new MethodGroupExpr (AllSetters, loc),
8226 set_arguments, false, loc);
8230 Report.Error (21, loc,
8231 "Type `" + TypeManager.CSharpName (indexer_type) +
8232 "' does not have any indexers defined");
8236 if (!found_any_setters) {
8237 Error (154, "indexer can not be used in this context, because " +
8238 "it lacks a `set' accessor");
8243 Error (1501, "No Overload for method `this' takes `" +
8244 arguments.Count + "' arguments");
8249 // Only base will allow this invocation to happen.
8251 if (set.IsAbstract && this is BaseIndexerAccess){
8252 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
8257 // Now look for the actual match in the list of indexers to set our "return" type
8259 type = TypeManager.void_type; // default value
8260 foreach (Indexers.Indexer ix in ilist.Properties){
8261 if (ix.Setter == set){
8267 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8269 eclass = ExprClass.IndexerAccess;
8273 bool prepared = false;
8274 LocalTemporary temp;
8276 public void Emit (EmitContext ec, bool leave_copy)
8278 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc, prepared, false);
8280 ec.ig.Emit (OpCodes.Dup);
8281 temp = new LocalTemporary (ec, Type);
8287 // source is ignored, because we already have a copy of it from the
8288 // LValue resolution and we have already constructed a pre-cached
8289 // version of the arguments (ea.set_arguments);
8291 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8293 prepared = prepare_for_load;
8294 Argument a = (Argument) set_arguments [set_arguments.Count - 1];
8299 ec.ig.Emit (OpCodes.Dup);
8300 temp = new LocalTemporary (ec, Type);
8303 } else if (leave_copy) {
8304 temp = new LocalTemporary (ec, Type);
8310 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc, false, prepared);
8317 public override void Emit (EmitContext ec)
8324 /// The base operator for method names
8326 public class BaseAccess : Expression {
8329 public BaseAccess (string member, Location l)
8331 this.member = member;
8335 public override Expression DoResolve (EmitContext ec)
8337 Expression c = CommonResolve (ec);
8343 // MethodGroups use this opportunity to flag an error on lacking ()
8345 if (!(c is MethodGroupExpr))
8346 return c.Resolve (ec);
8350 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8352 Expression c = CommonResolve (ec);
8358 // MethodGroups use this opportunity to flag an error on lacking ()
8360 if (! (c is MethodGroupExpr))
8361 return c.DoResolveLValue (ec, right_side);
8366 Expression CommonResolve (EmitContext ec)
8368 Expression member_lookup;
8369 Type current_type = ec.ContainerType;
8370 Type base_type = current_type.BaseType;
8374 Error (1511, "Keyword base is not allowed in static method");
8378 if (ec.IsFieldInitializer){
8379 Error (1512, "Keyword base is not available in the current context");
8383 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type, member,
8384 AllMemberTypes, AllBindingFlags, loc);
8385 if (member_lookup == null) {
8386 MemberLookupFailed (ec, base_type, base_type, member, null, loc);
8393 left = new TypeExpression (base_type, loc);
8395 left = ec.GetThis (loc);
8397 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
8399 if (e is PropertyExpr){
8400 PropertyExpr pe = (PropertyExpr) e;
8405 if (e is MethodGroupExpr)
8406 ((MethodGroupExpr) e).IsBase = true;
8411 public override void Emit (EmitContext ec)
8413 throw new Exception ("Should never be called");
8418 /// The base indexer operator
8420 public class BaseIndexerAccess : IndexerAccess {
8421 public BaseIndexerAccess (ArrayList args, Location loc)
8422 : base (null, true, loc)
8424 arguments = new ArrayList ();
8425 foreach (Expression tmp in args)
8426 arguments.Add (new Argument (tmp, Argument.AType.Expression));
8429 protected override bool CommonResolve (EmitContext ec)
8431 instance_expr = ec.GetThis (loc);
8433 current_type = ec.ContainerType.BaseType;
8434 indexer_type = current_type;
8436 foreach (Argument a in arguments){
8437 if (!a.Resolve (ec, loc))
8446 /// This class exists solely to pass the Type around and to be a dummy
8447 /// that can be passed to the conversion functions (this is used by
8448 /// foreach implementation to typecast the object return value from
8449 /// get_Current into the proper type. All code has been generated and
8450 /// we only care about the side effect conversions to be performed
8452 /// This is also now used as a placeholder where a no-action expression
8453 /// is needed (the `New' class).
8455 public class EmptyExpression : Expression {
8456 public static readonly EmptyExpression Null = new EmptyExpression ();
8458 // TODO: should be protected
8459 public EmptyExpression ()
8461 type = TypeManager.object_type;
8462 eclass = ExprClass.Value;
8463 loc = Location.Null;
8466 public EmptyExpression (Type t)
8469 eclass = ExprClass.Value;
8470 loc = Location.Null;
8473 public override Expression DoResolve (EmitContext ec)
8478 public override void Emit (EmitContext ec)
8480 // nothing, as we only exist to not do anything.
8484 // This is just because we might want to reuse this bad boy
8485 // instead of creating gazillions of EmptyExpressions.
8486 // (CanImplicitConversion uses it)
8488 public void SetType (Type t)
8494 public class UserCast : Expression {
8498 public UserCast (MethodInfo method, Expression source, Location l)
8500 this.method = method;
8501 this.source = source;
8502 type = method.ReturnType;
8503 eclass = ExprClass.Value;
8507 public Expression Source {
8513 public override Expression DoResolve (EmitContext ec)
8516 // We are born fully resolved
8521 public override void Emit (EmitContext ec)
8523 ILGenerator ig = ec.ig;
8527 if (method is MethodInfo)
8528 ig.Emit (OpCodes.Call, (MethodInfo) method);
8530 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
8536 // This class is used to "construct" the type during a typecast
8537 // operation. Since the Type.GetType class in .NET can parse
8538 // the type specification, we just use this to construct the type
8539 // one bit at a time.
8541 public class ComposedCast : TypeExpr {
8545 public ComposedCast (Expression left, string dim, Location l)
8552 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
8554 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec, false);
8558 Type ltype = lexpr.ResolveType (ec);
8560 if ((ltype == TypeManager.void_type) && (dim != "*")) {
8561 Report.Error (1547, Location,
8562 "Keyword 'void' cannot be used in this context");
8567 // ltype.Fullname is already fully qualified, so we can skip
8568 // a lot of probes, and go directly to TypeManager.LookupType
8570 string cname = ltype.FullName + dim;
8571 type = TypeManager.LookupTypeDirect (cname);
8574 // For arrays of enumerations we are having a problem
8575 // with the direct lookup. Need to investigate.
8577 // For now, fall back to the full lookup in that case.
8579 type = RootContext.LookupType (
8580 ec.DeclSpace, cname, false, loc);
8586 if (!ec.InUnsafe && type.IsPointer){
8591 eclass = ExprClass.Type;
8595 public override string Name {
8603 // This class is used to represent the address of an array, used
8604 // only by the Fixed statement, this is like the C "&a [0]" construct.
8606 public class ArrayPtr : Expression {
8609 public ArrayPtr (Expression array, Location l)
8611 Type array_type = TypeManager.GetElementType (array.Type);
8615 type = TypeManager.GetPointerType (array_type);
8616 eclass = ExprClass.Value;
8620 public override void Emit (EmitContext ec)
8622 ILGenerator ig = ec.ig;
8625 IntLiteral.EmitInt (ig, 0);
8626 ig.Emit (OpCodes.Ldelema, TypeManager.GetElementType (array.Type));
8629 public override Expression DoResolve (EmitContext ec)
8632 // We are born fully resolved
8639 // Used by the fixed statement
8641 public class StringPtr : Expression {
8644 public StringPtr (LocalBuilder b, Location l)
8647 eclass = ExprClass.Value;
8648 type = TypeManager.char_ptr_type;
8652 public override Expression DoResolve (EmitContext ec)
8654 // This should never be invoked, we are born in fully
8655 // initialized state.
8660 public override void Emit (EmitContext ec)
8662 ILGenerator ig = ec.ig;
8664 ig.Emit (OpCodes.Ldloc, b);
8665 ig.Emit (OpCodes.Conv_I);
8666 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
8667 ig.Emit (OpCodes.Add);
8672 // Implements the `stackalloc' keyword
8674 public class StackAlloc : Expression {
8679 public StackAlloc (Expression type, Expression count, Location l)
8686 public override Expression DoResolve (EmitContext ec)
8688 count = count.Resolve (ec);
8692 if (count.Type != TypeManager.int32_type){
8693 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8698 Constant c = count as Constant;
8699 if (c != null && c.IsNegative) {
8700 Report.Error (247, loc, "Cannot use a negative size with stackalloc");
8704 if (ec.CurrentBranching.InCatch () ||
8705 ec.CurrentBranching.InFinally (true)) {
8707 "stackalloc can not be used in a catch or finally block");
8711 TypeExpr texpr = t.ResolveAsTypeTerminal (ec, false);
8715 otype = texpr.ResolveType (ec);
8717 if (!TypeManager.VerifyUnManaged (otype, loc))
8720 type = TypeManager.GetPointerType (otype);
8721 eclass = ExprClass.Value;
8726 public override void Emit (EmitContext ec)
8728 int size = GetTypeSize (otype);
8729 ILGenerator ig = ec.ig;
8732 ig.Emit (OpCodes.Sizeof, otype);
8734 IntConstant.EmitInt (ig, size);
8736 ig.Emit (OpCodes.Mul);
8737 ig.Emit (OpCodes.Localloc);