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)
326 Type expr_type = Expr.Type;
329 // Step 1: Perform Operator Overload location
334 op_name = oper_names [(int) Oper];
336 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
339 Expression e = StaticCallExpr.MakeSimpleCall (
340 ec, (MethodGroupExpr) mg, Expr, loc);
350 // Only perform numeric promotions on:
353 if (expr_type == null)
357 // Step 2: Default operations on CLI native types.
360 // Attempt to use a constant folding operation.
361 if (Expr is Constant){
364 if (Reduce (ec, (Constant) Expr, out result))
369 case Operator.LogicalNot:
370 if (expr_type != TypeManager.bool_type) {
371 Expr = ResolveBoolean (ec, Expr, loc);
378 type = TypeManager.bool_type;
381 case Operator.OnesComplement:
382 if (!((expr_type == TypeManager.int32_type) ||
383 (expr_type == TypeManager.uint32_type) ||
384 (expr_type == TypeManager.int64_type) ||
385 (expr_type == TypeManager.uint64_type) ||
386 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
389 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
391 type = TypeManager.int32_type;
394 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint32_type, loc);
396 type = TypeManager.uint32_type;
399 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
401 type = TypeManager.int64_type;
404 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint64_type, loc);
406 type = TypeManager.uint64_type;
415 case Operator.AddressOf:
416 if (Expr.eclass != ExprClass.Variable){
417 Error (211, "Cannot take the address of non-variables");
426 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
430 IVariable variable = Expr as IVariable;
431 if (!ec.InFixedInitializer && ((variable == null) || !variable.VerifyFixed (false))) {
432 Error (212, "You can only take the address of an unfixed expression inside " +
433 "of a fixed statement initializer");
437 if (ec.InFixedInitializer && ((variable != null) && variable.VerifyFixed (false))) {
438 Error (213, "You can not fix an already fixed expression");
442 LocalVariableReference lr = Expr as LocalVariableReference;
444 if (lr.local_info.IsCaptured){
445 AnonymousMethod.Error_AddressOfCapturedVar (lr.Name, loc);
448 lr.local_info.AddressTaken = true;
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);
456 type = TypeManager.GetPointerType (Expr.Type);
459 case Operator.Indirection:
465 if (!expr_type.IsPointer){
466 Error (193, "The * or -> operator can only be applied to pointers");
471 // We create an Indirection expression, because
472 // it can implement the IMemoryLocation.
474 return new Indirection (Expr, loc);
476 case Operator.UnaryPlus:
478 // A plus in front of something is just a no-op, so return the child.
482 case Operator.UnaryNegation:
484 // Deals with -literals
485 // int operator- (int x)
486 // long operator- (long x)
487 // float operator- (float f)
488 // double operator- (double d)
489 // decimal operator- (decimal d)
491 Expression expr = null;
494 // transform - - expr into expr
497 Unary unary = (Unary) Expr;
499 if (unary.Oper == Operator.UnaryNegation)
504 // perform numeric promotions to int,
508 // The following is inneficient, because we call
509 // ImplicitConversion too many times.
511 // It is also not clear if we should convert to Float
512 // or Double initially.
514 if (expr_type == TypeManager.uint32_type){
516 // FIXME: handle exception to this rule that
517 // permits the int value -2147483648 (-2^31) to
518 // bt wrote as a decimal interger literal
520 type = TypeManager.int64_type;
521 Expr = Convert.ImplicitConversion (ec, Expr, type, loc);
525 if (expr_type == TypeManager.uint64_type){
527 // FIXME: Handle exception of `long value'
528 // -92233720368547758087 (-2^63) to be wrote as
529 // decimal integer literal.
535 if (expr_type == TypeManager.float_type){
540 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
547 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
554 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.double_type, loc);
565 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
566 TypeManager.CSharpName (expr_type) + "'");
570 public override Expression DoResolve (EmitContext ec)
572 if (Oper == Operator.AddressOf)
573 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
575 Expr = Expr.Resolve (ec);
580 eclass = ExprClass.Value;
581 return ResolveOperator (ec);
584 public override Expression DoResolveLValue (EmitContext ec, Expression right)
586 if (Oper == Operator.Indirection)
587 return base.DoResolveLValue (ec, right);
589 Error (131, "The left-hand side of an assignment must be a " +
590 "variable, property or indexer");
594 public override void Emit (EmitContext ec)
596 ILGenerator ig = ec.ig;
599 case Operator.UnaryPlus:
600 throw new Exception ("This should be caught by Resolve");
602 case Operator.UnaryNegation:
604 ig.Emit (OpCodes.Ldc_I4_0);
605 if (type == TypeManager.int64_type)
606 ig.Emit (OpCodes.Conv_U8);
608 ig.Emit (OpCodes.Sub_Ovf);
611 ig.Emit (OpCodes.Neg);
616 case Operator.LogicalNot:
618 ig.Emit (OpCodes.Ldc_I4_0);
619 ig.Emit (OpCodes.Ceq);
622 case Operator.OnesComplement:
624 ig.Emit (OpCodes.Not);
627 case Operator.AddressOf:
628 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
632 throw new Exception ("This should not happen: Operator = "
637 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
639 if (Oper == Operator.LogicalNot)
640 Expr.EmitBranchable (ec, target, !onTrue);
642 base.EmitBranchable (ec, target, onTrue);
645 public override string ToString ()
647 return "Unary (" + Oper + ", " + Expr + ")";
653 // Unary operators are turned into Indirection expressions
654 // after semantic analysis (this is so we can take the address
655 // of an indirection).
657 public class Indirection : Expression, IMemoryLocation, IAssignMethod {
659 LocalTemporary temporary;
662 public Indirection (Expression expr, Location l)
665 this.type = TypeManager.GetElementType (expr.Type);
666 eclass = ExprClass.Variable;
670 void LoadExprValue (EmitContext ec)
674 public override void Emit (EmitContext ec)
679 LoadFromPtr (ec.ig, Type);
682 public void Emit (EmitContext ec, bool leave_copy)
686 ec.ig.Emit (OpCodes.Dup);
687 temporary = new LocalTemporary (ec, expr.Type);
688 temporary.Store (ec);
692 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
694 prepared = prepare_for_load;
698 if (prepare_for_load)
699 ec.ig.Emit (OpCodes.Dup);
703 ec.ig.Emit (OpCodes.Dup);
704 temporary = new LocalTemporary (ec, expr.Type);
705 temporary.Store (ec);
708 StoreFromPtr (ec.ig, type);
710 if (temporary != null)
714 public void AddressOf (EmitContext ec, AddressOp Mode)
719 public override Expression DoResolve (EmitContext ec)
722 // Born fully resolved
727 public override string ToString ()
729 return "*(" + expr + ")";
734 /// Unary Mutator expressions (pre and post ++ and --)
738 /// UnaryMutator implements ++ and -- expressions. It derives from
739 /// ExpressionStatement becuase the pre/post increment/decrement
740 /// operators can be used in a statement context.
742 /// FIXME: Idea, we could split this up in two classes, one simpler
743 /// for the common case, and one with the extra fields for more complex
744 /// classes (indexers require temporary access; overloaded require method)
747 public class UnaryMutator : ExpressionStatement {
749 public enum Mode : byte {
756 PreDecrement = IsDecrement,
757 PostIncrement = IsPost,
758 PostDecrement = IsPost | IsDecrement
762 bool is_expr = false;
763 bool recurse = false;
768 // This is expensive for the simplest case.
770 StaticCallExpr method;
772 public UnaryMutator (Mode m, Expression e, Location l)
779 static string OperName (Mode mode)
781 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
785 void Error23 (Type t)
788 23, "Operator " + OperName (mode) +
789 " cannot be applied to operand of type `" +
790 TypeManager.CSharpName (t) + "'");
794 /// Returns whether an object of type `t' can be incremented
795 /// or decremented with add/sub (ie, basically whether we can
796 /// use pre-post incr-decr operations on it, but it is not a
797 /// System.Decimal, which we require operator overloading to catch)
799 static bool IsIncrementableNumber (Type t)
801 return (t == TypeManager.sbyte_type) ||
802 (t == TypeManager.byte_type) ||
803 (t == TypeManager.short_type) ||
804 (t == TypeManager.ushort_type) ||
805 (t == TypeManager.int32_type) ||
806 (t == TypeManager.uint32_type) ||
807 (t == TypeManager.int64_type) ||
808 (t == TypeManager.uint64_type) ||
809 (t == TypeManager.char_type) ||
810 (t.IsSubclassOf (TypeManager.enum_type)) ||
811 (t == TypeManager.float_type) ||
812 (t == TypeManager.double_type) ||
813 (t.IsPointer && t != TypeManager.void_ptr_type);
816 Expression ResolveOperator (EmitContext ec)
818 Type expr_type = expr.Type;
821 // Step 1: Perform Operator Overload location
826 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
827 op_name = "op_Increment";
829 op_name = "op_Decrement";
831 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
833 if (mg == null && expr_type.BaseType != null)
834 mg = MemberLookup (ec, expr_type.BaseType, op_name,
835 MemberTypes.Method, AllBindingFlags, loc);
838 method = StaticCallExpr.MakeSimpleCall (
839 ec, (MethodGroupExpr) mg, expr, loc);
846 // The operand of the prefix/postfix increment decrement operators
847 // should be an expression that is classified as a variable,
848 // a property access or an indexer access
851 if (expr.eclass == ExprClass.Variable){
852 LocalVariableReference var = expr as LocalVariableReference;
853 if ((var != null) && var.IsReadOnly)
854 Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
855 if (IsIncrementableNumber (expr_type) ||
856 expr_type == TypeManager.decimal_type){
859 } else if (expr.eclass == ExprClass.IndexerAccess){
860 IndexerAccess ia = (IndexerAccess) expr;
862 expr = ia.ResolveLValue (ec, this);
867 } else if (expr.eclass == ExprClass.PropertyAccess){
868 PropertyExpr pe = (PropertyExpr) expr;
870 if (pe.VerifyAssignable ())
875 expr.Error_UnexpectedKind ("variable, indexer or property access", loc);
879 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
880 TypeManager.CSharpName (expr_type) + "'");
884 public override Expression DoResolve (EmitContext ec)
886 expr = expr.Resolve (ec);
891 eclass = ExprClass.Value;
892 return ResolveOperator (ec);
895 static int PtrTypeSize (Type t)
897 return GetTypeSize (TypeManager.GetElementType (t));
901 // Loads the proper "1" into the stack based on the type, then it emits the
902 // opcode for the operation requested
904 void LoadOneAndEmitOp (EmitContext ec, Type t)
907 // Measure if getting the typecode and using that is more/less efficient
908 // that comparing types. t.GetTypeCode() is an internal call.
910 ILGenerator ig = ec.ig;
912 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
913 LongConstant.EmitLong (ig, 1);
914 else if (t == TypeManager.double_type)
915 ig.Emit (OpCodes.Ldc_R8, 1.0);
916 else if (t == TypeManager.float_type)
917 ig.Emit (OpCodes.Ldc_R4, 1.0F);
918 else if (t.IsPointer){
919 int n = PtrTypeSize (t);
922 ig.Emit (OpCodes.Sizeof, t);
924 IntConstant.EmitInt (ig, n);
926 ig.Emit (OpCodes.Ldc_I4_1);
929 // Now emit the operation
932 if (t == TypeManager.int32_type ||
933 t == TypeManager.int64_type){
934 if ((mode & Mode.IsDecrement) != 0)
935 ig.Emit (OpCodes.Sub_Ovf);
937 ig.Emit (OpCodes.Add_Ovf);
938 } else if (t == TypeManager.uint32_type ||
939 t == TypeManager.uint64_type){
940 if ((mode & Mode.IsDecrement) != 0)
941 ig.Emit (OpCodes.Sub_Ovf_Un);
943 ig.Emit (OpCodes.Add_Ovf_Un);
945 if ((mode & Mode.IsDecrement) != 0)
946 ig.Emit (OpCodes.Sub_Ovf);
948 ig.Emit (OpCodes.Add_Ovf);
951 if ((mode & Mode.IsDecrement) != 0)
952 ig.Emit (OpCodes.Sub);
954 ig.Emit (OpCodes.Add);
957 if (t == TypeManager.sbyte_type){
959 ig.Emit (OpCodes.Conv_Ovf_I1);
961 ig.Emit (OpCodes.Conv_I1);
962 } else if (t == TypeManager.byte_type){
964 ig.Emit (OpCodes.Conv_Ovf_U1);
966 ig.Emit (OpCodes.Conv_U1);
967 } else if (t == TypeManager.short_type){
969 ig.Emit (OpCodes.Conv_Ovf_I2);
971 ig.Emit (OpCodes.Conv_I2);
972 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
974 ig.Emit (OpCodes.Conv_Ovf_U2);
976 ig.Emit (OpCodes.Conv_U2);
981 void EmitCode (EmitContext ec, bool is_expr)
984 this.is_expr = is_expr;
985 ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
989 public override void Emit (EmitContext ec)
992 // We use recurse to allow ourselfs to be the source
993 // of an assignment. This little hack prevents us from
994 // having to allocate another expression
997 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
999 LoadOneAndEmitOp (ec, expr.Type);
1001 ec.ig.Emit (OpCodes.Call, method.Method);
1006 EmitCode (ec, true);
1009 public override void EmitStatement (EmitContext ec)
1011 EmitCode (ec, false);
1016 /// Base class for the `Is' and `As' classes.
1020 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1023 public abstract class Probe : Expression {
1024 public Expression ProbeType;
1025 protected Expression expr;
1026 protected Type probe_type;
1028 public Probe (Expression expr, Expression probe_type, Location l)
1030 ProbeType = probe_type;
1035 public Expression Expr {
1041 public override Expression DoResolve (EmitContext ec)
1043 TypeExpr texpr = ProbeType.ResolveAsTypeTerminal (ec);
1046 probe_type = texpr.Type;
1048 CheckObsoleteAttribute (probe_type);
1050 expr = expr.Resolve (ec);
1054 if (expr.Type.IsPointer) {
1055 Report.Error (244, loc, "\"is\" or \"as\" are not valid on pointer types");
1063 /// Implementation of the `is' operator.
1065 public class Is : Probe {
1066 public Is (Expression expr, Expression probe_type, Location l)
1067 : base (expr, probe_type, l)
1072 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1077 public override void Emit (EmitContext ec)
1079 ILGenerator ig = ec.ig;
1084 case Action.AlwaysFalse:
1085 ig.Emit (OpCodes.Pop);
1086 IntConstant.EmitInt (ig, 0);
1088 case Action.AlwaysTrue:
1089 ig.Emit (OpCodes.Pop);
1090 IntConstant.EmitInt (ig, 1);
1092 case Action.LeaveOnStack:
1093 // the `e != null' rule.
1094 ig.Emit (OpCodes.Ldnull);
1095 ig.Emit (OpCodes.Ceq);
1096 ig.Emit (OpCodes.Ldc_I4_0);
1097 ig.Emit (OpCodes.Ceq);
1100 ig.Emit (OpCodes.Isinst, probe_type);
1101 ig.Emit (OpCodes.Ldnull);
1102 ig.Emit (OpCodes.Cgt_Un);
1105 throw new Exception ("never reached");
1108 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
1110 ILGenerator ig = ec.ig;
1113 case Action.AlwaysFalse:
1115 ig.Emit (OpCodes.Br, target);
1118 case Action.AlwaysTrue:
1120 ig.Emit (OpCodes.Br, target);
1123 case Action.LeaveOnStack:
1124 // the `e != null' rule.
1126 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1130 ig.Emit (OpCodes.Isinst, probe_type);
1131 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1134 throw new Exception ("never reached");
1137 public override Expression DoResolve (EmitContext ec)
1139 Expression e = base.DoResolve (ec);
1141 if ((e == null) || (expr == null))
1144 Type etype = expr.Type;
1145 bool warning_always_matches = false;
1146 bool warning_never_matches = false;
1148 type = TypeManager.bool_type;
1149 eclass = ExprClass.Value;
1152 // First case, if at compile time, there is an implicit conversion
1153 // then e != null (objects) or true (value types)
1155 e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1158 if (etype.IsValueType)
1159 action = Action.AlwaysTrue;
1161 action = Action.LeaveOnStack;
1163 warning_always_matches = true;
1164 } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1166 // Second case: explicit reference convresion
1168 if (expr is NullLiteral)
1169 action = Action.AlwaysFalse;
1171 action = Action.Probe;
1173 action = Action.AlwaysFalse;
1174 warning_never_matches = true;
1177 if (warning_always_matches)
1178 Warning (183, "The given expression is always of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1179 else if (warning_never_matches){
1180 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1181 Warning (184, "The given expression is never of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1189 /// Implementation of the `as' operator.
1191 public class As : Probe {
1192 public As (Expression expr, Expression probe_type, Location l)
1193 : base (expr, probe_type, l)
1197 bool do_isinst = false;
1199 public override void Emit (EmitContext ec)
1201 ILGenerator ig = ec.ig;
1206 ig.Emit (OpCodes.Isinst, probe_type);
1209 static void Error_CannotConvertType (Type source, Type target, Location loc)
1212 39, loc, "as operator can not convert from `" +
1213 TypeManager.CSharpName (source) + "' to `" +
1214 TypeManager.CSharpName (target) + "'");
1217 public override Expression DoResolve (EmitContext ec)
1219 Expression e = base.DoResolve (ec);
1225 eclass = ExprClass.Value;
1226 Type etype = expr.Type;
1228 if (TypeManager.IsValueType (probe_type)){
1229 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1230 TypeManager.CSharpName (probe_type) + " is a value type)");
1235 e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1242 if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1247 Error_CannotConvertType (etype, probe_type, loc);
1253 /// This represents a typecast in the source language.
1255 /// FIXME: Cast expressions have an unusual set of parsing
1256 /// rules, we need to figure those out.
1258 public class Cast : Expression {
1259 Expression target_type;
1262 public Cast (Expression cast_type, Expression expr, Location loc)
1264 this.target_type = cast_type;
1269 public Expression TargetType {
1275 public Expression Expr {
1284 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1286 if (!ec.ConstantCheckState)
1289 if ((value < min) || (value > max)) {
1290 Error (221, "Constant value `" + value + "' cannot be converted " +
1291 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1292 "syntax to override)");
1299 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1301 if (!ec.ConstantCheckState)
1305 Error (221, "Constant value `" + value + "' cannot be converted " +
1306 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1307 "syntax to override)");
1314 bool CheckUnsigned (EmitContext ec, long value, Type type)
1316 if (!ec.ConstantCheckState)
1320 Error (221, "Constant value `" + value + "' cannot be converted " +
1321 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1322 "syntax to override)");
1330 /// Attempts to do a compile-time folding of a constant cast.
1332 Expression TryReduce (EmitContext ec, Type target_type)
1334 Expression real_expr = expr;
1335 if (real_expr is EnumConstant)
1336 real_expr = ((EnumConstant) real_expr).Child;
1338 if (real_expr is ByteConstant){
1339 byte v = ((ByteConstant) real_expr).Value;
1341 if (target_type == TypeManager.sbyte_type) {
1342 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1344 return new SByteConstant ((sbyte) v);
1346 if (target_type == TypeManager.short_type)
1347 return new ShortConstant ((short) v);
1348 if (target_type == TypeManager.ushort_type)
1349 return new UShortConstant ((ushort) v);
1350 if (target_type == TypeManager.int32_type)
1351 return new IntConstant ((int) v);
1352 if (target_type == TypeManager.uint32_type)
1353 return new UIntConstant ((uint) v);
1354 if (target_type == TypeManager.int64_type)
1355 return new LongConstant ((long) v);
1356 if (target_type == TypeManager.uint64_type)
1357 return new ULongConstant ((ulong) v);
1358 if (target_type == TypeManager.float_type)
1359 return new FloatConstant ((float) v);
1360 if (target_type == TypeManager.double_type)
1361 return new DoubleConstant ((double) v);
1362 if (target_type == TypeManager.char_type)
1363 return new CharConstant ((char) v);
1364 if (target_type == TypeManager.decimal_type)
1365 return new DecimalConstant ((decimal) v);
1367 if (real_expr is SByteConstant){
1368 sbyte v = ((SByteConstant) real_expr).Value;
1370 if (target_type == TypeManager.byte_type) {
1371 if (!CheckUnsigned (ec, v, target_type))
1373 return new ByteConstant ((byte) v);
1375 if (target_type == TypeManager.short_type)
1376 return new ShortConstant ((short) v);
1377 if (target_type == TypeManager.ushort_type) {
1378 if (!CheckUnsigned (ec, v, target_type))
1380 return new UShortConstant ((ushort) v);
1381 } if (target_type == TypeManager.int32_type)
1382 return new IntConstant ((int) v);
1383 if (target_type == TypeManager.uint32_type) {
1384 if (!CheckUnsigned (ec, v, target_type))
1386 return new UIntConstant ((uint) v);
1387 } if (target_type == TypeManager.int64_type)
1388 return new LongConstant ((long) v);
1389 if (target_type == TypeManager.uint64_type) {
1390 if (!CheckUnsigned (ec, v, target_type))
1392 return new ULongConstant ((ulong) v);
1394 if (target_type == TypeManager.float_type)
1395 return new FloatConstant ((float) v);
1396 if (target_type == TypeManager.double_type)
1397 return new DoubleConstant ((double) v);
1398 if (target_type == TypeManager.char_type) {
1399 if (!CheckUnsigned (ec, v, target_type))
1401 return new CharConstant ((char) v);
1403 if (target_type == TypeManager.decimal_type)
1404 return new DecimalConstant ((decimal) v);
1406 if (real_expr is ShortConstant){
1407 short v = ((ShortConstant) real_expr).Value;
1409 if (target_type == TypeManager.byte_type) {
1410 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1412 return new ByteConstant ((byte) v);
1414 if (target_type == TypeManager.sbyte_type) {
1415 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1417 return new SByteConstant ((sbyte) v);
1419 if (target_type == TypeManager.ushort_type) {
1420 if (!CheckUnsigned (ec, v, target_type))
1422 return new UShortConstant ((ushort) v);
1424 if (target_type == TypeManager.int32_type)
1425 return new IntConstant ((int) v);
1426 if (target_type == TypeManager.uint32_type) {
1427 if (!CheckUnsigned (ec, v, target_type))
1429 return new UIntConstant ((uint) v);
1431 if (target_type == TypeManager.int64_type)
1432 return new LongConstant ((long) v);
1433 if (target_type == TypeManager.uint64_type) {
1434 if (!CheckUnsigned (ec, v, target_type))
1436 return new ULongConstant ((ulong) v);
1438 if (target_type == TypeManager.float_type)
1439 return new FloatConstant ((float) v);
1440 if (target_type == TypeManager.double_type)
1441 return new DoubleConstant ((double) v);
1442 if (target_type == TypeManager.char_type) {
1443 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1445 return new CharConstant ((char) v);
1447 if (target_type == TypeManager.decimal_type)
1448 return new DecimalConstant ((decimal) v);
1450 if (real_expr is UShortConstant){
1451 ushort v = ((UShortConstant) real_expr).Value;
1453 if (target_type == TypeManager.byte_type) {
1454 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1456 return new ByteConstant ((byte) v);
1458 if (target_type == TypeManager.sbyte_type) {
1459 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1461 return new SByteConstant ((sbyte) v);
1463 if (target_type == TypeManager.short_type) {
1464 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1466 return new ShortConstant ((short) v);
1468 if (target_type == TypeManager.int32_type)
1469 return new IntConstant ((int) v);
1470 if (target_type == TypeManager.uint32_type)
1471 return new UIntConstant ((uint) v);
1472 if (target_type == TypeManager.int64_type)
1473 return new LongConstant ((long) v);
1474 if (target_type == TypeManager.uint64_type)
1475 return new ULongConstant ((ulong) v);
1476 if (target_type == TypeManager.float_type)
1477 return new FloatConstant ((float) v);
1478 if (target_type == TypeManager.double_type)
1479 return new DoubleConstant ((double) v);
1480 if (target_type == TypeManager.char_type) {
1481 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1483 return new CharConstant ((char) v);
1485 if (target_type == TypeManager.decimal_type)
1486 return new DecimalConstant ((decimal) v);
1488 if (real_expr is IntConstant){
1489 int v = ((IntConstant) real_expr).Value;
1491 if (target_type == TypeManager.byte_type) {
1492 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1494 return new ByteConstant ((byte) v);
1496 if (target_type == TypeManager.sbyte_type) {
1497 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1499 return new SByteConstant ((sbyte) v);
1501 if (target_type == TypeManager.short_type) {
1502 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1504 return new ShortConstant ((short) v);
1506 if (target_type == TypeManager.ushort_type) {
1507 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1509 return new UShortConstant ((ushort) v);
1511 if (target_type == TypeManager.uint32_type) {
1512 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1514 return new UIntConstant ((uint) v);
1516 if (target_type == TypeManager.int64_type)
1517 return new LongConstant ((long) v);
1518 if (target_type == TypeManager.uint64_type) {
1519 if (!CheckUnsigned (ec, v, target_type))
1521 return new ULongConstant ((ulong) v);
1523 if (target_type == TypeManager.float_type)
1524 return new FloatConstant ((float) v);
1525 if (target_type == TypeManager.double_type)
1526 return new DoubleConstant ((double) v);
1527 if (target_type == TypeManager.char_type) {
1528 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1530 return new CharConstant ((char) v);
1532 if (target_type == TypeManager.decimal_type)
1533 return new DecimalConstant ((decimal) v);
1535 if (real_expr is UIntConstant){
1536 uint v = ((UIntConstant) real_expr).Value;
1538 if (target_type == TypeManager.byte_type) {
1539 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1541 return new ByteConstant ((byte) v);
1543 if (target_type == TypeManager.sbyte_type) {
1544 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1546 return new SByteConstant ((sbyte) v);
1548 if (target_type == TypeManager.short_type) {
1549 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1551 return new ShortConstant ((short) v);
1553 if (target_type == TypeManager.ushort_type) {
1554 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1556 return new UShortConstant ((ushort) v);
1558 if (target_type == TypeManager.int32_type) {
1559 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1561 return new IntConstant ((int) v);
1563 if (target_type == TypeManager.int64_type)
1564 return new LongConstant ((long) v);
1565 if (target_type == TypeManager.uint64_type)
1566 return new ULongConstant ((ulong) v);
1567 if (target_type == TypeManager.float_type)
1568 return new FloatConstant ((float) v);
1569 if (target_type == TypeManager.double_type)
1570 return new DoubleConstant ((double) v);
1571 if (target_type == TypeManager.char_type) {
1572 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1574 return new CharConstant ((char) v);
1576 if (target_type == TypeManager.decimal_type)
1577 return new DecimalConstant ((decimal) v);
1579 if (real_expr is LongConstant){
1580 long v = ((LongConstant) real_expr).Value;
1582 if (target_type == TypeManager.byte_type) {
1583 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1585 return new ByteConstant ((byte) v);
1587 if (target_type == TypeManager.sbyte_type) {
1588 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1590 return new SByteConstant ((sbyte) v);
1592 if (target_type == TypeManager.short_type) {
1593 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1595 return new ShortConstant ((short) v);
1597 if (target_type == TypeManager.ushort_type) {
1598 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1600 return new UShortConstant ((ushort) v);
1602 if (target_type == TypeManager.int32_type) {
1603 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1605 return new IntConstant ((int) v);
1607 if (target_type == TypeManager.uint32_type) {
1608 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1610 return new UIntConstant ((uint) v);
1612 if (target_type == TypeManager.uint64_type) {
1613 if (!CheckUnsigned (ec, v, target_type))
1615 return new ULongConstant ((ulong) v);
1617 if (target_type == TypeManager.float_type)
1618 return new FloatConstant ((float) v);
1619 if (target_type == TypeManager.double_type)
1620 return new DoubleConstant ((double) v);
1621 if (target_type == TypeManager.char_type) {
1622 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1624 return new CharConstant ((char) v);
1626 if (target_type == TypeManager.decimal_type)
1627 return new DecimalConstant ((decimal) v);
1629 if (real_expr is ULongConstant){
1630 ulong v = ((ULongConstant) real_expr).Value;
1632 if (target_type == TypeManager.byte_type) {
1633 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1635 return new ByteConstant ((byte) v);
1637 if (target_type == TypeManager.sbyte_type) {
1638 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1640 return new SByteConstant ((sbyte) v);
1642 if (target_type == TypeManager.short_type) {
1643 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1645 return new ShortConstant ((short) v);
1647 if (target_type == TypeManager.ushort_type) {
1648 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1650 return new UShortConstant ((ushort) v);
1652 if (target_type == TypeManager.int32_type) {
1653 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1655 return new IntConstant ((int) v);
1657 if (target_type == TypeManager.uint32_type) {
1658 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1660 return new UIntConstant ((uint) v);
1662 if (target_type == TypeManager.int64_type) {
1663 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1665 return new LongConstant ((long) v);
1667 if (target_type == TypeManager.float_type)
1668 return new FloatConstant ((float) v);
1669 if (target_type == TypeManager.double_type)
1670 return new DoubleConstant ((double) v);
1671 if (target_type == TypeManager.char_type) {
1672 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1674 return new CharConstant ((char) v);
1676 if (target_type == TypeManager.decimal_type)
1677 return new DecimalConstant ((decimal) v);
1679 if (real_expr is FloatConstant){
1680 float v = ((FloatConstant) real_expr).Value;
1682 if (target_type == TypeManager.byte_type)
1683 return new ByteConstant ((byte) v);
1684 if (target_type == TypeManager.sbyte_type)
1685 return new SByteConstant ((sbyte) v);
1686 if (target_type == TypeManager.short_type)
1687 return new ShortConstant ((short) v);
1688 if (target_type == TypeManager.ushort_type)
1689 return new UShortConstant ((ushort) v);
1690 if (target_type == TypeManager.int32_type)
1691 return new IntConstant ((int) v);
1692 if (target_type == TypeManager.uint32_type)
1693 return new UIntConstant ((uint) v);
1694 if (target_type == TypeManager.int64_type)
1695 return new LongConstant ((long) v);
1696 if (target_type == TypeManager.uint64_type)
1697 return new ULongConstant ((ulong) v);
1698 if (target_type == TypeManager.double_type)
1699 return new DoubleConstant ((double) v);
1700 if (target_type == TypeManager.char_type)
1701 return new CharConstant ((char) v);
1702 if (target_type == TypeManager.decimal_type)
1703 return new DecimalConstant ((decimal) v);
1705 if (real_expr is DoubleConstant){
1706 double v = ((DoubleConstant) real_expr).Value;
1708 if (target_type == TypeManager.byte_type){
1709 return new ByteConstant ((byte) v);
1710 } if (target_type == TypeManager.sbyte_type)
1711 return new SByteConstant ((sbyte) v);
1712 if (target_type == TypeManager.short_type)
1713 return new ShortConstant ((short) v);
1714 if (target_type == TypeManager.ushort_type)
1715 return new UShortConstant ((ushort) v);
1716 if (target_type == TypeManager.int32_type)
1717 return new IntConstant ((int) v);
1718 if (target_type == TypeManager.uint32_type)
1719 return new UIntConstant ((uint) v);
1720 if (target_type == TypeManager.int64_type)
1721 return new LongConstant ((long) v);
1722 if (target_type == TypeManager.uint64_type)
1723 return new ULongConstant ((ulong) v);
1724 if (target_type == TypeManager.float_type)
1725 return new FloatConstant ((float) v);
1726 if (target_type == TypeManager.char_type)
1727 return new CharConstant ((char) v);
1728 if (target_type == TypeManager.decimal_type)
1729 return new DecimalConstant ((decimal) v);
1732 if (real_expr is CharConstant){
1733 char v = ((CharConstant) real_expr).Value;
1735 if (target_type == TypeManager.byte_type) {
1736 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1738 return new ByteConstant ((byte) v);
1740 if (target_type == TypeManager.sbyte_type) {
1741 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1743 return new SByteConstant ((sbyte) v);
1745 if (target_type == TypeManager.short_type) {
1746 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1748 return new ShortConstant ((short) v);
1750 if (target_type == TypeManager.int32_type)
1751 return new IntConstant ((int) v);
1752 if (target_type == TypeManager.uint32_type)
1753 return new UIntConstant ((uint) v);
1754 if (target_type == TypeManager.int64_type)
1755 return new LongConstant ((long) v);
1756 if (target_type == TypeManager.uint64_type)
1757 return new ULongConstant ((ulong) v);
1758 if (target_type == TypeManager.float_type)
1759 return new FloatConstant ((float) v);
1760 if (target_type == TypeManager.double_type)
1761 return new DoubleConstant ((double) v);
1762 if (target_type == TypeManager.char_type) {
1763 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1765 return new CharConstant ((char) v);
1767 if (target_type == TypeManager.decimal_type)
1768 return new DecimalConstant ((decimal) v);
1774 public override Expression DoResolve (EmitContext ec)
1776 expr = expr.Resolve (ec);
1780 TypeExpr target = target_type.ResolveAsTypeTerminal (ec);
1786 CheckObsoleteAttribute (type);
1788 if (type.IsAbstract && type.IsSealed) {
1789 Report.Error (716, loc, "Cannot convert to static type '{0}'", TypeManager.CSharpName (type));
1793 eclass = ExprClass.Value;
1795 if (expr is Constant){
1796 Expression e = TryReduce (ec, type);
1802 if (type.IsPointer && !ec.InUnsafe) {
1806 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1810 public override void Emit (EmitContext ec)
1813 // This one will never happen
1815 throw new Exception ("Should not happen");
1820 /// Binary operators
1822 public class Binary : Expression {
1823 public enum Operator : byte {
1824 Multiply, Division, Modulus,
1825 Addition, Subtraction,
1826 LeftShift, RightShift,
1827 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1828 Equality, Inequality,
1838 Expression left, right;
1840 // This must be kept in sync with Operator!!!
1841 public static readonly string [] oper_names;
1845 oper_names = new string [(int) Operator.TOP];
1847 oper_names [(int) Operator.Multiply] = "op_Multiply";
1848 oper_names [(int) Operator.Division] = "op_Division";
1849 oper_names [(int) Operator.Modulus] = "op_Modulus";
1850 oper_names [(int) Operator.Addition] = "op_Addition";
1851 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1852 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1853 oper_names [(int) Operator.RightShift] = "op_RightShift";
1854 oper_names [(int) Operator.LessThan] = "op_LessThan";
1855 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1856 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1857 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1858 oper_names [(int) Operator.Equality] = "op_Equality";
1859 oper_names [(int) Operator.Inequality] = "op_Inequality";
1860 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1861 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1862 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1863 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1864 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1867 public Binary (Operator oper, Expression left, Expression right, Location loc)
1875 public Operator Oper {
1884 public Expression Left {
1893 public Expression Right {
1904 /// Returns a stringified representation of the Operator
1906 static string OperName (Operator oper)
1909 case Operator.Multiply:
1911 case Operator.Division:
1913 case Operator.Modulus:
1915 case Operator.Addition:
1917 case Operator.Subtraction:
1919 case Operator.LeftShift:
1921 case Operator.RightShift:
1923 case Operator.LessThan:
1925 case Operator.GreaterThan:
1927 case Operator.LessThanOrEqual:
1929 case Operator.GreaterThanOrEqual:
1931 case Operator.Equality:
1933 case Operator.Inequality:
1935 case Operator.BitwiseAnd:
1937 case Operator.BitwiseOr:
1939 case Operator.ExclusiveOr:
1941 case Operator.LogicalOr:
1943 case Operator.LogicalAnd:
1947 return oper.ToString ();
1950 public override string ToString ()
1952 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1953 right.ToString () + ")";
1956 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1958 if (expr.Type == target_type)
1961 return Convert.ImplicitConversion (ec, expr, target_type, loc);
1964 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1967 34, loc, "Operator `" + OperName (oper)
1968 + "' is ambiguous on operands of type `"
1969 + TypeManager.CSharpName (l) + "' "
1970 + "and `" + TypeManager.CSharpName (r)
1974 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
1976 if ((l == t) || (r == t))
1979 if (!check_user_conversions)
1982 if (Convert.ImplicitUserConversionExists (ec, l, t))
1984 else if (Convert.ImplicitUserConversionExists (ec, r, t))
1991 // Note that handling the case l == Decimal || r == Decimal
1992 // is taken care of by the Step 1 Operator Overload resolution.
1994 // If `check_user_conv' is true, we also check whether a user-defined conversion
1995 // exists. Note that we only need to do this if both arguments are of a user-defined
1996 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
1997 // so we don't explicitly check for performance reasons.
1999 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
2001 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
2003 // If either operand is of type double, the other operand is
2004 // conveted to type double.
2006 if (r != TypeManager.double_type)
2007 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
2008 if (l != TypeManager.double_type)
2009 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
2011 type = TypeManager.double_type;
2012 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
2014 // if either operand is of type float, the other operand is
2015 // converted to type float.
2017 if (r != TypeManager.double_type)
2018 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
2019 if (l != TypeManager.double_type)
2020 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
2021 type = TypeManager.float_type;
2022 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2026 // If either operand is of type ulong, the other operand is
2027 // converted to type ulong. or an error ocurrs if the other
2028 // operand is of type sbyte, short, int or long
2030 if (l == TypeManager.uint64_type){
2031 if (r != TypeManager.uint64_type){
2032 if (right is IntConstant){
2033 IntConstant ic = (IntConstant) right;
2035 e = Convert.TryImplicitIntConversion (l, ic);
2038 } else if (right is LongConstant){
2039 long ll = ((LongConstant) right).Value;
2042 right = new ULongConstant ((ulong) ll);
2044 e = Convert.ImplicitNumericConversion (ec, right, l, loc);
2051 if (left is IntConstant){
2052 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
2055 } else if (left is LongConstant){
2056 long ll = ((LongConstant) left).Value;
2059 left = new ULongConstant ((ulong) ll);
2061 e = Convert.ImplicitNumericConversion (ec, left, r, loc);
2068 if ((other == TypeManager.sbyte_type) ||
2069 (other == TypeManager.short_type) ||
2070 (other == TypeManager.int32_type) ||
2071 (other == TypeManager.int64_type))
2072 Error_OperatorAmbiguous (loc, oper, l, r);
2074 left = ForceConversion (ec, left, TypeManager.uint64_type);
2075 right = ForceConversion (ec, right, TypeManager.uint64_type);
2077 type = TypeManager.uint64_type;
2078 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2080 // If either operand is of type long, the other operand is converted
2083 if (l != TypeManager.int64_type)
2084 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
2085 if (r != TypeManager.int64_type)
2086 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
2088 type = TypeManager.int64_type;
2089 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2091 // If either operand is of type uint, and the other
2092 // operand is of type sbyte, short or int, othe operands are
2093 // converted to type long (unless we have an int constant).
2097 if (l == TypeManager.uint32_type){
2098 if (right is IntConstant){
2099 IntConstant ic = (IntConstant) right;
2103 right = new UIntConstant ((uint) val);
2110 } else if (r == TypeManager.uint32_type){
2111 if (left is IntConstant){
2112 IntConstant ic = (IntConstant) left;
2116 left = new UIntConstant ((uint) val);
2125 if ((other == TypeManager.sbyte_type) ||
2126 (other == TypeManager.short_type) ||
2127 (other == TypeManager.int32_type)){
2128 left = ForceConversion (ec, left, TypeManager.int64_type);
2129 right = ForceConversion (ec, right, TypeManager.int64_type);
2130 type = TypeManager.int64_type;
2133 // if either operand is of type uint, the other
2134 // operand is converd to type uint
2136 left = ForceConversion (ec, left, TypeManager.uint32_type);
2137 right = ForceConversion (ec, right, TypeManager.uint32_type);
2138 type = TypeManager.uint32_type;
2140 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2141 if (l != TypeManager.decimal_type)
2142 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
2144 if (r != TypeManager.decimal_type)
2145 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
2146 type = TypeManager.decimal_type;
2148 left = ForceConversion (ec, left, TypeManager.int32_type);
2149 right = ForceConversion (ec, right, TypeManager.int32_type);
2151 type = TypeManager.int32_type;
2154 return (left != null) && (right != null);
2157 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2159 Report.Error (19, loc,
2160 "Operator " + name + " cannot be applied to operands of type `" +
2161 TypeManager.CSharpName (l) + "' and `" +
2162 TypeManager.CSharpName (r) + "'");
2165 void Error_OperatorCannotBeApplied ()
2167 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2170 static bool is_unsigned (Type t)
2172 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2173 t == TypeManager.short_type || t == TypeManager.byte_type);
2176 static bool is_user_defined (Type t)
2178 if (t.IsSubclassOf (TypeManager.value_type) &&
2179 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2185 Expression Make32or64 (EmitContext ec, Expression e)
2189 if (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2190 t == TypeManager.int64_type || t == TypeManager.uint64_type)
2192 Expression ee = Convert.ImplicitConversion (ec, e, TypeManager.int32_type, loc);
2195 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint32_type, loc);
2198 ee = Convert.ImplicitConversion (ec, e, TypeManager.int64_type, loc);
2201 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint64_type, loc);
2207 Expression CheckShiftArguments (EmitContext ec)
2211 e = ForceConversion (ec, right, TypeManager.int32_type);
2213 Error_OperatorCannotBeApplied ();
2218 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
2219 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
2220 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
2221 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
2225 if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
2226 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (31), loc);
2227 right = right.DoResolve (ec);
2229 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (63), loc);
2230 right = right.DoResolve (ec);
2235 Error_OperatorCannotBeApplied ();
2239 Expression ResolveOperator (EmitContext ec)
2242 Type r = right.Type;
2245 // Special cases: string or type parameter comapred to null
2247 if (oper == Operator.Equality || oper == Operator.Inequality){
2248 if ((!TypeManager.IsValueType (l) && r == TypeManager.null_type) ||
2249 (!TypeManager.IsValueType (r) && l == TypeManager.null_type)) {
2250 Type = TypeManager.bool_type;
2255 if (l.IsGenericParameter && (right is NullLiteral)) {
2256 if (l.BaseType == TypeManager.value_type) {
2257 Error_OperatorCannotBeApplied ();
2261 left = new BoxedCast (left);
2262 Type = TypeManager.bool_type;
2266 if (r.IsGenericParameter && (left is NullLiteral)) {
2267 if (r.BaseType == TypeManager.value_type) {
2268 Error_OperatorCannotBeApplied ();
2272 right = new BoxedCast (right);
2273 Type = TypeManager.bool_type;
2278 if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
2279 Type = TypeManager.bool_type;
2286 // Do not perform operator overload resolution when both sides are
2289 if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
2291 // Step 1: Perform Operator Overload location
2293 Expression left_expr, right_expr;
2295 string op = oper_names [(int) oper];
2297 MethodGroupExpr union;
2298 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2300 right_expr = MemberLookup (
2301 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2302 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2304 union = (MethodGroupExpr) left_expr;
2306 if (union != null) {
2307 ArrayList args = new ArrayList (2);
2308 args.Add (new Argument (left, Argument.AType.Expression));
2309 args.Add (new Argument (right, Argument.AType.Expression));
2311 MethodBase method = Invocation.OverloadResolve (
2312 ec, union, args, true, Location.Null);
2314 if (method != null) {
2315 MethodInfo mi = (MethodInfo) method;
2317 return new BinaryMethod (mi.ReturnType, method, args);
2323 // Step 0: String concatenation (because overloading will get this wrong)
2325 if (oper == Operator.Addition){
2327 // If any of the arguments is a string, cast to string
2330 // Simple constant folding
2331 if (left is StringConstant && right is StringConstant)
2332 return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value);
2334 if (l == TypeManager.string_type || r == TypeManager.string_type) {
2336 if (r == TypeManager.void_type || l == TypeManager.void_type) {
2337 Error_OperatorCannotBeApplied ();
2341 // try to fold it in on the left
2342 if (left is StringConcat) {
2345 // We have to test here for not-null, since we can be doubly-resolved
2346 // take care of not appending twice
2349 type = TypeManager.string_type;
2350 ((StringConcat) left).Append (ec, right);
2351 return left.Resolve (ec);
2357 // Otherwise, start a new concat expression
2358 return new StringConcat (ec, loc, left, right).Resolve (ec);
2362 // Transform a + ( - b) into a - b
2364 if (right is Unary){
2365 Unary right_unary = (Unary) right;
2367 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2368 oper = Operator.Subtraction;
2369 right = right_unary.Expr;
2375 if (oper == Operator.Equality || oper == Operator.Inequality){
2376 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2377 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2378 Error_OperatorCannotBeApplied ();
2382 type = TypeManager.bool_type;
2387 // operator != (object a, object b)
2388 // operator == (object a, object b)
2390 // For this to be used, both arguments have to be reference-types.
2391 // Read the rationale on the spec (14.9.6)
2393 // Also, if at compile time we know that the classes do not inherit
2394 // one from the other, then we catch the error there.
2396 if (!(l.IsValueType || r.IsValueType)){
2397 type = TypeManager.bool_type;
2402 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2406 // Also, a standard conversion must exist from either one
2408 if (!(Convert.ImplicitStandardConversionExists (ec, left, r) ||
2409 Convert.ImplicitStandardConversionExists (ec, right, l))){
2410 Error_OperatorCannotBeApplied ();
2414 // We are going to have to convert to an object to compare
2416 if (l != TypeManager.object_type)
2417 left = new EmptyCast (left, TypeManager.object_type);
2418 if (r != TypeManager.object_type)
2419 right = new EmptyCast (right, TypeManager.object_type);
2422 // FIXME: CSC here catches errors cs254 and cs252
2428 // One of them is a valuetype, but the other one is not.
2430 if (!l.IsValueType || !r.IsValueType) {
2431 Error_OperatorCannotBeApplied ();
2436 // Only perform numeric promotions on:
2437 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2439 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2440 if (TypeManager.IsDelegateType (l)){
2441 if (((right.eclass == ExprClass.MethodGroup) ||
2442 (r == TypeManager.anonymous_method_type))){
2443 if ((RootContext.Version != LanguageVersion.ISO_1)){
2444 Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2452 if (TypeManager.IsDelegateType (r)){
2454 ArrayList args = new ArrayList (2);
2456 args = new ArrayList (2);
2457 args.Add (new Argument (left, Argument.AType.Expression));
2458 args.Add (new Argument (right, Argument.AType.Expression));
2460 if (oper == Operator.Addition)
2461 method = TypeManager.delegate_combine_delegate_delegate;
2463 method = TypeManager.delegate_remove_delegate_delegate;
2466 Error_OperatorCannotBeApplied ();
2470 return new BinaryDelegate (l, method, args);
2475 // Pointer arithmetic:
2477 // T* operator + (T* x, int y);
2478 // T* operator + (T* x, uint y);
2479 // T* operator + (T* x, long y);
2480 // T* operator + (T* x, ulong y);
2482 // T* operator + (int y, T* x);
2483 // T* operator + (uint y, T *x);
2484 // T* operator + (long y, T *x);
2485 // T* operator + (ulong y, T *x);
2487 // T* operator - (T* x, int y);
2488 // T* operator - (T* x, uint y);
2489 // T* operator - (T* x, long y);
2490 // T* operator - (T* x, ulong y);
2492 // long operator - (T* x, T *y)
2495 if (r.IsPointer && oper == Operator.Subtraction){
2497 return new PointerArithmetic (
2498 false, left, right, TypeManager.int64_type,
2501 Expression t = Make32or64 (ec, right);
2503 return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc).Resolve (ec);
2505 } else if (r.IsPointer && oper == Operator.Addition){
2506 Expression t = Make32or64 (ec, left);
2508 return new PointerArithmetic (true, right, t, r, loc).Resolve (ec);
2513 // Enumeration operators
2515 bool lie = TypeManager.IsEnumType (l);
2516 bool rie = TypeManager.IsEnumType (r);
2520 // U operator - (E e, E f)
2522 if (oper == Operator.Subtraction){
2524 type = TypeManager.EnumToUnderlying (l);
2527 Error_OperatorCannotBeApplied ();
2533 // operator + (E e, U x)
2534 // operator - (E e, U x)
2536 if (oper == Operator.Addition || oper == Operator.Subtraction){
2537 Type enum_type = lie ? l : r;
2538 Type other_type = lie ? r : l;
2539 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2541 if (underlying_type != other_type){
2542 temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
2552 Error_OperatorCannotBeApplied ();
2561 temp = Convert.ImplicitConversion (ec, right, l, loc);
2565 Error_OperatorCannotBeApplied ();
2569 temp = Convert.ImplicitConversion (ec, left, r, loc);
2574 Error_OperatorCannotBeApplied ();
2579 if (oper == Operator.Equality || oper == Operator.Inequality ||
2580 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2581 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2582 if (left.Type != right.Type){
2583 Error_OperatorCannotBeApplied ();
2586 type = TypeManager.bool_type;
2590 if (oper == Operator.BitwiseAnd ||
2591 oper == Operator.BitwiseOr ||
2592 oper == Operator.ExclusiveOr){
2596 Error_OperatorCannotBeApplied ();
2600 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2601 return CheckShiftArguments (ec);
2603 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2604 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2605 type = TypeManager.bool_type;
2610 Error_OperatorCannotBeApplied ();
2614 Expression e = new ConditionalLogicalOperator (
2615 oper == Operator.LogicalAnd, left, right, l, loc);
2616 return e.Resolve (ec);
2620 // operator & (bool x, bool y)
2621 // operator | (bool x, bool y)
2622 // operator ^ (bool x, bool y)
2624 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2625 if (oper == Operator.BitwiseAnd ||
2626 oper == Operator.BitwiseOr ||
2627 oper == Operator.ExclusiveOr){
2634 // Pointer comparison
2636 if (l.IsPointer && r.IsPointer){
2637 if (oper == Operator.Equality || oper == Operator.Inequality ||
2638 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2639 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2640 type = TypeManager.bool_type;
2646 // This will leave left or right set to null if there is an error
2648 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2649 DoNumericPromotions (ec, l, r, check_user_conv);
2650 if (left == null || right == null){
2651 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2656 // reload our cached types if required
2661 if (oper == Operator.BitwiseAnd ||
2662 oper == Operator.BitwiseOr ||
2663 oper == Operator.ExclusiveOr){
2665 if (((l == TypeManager.int32_type) ||
2666 (l == TypeManager.uint32_type) ||
2667 (l == TypeManager.short_type) ||
2668 (l == TypeManager.ushort_type) ||
2669 (l == TypeManager.int64_type) ||
2670 (l == TypeManager.uint64_type))){
2673 Error_OperatorCannotBeApplied ();
2677 Error_OperatorCannotBeApplied ();
2682 if (oper == Operator.Equality ||
2683 oper == Operator.Inequality ||
2684 oper == Operator.LessThanOrEqual ||
2685 oper == Operator.LessThan ||
2686 oper == Operator.GreaterThanOrEqual ||
2687 oper == Operator.GreaterThan){
2688 type = TypeManager.bool_type;
2694 public override Expression DoResolve (EmitContext ec)
2696 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2697 left = ((ParenthesizedExpression) left).Expr;
2698 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2702 if (left.eclass == ExprClass.Type) {
2703 Error (75, "Casting a negative value needs to have the value in parentheses.");
2707 left = left.Resolve (ec);
2708 right = right.Resolve (ec);
2710 if (left == null || right == null)
2713 eclass = ExprClass.Value;
2715 Constant rc = right as Constant;
2716 Constant lc = left as Constant;
2718 if (rc != null & lc != null){
2719 Expression e = ConstantFold.BinaryFold (
2720 ec, oper, lc, rc, loc);
2725 return ResolveOperator (ec);
2729 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2730 /// context of a conditional bool expression. This function will return
2731 /// false if it is was possible to use EmitBranchable, or true if it was.
2733 /// The expression's code is generated, and we will generate a branch to `target'
2734 /// if the resulting expression value is equal to isTrue
2736 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2738 ILGenerator ig = ec.ig;
2741 // This is more complicated than it looks, but its just to avoid
2742 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2743 // but on top of that we want for == and != to use a special path
2744 // if we are comparing against null
2746 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
2747 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2750 // put the constant on the rhs, for simplicity
2752 if (left is Constant) {
2753 Expression swap = right;
2758 if (((Constant) right).IsZeroInteger) {
2761 ig.Emit (OpCodes.Brtrue, target);
2763 ig.Emit (OpCodes.Brfalse, target);
2766 } else if (right is BoolConstant){
2768 if (my_on_true != ((BoolConstant) right).Value)
2769 ig.Emit (OpCodes.Brtrue, target);
2771 ig.Emit (OpCodes.Brfalse, target);
2776 } else if (oper == Operator.LogicalAnd) {
2779 Label tests_end = ig.DefineLabel ();
2781 left.EmitBranchable (ec, tests_end, false);
2782 right.EmitBranchable (ec, target, true);
2783 ig.MarkLabel (tests_end);
2785 left.EmitBranchable (ec, target, false);
2786 right.EmitBranchable (ec, target, false);
2791 } else if (oper == Operator.LogicalOr){
2793 left.EmitBranchable (ec, target, true);
2794 right.EmitBranchable (ec, target, true);
2797 Label tests_end = ig.DefineLabel ();
2798 left.EmitBranchable (ec, tests_end, true);
2799 right.EmitBranchable (ec, target, false);
2800 ig.MarkLabel (tests_end);
2805 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2806 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2807 oper == Operator.Equality || oper == Operator.Inequality)) {
2808 base.EmitBranchable (ec, target, onTrue);
2816 bool isUnsigned = is_unsigned (t) || t == TypeManager.double_type || t == TypeManager.float_type;
2819 case Operator.Equality:
2821 ig.Emit (OpCodes.Beq, target);
2823 ig.Emit (OpCodes.Bne_Un, target);
2826 case Operator.Inequality:
2828 ig.Emit (OpCodes.Bne_Un, target);
2830 ig.Emit (OpCodes.Beq, target);
2833 case Operator.LessThan:
2836 ig.Emit (OpCodes.Blt_Un, target);
2838 ig.Emit (OpCodes.Blt, target);
2841 ig.Emit (OpCodes.Bge_Un, target);
2843 ig.Emit (OpCodes.Bge, target);
2846 case Operator.GreaterThan:
2849 ig.Emit (OpCodes.Bgt_Un, target);
2851 ig.Emit (OpCodes.Bgt, target);
2854 ig.Emit (OpCodes.Ble_Un, target);
2856 ig.Emit (OpCodes.Ble, target);
2859 case Operator.LessThanOrEqual:
2862 ig.Emit (OpCodes.Ble_Un, target);
2864 ig.Emit (OpCodes.Ble, target);
2867 ig.Emit (OpCodes.Bgt_Un, target);
2869 ig.Emit (OpCodes.Bgt, target);
2873 case Operator.GreaterThanOrEqual:
2876 ig.Emit (OpCodes.Bge_Un, target);
2878 ig.Emit (OpCodes.Bge, target);
2881 ig.Emit (OpCodes.Blt_Un, target);
2883 ig.Emit (OpCodes.Blt, target);
2886 Console.WriteLine (oper);
2887 throw new Exception ("what is THAT");
2891 public override void Emit (EmitContext ec)
2893 ILGenerator ig = ec.ig;
2898 // Handle short-circuit operators differently
2901 if (oper == Operator.LogicalAnd) {
2902 Label load_zero = ig.DefineLabel ();
2903 Label end = ig.DefineLabel ();
2905 left.EmitBranchable (ec, load_zero, false);
2907 ig.Emit (OpCodes.Br, end);
2909 ig.MarkLabel (load_zero);
2910 ig.Emit (OpCodes.Ldc_I4_0);
2913 } else if (oper == Operator.LogicalOr) {
2914 Label load_one = ig.DefineLabel ();
2915 Label end = ig.DefineLabel ();
2917 left.EmitBranchable (ec, load_one, true);
2919 ig.Emit (OpCodes.Br, end);
2921 ig.MarkLabel (load_one);
2922 ig.Emit (OpCodes.Ldc_I4_1);
2930 bool isUnsigned = is_unsigned (left.Type);
2933 case Operator.Multiply:
2935 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2936 opcode = OpCodes.Mul_Ovf;
2937 else if (isUnsigned)
2938 opcode = OpCodes.Mul_Ovf_Un;
2940 opcode = OpCodes.Mul;
2942 opcode = OpCodes.Mul;
2946 case Operator.Division:
2948 opcode = OpCodes.Div_Un;
2950 opcode = OpCodes.Div;
2953 case Operator.Modulus:
2955 opcode = OpCodes.Rem_Un;
2957 opcode = OpCodes.Rem;
2960 case Operator.Addition:
2962 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2963 opcode = OpCodes.Add_Ovf;
2964 else if (isUnsigned)
2965 opcode = OpCodes.Add_Ovf_Un;
2967 opcode = OpCodes.Add;
2969 opcode = OpCodes.Add;
2972 case Operator.Subtraction:
2974 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2975 opcode = OpCodes.Sub_Ovf;
2976 else if (isUnsigned)
2977 opcode = OpCodes.Sub_Ovf_Un;
2979 opcode = OpCodes.Sub;
2981 opcode = OpCodes.Sub;
2984 case Operator.RightShift:
2986 opcode = OpCodes.Shr_Un;
2988 opcode = OpCodes.Shr;
2991 case Operator.LeftShift:
2992 opcode = OpCodes.Shl;
2995 case Operator.Equality:
2996 opcode = OpCodes.Ceq;
2999 case Operator.Inequality:
3000 ig.Emit (OpCodes.Ceq);
3001 ig.Emit (OpCodes.Ldc_I4_0);
3003 opcode = OpCodes.Ceq;
3006 case Operator.LessThan:
3008 opcode = OpCodes.Clt_Un;
3010 opcode = OpCodes.Clt;
3013 case Operator.GreaterThan:
3015 opcode = OpCodes.Cgt_Un;
3017 opcode = OpCodes.Cgt;
3020 case Operator.LessThanOrEqual:
3021 Type lt = left.Type;
3023 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
3024 ig.Emit (OpCodes.Cgt_Un);
3026 ig.Emit (OpCodes.Cgt);
3027 ig.Emit (OpCodes.Ldc_I4_0);
3029 opcode = OpCodes.Ceq;
3032 case Operator.GreaterThanOrEqual:
3033 Type le = left.Type;
3035 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3036 ig.Emit (OpCodes.Clt_Un);
3038 ig.Emit (OpCodes.Clt);
3040 ig.Emit (OpCodes.Ldc_I4_0);
3042 opcode = OpCodes.Ceq;
3045 case Operator.BitwiseOr:
3046 opcode = OpCodes.Or;
3049 case Operator.BitwiseAnd:
3050 opcode = OpCodes.And;
3053 case Operator.ExclusiveOr:
3054 opcode = OpCodes.Xor;
3058 throw new Exception ("This should not happen: Operator = "
3059 + oper.ToString ());
3067 // Object created by Binary when the binary operator uses an method instead of being
3068 // a binary operation that maps to a CIL binary operation.
3070 public class BinaryMethod : Expression {
3071 public MethodBase method;
3072 public ArrayList Arguments;
3074 public BinaryMethod (Type t, MethodBase m, ArrayList args)
3079 eclass = ExprClass.Value;
3082 public override Expression DoResolve (EmitContext ec)
3087 public override void Emit (EmitContext ec)
3089 ILGenerator ig = ec.ig;
3091 if (Arguments != null)
3092 Invocation.EmitArguments (ec, method, Arguments, false, null);
3094 if (method is MethodInfo)
3095 ig.Emit (OpCodes.Call, (MethodInfo) method);
3097 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3102 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3103 // b, c, d... may be strings or objects.
3105 public class StringConcat : Expression {
3107 bool invalid = false;
3108 bool emit_conv_done = false;
3110 // Are we also concating objects?
3112 bool is_strings_only = true;
3114 public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
3117 type = TypeManager.string_type;
3118 eclass = ExprClass.Value;
3120 operands = new ArrayList (2);
3125 public override Expression DoResolve (EmitContext ec)
3133 public void Append (EmitContext ec, Expression operand)
3138 if (operand is StringConstant && operands.Count != 0) {
3139 StringConstant last_operand = operands [operands.Count - 1] as StringConstant;
3140 if (last_operand != null) {
3141 operands [operands.Count - 1] = new StringConstant (last_operand.Value + ((StringConstant) operand).Value);
3147 // Conversion to object
3149 if (operand.Type != TypeManager.string_type) {
3150 Expression no = Convert.ImplicitConversion (ec, operand, TypeManager.object_type, loc);
3153 Binary.Error_OperatorCannotBeApplied (loc, "+", TypeManager.string_type, operand.Type);
3159 operands.Add (operand);
3162 public override void Emit (EmitContext ec)
3164 MethodInfo concat_method = null;
3167 // Do conversion to arguments; check for strings only
3170 // This can get called multiple times, so we have to deal with that.
3171 if (!emit_conv_done) {
3172 emit_conv_done = true;
3173 for (int i = 0; i < operands.Count; i ++) {
3174 Expression e = (Expression) operands [i];
3175 is_strings_only &= e.Type == TypeManager.string_type;
3178 for (int i = 0; i < operands.Count; i ++) {
3179 Expression e = (Expression) operands [i];
3181 if (! is_strings_only && e.Type == TypeManager.string_type) {
3182 // need to make sure this is an object, because the EmitParams
3183 // method might look at the type of this expression, see it is a
3184 // string and emit a string [] when we want an object [];
3186 e = new EmptyCast (e, TypeManager.object_type);
3188 operands [i] = new Argument (e, Argument.AType.Expression);
3193 // Find the right method
3195 switch (operands.Count) {
3198 // This should not be possible, because simple constant folding
3199 // is taken care of in the Binary code.
3201 throw new Exception ("how did you get here?");
3204 concat_method = is_strings_only ?
3205 TypeManager.string_concat_string_string :
3206 TypeManager.string_concat_object_object ;
3209 concat_method = is_strings_only ?
3210 TypeManager.string_concat_string_string_string :
3211 TypeManager.string_concat_object_object_object ;
3215 // There is not a 4 param overlaod for object (the one that there is
3216 // is actually a varargs methods, and is only in corlib because it was
3217 // introduced there before.).
3219 if (!is_strings_only)
3222 concat_method = TypeManager.string_concat_string_string_string_string;
3225 concat_method = is_strings_only ?
3226 TypeManager.string_concat_string_dot_dot_dot :
3227 TypeManager.string_concat_object_dot_dot_dot ;
3231 Invocation.EmitArguments (ec, concat_method, operands, false, null);
3232 ec.ig.Emit (OpCodes.Call, concat_method);
3237 // Object created with +/= on delegates
3239 public class BinaryDelegate : Expression {
3243 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3248 eclass = ExprClass.Value;
3251 public override Expression DoResolve (EmitContext ec)
3256 public override void Emit (EmitContext ec)
3258 ILGenerator ig = ec.ig;
3260 Invocation.EmitArguments (ec, method, args, false, null);
3262 ig.Emit (OpCodes.Call, (MethodInfo) method);
3263 ig.Emit (OpCodes.Castclass, type);
3266 public Expression Right {
3268 Argument arg = (Argument) args [1];
3273 public bool IsAddition {
3275 return method == TypeManager.delegate_combine_delegate_delegate;
3281 // User-defined conditional logical operator
3282 public class ConditionalLogicalOperator : Expression {
3283 Expression left, right;
3286 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3289 eclass = ExprClass.Value;
3293 this.is_and = is_and;
3296 protected void Error19 ()
3298 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3301 protected void Error218 ()
3303 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3304 "declarations of operator true and operator false");
3307 Expression op_true, op_false, op;
3308 LocalTemporary left_temp;
3310 public override Expression DoResolve (EmitContext ec)
3313 Expression operator_group;
3315 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3316 if (operator_group == null) {
3321 left_temp = new LocalTemporary (ec, type);
3323 ArrayList arguments = new ArrayList ();
3324 arguments.Add (new Argument (left_temp, Argument.AType.Expression));
3325 arguments.Add (new Argument (right, Argument.AType.Expression));
3326 method = Invocation.OverloadResolve (
3327 ec, (MethodGroupExpr) operator_group, arguments, false, loc)
3329 if ((method == null) || (method.ReturnType != type)) {
3334 op = new StaticCallExpr (method, arguments, loc);
3336 op_true = GetOperatorTrue (ec, left_temp, loc);
3337 op_false = GetOperatorFalse (ec, left_temp, loc);
3338 if ((op_true == null) || (op_false == null)) {
3346 public override void Emit (EmitContext ec)
3348 ILGenerator ig = ec.ig;
3349 Label false_target = ig.DefineLabel ();
3350 Label end_target = ig.DefineLabel ();
3353 left_temp.Store (ec);
3355 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
3356 left_temp.Emit (ec);
3357 ig.Emit (OpCodes.Br, end_target);
3358 ig.MarkLabel (false_target);
3360 ig.MarkLabel (end_target);
3364 public class PointerArithmetic : Expression {
3365 Expression left, right;
3369 // We assume that `l' is always a pointer
3371 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3377 is_add = is_addition;
3380 public override Expression DoResolve (EmitContext ec)
3382 eclass = ExprClass.Variable;
3384 if (left.Type == TypeManager.void_ptr_type) {
3385 Error (242, "The operation in question is undefined on void pointers");
3392 public override void Emit (EmitContext ec)
3394 Type op_type = left.Type;
3395 ILGenerator ig = ec.ig;
3396 Type element = TypeManager.GetElementType (op_type);
3397 int size = GetTypeSize (element);
3398 Type rtype = right.Type;
3400 if (rtype.IsPointer){
3402 // handle (pointer - pointer)
3406 ig.Emit (OpCodes.Sub);
3410 ig.Emit (OpCodes.Sizeof, element);
3412 IntLiteral.EmitInt (ig, size);
3413 ig.Emit (OpCodes.Div);
3415 ig.Emit (OpCodes.Conv_I8);
3418 // handle + and - on (pointer op int)
3421 ig.Emit (OpCodes.Conv_I);
3425 ig.Emit (OpCodes.Sizeof, element);
3427 IntLiteral.EmitInt (ig, size);
3428 if (rtype == TypeManager.int64_type)
3429 ig.Emit (OpCodes.Conv_I8);
3430 else if (rtype == TypeManager.uint64_type)
3431 ig.Emit (OpCodes.Conv_U8);
3432 ig.Emit (OpCodes.Mul);
3435 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
3436 ig.Emit (OpCodes.Conv_I);
3439 ig.Emit (OpCodes.Add);
3441 ig.Emit (OpCodes.Sub);
3447 /// Implements the ternary conditional operator (?:)
3449 public class Conditional : Expression {
3450 Expression expr, trueExpr, falseExpr;
3452 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3455 this.trueExpr = trueExpr;
3456 this.falseExpr = falseExpr;
3460 public Expression Expr {
3466 public Expression TrueExpr {
3472 public Expression FalseExpr {
3478 public override Expression DoResolve (EmitContext ec)
3480 expr = expr.Resolve (ec);
3485 if (expr.Type != TypeManager.bool_type){
3486 expr = Expression.ResolveBoolean (
3493 trueExpr = trueExpr.Resolve (ec);
3494 falseExpr = falseExpr.Resolve (ec);
3496 if (trueExpr == null || falseExpr == null)
3499 eclass = ExprClass.Value;
3500 if (trueExpr.Type == falseExpr.Type)
3501 type = trueExpr.Type;
3504 Type true_type = trueExpr.Type;
3505 Type false_type = falseExpr.Type;
3508 // First, if an implicit conversion exists from trueExpr
3509 // to falseExpr, then the result type is of type falseExpr.Type
3511 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3514 // Check if both can convert implicitl to each other's type
3516 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3518 "Can not compute type of conditional expression " +
3519 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3520 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3521 "' convert implicitly to each other");
3526 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3530 Error (173, "The type of the conditional expression can " +
3531 "not be computed because there is no implicit conversion" +
3532 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3533 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3538 if (expr is BoolConstant){
3539 BoolConstant bc = (BoolConstant) expr;
3550 public override void Emit (EmitContext ec)
3552 ILGenerator ig = ec.ig;
3553 Label false_target = ig.DefineLabel ();
3554 Label end_target = ig.DefineLabel ();
3556 expr.EmitBranchable (ec, false_target, false);
3558 ig.Emit (OpCodes.Br, end_target);
3559 ig.MarkLabel (false_target);
3560 falseExpr.Emit (ec);
3561 ig.MarkLabel (end_target);
3569 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3570 public readonly string Name;
3571 public readonly Block Block;
3572 public LocalInfo local_info;
3575 LocalTemporary temp;
3577 public LocalVariableReference (Block block, string name, Location l)
3582 eclass = ExprClass.Variable;
3586 // Setting `is_readonly' to false will allow you to create a writable
3587 // reference to a read-only variable. This is used by foreach and using.
3589 public LocalVariableReference (Block block, string name, Location l,
3590 LocalInfo local_info, bool is_readonly)
3591 : this (block, name, l)
3593 this.local_info = local_info;
3594 this.is_readonly = is_readonly;
3597 public VariableInfo VariableInfo {
3599 return local_info.VariableInfo;
3603 public bool IsReadOnly {
3609 protected Expression DoResolveBase (EmitContext ec, Expression lvalue_right_side)
3611 if (local_info == null) {
3612 local_info = Block.GetLocalInfo (Name);
3613 is_readonly = local_info.ReadOnly;
3616 type = local_info.VariableType;
3618 VariableInfo variable_info = local_info.VariableInfo;
3619 if (lvalue_right_side != null){
3621 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3625 if (variable_info != null)
3626 variable_info.SetAssigned (ec);
3629 Expression e = Block.GetConstantExpression (Name);
3631 local_info.Used = true;
3632 eclass = ExprClass.Value;
3633 return e.Resolve (ec);
3636 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3639 if (lvalue_right_side == null)
3640 local_info.Used = true;
3642 if (ec.CurrentAnonymousMethod != null){
3644 // If we are referencing a variable from the external block
3645 // flag it for capturing
3647 if (local_info.Block.Toplevel != ec.CurrentBlock.Toplevel){
3648 if (local_info.AddressTaken){
3649 AnonymousMethod.Error_AddressOfCapturedVar (local_info.Name, loc);
3652 ec.CaptureVariable (local_info);
3659 public override Expression DoResolve (EmitContext ec)
3661 return DoResolveBase (ec, null);
3664 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3666 Expression ret = DoResolveBase (ec, right_side);
3668 CheckObsoleteAttribute (ret.Type);
3673 public bool VerifyFixed (bool is_expression)
3675 return !is_expression || local_info.IsFixed;
3678 public override void Emit (EmitContext ec)
3680 ILGenerator ig = ec.ig;
3682 if (local_info.FieldBuilder == null){
3684 // A local variable on the local CLR stack
3686 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3689 // A local variable captured by anonymous methods.
3692 ec.EmitCapturedVariableInstance (local_info);
3694 ig.Emit (OpCodes.Ldfld, local_info.FieldBuilder);
3698 public void Emit (EmitContext ec, bool leave_copy)
3702 ec.ig.Emit (OpCodes.Dup);
3703 if (local_info.FieldBuilder != null){
3704 temp = new LocalTemporary (ec, Type);
3710 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3712 ILGenerator ig = ec.ig;
3713 prepared = prepare_for_load;
3715 if (local_info.FieldBuilder == null){
3717 // A local variable on the local CLR stack
3719 if (local_info.LocalBuilder == null)
3720 throw new Exception ("This should not happen: both Field and Local are null");
3724 ec.ig.Emit (OpCodes.Dup);
3725 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3728 // A local variable captured by anonymous methods or itereators.
3730 ec.EmitCapturedVariableInstance (local_info);
3732 if (prepare_for_load)
3733 ig.Emit (OpCodes.Dup);
3736 ig.Emit (OpCodes.Dup);
3737 temp = new LocalTemporary (ec, Type);
3740 ig.Emit (OpCodes.Stfld, local_info.FieldBuilder);
3746 public void AddressOf (EmitContext ec, AddressOp mode)
3748 ILGenerator ig = ec.ig;
3750 if (local_info.FieldBuilder == null){
3752 // A local variable on the local CLR stack
3754 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3757 // A local variable captured by anonymous methods or iterators
3759 ec.EmitCapturedVariableInstance (local_info);
3760 ig.Emit (OpCodes.Ldflda, local_info.FieldBuilder);
3764 public override string ToString ()
3766 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3771 /// This represents a reference to a parameter in the intermediate
3774 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3780 public Parameter.Modifier mod;
3781 public bool is_ref, is_out, prepared;
3795 LocalTemporary temp;
3797 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3804 eclass = ExprClass.Variable;
3807 public VariableInfo VariableInfo {
3811 public bool VerifyFixed (bool is_expression)
3813 return !is_expression || TypeManager.IsValueType (type);
3816 public bool IsAssigned (EmitContext ec, Location loc)
3818 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsAssigned (vi))
3821 Report.Error (165, loc,
3822 "Use of unassigned parameter `" + name + "'");
3826 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3828 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3831 Report.Error (170, loc,
3832 "Use of possibly unassigned field `" + field_name + "'");
3836 public void SetAssigned (EmitContext ec)
3838 if (is_out && ec.DoFlowAnalysis)
3839 ec.CurrentBranching.SetAssigned (vi);
3842 public void SetFieldAssigned (EmitContext ec, string field_name)
3844 if (is_out && ec.DoFlowAnalysis)
3845 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3848 protected void DoResolveBase (EmitContext ec)
3850 type = pars.GetParameterInfo (ec, idx, out mod);
3851 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3852 is_out = (mod & Parameter.Modifier.OUT) != 0;
3853 eclass = ExprClass.Variable;
3856 vi = block.ParameterMap [idx];
3858 if (ec.CurrentAnonymousMethod != null){
3860 Report.Error (1628, Location,
3861 "Can not reference a ref or out parameter in an anonymous method");
3866 // If we are referencing the parameter from the external block
3867 // flag it for capturing
3869 //Console.WriteLine ("Is parameter `{0}' local? {1}", name, block.IsLocalParameter (name));
3870 if (!block.IsLocalParameter (name)){
3871 ec.CaptureParameter (name, type, idx);
3877 // Notice that for ref/out parameters, the type exposed is not the
3878 // same type exposed externally.
3881 // externally we expose "int&"
3882 // here we expose "int".
3884 // We record this in "is_ref". This means that the type system can treat
3885 // the type as it is expected, but when we generate the code, we generate
3886 // the alternate kind of code.
3888 public override Expression DoResolve (EmitContext ec)
3892 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3895 if (ec.RemapToProxy)
3896 return ec.RemapParameter (idx);
3901 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3907 if (ec.RemapToProxy)
3908 return ec.RemapParameterLValue (idx, right_side);
3913 static public void EmitLdArg (ILGenerator ig, int x)
3917 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3918 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3919 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3920 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3921 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3924 ig.Emit (OpCodes.Ldarg, x);
3928 // This method is used by parameters that are references, that are
3929 // being passed as references: we only want to pass the pointer (that
3930 // is already stored in the parameter, not the address of the pointer,
3931 // and not the value of the variable).
3933 public void EmitLoad (EmitContext ec)
3935 ILGenerator ig = ec.ig;
3941 EmitLdArg (ig, arg_idx);
3944 // FIXME: Review for anonymous methods
3948 public override void Emit (EmitContext ec)
3950 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
3951 ec.EmitParameter (name);
3958 public void Emit (EmitContext ec, bool leave_copy)
3960 ILGenerator ig = ec.ig;
3966 EmitLdArg (ig, arg_idx);
3970 ec.ig.Emit (OpCodes.Dup);
3973 // If we are a reference, we loaded on the stack a pointer
3974 // Now lets load the real value
3976 LoadFromPtr (ig, type);
3980 ec.ig.Emit (OpCodes.Dup);
3983 temp = new LocalTemporary (ec, type);
3989 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3991 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
3992 ec.EmitAssignParameter (name, source, leave_copy, prepare_for_load);
3996 ILGenerator ig = ec.ig;
3999 prepared = prepare_for_load;
4004 if (is_ref && !prepared)
4005 EmitLdArg (ig, arg_idx);
4010 ec.ig.Emit (OpCodes.Dup);
4014 temp = new LocalTemporary (ec, type);
4018 StoreFromPtr (ig, type);
4024 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
4026 ig.Emit (OpCodes.Starg, arg_idx);
4030 public void AddressOf (EmitContext ec, AddressOp mode)
4032 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4033 ec.EmitAddressOfParameter (name);
4044 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
4046 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
4049 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
4051 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
4058 /// Used for arguments to New(), Invocation()
4060 public class Argument {
4061 public enum AType : byte {
4068 public readonly AType ArgType;
4069 public Expression Expr;
4071 public Argument (Expression expr, AType type)
4074 this.ArgType = type;
4077 public Argument (Expression expr)
4080 this.ArgType = AType.Expression;
4085 if (ArgType == AType.Ref || ArgType == AType.Out)
4086 return TypeManager.GetReferenceType (Expr.Type);
4092 public Parameter.Modifier GetParameterModifier ()
4096 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
4099 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
4102 return Parameter.Modifier.NONE;
4106 public static string FullDesc (Argument a)
4108 if (a.ArgType == AType.ArgList)
4111 return (a.ArgType == AType.Ref ? "ref " :
4112 (a.ArgType == AType.Out ? "out " : "")) +
4113 TypeManager.CSharpName (a.Expr.Type);
4116 public bool ResolveMethodGroup (EmitContext ec, Location loc)
4118 ConstructedType ctype = Expr as ConstructedType;
4120 Expr = ctype.GetSimpleName (ec);
4122 // FIXME: csc doesn't report any error if you try to use `ref' or
4123 // `out' in a delegate creation expression.
4124 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4131 public bool Resolve (EmitContext ec, Location loc)
4133 if (ArgType == AType.Ref) {
4134 Expr = Expr.Resolve (ec);
4138 if (!ec.IsConstructor) {
4139 FieldExpr fe = Expr as FieldExpr;
4140 if (fe != null && fe.FieldInfo.IsInitOnly) {
4141 if (fe.FieldInfo.IsStatic)
4142 Report.Error (199, loc, "A static readonly field cannot be passed ref or out (except in a static constructor)");
4144 Report.Error (192, loc, "A readonly field cannot be passed ref or out (except in a constructor)");
4148 Expr = Expr.ResolveLValue (ec, Expr);
4149 } else if (ArgType == AType.Out)
4150 Expr = Expr.ResolveLValue (ec, EmptyExpression.Null);
4152 Expr = Expr.Resolve (ec);
4157 if (ArgType == AType.Expression)
4161 // Catch errors where fields of a MarshalByRefObject are passed as ref or out
4162 // This is only allowed for `this'
4164 FieldExpr fe = Expr as FieldExpr;
4165 if (fe != null && !fe.IsStatic){
4166 Expression instance = fe.InstanceExpression;
4168 if (instance.GetType () != typeof (This)){
4169 if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
4170 Report.Error (197, loc,
4171 "Can not pass a type that derives from MarshalByRefObject with out or ref");
4178 if (Expr.eclass != ExprClass.Variable){
4180 // We just probe to match the CSC output
4182 if (Expr.eclass == ExprClass.PropertyAccess ||
4183 Expr.eclass == ExprClass.IndexerAccess){
4186 "A property or indexer can not be passed as an out or ref " +
4191 "An lvalue is required as an argument to out or ref");
4199 public void Emit (EmitContext ec)
4202 // Ref and Out parameters need to have their addresses taken.
4204 // ParameterReferences might already be references, so we want
4205 // to pass just the value
4207 if (ArgType == AType.Ref || ArgType == AType.Out){
4208 AddressOp mode = AddressOp.Store;
4210 if (ArgType == AType.Ref)
4211 mode |= AddressOp.Load;
4213 if (Expr is ParameterReference){
4214 ParameterReference pr = (ParameterReference) Expr;
4220 pr.AddressOf (ec, mode);
4223 ((IMemoryLocation)Expr).AddressOf (ec, mode);
4231 /// Invocation of methods or delegates.
4233 public class Invocation : ExpressionStatement {
4234 public readonly ArrayList Arguments;
4237 MethodBase method = null;
4239 static Hashtable method_parameter_cache;
4241 static Invocation ()
4243 method_parameter_cache = new PtrHashtable ();
4247 // arguments is an ArrayList, but we do not want to typecast,
4248 // as it might be null.
4250 // FIXME: only allow expr to be a method invocation or a
4251 // delegate invocation (7.5.5)
4253 public Invocation (Expression expr, ArrayList arguments, Location l)
4256 Arguments = arguments;
4260 public Expression Expr {
4267 /// Returns the Parameters (a ParameterData interface) for the
4270 public static ParameterData GetParameterData (MethodBase mb)
4272 object pd = method_parameter_cache [mb];
4276 return (ParameterData) pd;
4278 ip = TypeManager.LookupParametersByBuilder (mb);
4280 method_parameter_cache [mb] = ip;
4282 return (ParameterData) ip;
4284 ReflectionParameters rp = new ReflectionParameters (mb);
4285 method_parameter_cache [mb] = rp;
4287 return (ParameterData) rp;
4292 /// Determines "better conversion" as specified in 7.4.2.3
4294 /// Returns : p if a->p is better,
4295 /// q if a->q is better,
4296 /// null if neither is better
4298 static Type BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
4300 Type argument_type = TypeManager.TypeToCoreType (a.Type);
4301 Expression argument_expr = a.Expr;
4303 // p = TypeManager.TypeToCoreType (p);
4304 // q = TypeManager.TypeToCoreType (q);
4306 if (argument_type == null)
4307 throw new Exception ("Expression of type " + a.Expr +
4308 " does not resolve its type");
4310 if (p == null || q == null)
4311 throw new InternalErrorException ("BetterConversion Got a null conversion");
4316 if (argument_expr is NullLiteral) {
4318 // If the argument is null and one of the types to compare is 'object' and
4319 // the other is a reference type, we prefer the other.
4321 // This follows from the usual rules:
4322 // * There is an implicit conversion from 'null' to type 'object'
4323 // * There is an implicit conversion from 'null' to any reference type
4324 // * There is an implicit conversion from any reference type to type 'object'
4325 // * There is no implicit conversion from type 'object' to other reference types
4326 // => Conversion of 'null' to a reference type is better than conversion to 'object'
4328 // FIXME: This probably isn't necessary, since the type of a NullLiteral is the
4329 // null type. I think it used to be 'object' and thus needed a special
4330 // case to avoid the immediately following two checks.
4332 if (!p.IsValueType && q == TypeManager.object_type)
4334 if (!q.IsValueType && p == TypeManager.object_type)
4338 if (argument_type == p)
4341 if (argument_type == q)
4344 Expression p_tmp = new EmptyExpression (p);
4345 Expression q_tmp = new EmptyExpression (q);
4347 bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
4348 bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
4350 if (p_to_q && !q_to_p)
4353 if (q_to_p && !p_to_q)
4356 if (p == TypeManager.sbyte_type)
4357 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4358 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4360 if (q == TypeManager.sbyte_type)
4361 if (p == TypeManager.byte_type || p == TypeManager.ushort_type ||
4362 p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4365 if (p == TypeManager.short_type)
4366 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4367 q == TypeManager.uint64_type)
4370 if (q == TypeManager.short_type)
4371 if (p == TypeManager.ushort_type || p == TypeManager.uint32_type ||
4372 p == TypeManager.uint64_type)
4375 if (p == TypeManager.int32_type)
4376 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4379 if (q == TypeManager.int32_type)
4380 if (p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4383 if (p == TypeManager.int64_type)
4384 if (q == TypeManager.uint64_type)
4386 if (q == TypeManager.int64_type)
4387 if (p == TypeManager.uint64_type)
4394 /// Determines "Better function" between candidate
4395 /// and the current best match
4398 /// Returns a boolean indicating :
4399 /// false if candidate ain't better
4400 /// true if candidate is better than the current best match
4402 static bool BetterFunction (EmitContext ec, ArrayList args, int argument_count,
4403 MethodBase candidate, bool candidate_params,
4404 MethodBase best, bool best_params, Location loc)
4406 ParameterData candidate_pd = GetParameterData (candidate);
4407 ParameterData best_pd = GetParameterData (best);
4409 int cand_count = candidate_pd.Count;
4412 // If there is no best method, than this one
4413 // is better, however, if we already found a
4414 // best method, we cant tell. This happens
4425 // interface IFooBar : IFoo, IBar {}
4427 // We cant tell if IFoo.DoIt is better than IBar.DoIt
4429 // However, we have to consider that
4430 // Trim (); is better than Trim (params char[] chars);
4432 if (cand_count == 0 && argument_count == 0)
4433 return !candidate_params && best_params;
4435 if ((candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS) &&
4436 (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.ARGLIST))
4437 if (cand_count != argument_count)
4440 bool better_at_least_one = false;
4441 bool is_equal = true;
4443 for (int j = 0; j < argument_count; ++j) {
4444 Argument a = (Argument) args [j];
4446 Type ct = TypeManager.TypeToCoreType (candidate_pd.ParameterType (j));
4447 Type bt = TypeManager.TypeToCoreType (best_pd.ParameterType (j));
4449 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4450 if (candidate_params)
4451 ct = TypeManager.GetElementType (ct);
4453 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4455 bt = TypeManager.GetElementType (bt);
4457 if (!ct.Equals (bt))
4460 Type better = BetterConversion (ec, a, ct, bt, loc);
4461 // for each argument, the conversion to 'ct' should be no worse than
4462 // the conversion to 'bt'.
4466 // for at least one argument, the conversion to 'ct' should be better than
4467 // the conversion to 'bt'.
4469 better_at_least_one = true;
4473 // If a method (in the normal form) with the
4474 // same signature as the expanded form of the
4475 // current best params method already exists,
4476 // the expanded form is not applicable so we
4477 // force it to select the candidate
4479 if (!candidate_params && best_params && cand_count == argument_count)
4483 // If two methods have equal parameter types, but
4484 // only one of them is generic, the non-generic one wins.
4487 if (TypeManager.IsGenericMethod (best) && !TypeManager.IsGenericMethod (candidate))
4489 else if (!TypeManager.IsGenericMethod (best) && TypeManager.IsGenericMethod (candidate))
4493 return better_at_least_one;
4496 public static string FullMethodDesc (MethodBase mb)
4498 string ret_type = "";
4503 if (mb is MethodInfo)
4504 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
4506 StringBuilder sb = new StringBuilder (ret_type);
4508 sb.Append (mb.ReflectedType.ToString ());
4510 sb.Append (mb.Name);
4512 ParameterData pd = GetParameterData (mb);
4514 int count = pd.Count;
4517 for (int i = count; i > 0; ) {
4520 sb.Append (pd.ParameterDesc (count - i - 1));
4526 return sb.ToString ();
4529 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4531 MemberInfo [] miset;
4532 MethodGroupExpr union;
4537 return (MethodGroupExpr) mg2;
4540 return (MethodGroupExpr) mg1;
4543 MethodGroupExpr left_set = null, right_set = null;
4544 int length1 = 0, length2 = 0;
4546 left_set = (MethodGroupExpr) mg1;
4547 length1 = left_set.Methods.Length;
4549 right_set = (MethodGroupExpr) mg2;
4550 length2 = right_set.Methods.Length;
4552 ArrayList common = new ArrayList ();
4554 foreach (MethodBase r in right_set.Methods){
4555 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
4559 miset = new MemberInfo [length1 + length2 - common.Count];
4560 left_set.Methods.CopyTo (miset, 0);
4564 foreach (MethodBase r in right_set.Methods) {
4565 if (!common.Contains (r))
4569 union = new MethodGroupExpr (miset, loc);
4574 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4575 ArrayList arguments, int arg_count,
4576 ref MethodBase candidate)
4578 return IsParamsMethodApplicable (
4579 ec, me, arguments, arg_count, false, ref candidate) ||
4580 IsParamsMethodApplicable (
4581 ec, me, arguments, arg_count, true, ref candidate);
4586 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4587 ArrayList arguments, int arg_count,
4588 bool do_varargs, ref MethodBase candidate)
4590 if (!me.HasTypeArguments &&
4591 !InferParamsTypeArguments (ec, arguments, ref candidate))
4594 return IsParamsMethodApplicable (
4595 ec, arguments, arg_count, candidate, do_varargs);
4599 /// Determines if the candidate method, if a params method, is applicable
4600 /// in its expanded form to the given set of arguments
4602 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
4603 int arg_count, MethodBase candidate,
4606 ParameterData pd = GetParameterData (candidate);
4608 int pd_count = pd.Count;
4613 int count = pd_count - 1;
4615 if (pd.ParameterModifier (count) != Parameter.Modifier.ARGLIST)
4617 if (pd_count != arg_count)
4620 if (pd.ParameterModifier (count) != Parameter.Modifier.PARAMS)
4624 if (count > arg_count)
4627 if (pd_count == 1 && arg_count == 0)
4631 // If we have come this far, the case which
4632 // remains is when the number of parameters is
4633 // less than or equal to the argument count.
4635 for (int i = 0; i < count; ++i) {
4637 Argument a = (Argument) arguments [i];
4639 Parameter.Modifier a_mod = a.GetParameterModifier () &
4640 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4641 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4642 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4644 if (a_mod == p_mod) {
4646 if (a_mod == Parameter.Modifier.NONE)
4647 if (!Convert.ImplicitConversionExists (ec,
4649 pd.ParameterType (i)))
4652 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4653 Type pt = pd.ParameterType (i);
4656 pt = TypeManager.GetReferenceType (pt);
4667 Argument a = (Argument) arguments [count];
4668 if (!(a.Expr is Arglist))
4674 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4676 for (int i = pd_count - 1; i < arg_count; i++) {
4677 Argument a = (Argument) arguments [i];
4679 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4686 static bool IsApplicable (EmitContext ec, MethodGroupExpr me,
4687 ArrayList arguments, int arg_count,
4688 ref MethodBase candidate)
4690 if (!me.HasTypeArguments &&
4691 !InferTypeArguments (ec, arguments, ref candidate))
4694 return IsApplicable (ec, arguments, arg_count, candidate);
4698 /// Determines if the candidate method is applicable (section 14.4.2.1)
4699 /// to the given set of arguments
4701 static bool IsApplicable (EmitContext ec, ArrayList arguments, int arg_count,
4702 MethodBase candidate)
4704 ParameterData pd = GetParameterData (candidate);
4706 if (arg_count != pd.Count)
4709 for (int i = arg_count; i > 0; ) {
4712 Argument a = (Argument) arguments [i];
4714 Parameter.Modifier a_mod = a.GetParameterModifier () &
4715 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4716 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4717 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4720 if (a_mod == p_mod ||
4721 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4722 if (a_mod == Parameter.Modifier.NONE) {
4723 if (!Convert.ImplicitConversionExists (ec,
4725 pd.ParameterType (i)))
4729 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4730 Type pt = pd.ParameterType (i);
4733 pt = TypeManager.GetReferenceType (pt);
4745 static private bool IsAncestralType (Type first_type, Type second_type)
4747 return first_type != second_type &&
4748 (second_type.IsSubclassOf (first_type) ||
4749 TypeManager.ImplementsInterface (second_type, first_type));
4753 /// Find the Applicable Function Members (7.4.2.1)
4755 /// me: Method Group expression with the members to select.
4756 /// it might contain constructors or methods (or anything
4757 /// that maps to a method).
4759 /// Arguments: ArrayList containing resolved Argument objects.
4761 /// loc: The location if we want an error to be reported, or a Null
4762 /// location for "probing" purposes.
4764 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4765 /// that is the best match of me on Arguments.
4768 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4769 ArrayList Arguments, bool may_fail,
4772 MethodBase method = null;
4773 bool method_params = false;
4774 Type applicable_type = null;
4776 ArrayList candidates = new ArrayList ();
4779 // Used to keep a map between the candidate
4780 // and whether it is being considered in its
4781 // normal or expanded form
4783 // false is normal form, true is expanded form
4785 Hashtable candidate_to_form = null;
4787 if (Arguments != null)
4788 arg_count = Arguments.Count;
4790 if ((me.Name == "Invoke") &&
4791 TypeManager.IsDelegateType (me.DeclaringType)) {
4792 Error_InvokeOnDelegate (loc);
4796 MethodBase[] methods = me.Methods;
4799 // First we construct the set of applicable methods
4801 bool is_sorted = true;
4802 for (int i = 0; i < methods.Length; i++){
4803 Type decl_type = methods [i].DeclaringType;
4806 // If we have already found an applicable method
4807 // we eliminate all base types (Section 14.5.5.1)
4809 if ((applicable_type != null) &&
4810 IsAncestralType (decl_type, applicable_type))
4814 // Check if candidate is applicable (section 14.4.2.1)
4815 // Is candidate applicable in normal form?
4817 bool is_applicable = IsApplicable (
4818 ec, me, Arguments, arg_count, ref methods [i]);
4820 if (!is_applicable &&
4821 (IsParamsMethodApplicable (
4822 ec, me, Arguments, arg_count, ref methods [i]))) {
4823 MethodBase candidate = methods [i];
4824 if (candidate_to_form == null)
4825 candidate_to_form = new PtrHashtable ();
4826 candidate_to_form [candidate] = candidate;
4827 // Candidate is applicable in expanded form
4828 is_applicable = true;
4834 candidates.Add (methods [i]);
4836 if (applicable_type == null)
4837 applicable_type = decl_type;
4838 else if (applicable_type != decl_type) {
4840 if (IsAncestralType (applicable_type, decl_type))
4841 applicable_type = decl_type;
4845 int candidate_top = candidates.Count;
4847 if (candidate_top == 0) {
4849 // Okay so we have failed to find anything so we
4850 // return by providing info about the closest match
4852 for (int i = 0; i < methods.Length; ++i) {
4853 MethodBase c = (MethodBase) methods [i];
4854 ParameterData pd = GetParameterData (c);
4856 if (pd.Count != arg_count)
4859 if (!InferTypeArguments (ec, Arguments, ref c))
4862 VerifyArgumentsCompat (ec, Arguments, arg_count,
4863 c, false, null, may_fail, loc);
4868 string report_name = me.Name;
4869 if (report_name == ".ctor")
4870 report_name = me.DeclaringType.ToString ();
4872 for (int i = 0; i < methods.Length; ++i) {
4873 MethodBase c = methods [i];
4874 ParameterData pd = GetParameterData (c);
4876 if (pd.Count != arg_count)
4879 if (InferTypeArguments (ec, Arguments, ref c))
4883 411, loc, "The type arguments for " +
4884 "method `{0}' cannot be infered from " +
4885 "the usage. Try specifying the type " +
4886 "arguments explicitly.", report_name);
4890 Error_WrongNumArguments (
4891 loc, report_name, arg_count);
4900 // At this point, applicable_type is _one_ of the most derived types
4901 // in the set of types containing the methods in this MethodGroup.
4902 // Filter the candidates so that they only contain methods from the
4903 // most derived types.
4906 int finalized = 0; // Number of finalized candidates
4909 // Invariant: applicable_type is a most derived type
4911 // We'll try to complete Section 14.5.5.1 for 'applicable_type' by
4912 // eliminating all it's base types. At the same time, we'll also move
4913 // every unrelated type to the end of the array, and pick the next
4914 // 'applicable_type'.
4916 Type next_applicable_type = null;
4917 int j = finalized; // where to put the next finalized candidate
4918 int k = finalized; // where to put the next undiscarded candidate
4919 for (int i = finalized; i < candidate_top; ++i) {
4920 Type decl_type = ((MethodBase) candidates[i]).DeclaringType;
4922 if (decl_type == applicable_type) {
4923 candidates[k++] = candidates[j];
4924 candidates[j++] = candidates[i];
4928 if (IsAncestralType (decl_type, applicable_type))
4931 if (next_applicable_type != null &&
4932 IsAncestralType (decl_type, next_applicable_type))
4935 candidates[k++] = candidates[i];
4937 if (next_applicable_type == null ||
4938 IsAncestralType (next_applicable_type, decl_type))
4939 next_applicable_type = decl_type;
4942 applicable_type = next_applicable_type;
4945 } while (applicable_type != null);
4949 // Now we actually find the best method
4952 method = (MethodBase) candidates[0];
4953 method_params = candidate_to_form != null && candidate_to_form.Contains (method);
4954 for (int ix = 1; ix < candidate_top; ix++){
4955 MethodBase candidate = (MethodBase) candidates [ix];
4956 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4958 if (BetterFunction (ec, Arguments, arg_count,
4959 candidate, cand_params,
4960 method, method_params, loc)) {
4962 method_params = cand_params;
4967 // Now check that there are no ambiguities i.e the selected method
4968 // should be better than all the others
4970 bool ambiguous = false;
4971 for (int ix = 0; ix < candidate_top; ix++){
4972 MethodBase candidate = (MethodBase) candidates [ix];
4974 if (candidate == method)
4977 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4978 if (!BetterFunction (ec, Arguments, arg_count,
4979 method, method_params,
4980 candidate, cand_params,
4982 Report.SymbolRelatedToPreviousError (candidate);
4988 Report.SymbolRelatedToPreviousError (method);
4989 Report.Error (121, loc, "Ambiguous call when selecting function due to implicit casts");
4994 // And now check if the arguments are all
4995 // compatible, perform conversions if
4996 // necessary etc. and return if everything is
4999 if (!VerifyArgumentsCompat (ec, Arguments, arg_count, method,
5000 method_params, null, may_fail, loc))
5006 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
5008 Report.Error (1501, loc,
5009 "No overload for method `" + name + "' takes `" +
5010 arg_count + "' arguments");
5013 static void Error_InvokeOnDelegate (Location loc)
5015 Report.Error (1533, loc,
5016 "Invoke cannot be called directly on a delegate");
5019 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
5020 Type delegate_type, string arg_sig, string par_desc)
5022 if (delegate_type == null)
5023 Report.Error (1502, loc,
5024 "The best overloaded match for method '" +
5025 FullMethodDesc (method) +
5026 "' has some invalid arguments");
5028 Report.Error (1594, loc,
5029 "Delegate '" + delegate_type.ToString () +
5030 "' has some invalid arguments.");
5031 Report.Error (1503, loc,
5032 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
5033 idx, arg_sig, par_desc));
5036 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
5037 int arg_count, MethodBase method,
5038 bool chose_params_expanded,
5039 Type delegate_type, bool may_fail,
5042 ParameterData pd = GetParameterData (method);
5043 int pd_count = pd.Count;
5045 for (int j = 0; j < arg_count; j++) {
5046 Argument a = (Argument) Arguments [j];
5047 Expression a_expr = a.Expr;
5048 Type parameter_type = pd.ParameterType (j);
5049 Parameter.Modifier pm = pd.ParameterModifier (j);
5051 if (pm == Parameter.Modifier.PARAMS){
5052 if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
5054 Error_InvalidArguments (
5055 loc, j, method, delegate_type,
5056 Argument.FullDesc (a), pd.ParameterDesc (j));
5060 if (chose_params_expanded)
5061 parameter_type = TypeManager.GetElementType (parameter_type);
5062 } else if (pm == Parameter.Modifier.ARGLIST){
5068 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
5070 Error_InvalidArguments (
5071 loc, j, method, delegate_type,
5072 Argument.FullDesc (a), pd.ParameterDesc (j));
5080 if (!TypeManager.IsEqual (a.Type, parameter_type)){
5083 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
5087 Error_InvalidArguments (
5088 loc, j, method, delegate_type,
5089 Argument.FullDesc (a), pd.ParameterDesc (j));
5094 // Update the argument with the implicit conversion
5100 if (parameter_type.IsPointer){
5107 Parameter.Modifier a_mod = a.GetParameterModifier () &
5108 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5109 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
5110 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5112 if (a_mod != p_mod &&
5113 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
5115 Report.Error (1502, loc,
5116 "The best overloaded match for method '" + FullMethodDesc (method)+
5117 "' has some invalid arguments");
5118 Report.Error (1503, loc,
5119 "Argument " + (j+1) +
5120 ": Cannot convert from '" + Argument.FullDesc (a)
5121 + "' to '" + pd.ParameterDesc (j) + "'");
5131 static bool InferType (Type pt, Type at, ref Type[] infered)
5133 if (pt.IsGenericParameter && (pt.DeclaringMethod != null)) {
5134 int pos = pt.GenericParameterPosition;
5136 if (infered [pos] == null) {
5138 while (check.IsArray)
5139 check = check.GetElementType ();
5148 if (infered [pos] != at)
5154 if (!pt.ContainsGenericParameters)
5159 (at.GetArrayRank () != pt.GetArrayRank ()))
5162 return InferType (pt.GetElementType (), at.GetElementType (),
5168 (pt.GetArrayRank () != at.GetArrayRank ()))
5171 return InferType (pt.GetElementType (), at.GetElementType (),
5175 ArrayList list = new ArrayList ();
5176 if (at.IsGenericInstance)
5179 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
5182 list.AddRange (TypeManager.GetInterfaces (at));
5185 bool found_one = false;
5187 foreach (Type type in list) {
5188 if (!type.IsGenericInstance)
5191 Type[] infered_types = new Type [infered.Length];
5193 if (!InferGenericInstance (pt, type, infered_types))
5196 for (int i = 0; i < infered_types.Length; i++) {
5197 if (infered [i] == null) {
5198 infered [i] = infered_types [i];
5202 if (infered [i] != infered_types [i])
5212 static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
5214 Type[] at_args = at.GetGenericArguments ();
5215 Type[] pt_args = pt.GetGenericArguments ();
5217 if (at_args.Length != pt_args.Length)
5220 for (int i = 0; i < at_args.Length; i++) {
5221 if (!InferType (pt_args [i], at_args [i], ref infered_types))
5225 for (int i = 0; i < infered_types.Length; i++) {
5226 if (infered_types [i] == null)
5233 static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
5234 ref MethodBase method)
5236 if ((arguments == null) || !TypeManager.IsGenericMethod (method))
5241 if (arguments == null)
5244 arg_count = arguments.Count;
5246 ParameterData pd = GetParameterData (method);
5248 int pd_count = pd.Count;
5253 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
5256 if (pd_count - 1 > arg_count)
5259 if (pd_count == 1 && arg_count == 0)
5262 Type[] method_args = method.GetGenericArguments ();
5263 Type[] infered_types = new Type [method_args.Length];
5266 // If we have come this far, the case which
5267 // remains is when the number of parameters is
5268 // less than or equal to the argument count.
5270 for (int i = 0; i < pd_count - 1; ++i) {
5271 Argument a = (Argument) arguments [i];
5273 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
5276 Type pt = pd.ParameterType (i);
5279 if (!InferType (pt, at, ref infered_types))
5283 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
5285 for (int i = pd_count - 1; i < arg_count; i++) {
5286 Argument a = (Argument) arguments [i];
5288 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
5291 if (!InferType (element_type, a.Type, ref infered_types))
5295 for (int i = 0; i < infered_types.Length; i++)
5296 if (infered_types [i] == null)
5299 method = method.BindGenericParameters (infered_types);
5303 public static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
5304 ref Type[] infered_types)
5306 if (infered_types == null)
5309 for (int i = 0; i < arg_types.Length; i++) {
5310 if (arg_types [i] == null)
5313 if (!InferType (param_types [i], arg_types [i], ref infered_types))
5317 for (int i = 0; i < infered_types.Length; i++)
5318 if (infered_types [i] == null)
5324 static bool InferTypeArguments (EmitContext ec, ArrayList arguments,
5325 ref MethodBase method)
5327 if (!TypeManager.IsGenericMethod (method))
5331 if (arguments != null)
5332 arg_count = arguments.Count;
5336 ParameterData pd = GetParameterData (method);
5337 if (arg_count != pd.Count)
5340 Type[] method_args = method.GetGenericArguments ();
5342 bool is_open = false;
5343 for (int i = 0; i < method_args.Length; i++) {
5344 if (method_args [i].IsGenericParameter) {
5352 Type[] infered_types = new Type [method_args.Length];
5354 Type[] param_types = new Type [pd.Count];
5355 Type[] arg_types = new Type [pd.Count];
5357 for (int i = 0; i < arg_count; i++) {
5358 param_types [i] = pd.ParameterType (i);
5360 Argument a = (Argument) arguments [i];
5361 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
5364 arg_types [i] = a.Type;
5367 if (!InferTypeArguments (param_types, arg_types, ref infered_types))
5370 method = method.BindGenericParameters (infered_types);
5374 public static bool InferTypeArguments (EmitContext ec, ParameterData apd,
5375 ref MethodBase method)
5377 if (!TypeManager.IsGenericMethod (method))
5380 ParameterData pd = GetParameterData (method);
5381 if (apd.Count != pd.Count)
5384 Type[] method_args = method.GetGenericArguments ();
5385 Type[] infered_types = new Type [method_args.Length];
5387 Type[] param_types = new Type [pd.Count];
5388 Type[] arg_types = new Type [pd.Count];
5390 for (int i = 0; i < apd.Count; i++) {
5391 param_types [i] = pd.ParameterType (i);
5392 arg_types [i] = apd.ParameterType (i);
5395 if (!InferTypeArguments (param_types, arg_types, ref infered_types))
5398 method = method.BindGenericParameters (infered_types);
5402 public override Expression DoResolve (EmitContext ec)
5405 // First, resolve the expression that is used to
5406 // trigger the invocation
5408 if (expr is ConstructedType)
5409 expr = ((ConstructedType) expr).GetSimpleName (ec);
5411 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
5415 if (!(expr is MethodGroupExpr)) {
5416 Type expr_type = expr.Type;
5418 if (expr_type != null){
5419 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
5421 return (new DelegateInvocation (
5422 this.expr, Arguments, loc)).Resolve (ec);
5426 if (!(expr is MethodGroupExpr)){
5427 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup, loc);
5432 // Next, evaluate all the expressions in the argument list
5434 if (Arguments != null){
5435 foreach (Argument a in Arguments){
5436 if (!a.Resolve (ec, loc))
5441 MethodGroupExpr mg = (MethodGroupExpr) expr;
5442 method = OverloadResolve (ec, mg, Arguments, false, loc);
5447 MethodInfo mi = method as MethodInfo;
5449 type = TypeManager.TypeToCoreType (mi.ReturnType);
5450 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null)) {
5451 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
5455 Expression iexpr = mg.InstanceExpression;
5456 if (mi.IsStatic && (iexpr != null) && !(iexpr is This)) {
5457 if (mg.IdenticalTypeName)
5458 mg.InstanceExpression = null;
5460 MemberAccess.error176 (loc, mi.Name);
5466 if (type.IsPointer){
5474 // Only base will allow this invocation to happen.
5476 if (mg.IsBase && method.IsAbstract){
5477 Report.Error (205, loc, "Cannot call an abstract base member: " +
5478 FullMethodDesc (method));
5482 if (method.Name == "Finalize" && Arguments == null) {
5484 Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
5486 Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
5490 if ((method.Attributes & MethodAttributes.SpecialName) != 0){
5491 if (TypeManager.LookupDeclSpace (method.DeclaringType) != null || TypeManager.IsSpecialMethod (method)) {
5492 Report.Error (571, loc, TypeManager.CSharpSignature (method) + ": can not call operator or accessor");
5497 eclass = ExprClass.Value;
5502 // Emits the list of arguments as an array
5504 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
5506 ILGenerator ig = ec.ig;
5507 int count = arguments.Count - idx;
5508 Argument a = (Argument) arguments [idx];
5509 Type t = a.Expr.Type;
5511 IntConstant.EmitInt (ig, count);
5512 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
5514 int top = arguments.Count;
5515 for (int j = idx; j < top; j++){
5516 a = (Argument) arguments [j];
5518 ig.Emit (OpCodes.Dup);
5519 IntConstant.EmitInt (ig, j - idx);
5521 bool is_stobj, has_type_arg;
5522 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj, out has_type_arg);
5524 ig.Emit (OpCodes.Ldelema, t);
5536 /// Emits a list of resolved Arguments that are in the arguments
5539 /// The MethodBase argument might be null if the
5540 /// emission of the arguments is known not to contain
5541 /// a `params' field (for example in constructors or other routines
5542 /// that keep their arguments in this structure)
5544 /// if `dup_args' is true, a copy of the arguments will be left
5545 /// on the stack. If `dup_args' is true, you can specify `this_arg'
5546 /// which will be duplicated before any other args. Only EmitCall
5547 /// should be using this interface.
5549 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments, bool dup_args, LocalTemporary this_arg)
5553 pd = GetParameterData (mb);
5557 LocalTemporary [] temps = null;
5560 temps = new LocalTemporary [arguments.Count];
5563 // If we are calling a params method with no arguments, special case it
5565 if (arguments == null){
5566 if (pd != null && pd.Count > 0 &&
5567 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
5568 ILGenerator ig = ec.ig;
5570 IntConstant.EmitInt (ig, 0);
5571 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
5577 int top = arguments.Count;
5579 for (int i = 0; i < top; i++){
5580 Argument a = (Argument) arguments [i];
5583 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
5585 // Special case if we are passing the same data as the
5586 // params argument, do not put it in an array.
5588 if (pd.ParameterType (i) == a.Type)
5591 EmitParams (ec, i, arguments);
5598 ec.ig.Emit (OpCodes.Dup);
5599 (temps [i] = new LocalTemporary (ec, a.Type)).Store (ec);
5604 if (this_arg != null)
5607 for (int i = 0; i < top; i ++)
5608 temps [i].Emit (ec);
5611 if (pd != null && pd.Count > top &&
5612 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
5613 ILGenerator ig = ec.ig;
5615 IntConstant.EmitInt (ig, 0);
5616 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
5620 static Type[] GetVarargsTypes (EmitContext ec, MethodBase mb,
5621 ArrayList arguments)
5623 ParameterData pd = GetParameterData (mb);
5625 if (arguments == null)
5626 return new Type [0];
5628 Argument a = (Argument) arguments [pd.Count - 1];
5629 Arglist list = (Arglist) a.Expr;
5631 return list.ArgumentTypes;
5635 /// This checks the ConditionalAttribute on the method
5637 static bool IsMethodExcluded (MethodBase method, EmitContext ec)
5639 if (method.IsConstructor)
5642 IMethodData md = TypeManager.GetMethod (method);
5644 return md.IsExcluded (ec);
5646 // For some methods (generated by delegate class) GetMethod returns null
5647 // because they are not included in builder_to_method table
5648 if (method.DeclaringType is TypeBuilder)
5651 return AttributeTester.IsConditionalMethodExcluded (method);
5655 /// is_base tells whether we want to force the use of the `call'
5656 /// opcode instead of using callvirt. Call is required to call
5657 /// a specific method, while callvirt will always use the most
5658 /// recent method in the vtable.
5660 /// is_static tells whether this is an invocation on a static method
5662 /// instance_expr is an expression that represents the instance
5663 /// it must be non-null if is_static is false.
5665 /// method is the method to invoke.
5667 /// Arguments is the list of arguments to pass to the method or constructor.
5669 public static void EmitCall (EmitContext ec, bool is_base,
5670 bool is_static, Expression instance_expr,
5671 MethodBase method, ArrayList Arguments, Location loc)
5673 EmitCall (ec, is_base, is_static, instance_expr, method, Arguments, loc, false, false);
5676 // `dup_args' leaves an extra copy of the arguments on the stack
5677 // `omit_args' does not leave any arguments at all.
5678 // So, basically, you could make one call with `dup_args' set to true,
5679 // and then another with `omit_args' set to true, and the two calls
5680 // would have the same set of arguments. However, each argument would
5681 // only have been evaluated once.
5682 public static void EmitCall (EmitContext ec, bool is_base,
5683 bool is_static, Expression instance_expr,
5684 MethodBase method, ArrayList Arguments, Location loc,
5685 bool dup_args, bool omit_args)
5687 ILGenerator ig = ec.ig;
5688 bool struct_call = false;
5689 bool this_call = false;
5690 LocalTemporary this_arg = null;
5692 Type decl_type = method.DeclaringType;
5694 if (!RootContext.StdLib) {
5695 // Replace any calls to the system's System.Array type with calls to
5696 // the newly created one.
5697 if (method == TypeManager.system_int_array_get_length)
5698 method = TypeManager.int_array_get_length;
5699 else if (method == TypeManager.system_int_array_get_rank)
5700 method = TypeManager.int_array_get_rank;
5701 else if (method == TypeManager.system_object_array_clone)
5702 method = TypeManager.object_array_clone;
5703 else if (method == TypeManager.system_int_array_get_length_int)
5704 method = TypeManager.int_array_get_length_int;
5705 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5706 method = TypeManager.int_array_get_lower_bound_int;
5707 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5708 method = TypeManager.int_array_get_upper_bound_int;
5709 else if (method == TypeManager.system_void_array_copyto_array_int)
5710 method = TypeManager.void_array_copyto_array_int;
5713 if (ec.TestObsoleteMethodUsage) {
5715 // This checks ObsoleteAttribute on the method and on the declaring type
5717 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
5719 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
5721 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
5723 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
5727 if (IsMethodExcluded (method, ec))
5731 this_call = instance_expr == null;
5732 if (decl_type.IsValueType || (!this_call && instance_expr.Type.IsValueType))
5736 // If this is ourselves, push "this"
5741 ig.Emit (OpCodes.Ldarg_0);
5744 Type iexpr_type = instance_expr.Type;
5747 // Push the instance expression
5749 if (TypeManager.IsValueType (iexpr_type)) {
5751 // Special case: calls to a function declared in a
5752 // reference-type with a value-type argument need
5753 // to have their value boxed.
5754 if (decl_type.IsValueType ||
5755 iexpr_type.IsGenericParameter) {
5757 // If the expression implements IMemoryLocation, then
5758 // we can optimize and use AddressOf on the
5761 // If not we have to use some temporary storage for
5763 if (instance_expr is IMemoryLocation) {
5764 ((IMemoryLocation)instance_expr).
5765 AddressOf (ec, AddressOp.LoadStore);
5767 LocalTemporary temp = new LocalTemporary (ec, iexpr_type);
5768 instance_expr.Emit (ec);
5770 temp.AddressOf (ec, AddressOp.Load);
5773 // avoid the overhead of doing this all the time.
5775 t = TypeManager.GetReferenceType (iexpr_type);
5777 instance_expr.Emit (ec);
5778 ig.Emit (OpCodes.Box, instance_expr.Type);
5779 t = TypeManager.object_type;
5782 instance_expr.Emit (ec);
5783 t = instance_expr.Type;
5788 this_arg = new LocalTemporary (ec, t);
5789 ig.Emit (OpCodes.Dup);
5790 this_arg.Store (ec);
5796 EmitArguments (ec, method, Arguments, dup_args, this_arg);
5798 if ((instance_expr != null) && (instance_expr.Type.IsGenericParameter))
5799 ig.Emit (OpCodes.Constrained, instance_expr.Type);
5802 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
5803 call_op = OpCodes.Call;
5805 call_op = OpCodes.Callvirt;
5807 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
5808 Type[] varargs_types = GetVarargsTypes (ec, method, Arguments);
5809 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
5816 // and DoFoo is not virtual, you can omit the callvirt,
5817 // because you don't need the null checking behavior.
5819 if (method is MethodInfo)
5820 ig.Emit (call_op, (MethodInfo) method);
5822 ig.Emit (call_op, (ConstructorInfo) method);
5825 public override void Emit (EmitContext ec)
5827 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5829 EmitCall (ec, mg.IsBase, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5832 public override void EmitStatement (EmitContext ec)
5837 // Pop the return value if there is one
5839 if (method is MethodInfo){
5840 Type ret = ((MethodInfo)method).ReturnType;
5841 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5842 ec.ig.Emit (OpCodes.Pop);
5847 public class InvocationOrCast : ExpressionStatement
5850 Expression argument;
5852 public InvocationOrCast (Expression expr, Expression argument, Location loc)
5855 this.argument = argument;
5859 public override Expression DoResolve (EmitContext ec)
5862 // First try to resolve it as a cast.
5864 TypeExpr te = expr.ResolveAsTypeStep (ec) as TypeExpr;
5865 if ((te != null) && (te.eclass == ExprClass.Type)) {
5866 Cast cast = new Cast (te, argument, loc);
5867 return cast.Resolve (ec);
5871 // This can either be a type or a delegate invocation.
5872 // Let's just resolve it and see what we'll get.
5874 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5879 // Ok, so it's a Cast.
5881 if (expr.eclass == ExprClass.Type) {
5882 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
5883 return cast.Resolve (ec);
5887 // It's a delegate invocation.
5889 if (!TypeManager.IsDelegateType (expr.Type)) {
5890 Error (149, "Method name expected");
5894 ArrayList args = new ArrayList ();
5895 args.Add (new Argument (argument, Argument.AType.Expression));
5896 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5897 return invocation.Resolve (ec);
5902 Error (201, "Only assignment, call, increment, decrement and new object " +
5903 "expressions can be used as a statement");
5906 public override ExpressionStatement ResolveStatement (EmitContext ec)
5909 // First try to resolve it as a cast.
5911 TypeExpr te = expr.ResolveAsTypeStep (ec) as TypeExpr;
5912 if ((te != null) && (te.eclass == ExprClass.Type)) {
5918 // This can either be a type or a delegate invocation.
5919 // Let's just resolve it and see what we'll get.
5921 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5922 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5928 // It's a delegate invocation.
5930 if (!TypeManager.IsDelegateType (expr.Type)) {
5931 Error (149, "Method name expected");
5935 ArrayList args = new ArrayList ();
5936 args.Add (new Argument (argument, Argument.AType.Expression));
5937 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5938 return invocation.ResolveStatement (ec);
5941 public override void Emit (EmitContext ec)
5943 throw new Exception ("Cannot happen");
5946 public override void EmitStatement (EmitContext ec)
5948 throw new Exception ("Cannot happen");
5953 // This class is used to "disable" the code generation for the
5954 // temporary variable when initializing value types.
5956 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5957 public void AddressOf (EmitContext ec, AddressOp Mode)
5964 /// Implements the new expression
5966 public class New : ExpressionStatement, IMemoryLocation {
5967 public readonly ArrayList Arguments;
5970 // During bootstrap, it contains the RequestedType,
5971 // but if `type' is not null, it *might* contain a NewDelegate
5972 // (because of field multi-initialization)
5974 public Expression RequestedType;
5976 MethodBase method = null;
5979 // If set, the new expression is for a value_target, and
5980 // we will not leave anything on the stack.
5982 Expression value_target;
5983 bool value_target_set = false;
5984 bool is_type_parameter = false;
5986 public New (Expression requested_type, ArrayList arguments, Location l)
5988 RequestedType = requested_type;
5989 Arguments = arguments;
5993 public bool SetValueTypeVariable (Expression value)
5995 value_target = value;
5996 value_target_set = true;
5997 if (!(value_target is IMemoryLocation)){
5998 Error_UnexpectedKind ("variable", loc);
6005 // This function is used to disable the following code sequence for
6006 // value type initialization:
6008 // AddressOf (temporary)
6012 // Instead the provide will have provided us with the address on the
6013 // stack to store the results.
6015 static Expression MyEmptyExpression;
6017 public void DisableTemporaryValueType ()
6019 if (MyEmptyExpression == null)
6020 MyEmptyExpression = new EmptyAddressOf ();
6023 // To enable this, look into:
6024 // test-34 and test-89 and self bootstrapping.
6026 // For instance, we can avoid a copy by using `newobj'
6027 // instead of Call + Push-temp on value types.
6028 // value_target = MyEmptyExpression;
6031 public override Expression DoResolve (EmitContext ec)
6034 // The New DoResolve might be called twice when initializing field
6035 // expressions (see EmitFieldInitializers, the call to
6036 // GetInitializerExpression will perform a resolve on the expression,
6037 // and later the assign will trigger another resolution
6039 // This leads to bugs (#37014)
6042 if (RequestedType is NewDelegate)
6043 return RequestedType;
6047 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec);
6055 CheckObsoleteAttribute (type);
6057 bool IsDelegate = TypeManager.IsDelegateType (type);
6060 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
6061 if (RequestedType != null)
6062 if (!(RequestedType is NewDelegate))
6063 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
6064 return RequestedType;
6067 if (type.IsGenericParameter) {
6068 if (!TypeManager.HasConstructorConstraint (type)) {
6069 Error (304, String.Format (
6070 "Cannot create an instance of the " +
6071 "variable type '{0}' because it " +
6072 "doesn't have the new() constraint",
6077 if ((Arguments != null) && (Arguments.Count != 0)) {
6078 Error (417, String.Format (
6079 "`{0}': cannot provide arguments " +
6080 "when creating an instance of a " +
6081 "variable type.", type));
6085 is_type_parameter = true;
6086 eclass = ExprClass.Value;
6090 if (type.IsInterface || type.IsAbstract){
6091 Error (144, "It is not possible to create instances of interfaces or abstract classes");
6095 if (type.IsAbstract && type.IsSealed) {
6096 Report.Error (712, loc, "Cannot create an instance of the static class '{0}'", TypeManager.CSharpName (type));
6100 bool is_struct = type.IsValueType;
6101 eclass = ExprClass.Value;
6104 // SRE returns a match for .ctor () on structs (the object constructor),
6105 // so we have to manually ignore it.
6107 if (is_struct && Arguments == null)
6111 ml = MemberLookupFinal (ec, type, type, ".ctor",
6112 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
6113 MemberTypes.Constructor,
6114 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
6119 if (! (ml is MethodGroupExpr)){
6121 ml.Error_UnexpectedKind ("method group", loc);
6127 if (Arguments != null){
6128 foreach (Argument a in Arguments){
6129 if (!a.Resolve (ec, loc))
6134 method = Invocation.OverloadResolve (
6135 ec, (MethodGroupExpr) ml, Arguments, false, loc);
6139 if (method == null) {
6140 if (!is_struct || Arguments.Count > 0) {
6141 Error (1501, String.Format (
6142 "New invocation: Can not find a constructor in `{0}' for this argument list",
6143 TypeManager.CSharpName (type)));
6151 bool DoEmitTypeParameter (EmitContext ec)
6153 ILGenerator ig = ec.ig;
6155 ig.Emit (OpCodes.Ldtoken, type);
6156 ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6157 ig.Emit (OpCodes.Call, TypeManager.activator_create_instance);
6158 ig.Emit (OpCodes.Unbox_Any, type);
6164 // This DoEmit can be invoked in two contexts:
6165 // * As a mechanism that will leave a value on the stack (new object)
6166 // * As one that wont (init struct)
6168 // You can control whether a value is required on the stack by passing
6169 // need_value_on_stack. The code *might* leave a value on the stack
6170 // so it must be popped manually
6172 // If we are dealing with a ValueType, we have a few
6173 // situations to deal with:
6175 // * The target is a ValueType, and we have been provided
6176 // the instance (this is easy, we are being assigned).
6178 // * The target of New is being passed as an argument,
6179 // to a boxing operation or a function that takes a
6182 // In this case, we need to create a temporary variable
6183 // that is the argument of New.
6185 // Returns whether a value is left on the stack
6187 bool DoEmit (EmitContext ec, bool need_value_on_stack)
6189 bool is_value_type = TypeManager.IsValueType (type);
6190 ILGenerator ig = ec.ig;
6195 // Allow DoEmit() to be called multiple times.
6196 // We need to create a new LocalTemporary each time since
6197 // you can't share LocalBuilders among ILGeneators.
6198 if (!value_target_set)
6199 value_target = new LocalTemporary (ec, type);
6201 ml = (IMemoryLocation) value_target;
6202 ml.AddressOf (ec, AddressOp.Store);
6206 Invocation.EmitArguments (ec, method, Arguments, false, null);
6210 ig.Emit (OpCodes.Initobj, type);
6212 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6213 if (need_value_on_stack){
6214 value_target.Emit (ec);
6219 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
6224 public override void Emit (EmitContext ec)
6226 if (is_type_parameter)
6227 DoEmitTypeParameter (ec);
6232 public override void EmitStatement (EmitContext ec)
6234 if (is_type_parameter)
6235 throw new InvalidOperationException ();
6237 if (DoEmit (ec, false))
6238 ec.ig.Emit (OpCodes.Pop);
6241 public void AddressOf (EmitContext ec, AddressOp Mode)
6243 if (is_type_parameter)
6244 throw new InvalidOperationException ();
6246 if (!type.IsValueType){
6248 // We throw an exception. So far, I believe we only need to support
6250 // foreach (int j in new StructType ())
6253 throw new Exception ("AddressOf should not be used for classes");
6256 if (!value_target_set)
6257 value_target = new LocalTemporary (ec, type);
6259 IMemoryLocation ml = (IMemoryLocation) value_target;
6260 ml.AddressOf (ec, AddressOp.Store);
6262 Invocation.EmitArguments (ec, method, Arguments, false, null);
6265 ec.ig.Emit (OpCodes.Initobj, type);
6267 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6269 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
6274 /// 14.5.10.2: Represents an array creation expression.
6278 /// There are two possible scenarios here: one is an array creation
6279 /// expression that specifies the dimensions and optionally the
6280 /// initialization data and the other which does not need dimensions
6281 /// specified but where initialization data is mandatory.
6283 public class ArrayCreation : Expression {
6284 Expression requested_base_type;
6285 ArrayList initializers;
6288 // The list of Argument types.
6289 // This is used to construct the `newarray' or constructor signature
6291 ArrayList arguments;
6294 // Method used to create the array object.
6296 MethodBase new_method = null;
6298 Type array_element_type;
6299 Type underlying_type;
6300 bool is_one_dimensional = false;
6301 bool is_builtin_type = false;
6302 bool expect_initializers = false;
6303 int num_arguments = 0;
6307 ArrayList array_data;
6312 // The number of array initializers that we can handle
6313 // via the InitializeArray method - through EmitStaticInitializers
6315 int num_automatic_initializers;
6317 const int max_automatic_initializers = 6;
6319 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
6321 this.requested_base_type = requested_base_type;
6322 this.initializers = initializers;
6326 arguments = new ArrayList ();
6328 foreach (Expression e in exprs) {
6329 arguments.Add (new Argument (e, Argument.AType.Expression));
6334 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
6336 this.requested_base_type = requested_base_type;
6337 this.initializers = initializers;
6341 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
6343 //string tmp = rank.Substring (rank.LastIndexOf ('['));
6345 //dimensions = tmp.Length - 1;
6346 expect_initializers = true;
6349 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
6351 StringBuilder sb = new StringBuilder (rank);
6354 for (int i = 1; i < idx_count; i++)
6359 return new ComposedCast (base_type, sb.ToString (), loc);
6362 void Error_IncorrectArrayInitializer ()
6364 Error (178, "Incorrectly structured array initializer");
6367 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
6369 if (specified_dims) {
6370 Argument a = (Argument) arguments [idx];
6372 if (!a.Resolve (ec, loc))
6375 if (!(a.Expr is Constant)) {
6376 Error (150, "A constant value is expected");
6380 int value = (int) ((Constant) a.Expr).GetValue ();
6382 if (value != probe.Count) {
6383 Error_IncorrectArrayInitializer ();
6387 bounds [idx] = value;
6390 int child_bounds = -1;
6391 foreach (object o in probe) {
6392 if (o is ArrayList) {
6393 int current_bounds = ((ArrayList) o).Count;
6395 if (child_bounds == -1)
6396 child_bounds = current_bounds;
6398 else if (child_bounds != current_bounds){
6399 Error_IncorrectArrayInitializer ();
6402 if (specified_dims && (idx + 1 >= arguments.Count)){
6403 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
6407 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
6411 if (child_bounds != -1){
6412 Error_IncorrectArrayInitializer ();
6416 Expression tmp = (Expression) o;
6417 tmp = tmp.Resolve (ec);
6421 // Console.WriteLine ("I got: " + tmp);
6422 // Handle initialization from vars, fields etc.
6424 Expression conv = Convert.ImplicitConversionRequired (
6425 ec, tmp, underlying_type, loc);
6430 if (conv is StringConstant || conv is DecimalConstant || conv is NullCast) {
6431 // These are subclasses of Constant that can appear as elements of an
6432 // array that cannot be statically initialized (with num_automatic_initializers
6433 // > max_automatic_initializers), so num_automatic_initializers should be left as zero.
6434 array_data.Add (conv);
6435 } else if (conv is Constant) {
6436 // These are the types of Constant that can appear in arrays that can be
6437 // statically allocated.
6438 array_data.Add (conv);
6439 num_automatic_initializers++;
6441 array_data.Add (conv);
6448 public void UpdateIndices (EmitContext ec)
6451 for (ArrayList probe = initializers; probe != null;) {
6452 if (probe.Count > 0 && probe [0] is ArrayList) {
6453 Expression e = new IntConstant (probe.Count);
6454 arguments.Add (new Argument (e, Argument.AType.Expression));
6456 bounds [i++] = probe.Count;
6458 probe = (ArrayList) probe [0];
6461 Expression e = new IntConstant (probe.Count);
6462 arguments.Add (new Argument (e, Argument.AType.Expression));
6464 bounds [i++] = probe.Count;
6471 public bool ValidateInitializers (EmitContext ec, Type array_type)
6473 if (initializers == null) {
6474 if (expect_initializers)
6480 if (underlying_type == null)
6484 // We use this to store all the date values in the order in which we
6485 // will need to store them in the byte blob later
6487 array_data = new ArrayList ();
6488 bounds = new Hashtable ();
6492 if (arguments != null) {
6493 ret = CheckIndices (ec, initializers, 0, true);
6496 arguments = new ArrayList ();
6498 ret = CheckIndices (ec, initializers, 0, false);
6505 if (arguments.Count != dimensions) {
6506 Error_IncorrectArrayInitializer ();
6515 // Converts `source' to an int, uint, long or ulong.
6517 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
6521 bool old_checked = ec.CheckState;
6522 ec.CheckState = true;
6524 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
6525 if (target == null){
6526 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
6527 if (target == null){
6528 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
6529 if (target == null){
6530 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
6532 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
6536 ec.CheckState = old_checked;
6539 // Only positive constants are allowed at compile time
6541 if (target is Constant){
6542 if (target is IntConstant){
6543 if (((IntConstant) target).Value < 0){
6544 Expression.Error_NegativeArrayIndex (loc);
6549 if (target is LongConstant){
6550 if (((LongConstant) target).Value < 0){
6551 Expression.Error_NegativeArrayIndex (loc);
6562 // Creates the type of the array
6564 bool LookupType (EmitContext ec)
6566 StringBuilder array_qualifier = new StringBuilder (rank);
6569 // `In the first form allocates an array instace of the type that results
6570 // from deleting each of the individual expression from the expression list'
6572 if (num_arguments > 0) {
6573 array_qualifier.Append ("[");
6574 for (int i = num_arguments-1; i > 0; i--)
6575 array_qualifier.Append (",");
6576 array_qualifier.Append ("]");
6582 TypeExpr array_type_expr;
6583 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
6584 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec);
6585 if (array_type_expr == null)
6588 type = array_type_expr.Type;
6590 if (!type.IsArray) {
6591 Error (622, "Can only use array initializer expressions to assign to array types. Try using a new expression instead.");
6594 underlying_type = TypeManager.GetElementType (type);
6595 dimensions = type.GetArrayRank ();
6600 public override Expression DoResolve (EmitContext ec)
6604 if (!LookupType (ec))
6608 // First step is to validate the initializers and fill
6609 // in any missing bits
6611 if (!ValidateInitializers (ec, type))
6614 if (arguments == null)
6617 arg_count = arguments.Count;
6618 foreach (Argument a in arguments){
6619 if (!a.Resolve (ec, loc))
6622 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
6623 if (real_arg == null)
6630 array_element_type = TypeManager.GetElementType (type);
6632 if (array_element_type.IsAbstract && array_element_type.IsSealed) {
6633 Report.Error (719, loc, "'{0}': array elements cannot be of static type", TypeManager.CSharpName (array_element_type));
6637 if (arg_count == 1) {
6638 is_one_dimensional = true;
6639 eclass = ExprClass.Value;
6643 is_builtin_type = TypeManager.IsBuiltinType (type);
6645 if (is_builtin_type) {
6648 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
6649 AllBindingFlags, loc);
6651 if (!(ml is MethodGroupExpr)) {
6652 ml.Error_UnexpectedKind ("method group", loc);
6657 Error (-6, "New invocation: Can not find a constructor for " +
6658 "this argument list");
6662 new_method = Invocation.OverloadResolve (
6663 ec, (MethodGroupExpr) ml, arguments, false, loc);
6665 if (new_method == null) {
6666 Error (-6, "New invocation: Can not find a constructor for " +
6667 "this argument list");
6671 eclass = ExprClass.Value;
6674 ModuleBuilder mb = CodeGen.Module.Builder;
6675 ArrayList args = new ArrayList ();
6677 if (arguments != null) {
6678 for (int i = 0; i < arg_count; i++)
6679 args.Add (TypeManager.int32_type);
6682 Type [] arg_types = null;
6685 arg_types = new Type [args.Count];
6687 args.CopyTo (arg_types, 0);
6689 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
6692 if (new_method == null) {
6693 Error (-6, "New invocation: Can not find a constructor for " +
6694 "this argument list");
6698 eclass = ExprClass.Value;
6703 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
6708 int count = array_data.Count;
6710 if (underlying_type.IsEnum)
6711 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
6713 factor = GetTypeSize (underlying_type);
6715 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
6717 data = new byte [(count * factor + 4) & ~3];
6720 for (int i = 0; i < count; ++i) {
6721 object v = array_data [i];
6723 if (v is EnumConstant)
6724 v = ((EnumConstant) v).Child;
6726 if (v is Constant && !(v is StringConstant))
6727 v = ((Constant) v).GetValue ();
6733 if (underlying_type == TypeManager.int64_type){
6734 if (!(v is Expression)){
6735 long val = (long) v;
6737 for (int j = 0; j < factor; ++j) {
6738 data [idx + j] = (byte) (val & 0xFF);
6742 } else if (underlying_type == TypeManager.uint64_type){
6743 if (!(v is Expression)){
6744 ulong val = (ulong) v;
6746 for (int j = 0; j < factor; ++j) {
6747 data [idx + j] = (byte) (val & 0xFF);
6751 } else if (underlying_type == TypeManager.float_type) {
6752 if (!(v is Expression)){
6753 element = BitConverter.GetBytes ((float) v);
6755 for (int j = 0; j < factor; ++j)
6756 data [idx + j] = element [j];
6758 } else if (underlying_type == TypeManager.double_type) {
6759 if (!(v is Expression)){
6760 element = BitConverter.GetBytes ((double) v);
6762 for (int j = 0; j < factor; ++j)
6763 data [idx + j] = element [j];
6765 } else if (underlying_type == TypeManager.char_type){
6766 if (!(v is Expression)){
6767 int val = (int) ((char) v);
6769 data [idx] = (byte) (val & 0xff);
6770 data [idx+1] = (byte) (val >> 8);
6772 } else if (underlying_type == TypeManager.short_type){
6773 if (!(v is Expression)){
6774 int val = (int) ((short) v);
6776 data [idx] = (byte) (val & 0xff);
6777 data [idx+1] = (byte) (val >> 8);
6779 } else if (underlying_type == TypeManager.ushort_type){
6780 if (!(v is Expression)){
6781 int val = (int) ((ushort) v);
6783 data [idx] = (byte) (val & 0xff);
6784 data [idx+1] = (byte) (val >> 8);
6786 } else if (underlying_type == TypeManager.int32_type) {
6787 if (!(v is Expression)){
6790 data [idx] = (byte) (val & 0xff);
6791 data [idx+1] = (byte) ((val >> 8) & 0xff);
6792 data [idx+2] = (byte) ((val >> 16) & 0xff);
6793 data [idx+3] = (byte) (val >> 24);
6795 } else if (underlying_type == TypeManager.uint32_type) {
6796 if (!(v is Expression)){
6797 uint val = (uint) v;
6799 data [idx] = (byte) (val & 0xff);
6800 data [idx+1] = (byte) ((val >> 8) & 0xff);
6801 data [idx+2] = (byte) ((val >> 16) & 0xff);
6802 data [idx+3] = (byte) (val >> 24);
6804 } else if (underlying_type == TypeManager.sbyte_type) {
6805 if (!(v is Expression)){
6806 sbyte val = (sbyte) v;
6807 data [idx] = (byte) val;
6809 } else if (underlying_type == TypeManager.byte_type) {
6810 if (!(v is Expression)){
6811 byte val = (byte) v;
6812 data [idx] = (byte) val;
6814 } else if (underlying_type == TypeManager.bool_type) {
6815 if (!(v is Expression)){
6816 bool val = (bool) v;
6817 data [idx] = (byte) (val ? 1 : 0);
6819 } else if (underlying_type == TypeManager.decimal_type){
6820 if (!(v is Expression)){
6821 int [] bits = Decimal.GetBits ((decimal) v);
6824 // FIXME: For some reason, this doesn't work on the MS runtime.
6825 int [] nbits = new int [4];
6826 nbits [0] = bits [3];
6827 nbits [1] = bits [2];
6828 nbits [2] = bits [0];
6829 nbits [3] = bits [1];
6831 for (int j = 0; j < 4; j++){
6832 data [p++] = (byte) (nbits [j] & 0xff);
6833 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6834 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6835 data [p++] = (byte) (nbits [j] >> 24);
6839 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6848 // Emits the initializers for the array
6850 void EmitStaticInitializers (EmitContext ec)
6853 // First, the static data
6856 ILGenerator ig = ec.ig;
6858 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6860 fb = RootContext.MakeStaticData (data);
6862 ig.Emit (OpCodes.Dup);
6863 ig.Emit (OpCodes.Ldtoken, fb);
6864 ig.Emit (OpCodes.Call,
6865 TypeManager.void_initializearray_array_fieldhandle);
6869 // Emits pieces of the array that can not be computed at compile
6870 // time (variables and string locations).
6872 // This always expect the top value on the stack to be the array
6874 void EmitDynamicInitializers (EmitContext ec)
6876 ILGenerator ig = ec.ig;
6877 int dims = bounds.Count;
6878 int [] current_pos = new int [dims];
6879 int top = array_data.Count;
6881 MethodInfo set = null;
6885 ModuleBuilder mb = null;
6886 mb = CodeGen.Module.Builder;
6887 args = new Type [dims + 1];
6890 for (j = 0; j < dims; j++)
6891 args [j] = TypeManager.int32_type;
6893 args [j] = array_element_type;
6895 set = mb.GetArrayMethod (
6897 CallingConventions.HasThis | CallingConventions.Standard,
6898 TypeManager.void_type, args);
6901 for (int i = 0; i < top; i++){
6903 Expression e = null;
6905 if (array_data [i] is Expression)
6906 e = (Expression) array_data [i];
6910 // Basically we do this for string literals and
6911 // other non-literal expressions
6913 if (e is EnumConstant){
6914 e = ((EnumConstant) e).Child;
6917 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6918 num_automatic_initializers <= max_automatic_initializers) {
6919 Type etype = e.Type;
6921 ig.Emit (OpCodes.Dup);
6923 for (int idx = 0; idx < dims; idx++)
6924 IntConstant.EmitInt (ig, current_pos [idx]);
6927 // If we are dealing with a struct, get the
6928 // address of it, so we can store it.
6931 etype.IsSubclassOf (TypeManager.value_type) &&
6932 (!TypeManager.IsBuiltinOrEnum (etype) ||
6933 etype == TypeManager.decimal_type)) {
6938 // Let new know that we are providing
6939 // the address where to store the results
6941 n.DisableTemporaryValueType ();
6944 ig.Emit (OpCodes.Ldelema, etype);
6950 bool is_stobj, has_type_arg;
6951 OpCode op = ArrayAccess.GetStoreOpcode (
6952 etype, out is_stobj,
6955 ig.Emit (OpCodes.Stobj, etype);
6956 else if (has_type_arg)
6957 ig.Emit (op, etype);
6961 ig.Emit (OpCodes.Call, set);
6968 for (int j = dims - 1; j >= 0; j--){
6970 if (current_pos [j] < (int) bounds [j])
6972 current_pos [j] = 0;
6977 void EmitArrayArguments (EmitContext ec)
6979 ILGenerator ig = ec.ig;
6981 foreach (Argument a in arguments) {
6982 Type atype = a.Type;
6985 if (atype == TypeManager.uint64_type)
6986 ig.Emit (OpCodes.Conv_Ovf_U4);
6987 else if (atype == TypeManager.int64_type)
6988 ig.Emit (OpCodes.Conv_Ovf_I4);
6992 public override void Emit (EmitContext ec)
6994 ILGenerator ig = ec.ig;
6996 EmitArrayArguments (ec);
6997 if (is_one_dimensional)
6998 ig.Emit (OpCodes.Newarr, array_element_type);
7000 if (is_builtin_type)
7001 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
7003 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
7006 if (initializers != null){
7008 // FIXME: Set this variable correctly.
7010 bool dynamic_initializers = true;
7012 // This will never be true for array types that cannot be statically
7013 // initialized. num_automatic_initializers will always be zero. See
7015 if (num_automatic_initializers > max_automatic_initializers)
7016 EmitStaticInitializers (ec);
7018 if (dynamic_initializers)
7019 EmitDynamicInitializers (ec);
7023 public object EncodeAsAttribute ()
7025 if (!is_one_dimensional){
7026 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
7030 if (array_data == null){
7031 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
7035 object [] ret = new object [array_data.Count];
7037 foreach (Expression e in array_data){
7040 if (e is NullLiteral)
7043 if (!Attribute.GetAttributeArgumentExpression (e, Location, array_element_type, out v))
7053 /// Represents the `this' construct
7055 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
7058 VariableInfo variable_info;
7060 public This (Block block, Location loc)
7066 public This (Location loc)
7071 public VariableInfo VariableInfo {
7072 get { return variable_info; }
7075 public bool VerifyFixed (bool is_expression)
7077 if ((variable_info == null) || (variable_info.LocalInfo == null))
7080 return variable_info.LocalInfo.IsFixed;
7083 public bool ResolveBase (EmitContext ec)
7085 eclass = ExprClass.Variable;
7087 if (ec.TypeContainer.CurrentType != null)
7088 type = ec.TypeContainer.CurrentType;
7090 type = ec.ContainerType;
7093 Error (26, "Keyword this not valid in static code");
7097 if ((block != null) && (block.ThisVariable != null))
7098 variable_info = block.ThisVariable.VariableInfo;
7103 public override Expression DoResolve (EmitContext ec)
7105 if (!ResolveBase (ec))
7108 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
7109 Error (188, "The this object cannot be used before all " +
7110 "of its fields are assigned to");
7111 variable_info.SetAssigned (ec);
7115 if (ec.IsFieldInitializer) {
7116 Error (27, "Keyword `this' can't be used outside a constructor, " +
7117 "a method or a property.");
7124 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
7126 if (!ResolveBase (ec))
7129 if (variable_info != null)
7130 variable_info.SetAssigned (ec);
7132 if (ec.TypeContainer is Class){
7133 Error (1604, "Cannot assign to `this'");
7140 public void Emit (EmitContext ec, bool leave_copy)
7144 ec.ig.Emit (OpCodes.Dup);
7147 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
7149 ILGenerator ig = ec.ig;
7151 if (ec.TypeContainer is Struct){
7155 ec.ig.Emit (OpCodes.Dup);
7156 ig.Emit (OpCodes.Stobj, type);
7158 throw new Exception ("how did you get here");
7162 public override void Emit (EmitContext ec)
7164 ILGenerator ig = ec.ig;
7167 if (ec.TypeContainer is Struct)
7168 ig.Emit (OpCodes.Ldobj, type);
7171 public void AddressOf (EmitContext ec, AddressOp mode)
7176 // FIGURE OUT WHY LDARG_S does not work
7178 // consider: struct X { int val; int P { set { val = value; }}}
7180 // Yes, this looks very bad. Look at `NOTAS' for
7182 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
7187 /// Represents the `__arglist' construct
7189 public class ArglistAccess : Expression
7191 public ArglistAccess (Location loc)
7196 public bool ResolveBase (EmitContext ec)
7198 eclass = ExprClass.Variable;
7199 type = TypeManager.runtime_argument_handle_type;
7203 public override Expression DoResolve (EmitContext ec)
7205 if (!ResolveBase (ec))
7208 if (ec.IsFieldInitializer || !ec.CurrentBlock.HasVarargs) {
7209 Error (190, "The __arglist construct is valid only within " +
7210 "a variable argument method.");
7217 public override void Emit (EmitContext ec)
7219 ec.ig.Emit (OpCodes.Arglist);
7224 /// Represents the `__arglist (....)' construct
7226 public class Arglist : Expression
7228 public readonly Argument[] Arguments;
7230 public Arglist (Argument[] args, Location l)
7236 public Type[] ArgumentTypes {
7238 Type[] retval = new Type [Arguments.Length];
7239 for (int i = 0; i < Arguments.Length; i++)
7240 retval [i] = Arguments [i].Type;
7245 public override Expression DoResolve (EmitContext ec)
7247 eclass = ExprClass.Variable;
7248 type = TypeManager.runtime_argument_handle_type;
7250 foreach (Argument arg in Arguments) {
7251 if (!arg.Resolve (ec, loc))
7258 public override void Emit (EmitContext ec)
7260 foreach (Argument arg in Arguments)
7266 // This produces the value that renders an instance, used by the iterators code
7268 public class ProxyInstance : Expression, IMemoryLocation {
7269 public override Expression DoResolve (EmitContext ec)
7271 eclass = ExprClass.Variable;
7272 type = ec.ContainerType;
7276 public override void Emit (EmitContext ec)
7278 ec.ig.Emit (OpCodes.Ldarg_0);
7282 public void AddressOf (EmitContext ec, AddressOp mode)
7284 ec.ig.Emit (OpCodes.Ldarg_0);
7289 /// Implements the typeof operator
7291 public class TypeOf : Expression {
7292 public Expression QueriedType;
7293 protected Type typearg;
7295 public TypeOf (Expression queried_type, Location l)
7297 QueriedType = queried_type;
7301 public override Expression DoResolve (EmitContext ec)
7303 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec);
7307 typearg = texpr.Type;
7309 if (typearg == TypeManager.void_type) {
7310 Error (673, "System.Void cannot be used from C# - " +
7311 "use typeof (void) to get the void type object");
7315 if (typearg.IsPointer && !ec.InUnsafe){
7319 CheckObsoleteAttribute (typearg);
7321 type = TypeManager.type_type;
7322 eclass = ExprClass.Type;
7326 public override void Emit (EmitContext ec)
7328 ec.ig.Emit (OpCodes.Ldtoken, typearg);
7329 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
7332 public Type TypeArg {
7333 get { return typearg; }
7338 /// Implements the `typeof (void)' operator
7340 public class TypeOfVoid : TypeOf {
7341 public TypeOfVoid (Location l) : base (null, l)
7346 public override Expression DoResolve (EmitContext ec)
7348 type = TypeManager.type_type;
7349 typearg = TypeManager.void_type;
7350 eclass = ExprClass.Type;
7356 /// Implements the sizeof expression
7358 public class SizeOf : Expression {
7359 public Expression QueriedType;
7362 public SizeOf (Expression queried_type, Location l)
7364 this.QueriedType = queried_type;
7368 public override Expression DoResolve (EmitContext ec)
7372 233, loc, "Sizeof may only be used in an unsafe context " +
7373 "(consider using System.Runtime.InteropServices.Marshal.SizeOf");
7377 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec);
7381 if (texpr is TypeParameterExpr){
7382 ((TypeParameterExpr)texpr).Error_CannotUseAsUnmanagedType (loc);
7386 type_queried = texpr.Type;
7388 CheckObsoleteAttribute (type_queried);
7390 if (!TypeManager.IsUnmanagedType (type_queried)){
7391 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
7395 type = TypeManager.int32_type;
7396 eclass = ExprClass.Value;
7400 public override void Emit (EmitContext ec)
7402 int size = GetTypeSize (type_queried);
7405 ec.ig.Emit (OpCodes.Sizeof, type_queried);
7407 IntConstant.EmitInt (ec.ig, size);
7412 /// Implements the member access expression
7414 public class MemberAccess : Expression {
7415 public string Identifier;
7416 protected Expression expr;
7417 protected TypeArguments args;
7419 public MemberAccess (Expression expr, string id, Location l)
7426 public MemberAccess (Expression expr, string id, TypeArguments args,
7428 : this (expr, id, l)
7433 public Expression Expr {
7439 public static void error176 (Location loc, string name)
7441 Report.Error (176, loc, "Static member `" +
7442 name + "' cannot be accessed " +
7443 "with an instance reference, qualify with a " +
7444 "type name instead");
7447 public static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Expression left, Location loc)
7449 SimpleName sn = left_original as SimpleName;
7450 if (sn == null || left == null || left.Type.Name != sn.Name)
7453 return RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc) != null;
7456 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
7457 Expression left, Location loc,
7458 Expression left_original)
7460 bool left_is_type, left_is_explicit;
7462 // If `left' is null, then we're called from SimpleNameResolve and this is
7463 // a member in the currently defining class.
7465 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
7466 left_is_explicit = false;
7468 // Implicitly default to `this' unless we're static.
7469 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
7470 left = ec.GetThis (loc);
7472 left_is_type = left is TypeExpr;
7473 left_is_explicit = true;
7476 if (member_lookup is FieldExpr){
7477 FieldExpr fe = (FieldExpr) member_lookup;
7478 FieldInfo fi = fe.FieldInfo.Mono_GetGenericFieldDefinition ();
7479 Type decl_type = fi.DeclaringType;
7481 if (fi is FieldBuilder) {
7482 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
7486 if (!c.LookupConstantValue (out o))
7489 object real_value = ((Constant) c.Expr).GetValue ();
7491 return Constantify (real_value, fi.FieldType);
7496 Type t = fi.FieldType;
7500 if (fi is FieldBuilder)
7501 o = TypeManager.GetValue ((FieldBuilder) fi);
7503 o = fi.GetValue (fi);
7505 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
7506 if (left_is_explicit && !left_is_type &&
7507 !IdenticalNameAndTypeName (ec, left_original, member_lookup, loc)) {
7508 error176 (loc, fe.FieldInfo.Name);
7512 Expression enum_member = MemberLookup (
7513 ec, decl_type, "value__", MemberTypes.Field,
7514 AllBindingFlags, loc);
7516 Enum en = TypeManager.LookupEnum (decl_type);
7520 c = Constantify (o, en.UnderlyingType);
7522 c = Constantify (o, enum_member.Type);
7524 return new EnumConstant (c, decl_type);
7527 Expression exp = Constantify (o, t);
7529 if (left_is_explicit && !left_is_type) {
7530 error176 (loc, fe.FieldInfo.Name);
7537 if (fi.FieldType.IsPointer && !ec.InUnsafe){
7543 if (member_lookup is EventExpr) {
7544 EventExpr ee = (EventExpr) member_lookup;
7547 // If the event is local to this class, we transform ourselves into
7551 if (ee.EventInfo.DeclaringType == ec.ContainerType ||
7552 TypeManager.IsNestedChildOf(ec.ContainerType, ee.EventInfo.DeclaringType)) {
7553 MemberInfo mi = GetFieldFromEvent (ee);
7557 // If this happens, then we have an event with its own
7558 // accessors and private field etc so there's no need
7559 // to transform ourselves.
7561 ee.InstanceExpression = left;
7565 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
7568 Report.Error (-200, loc, "Internal error!!");
7572 if (!left_is_explicit)
7575 ee.InstanceExpression = left;
7577 return ResolveMemberAccess (ec, ml, left, loc, left_original);
7581 if (member_lookup is IMemberExpr) {
7582 IMemberExpr me = (IMemberExpr) member_lookup;
7583 MethodGroupExpr mg = me as MethodGroupExpr;
7586 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
7587 mg.IsExplicitImpl = left_is_explicit;
7590 if ((ec.IsFieldInitializer || ec.IsStatic) &&
7591 IdenticalNameAndTypeName (ec, left_original, member_lookup, loc))
7592 return member_lookup;
7594 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
7599 if (!me.IsInstance){
7600 if (IdenticalNameAndTypeName (ec, left_original, left, loc))
7601 return member_lookup;
7603 if (left_is_explicit) {
7604 error176 (loc, me.Name);
7610 // Since we can not check for instance objects in SimpleName,
7611 // becaue of the rule that allows types and variables to share
7612 // the name (as long as they can be de-ambiguated later, see
7613 // IdenticalNameAndTypeName), we have to check whether left
7614 // is an instance variable in a static context
7616 // However, if the left-hand value is explicitly given, then
7617 // it is already our instance expression, so we aren't in
7621 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
7622 IMemberExpr mexp = (IMemberExpr) left;
7624 if (!mexp.IsStatic){
7625 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
7630 if ((mg != null) && IdenticalNameAndTypeName (ec, left_original, left, loc))
7631 mg.IdenticalTypeName = true;
7633 me.InstanceExpression = left;
7636 return member_lookup;
7639 Console.WriteLine ("Left is: " + left);
7640 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
7641 Environment.Exit (1);
7645 public virtual Expression DoResolve (EmitContext ec, Expression right_side,
7649 throw new Exception ();
7652 // Resolve the expression with flow analysis turned off, we'll do the definite
7653 // assignment checks later. This is because we don't know yet what the expression
7654 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7655 // definite assignment check on the actual field and not on the whole struct.
7658 Expression original = expr;
7659 expr = expr.Resolve (ec, flags | ResolveFlags.Intermediate | ResolveFlags.DisableFlowAnalysis);
7663 if (expr is SimpleName){
7664 SimpleName child_expr = (SimpleName) expr;
7665 string fqname = DeclSpace.MakeFQN (child_expr.Name, Identifier);
7667 Expression new_expr;
7669 new_expr = new ConstructedType (fqname, args, loc);
7671 new_expr = new SimpleName (fqname, loc);
7673 return new_expr.Resolve (ec, flags);
7677 // TODO: I mailed Ravi about this, and apparently we can get rid
7678 // of this and put it in the right place.
7680 // Handle enums here when they are in transit.
7681 // Note that we cannot afford to hit MemberLookup in this case because
7682 // it will fail to find any members at all
7686 if (expr is TypeExpr){
7687 expr_type = expr.Type;
7689 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
7690 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", expr_type);
7694 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
7695 Enum en = TypeManager.LookupEnum (expr_type);
7698 object value = en.LookupEnumValue (ec, Identifier, loc);
7701 MemberCore mc = en.GetDefinition (Identifier);
7702 ObsoleteAttribute oa = mc.GetObsoleteAttribute (en);
7704 AttributeTester.Report_ObsoleteMessage (oa, mc.GetSignatureForError (), Location);
7706 oa = en.GetObsoleteAttribute (en);
7708 AttributeTester.Report_ObsoleteMessage (oa, en.GetSignatureForError (), Location);
7711 Constant c = Constantify (value, en.UnderlyingType);
7712 return new EnumConstant (c, expr_type);
7715 CheckObsoleteAttribute (expr_type);
7717 FieldInfo fi = expr_type.GetField (Identifier);
7719 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
7721 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), Location);
7726 expr_type = expr.Type;
7728 if (expr_type.IsPointer){
7729 Error (23, "The `.' operator can not be applied to pointer operands (" +
7730 TypeManager.CSharpName (expr_type) + ")");
7734 int errors = Report.Errors;
7736 Expression member_lookup;
7737 member_lookup = MemberLookup (
7738 ec, expr_type, expr_type, Identifier, loc);
7739 if ((member_lookup == null) && (args != null)) {
7740 string lookup_id = MemberName.MakeName (Identifier, args);
7741 member_lookup = MemberLookup (
7742 ec, expr_type, expr_type, lookup_id, loc);
7744 if (member_lookup == null) {
7745 MemberLookupFailed (
7746 ec, expr_type, expr_type, Identifier, null, loc);
7750 if (member_lookup is TypeExpr) {
7751 if (!(expr is TypeExpr) && !(expr is SimpleName)) {
7752 Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
7753 member_lookup.Type + "' instead");
7757 return member_lookup;
7761 string full_name = expr_type + "." + Identifier;
7763 if (member_lookup is FieldExpr) {
7764 Report.Error (307, loc, "The field `{0}' cannot " +
7765 "be used with type arguments", full_name);
7767 } else if (member_lookup is EventExpr) {
7768 Report.Error (307, loc, "The event `{0}' cannot " +
7769 "be used with type arguments", full_name);
7771 } else if (member_lookup is PropertyExpr) {
7772 Report.Error (307, loc, "The property `{0}' cannot " +
7773 "be used with type arguments", full_name);
7778 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
7779 if (member_lookup == null)
7783 MethodGroupExpr mg = member_lookup as MethodGroupExpr;
7785 throw new InternalErrorException ();
7787 return mg.ResolveGeneric (ec, args);
7790 // The following DoResolve/DoResolveLValue will do the definite assignment
7793 if (right_side != null)
7794 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
7796 member_lookup = member_lookup.DoResolve (ec);
7798 return member_lookup;
7801 public override Expression DoResolve (EmitContext ec)
7803 return DoResolve (ec, null, ResolveFlags.VariableOrValue |
7804 ResolveFlags.SimpleName | ResolveFlags.Type);
7807 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7809 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
7810 ResolveFlags.SimpleName | ResolveFlags.Type);
7813 public override Expression ResolveAsTypeStep (EmitContext ec)
7815 string fname = null;
7816 MemberAccess full_expr = this;
7817 while (full_expr != null) {
7819 fname = String.Concat (full_expr.Identifier, ".", fname);
7821 fname = full_expr.Identifier;
7823 fname = MemberName.MakeName (fname, args);
7825 if (full_expr.Expr is SimpleName) {
7826 string full_name = String.Concat (((SimpleName) full_expr.Expr).Name, ".", fname);
7827 Type fully_qualified = ec.DeclSpace.FindType (loc, full_name);
7828 if (fully_qualified != null) {
7830 return new TypeExpression (fully_qualified, loc);
7832 ConstructedType ctype = new ConstructedType (fully_qualified, args, loc);
7833 return ctype.ResolveAsTypeStep (ec);
7837 full_expr = full_expr.Expr as MemberAccess;
7840 Expression new_expr = expr.ResolveAsTypeStep (ec);
7842 if (new_expr == null)
7845 if (new_expr is SimpleName){
7846 SimpleName child_expr = (SimpleName) new_expr;
7847 string fqname = DeclSpace.MakeFQN (child_expr.Name, Identifier);
7850 new_expr = new ConstructedType (fqname, args, loc);
7852 new_expr = new SimpleName (fqname, loc);
7854 return new_expr.ResolveAsTypeStep (ec);
7857 TypeExpr tnew_expr = new_expr.ResolveAsTypeTerminal (ec);
7858 if (tnew_expr == null)
7861 Type expr_type = tnew_expr.Type;
7863 if (expr_type.IsPointer){
7864 Error (23, "The `.' operator can not be applied to pointer operands (" +
7865 TypeManager.CSharpName (expr_type) + ")");
7869 Expression member_lookup;
7871 lookup_id = MemberName.MakeName (Identifier, args);
7872 member_lookup = MemberLookupFinal (
7873 ec, expr_type, expr_type, lookup_id, loc);
7874 if (member_lookup == null)
7877 TypeExpr texpr = member_lookup as TypeExpr;
7881 texpr = texpr.ResolveAsTypeTerminal (ec);
7885 TypeArguments the_args = args;
7886 if (TypeManager.HasGenericArguments (expr_type)) {
7887 Type[] decl_args = TypeManager.GetTypeArguments (expr_type);
7889 TypeArguments new_args = new TypeArguments (loc);
7890 foreach (Type decl in decl_args)
7891 new_args.Add (new TypeExpression (decl, loc));
7894 new_args.Add (args);
7896 the_args = new_args;
7899 if (the_args != null) {
7900 ConstructedType ctype = new ConstructedType (texpr.Type, the_args, loc);
7901 return ctype.ResolveAsTypeStep (ec);
7907 public override void Emit (EmitContext ec)
7909 throw new Exception ("Should not happen");
7912 public override string ToString ()
7914 return expr + "." + MemberName.MakeName (Identifier, args);
7919 /// Implements checked expressions
7921 public class CheckedExpr : Expression {
7923 public Expression Expr;
7925 public CheckedExpr (Expression e, Location l)
7931 public override Expression DoResolve (EmitContext ec)
7933 bool last_check = ec.CheckState;
7934 bool last_const_check = ec.ConstantCheckState;
7936 ec.CheckState = true;
7937 ec.ConstantCheckState = true;
7938 Expr = Expr.Resolve (ec);
7939 ec.CheckState = last_check;
7940 ec.ConstantCheckState = last_const_check;
7945 if (Expr is Constant)
7948 eclass = Expr.eclass;
7953 public override void Emit (EmitContext ec)
7955 bool last_check = ec.CheckState;
7956 bool last_const_check = ec.ConstantCheckState;
7958 ec.CheckState = true;
7959 ec.ConstantCheckState = true;
7961 ec.CheckState = last_check;
7962 ec.ConstantCheckState = last_const_check;
7968 /// Implements the unchecked expression
7970 public class UnCheckedExpr : Expression {
7972 public Expression Expr;
7974 public UnCheckedExpr (Expression e, Location l)
7980 public override Expression DoResolve (EmitContext ec)
7982 bool last_check = ec.CheckState;
7983 bool last_const_check = ec.ConstantCheckState;
7985 ec.CheckState = false;
7986 ec.ConstantCheckState = false;
7987 Expr = Expr.Resolve (ec);
7988 ec.CheckState = last_check;
7989 ec.ConstantCheckState = last_const_check;
7994 if (Expr is Constant)
7997 eclass = Expr.eclass;
8002 public override void Emit (EmitContext ec)
8004 bool last_check = ec.CheckState;
8005 bool last_const_check = ec.ConstantCheckState;
8007 ec.CheckState = false;
8008 ec.ConstantCheckState = false;
8010 ec.CheckState = last_check;
8011 ec.ConstantCheckState = last_const_check;
8017 /// An Element Access expression.
8019 /// During semantic analysis these are transformed into
8020 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
8022 public class ElementAccess : Expression {
8023 public ArrayList Arguments;
8024 public Expression Expr;
8026 public ElementAccess (Expression e, ArrayList e_list, Location l)
8035 Arguments = new ArrayList ();
8036 foreach (Expression tmp in e_list)
8037 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
8041 bool CommonResolve (EmitContext ec)
8043 Expr = Expr.Resolve (ec);
8048 if (Arguments == null)
8051 foreach (Argument a in Arguments){
8052 if (!a.Resolve (ec, loc))
8059 Expression MakePointerAccess (EmitContext ec)
8063 if (t == TypeManager.void_ptr_type){
8064 Error (242, "The array index operation is not valid for void pointers");
8067 if (Arguments.Count != 1){
8068 Error (196, "A pointer must be indexed by a single value");
8073 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc).Resolve (ec);
8076 return new Indirection (p, loc).Resolve (ec);
8079 public override Expression DoResolve (EmitContext ec)
8081 if (!CommonResolve (ec))
8085 // We perform some simple tests, and then to "split" the emit and store
8086 // code we create an instance of a different class, and return that.
8088 // I am experimenting with this pattern.
8092 if (t == TypeManager.array_type){
8093 Report.Error (21, loc, "Cannot use indexer on System.Array");
8098 return (new ArrayAccess (this, loc)).Resolve (ec);
8099 else if (t.IsPointer)
8100 return MakePointerAccess (ec);
8102 return (new IndexerAccess (this, loc)).Resolve (ec);
8105 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8107 if (!CommonResolve (ec))
8112 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
8113 else if (t.IsPointer)
8114 return MakePointerAccess (ec);
8116 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
8119 public override void Emit (EmitContext ec)
8121 throw new Exception ("Should never be reached");
8126 /// Implements array access
8128 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
8130 // Points to our "data" repository
8134 LocalTemporary temp;
8137 public ArrayAccess (ElementAccess ea_data, Location l)
8140 eclass = ExprClass.Variable;
8144 public override Expression DoResolve (EmitContext ec)
8147 ExprClass eclass = ea.Expr.eclass;
8149 // As long as the type is valid
8150 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
8151 eclass == ExprClass.Value)) {
8152 ea.Expr.Error_UnexpectedKind ("variable or value");
8157 Type t = ea.Expr.Type;
8158 if (t.GetArrayRank () != ea.Arguments.Count){
8160 "Incorrect number of indexes for array " +
8161 " expected: " + t.GetArrayRank () + " got: " +
8162 ea.Arguments.Count);
8166 type = TypeManager.GetElementType (t);
8167 if (type.IsPointer && !ec.InUnsafe){
8168 UnsafeError (ea.Location);
8172 foreach (Argument a in ea.Arguments){
8173 Type argtype = a.Type;
8175 if (argtype == TypeManager.int32_type ||
8176 argtype == TypeManager.uint32_type ||
8177 argtype == TypeManager.int64_type ||
8178 argtype == TypeManager.uint64_type) {
8179 Constant c = a.Expr as Constant;
8180 if (c != null && c.IsNegative) {
8181 Report.Warning (251, 2, a.Expr.Location, "Indexing an array with a negative index (array indices always start at zero)");
8187 // Mhm. This is strage, because the Argument.Type is not the same as
8188 // Argument.Expr.Type: the value changes depending on the ref/out setting.
8190 // Wonder if I will run into trouble for this.
8192 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
8197 eclass = ExprClass.Variable;
8203 /// Emits the right opcode to load an object of Type `t'
8204 /// from an array of T
8206 static public void EmitLoadOpcode (ILGenerator ig, Type type)
8208 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
8209 ig.Emit (OpCodes.Ldelem_U1);
8210 else if (type == TypeManager.sbyte_type)
8211 ig.Emit (OpCodes.Ldelem_I1);
8212 else if (type == TypeManager.short_type)
8213 ig.Emit (OpCodes.Ldelem_I2);
8214 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
8215 ig.Emit (OpCodes.Ldelem_U2);
8216 else if (type == TypeManager.int32_type)
8217 ig.Emit (OpCodes.Ldelem_I4);
8218 else if (type == TypeManager.uint32_type)
8219 ig.Emit (OpCodes.Ldelem_U4);
8220 else if (type == TypeManager.uint64_type)
8221 ig.Emit (OpCodes.Ldelem_I8);
8222 else if (type == TypeManager.int64_type)
8223 ig.Emit (OpCodes.Ldelem_I8);
8224 else if (type == TypeManager.float_type)
8225 ig.Emit (OpCodes.Ldelem_R4);
8226 else if (type == TypeManager.double_type)
8227 ig.Emit (OpCodes.Ldelem_R8);
8228 else if (type == TypeManager.intptr_type)
8229 ig.Emit (OpCodes.Ldelem_I);
8230 else if (TypeManager.IsEnumType (type)){
8231 EmitLoadOpcode (ig, TypeManager.EnumToUnderlying (type));
8232 } else if (type.IsValueType){
8233 ig.Emit (OpCodes.Ldelema, type);
8234 ig.Emit (OpCodes.Ldobj, type);
8235 } else if (type.IsGenericParameter)
8236 ig.Emit (OpCodes.Ldelem_Any, type);
8238 ig.Emit (OpCodes.Ldelem_Ref);
8242 /// Returns the right opcode to store an object of Type `t'
8243 /// from an array of T.
8245 static public OpCode GetStoreOpcode (Type t, out bool is_stobj, out bool has_type_arg)
8247 //Console.WriteLine (new System.Diagnostics.StackTrace ());
8248 has_type_arg = false; is_stobj = false;
8249 t = TypeManager.TypeToCoreType (t);
8250 if (TypeManager.IsEnumType (t))
8251 t = TypeManager.EnumToUnderlying (t);
8252 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
8253 t == TypeManager.bool_type)
8254 return OpCodes.Stelem_I1;
8255 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
8256 t == TypeManager.char_type)
8257 return OpCodes.Stelem_I2;
8258 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
8259 return OpCodes.Stelem_I4;
8260 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
8261 return OpCodes.Stelem_I8;
8262 else if (t == TypeManager.float_type)
8263 return OpCodes.Stelem_R4;
8264 else if (t == TypeManager.double_type)
8265 return OpCodes.Stelem_R8;
8266 else if (t == TypeManager.intptr_type) {
8267 has_type_arg = true;
8269 return OpCodes.Stobj;
8270 } else if (t.IsValueType) {
8271 has_type_arg = true;
8273 return OpCodes.Stobj;
8274 } else if (t.IsGenericParameter) {
8275 has_type_arg = true;
8276 return OpCodes.Stelem_Any;
8278 return OpCodes.Stelem_Ref;
8281 MethodInfo FetchGetMethod ()
8283 ModuleBuilder mb = CodeGen.Module.Builder;
8284 int arg_count = ea.Arguments.Count;
8285 Type [] args = new Type [arg_count];
8288 for (int i = 0; i < arg_count; i++){
8289 //args [i++] = a.Type;
8290 args [i] = TypeManager.int32_type;
8293 get = mb.GetArrayMethod (
8294 ea.Expr.Type, "Get",
8295 CallingConventions.HasThis |
8296 CallingConventions.Standard,
8302 MethodInfo FetchAddressMethod ()
8304 ModuleBuilder mb = CodeGen.Module.Builder;
8305 int arg_count = ea.Arguments.Count;
8306 Type [] args = new Type [arg_count];
8310 ret_type = TypeManager.GetReferenceType (type);
8312 for (int i = 0; i < arg_count; i++){
8313 //args [i++] = a.Type;
8314 args [i] = TypeManager.int32_type;
8317 address = mb.GetArrayMethod (
8318 ea.Expr.Type, "Address",
8319 CallingConventions.HasThis |
8320 CallingConventions.Standard,
8327 // Load the array arguments into the stack.
8329 // If we have been requested to cache the values (cached_locations array
8330 // initialized), then load the arguments the first time and store them
8331 // in locals. otherwise load from local variables.
8333 void LoadArrayAndArguments (EmitContext ec)
8335 ILGenerator ig = ec.ig;
8338 foreach (Argument a in ea.Arguments){
8339 Type argtype = a.Expr.Type;
8343 if (argtype == TypeManager.int64_type)
8344 ig.Emit (OpCodes.Conv_Ovf_I);
8345 else if (argtype == TypeManager.uint64_type)
8346 ig.Emit (OpCodes.Conv_Ovf_I_Un);
8350 public void Emit (EmitContext ec, bool leave_copy)
8352 int rank = ea.Expr.Type.GetArrayRank ();
8353 ILGenerator ig = ec.ig;
8356 LoadArrayAndArguments (ec);
8359 EmitLoadOpcode (ig, type);
8363 method = FetchGetMethod ();
8364 ig.Emit (OpCodes.Call, method);
8367 LoadFromPtr (ec.ig, this.type);
8370 ec.ig.Emit (OpCodes.Dup);
8371 temp = new LocalTemporary (ec, this.type);
8376 public override void Emit (EmitContext ec)
8381 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8383 int rank = ea.Expr.Type.GetArrayRank ();
8384 ILGenerator ig = ec.ig;
8385 Type t = source.Type;
8386 prepared = prepare_for_load;
8388 if (prepare_for_load) {
8389 AddressOf (ec, AddressOp.LoadStore);
8390 ec.ig.Emit (OpCodes.Dup);
8393 ec.ig.Emit (OpCodes.Dup);
8394 temp = new LocalTemporary (ec, this.type);
8397 StoreFromPtr (ec.ig, t);
8405 LoadArrayAndArguments (ec);
8408 bool is_stobj, has_type_arg;
8409 OpCode op = GetStoreOpcode (t, out is_stobj, out has_type_arg);
8412 // The stobj opcode used by value types will need
8413 // an address on the stack, not really an array/array
8417 ig.Emit (OpCodes.Ldelema, t);
8421 ec.ig.Emit (OpCodes.Dup);
8422 temp = new LocalTemporary (ec, this.type);
8427 ig.Emit (OpCodes.Stobj, t);
8428 else if (has_type_arg)
8433 ModuleBuilder mb = CodeGen.Module.Builder;
8434 int arg_count = ea.Arguments.Count;
8435 Type [] args = new Type [arg_count + 1];
8440 ec.ig.Emit (OpCodes.Dup);
8441 temp = new LocalTemporary (ec, this.type);
8445 for (int i = 0; i < arg_count; i++){
8446 //args [i++] = a.Type;
8447 args [i] = TypeManager.int32_type;
8450 args [arg_count] = type;
8452 set = mb.GetArrayMethod (
8453 ea.Expr.Type, "Set",
8454 CallingConventions.HasThis |
8455 CallingConventions.Standard,
8456 TypeManager.void_type, args);
8458 ig.Emit (OpCodes.Call, set);
8465 public void AddressOf (EmitContext ec, AddressOp mode)
8467 int rank = ea.Expr.Type.GetArrayRank ();
8468 ILGenerator ig = ec.ig;
8470 LoadArrayAndArguments (ec);
8473 ig.Emit (OpCodes.Ldelema, type);
8475 MethodInfo address = FetchAddressMethod ();
8476 ig.Emit (OpCodes.Call, address);
8483 public ArrayList Properties;
8484 static Hashtable map;
8486 public struct Indexer {
8487 public readonly Type Type;
8488 public readonly MethodInfo Getter, Setter;
8490 public Indexer (Type type, MethodInfo get, MethodInfo set)
8500 map = new Hashtable ();
8505 Properties = new ArrayList ();
8508 void Append (MemberInfo [] mi)
8510 foreach (PropertyInfo property in mi){
8511 MethodInfo get, set;
8513 get = property.GetGetMethod (true);
8514 set = property.GetSetMethod (true);
8515 Properties.Add (new Indexer (property.PropertyType, get, set));
8519 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
8521 string p_name = TypeManager.IndexerPropertyName (lookup_type);
8523 MemberInfo [] mi = TypeManager.MemberLookup (
8524 caller_type, caller_type, lookup_type, MemberTypes.Property,
8525 BindingFlags.Public | BindingFlags.Instance |
8526 BindingFlags.DeclaredOnly, p_name, null);
8528 if (mi == null || mi.Length == 0)
8534 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
8536 Indexers ix = (Indexers) map [lookup_type];
8541 Type copy = lookup_type;
8542 while (copy != TypeManager.object_type && copy != null){
8543 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
8547 ix = new Indexers ();
8552 copy = copy.BaseType;
8555 if (!lookup_type.IsInterface)
8558 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
8559 if (ifaces != null) {
8560 foreach (Type itype in ifaces) {
8561 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
8564 ix = new Indexers ();
8576 /// Expressions that represent an indexer call.
8578 public class IndexerAccess : Expression, IAssignMethod {
8580 // Points to our "data" repository
8582 MethodInfo get, set;
8583 ArrayList set_arguments;
8584 bool is_base_indexer;
8586 protected Type indexer_type;
8587 protected Type current_type;
8588 protected Expression instance_expr;
8589 protected ArrayList arguments;
8591 public IndexerAccess (ElementAccess ea, Location loc)
8592 : this (ea.Expr, false, loc)
8594 this.arguments = ea.Arguments;
8597 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
8600 this.instance_expr = instance_expr;
8601 this.is_base_indexer = is_base_indexer;
8602 this.eclass = ExprClass.Value;
8606 protected virtual bool CommonResolve (EmitContext ec)
8608 indexer_type = instance_expr.Type;
8609 current_type = ec.ContainerType;
8614 public override Expression DoResolve (EmitContext ec)
8616 ArrayList AllGetters = new ArrayList();
8617 if (!CommonResolve (ec))
8621 // Step 1: Query for all `Item' *properties*. Notice
8622 // that the actual methods are pointed from here.
8624 // This is a group of properties, piles of them.
8626 bool found_any = false, found_any_getters = false;
8627 Type lookup_type = indexer_type;
8630 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
8631 if (ilist != null) {
8633 if (ilist.Properties != null) {
8634 foreach (Indexers.Indexer ix in ilist.Properties) {
8635 if (ix.Getter != null)
8636 AllGetters.Add(ix.Getter);
8641 if (AllGetters.Count > 0) {
8642 found_any_getters = true;
8643 get = (MethodInfo) Invocation.OverloadResolve (
8644 ec, new MethodGroupExpr (AllGetters, loc),
8645 arguments, false, loc);
8649 Report.Error (21, loc,
8650 "Type `" + TypeManager.CSharpName (indexer_type) +
8651 "' does not have any indexers defined");
8655 if (!found_any_getters) {
8656 Error (154, "indexer can not be used in this context, because " +
8657 "it lacks a `get' accessor");
8662 Error (1501, "No Overload for method `this' takes `" +
8663 arguments.Count + "' arguments");
8668 // Only base will allow this invocation to happen.
8670 if (get.IsAbstract && this is BaseIndexerAccess){
8671 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
8675 type = get.ReturnType;
8676 if (type.IsPointer && !ec.InUnsafe){
8681 eclass = ExprClass.IndexerAccess;
8685 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8687 ArrayList AllSetters = new ArrayList();
8688 if (!CommonResolve (ec))
8691 bool found_any = false, found_any_setters = false;
8693 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
8694 if (ilist != null) {
8696 if (ilist.Properties != null) {
8697 foreach (Indexers.Indexer ix in ilist.Properties) {
8698 if (ix.Setter != null)
8699 AllSetters.Add(ix.Setter);
8703 if (AllSetters.Count > 0) {
8704 found_any_setters = true;
8705 set_arguments = (ArrayList) arguments.Clone ();
8706 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
8707 set = (MethodInfo) Invocation.OverloadResolve (
8708 ec, new MethodGroupExpr (AllSetters, loc),
8709 set_arguments, false, loc);
8713 Report.Error (21, loc,
8714 "Type `" + TypeManager.CSharpName (indexer_type) +
8715 "' does not have any indexers defined");
8719 if (!found_any_setters) {
8720 Error (154, "indexer can not be used in this context, because " +
8721 "it lacks a `set' accessor");
8726 Error (1501, "No Overload for method `this' takes `" +
8727 arguments.Count + "' arguments");
8732 // Only base will allow this invocation to happen.
8734 if (set.IsAbstract && this is BaseIndexerAccess){
8735 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
8740 // Now look for the actual match in the list of indexers to set our "return" type
8742 type = TypeManager.void_type; // default value
8743 foreach (Indexers.Indexer ix in ilist.Properties){
8744 if (ix.Setter == set){
8750 eclass = ExprClass.IndexerAccess;
8754 bool prepared = false;
8755 LocalTemporary temp;
8757 public void Emit (EmitContext ec, bool leave_copy)
8759 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc, prepared, false);
8761 ec.ig.Emit (OpCodes.Dup);
8762 temp = new LocalTemporary (ec, Type);
8768 // source is ignored, because we already have a copy of it from the
8769 // LValue resolution and we have already constructed a pre-cached
8770 // version of the arguments (ea.set_arguments);
8772 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8774 prepared = prepare_for_load;
8775 Argument a = (Argument) set_arguments [set_arguments.Count - 1];
8780 ec.ig.Emit (OpCodes.Dup);
8781 temp = new LocalTemporary (ec, Type);
8784 } else if (leave_copy) {
8785 temp = new LocalTemporary (ec, Type);
8791 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc, false, prepared);
8798 public override void Emit (EmitContext ec)
8805 /// The base operator for method names
8807 public class BaseAccess : Expression {
8810 public BaseAccess (string member, Location l)
8812 this.member = member;
8816 public override Expression DoResolve (EmitContext ec)
8818 Expression c = CommonResolve (ec);
8824 // MethodGroups use this opportunity to flag an error on lacking ()
8826 if (!(c is MethodGroupExpr))
8827 return c.Resolve (ec);
8831 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8833 Expression c = CommonResolve (ec);
8839 // MethodGroups use this opportunity to flag an error on lacking ()
8841 if (! (c is MethodGroupExpr))
8842 return c.DoResolveLValue (ec, right_side);
8847 Expression CommonResolve (EmitContext ec)
8849 Expression member_lookup;
8850 Type current_type = ec.ContainerType;
8851 Type base_type = current_type.BaseType;
8855 Error (1511, "Keyword base is not allowed in static method");
8859 if (ec.IsFieldInitializer){
8860 Error (1512, "Keyword base is not available in the current context");
8864 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type,
8865 member, AllMemberTypes, AllBindingFlags,
8867 if (member_lookup == null) {
8868 MemberLookupFailed (
8869 ec, base_type, base_type, member, null, loc);
8876 left = new TypeExpression (base_type, loc);
8878 left = ec.GetThis (loc);
8880 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
8882 if (e is PropertyExpr){
8883 PropertyExpr pe = (PropertyExpr) e;
8888 if (e is MethodGroupExpr)
8889 ((MethodGroupExpr) e).IsBase = true;
8894 public override void Emit (EmitContext ec)
8896 throw new Exception ("Should never be called");
8901 /// The base indexer operator
8903 public class BaseIndexerAccess : IndexerAccess {
8904 public BaseIndexerAccess (ArrayList args, Location loc)
8905 : base (null, true, loc)
8907 arguments = new ArrayList ();
8908 foreach (Expression tmp in args)
8909 arguments.Add (new Argument (tmp, Argument.AType.Expression));
8912 protected override bool CommonResolve (EmitContext ec)
8914 instance_expr = ec.GetThis (loc);
8916 current_type = ec.ContainerType.BaseType;
8917 indexer_type = current_type;
8919 foreach (Argument a in arguments){
8920 if (!a.Resolve (ec, loc))
8929 /// This class exists solely to pass the Type around and to be a dummy
8930 /// that can be passed to the conversion functions (this is used by
8931 /// foreach implementation to typecast the object return value from
8932 /// get_Current into the proper type. All code has been generated and
8933 /// we only care about the side effect conversions to be performed
8935 /// This is also now used as a placeholder where a no-action expression
8936 /// is needed (the `New' class).
8938 public class EmptyExpression : Expression {
8939 public static readonly EmptyExpression Null = new EmptyExpression ();
8941 // TODO: should be protected
8942 public EmptyExpression ()
8944 type = TypeManager.object_type;
8945 eclass = ExprClass.Value;
8946 loc = Location.Null;
8949 public EmptyExpression (Type t)
8952 eclass = ExprClass.Value;
8953 loc = Location.Null;
8956 public override Expression DoResolve (EmitContext ec)
8961 public override void Emit (EmitContext ec)
8963 // nothing, as we only exist to not do anything.
8967 // This is just because we might want to reuse this bad boy
8968 // instead of creating gazillions of EmptyExpressions.
8969 // (CanImplicitConversion uses it)
8971 public void SetType (Type t)
8977 public class UserCast : Expression {
8981 public UserCast (MethodInfo method, Expression source, Location l)
8983 this.method = method;
8984 this.source = source;
8985 type = method.ReturnType;
8986 eclass = ExprClass.Value;
8990 public override Expression DoResolve (EmitContext ec)
8993 // We are born fully resolved
8998 public override void Emit (EmitContext ec)
9000 ILGenerator ig = ec.ig;
9004 if (method is MethodInfo)
9005 ig.Emit (OpCodes.Call, (MethodInfo) method);
9007 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
9013 // This class is used to "construct" the type during a typecast
9014 // operation. Since the Type.GetType class in .NET can parse
9015 // the type specification, we just use this to construct the type
9016 // one bit at a time.
9018 public class ComposedCast : TypeExpr {
9022 public ComposedCast (Expression left, string dim, Location l)
9029 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
9031 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec);
9035 Type ltype = lexpr.Type;
9037 if ((ltype == TypeManager.void_type) && (dim != "*")) {
9038 Report.Error (1547, Location,
9039 "Keyword 'void' cannot be used in this context");
9044 while ((pos < dim.Length) && (dim [pos] == '[')) {
9047 if (dim [pos] == ']') {
9048 ltype = ltype.MakeArrayType ();
9051 if (pos < dim.Length)
9055 eclass = ExprClass.Type;
9060 while (dim [pos] == ',') {
9064 if ((dim [pos] != ']') || (pos != dim.Length-1))
9067 type = ltype.MakeArrayType (rank + 1);
9068 eclass = ExprClass.Type;
9073 // ltype.Fullname is already fully qualified, so we can skip
9074 // a lot of probes, and go directly to TypeManager.LookupType
9076 string fname = ltype.FullName != null ? ltype.FullName : ltype.Name;
9077 string cname = fname + dim;
9078 type = TypeManager.LookupTypeDirect (cname);
9081 // For arrays of enumerations we are having a problem
9082 // with the direct lookup. Need to investigate.
9084 // For now, fall back to the full lookup in that case.
9086 type = RootContext.LookupType (ec.DeclSpace, cname, false, loc);
9091 if (!ec.InUnsafe && type.IsPointer){
9096 eclass = ExprClass.Type;
9100 public override string Name {
9108 // This class is used to represent the address of an array, used
9109 // only by the Fixed statement, this is like the C "&a [0]" construct.
9111 public class ArrayPtr : Expression {
9114 public ArrayPtr (Expression array, Location l)
9116 Type array_type = TypeManager.GetElementType (array.Type);
9120 type = TypeManager.GetPointerType (array_type);
9121 eclass = ExprClass.Value;
9125 public override void Emit (EmitContext ec)
9127 ILGenerator ig = ec.ig;
9130 IntLiteral.EmitInt (ig, 0);
9131 ig.Emit (OpCodes.Ldelema, TypeManager.GetElementType (array.Type));
9134 public override Expression DoResolve (EmitContext ec)
9137 // We are born fully resolved
9144 // Used by the fixed statement
9146 public class StringPtr : Expression {
9149 public StringPtr (LocalBuilder b, Location l)
9152 eclass = ExprClass.Value;
9153 type = TypeManager.char_ptr_type;
9157 public override Expression DoResolve (EmitContext ec)
9159 // This should never be invoked, we are born in fully
9160 // initialized state.
9165 public override void Emit (EmitContext ec)
9167 ILGenerator ig = ec.ig;
9169 ig.Emit (OpCodes.Ldloc, b);
9170 ig.Emit (OpCodes.Conv_I);
9171 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
9172 ig.Emit (OpCodes.Add);
9177 // Implements the `stackalloc' keyword
9179 public class StackAlloc : Expression {
9184 public StackAlloc (Expression type, Expression count, Location l)
9191 public override Expression DoResolve (EmitContext ec)
9193 count = count.Resolve (ec);
9197 if (count.Type != TypeManager.int32_type){
9198 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
9203 Constant c = count as Constant;
9204 if (c != null && c.IsNegative) {
9205 Report.Error (247, loc, "Cannot use a negative size with stackalloc");
9209 if (ec.CurrentBranching.InCatch () ||
9210 ec.CurrentBranching.InFinally (true)) {
9212 "stackalloc can not be used in a catch or finally block");
9216 TypeExpr texpr = t.ResolveAsTypeTerminal (ec);
9222 if (!TypeManager.VerifyUnManaged (otype, loc))
9225 type = TypeManager.GetPointerType (otype);
9226 eclass = ExprClass.Value;
9231 public override void Emit (EmitContext ec)
9233 int size = GetTypeSize (otype);
9234 ILGenerator ig = ec.ig;
9237 ig.Emit (OpCodes.Sizeof, otype);
9239 IntConstant.EmitInt (ig, size);
9241 ig.Emit (OpCodes.Mul);
9242 ig.Emit (OpCodes.Localloc);