2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
8 // (C) 2003, 2004 Novell, Inc.
12 namespace Mono.CSharp {
14 using System.Collections;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// This is just a helper class, it is generated by Unary, UnaryMutator
21 /// when an overloaded method has been found. It just emits the code for a
24 public class StaticCallExpr : ExpressionStatement {
28 public StaticCallExpr (MethodInfo m, ArrayList a, Location l)
34 eclass = ExprClass.Value;
38 public override Expression DoResolve (EmitContext ec)
41 // We are born fully resolved
46 public override void Emit (EmitContext ec)
49 Invocation.EmitArguments (ec, mi, args, false, null);
51 ec.ig.Emit (OpCodes.Call, mi);
55 static public StaticCallExpr MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
56 Expression e, Location loc)
61 args = new ArrayList (1);
62 Argument a = new Argument (e, Argument.AType.Expression);
64 // We need to resolve the arguments before sending them in !
65 if (!a.Resolve (ec, loc))
69 method = Invocation.OverloadResolve (
70 ec, (MethodGroupExpr) mg, args, false, loc);
75 return new StaticCallExpr ((MethodInfo) method, args, loc);
78 public override void EmitStatement (EmitContext ec)
81 if (TypeManager.TypeToCoreType (type) != TypeManager.void_type)
82 ec.ig.Emit (OpCodes.Pop);
85 public MethodInfo Method {
90 public class ParenthesizedExpression : Expression
92 public Expression Expr;
94 public ParenthesizedExpression (Expression expr, Location loc)
100 public override Expression DoResolve (EmitContext ec)
102 Expr = Expr.Resolve (ec);
106 public override void Emit (EmitContext ec)
108 throw new Exception ("Should not happen");
113 /// Unary expressions.
117 /// Unary implements unary expressions. It derives from
118 /// ExpressionStatement becuase the pre/post increment/decrement
119 /// operators can be used in a statement context.
121 public class Unary : Expression {
122 public enum Operator : byte {
123 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
124 Indirection, AddressOf, TOP
127 public Operator Oper;
128 public Expression Expr;
130 public Unary (Operator op, Expression expr, Location loc)
138 /// Returns a stringified representation of the Operator
140 static public string OperName (Operator oper)
143 case Operator.UnaryPlus:
145 case Operator.UnaryNegation:
147 case Operator.LogicalNot:
149 case Operator.OnesComplement:
151 case Operator.AddressOf:
153 case Operator.Indirection:
157 return oper.ToString ();
160 public static readonly string [] oper_names;
164 oper_names = new string [(int)Operator.TOP];
166 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
167 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
168 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
169 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
170 oper_names [(int) Operator.Indirection] = "op_Indirection";
171 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
174 void Error23 (Type t)
177 23, "Operator " + OperName (Oper) +
178 " cannot be applied to operand of type `" +
179 TypeManager.CSharpName (t) + "'");
183 /// The result has been already resolved:
185 /// FIXME: a minus constant -128 sbyte cant be turned into a
188 static Expression TryReduceNegative (Constant expr)
192 if (expr is IntConstant)
193 e = new IntConstant (-((IntConstant) expr).Value);
194 else if (expr is UIntConstant){
195 uint value = ((UIntConstant) expr).Value;
197 if (value < 2147483649)
198 return new IntConstant (-(int)value);
200 e = new LongConstant (-value);
202 else if (expr is LongConstant)
203 e = new LongConstant (-((LongConstant) expr).Value);
204 else if (expr is ULongConstant){
205 ulong value = ((ULongConstant) expr).Value;
207 if (value < 9223372036854775809)
208 return new LongConstant(-(long)value);
210 else if (expr is FloatConstant)
211 e = new FloatConstant (-((FloatConstant) expr).Value);
212 else if (expr is DoubleConstant)
213 e = new DoubleConstant (-((DoubleConstant) expr).Value);
214 else if (expr is DecimalConstant)
215 e = new DecimalConstant (-((DecimalConstant) expr).Value);
216 else if (expr is ShortConstant)
217 e = new IntConstant (-((ShortConstant) expr).Value);
218 else if (expr is UShortConstant)
219 e = new IntConstant (-((UShortConstant) expr).Value);
220 else if (expr is SByteConstant)
221 e = new IntConstant (-((SByteConstant) expr).Value);
222 else if (expr is ByteConstant)
223 e = new IntConstant (-((ByteConstant) expr).Value);
228 // This routine will attempt to simplify the unary expression when the
229 // argument is a constant. The result is returned in `result' and the
230 // function returns true or false depending on whether a reduction
231 // was performed or not
233 bool Reduce (EmitContext ec, Constant e, out Expression result)
235 Type expr_type = e.Type;
238 case Operator.UnaryPlus:
242 case Operator.UnaryNegation:
243 result = TryReduceNegative (e);
244 return result != null;
246 case Operator.LogicalNot:
247 if (expr_type != TypeManager.bool_type) {
253 BoolConstant b = (BoolConstant) e;
254 result = new BoolConstant (!(b.Value));
257 case Operator.OnesComplement:
258 if (!((expr_type == TypeManager.int32_type) ||
259 (expr_type == TypeManager.uint32_type) ||
260 (expr_type == TypeManager.int64_type) ||
261 (expr_type == TypeManager.uint64_type) ||
262 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
265 if (Convert.ImplicitConversionExists (ec, e, TypeManager.int32_type)){
266 result = new Cast (new TypeExpression (TypeManager.int32_type, loc), e, loc);
267 result = result.Resolve (ec);
268 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint32_type)){
269 result = new Cast (new TypeExpression (TypeManager.uint32_type, loc), e, loc);
270 result = result.Resolve (ec);
271 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.int64_type)){
272 result = new Cast (new TypeExpression (TypeManager.int64_type, loc), e, loc);
273 result = result.Resolve (ec);
274 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint64_type)){
275 result = new Cast (new TypeExpression (TypeManager.uint64_type, loc), e, loc);
276 result = result.Resolve (ec);
279 if (result == null || !(result is Constant)){
285 expr_type = result.Type;
286 e = (Constant) result;
289 if (e is EnumConstant){
290 EnumConstant enum_constant = (EnumConstant) e;
293 if (Reduce (ec, enum_constant.Child, out reduced)){
294 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
302 if (expr_type == TypeManager.int32_type){
303 result = new IntConstant (~ ((IntConstant) e).Value);
304 } else if (expr_type == TypeManager.uint32_type){
305 result = new UIntConstant (~ ((UIntConstant) e).Value);
306 } else if (expr_type == TypeManager.int64_type){
307 result = new LongConstant (~ ((LongConstant) e).Value);
308 } else if (expr_type == TypeManager.uint64_type){
309 result = new ULongConstant (~ ((ULongConstant) e).Value);
317 case Operator.AddressOf:
321 case Operator.Indirection:
325 throw new Exception ("Can not constant fold: " + Oper.ToString());
328 Expression ResolveOperator (EmitContext ec)
331 // Step 1: Default operations on CLI native types.
334 // Attempt to use a constant folding operation.
335 if (Expr is Constant){
338 if (Reduce (ec, (Constant) Expr, out result))
343 // Step 2: Perform Operator Overload location
345 Type expr_type = Expr.Type;
349 op_name = oper_names [(int) Oper];
351 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
354 Expression e = StaticCallExpr.MakeSimpleCall (
355 ec, (MethodGroupExpr) mg, Expr, loc);
365 // Only perform numeric promotions on:
368 if (expr_type == null)
372 case Operator.LogicalNot:
373 if (expr_type != TypeManager.bool_type) {
374 Expr = ResolveBoolean (ec, Expr, loc);
381 type = TypeManager.bool_type;
384 case Operator.OnesComplement:
385 if (!((expr_type == TypeManager.int32_type) ||
386 (expr_type == TypeManager.uint32_type) ||
387 (expr_type == TypeManager.int64_type) ||
388 (expr_type == TypeManager.uint64_type) ||
389 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
392 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
394 type = TypeManager.int32_type;
397 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint32_type, loc);
399 type = TypeManager.uint32_type;
402 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
404 type = TypeManager.int64_type;
407 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint64_type, loc);
409 type = TypeManager.uint64_type;
418 case Operator.AddressOf:
424 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
428 IVariable variable = Expr as IVariable;
429 bool is_fixed = variable != null && variable.VerifyFixed (false);
431 if (!ec.InFixedInitializer && !is_fixed) {
432 Error (212, "You can only take the address of an unfixed expression inside " +
433 "of a fixed statement initializer");
437 if (ec.InFixedInitializer && is_fixed) {
438 Error (213, "You can not fix an already fixed expression");
442 LocalVariableReference lr = Expr as LocalVariableReference;
444 if (lr.local_info.IsCaptured){
445 AnonymousMethod.Error_AddressOfCapturedVar (lr.Name, loc);
448 lr.local_info.AddressTaken = true;
449 lr.local_info.Used = true;
452 // According to the specs, a variable is considered definitely assigned if you take
454 if ((variable != null) && (variable.VariableInfo != null)){
455 variable.VariableInfo.SetAssigned (ec);
458 type = TypeManager.GetPointerType (Expr.Type);
461 case Operator.Indirection:
467 if (!expr_type.IsPointer){
468 Error (193, "The * or -> operator can only be applied to pointers");
473 // We create an Indirection expression, because
474 // it can implement the IMemoryLocation.
476 return new Indirection (Expr, loc);
478 case Operator.UnaryPlus:
480 // A plus in front of something is just a no-op, so return the child.
484 case Operator.UnaryNegation:
486 // Deals with -literals
487 // int operator- (int x)
488 // long operator- (long x)
489 // float operator- (float f)
490 // double operator- (double d)
491 // decimal operator- (decimal d)
493 Expression expr = null;
496 // transform - - expr into expr
499 Unary unary = (Unary) Expr;
501 if (unary.Oper == Operator.UnaryNegation)
506 // perform numeric promotions to int,
510 // The following is inneficient, because we call
511 // ImplicitConversion too many times.
513 // It is also not clear if we should convert to Float
514 // or Double initially.
516 if (expr_type == TypeManager.uint32_type){
518 // FIXME: handle exception to this rule that
519 // permits the int value -2147483648 (-2^31) to
520 // bt wrote as a decimal interger literal
522 type = TypeManager.int64_type;
523 Expr = Convert.ImplicitConversion (ec, Expr, type, loc);
527 if (expr_type == TypeManager.uint64_type){
529 // FIXME: Handle exception of `long value'
530 // -92233720368547758087 (-2^63) to be wrote as
531 // decimal integer literal.
537 if (expr_type == TypeManager.float_type){
542 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
549 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
556 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.double_type, loc);
567 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
568 TypeManager.CSharpName (expr_type) + "'");
572 public override Expression DoResolve (EmitContext ec)
574 if (Oper == Operator.AddressOf) {
575 Expr = Expr.DoResolveLValue (ec, new EmptyExpression ());
577 if (Expr == null || Expr.eclass != ExprClass.Variable){
578 Error (211, "Cannot take the address of non-variables");
583 Expr = Expr.Resolve (ec);
588 eclass = ExprClass.Value;
589 return ResolveOperator (ec);
592 public override Expression DoResolveLValue (EmitContext ec, Expression right)
594 if (Oper == Operator.Indirection)
595 return DoResolve (ec);
600 public override void Emit (EmitContext ec)
602 ILGenerator ig = ec.ig;
605 case Operator.UnaryPlus:
606 throw new Exception ("This should be caught by Resolve");
608 case Operator.UnaryNegation:
610 ig.Emit (OpCodes.Ldc_I4_0);
611 if (type == TypeManager.int64_type)
612 ig.Emit (OpCodes.Conv_U8);
614 ig.Emit (OpCodes.Sub_Ovf);
617 ig.Emit (OpCodes.Neg);
622 case Operator.LogicalNot:
624 ig.Emit (OpCodes.Ldc_I4_0);
625 ig.Emit (OpCodes.Ceq);
628 case Operator.OnesComplement:
630 ig.Emit (OpCodes.Not);
633 case Operator.AddressOf:
634 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
638 throw new Exception ("This should not happen: Operator = "
643 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
645 if (Oper == Operator.LogicalNot)
646 Expr.EmitBranchable (ec, target, !onTrue);
648 base.EmitBranchable (ec, target, onTrue);
651 public override string ToString ()
653 return "Unary (" + Oper + ", " + Expr + ")";
659 // Unary operators are turned into Indirection expressions
660 // after semantic analysis (this is so we can take the address
661 // of an indirection).
663 public class Indirection : Expression, IMemoryLocation, IAssignMethod, IVariable {
665 LocalTemporary temporary;
668 public Indirection (Expression expr, Location l)
671 type = TypeManager.HasElementType (expr.Type) ? TypeManager.GetElementType (expr.Type) : expr.Type;
672 eclass = ExprClass.Variable;
676 public override void Emit (EmitContext ec)
681 LoadFromPtr (ec.ig, Type);
684 public void Emit (EmitContext ec, bool leave_copy)
688 ec.ig.Emit (OpCodes.Dup);
689 temporary = new LocalTemporary (ec, expr.Type);
690 temporary.Store (ec);
694 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
696 prepared = prepare_for_load;
700 if (prepare_for_load)
701 ec.ig.Emit (OpCodes.Dup);
705 ec.ig.Emit (OpCodes.Dup);
706 temporary = new LocalTemporary (ec, expr.Type);
707 temporary.Store (ec);
710 StoreFromPtr (ec.ig, type);
712 if (temporary != null)
716 public void AddressOf (EmitContext ec, AddressOp Mode)
721 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
723 return DoResolve (ec);
726 public override Expression DoResolve (EmitContext ec)
729 // Born fully resolved
734 public override string ToString ()
736 return "*(" + expr + ")";
739 #region IVariable Members
741 public VariableInfo VariableInfo {
747 public bool VerifyFixed (bool is_expression)
756 /// Unary Mutator expressions (pre and post ++ and --)
760 /// UnaryMutator implements ++ and -- expressions. It derives from
761 /// ExpressionStatement becuase the pre/post increment/decrement
762 /// operators can be used in a statement context.
764 /// FIXME: Idea, we could split this up in two classes, one simpler
765 /// for the common case, and one with the extra fields for more complex
766 /// classes (indexers require temporary access; overloaded require method)
769 public class UnaryMutator : ExpressionStatement {
771 public enum Mode : byte {
778 PreDecrement = IsDecrement,
779 PostIncrement = IsPost,
780 PostDecrement = IsPost | IsDecrement
784 bool is_expr = false;
785 bool recurse = false;
790 // This is expensive for the simplest case.
792 StaticCallExpr method;
794 public UnaryMutator (Mode m, Expression e, Location l)
801 static string OperName (Mode mode)
803 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
808 /// Returns whether an object of type `t' can be incremented
809 /// or decremented with add/sub (ie, basically whether we can
810 /// use pre-post incr-decr operations on it, but it is not a
811 /// System.Decimal, which we require operator overloading to catch)
813 static bool IsIncrementableNumber (Type t)
815 return (t == TypeManager.sbyte_type) ||
816 (t == TypeManager.byte_type) ||
817 (t == TypeManager.short_type) ||
818 (t == TypeManager.ushort_type) ||
819 (t == TypeManager.int32_type) ||
820 (t == TypeManager.uint32_type) ||
821 (t == TypeManager.int64_type) ||
822 (t == TypeManager.uint64_type) ||
823 (t == TypeManager.char_type) ||
824 (t.IsSubclassOf (TypeManager.enum_type)) ||
825 (t == TypeManager.float_type) ||
826 (t == TypeManager.double_type) ||
827 (t.IsPointer && t != TypeManager.void_ptr_type);
830 Expression ResolveOperator (EmitContext ec)
832 Type expr_type = expr.Type;
835 // Step 1: Perform Operator Overload location
840 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
841 op_name = "op_Increment";
843 op_name = "op_Decrement";
845 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
848 method = StaticCallExpr.MakeSimpleCall (
849 ec, (MethodGroupExpr) mg, expr, loc);
852 } else if (!IsIncrementableNumber (expr_type)) {
853 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
854 TypeManager.CSharpName (expr_type) + "'");
859 // The operand of the prefix/postfix increment decrement operators
860 // should be an expression that is classified as a variable,
861 // a property access or an indexer access
864 if (expr.eclass == ExprClass.Variable){
865 LocalVariableReference var = expr as LocalVariableReference;
866 if ((var != null) && var.IsReadOnly) {
867 Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
870 } else if (expr.eclass == ExprClass.IndexerAccess || expr.eclass == ExprClass.PropertyAccess){
871 expr = expr.ResolveLValue (ec, this);
875 expr.Error_UnexpectedKind ("variable, indexer or property access", loc);
882 public override Expression DoResolve (EmitContext ec)
884 expr = expr.Resolve (ec);
889 eclass = ExprClass.Value;
890 return ResolveOperator (ec);
893 static int PtrTypeSize (Type t)
895 return GetTypeSize (TypeManager.GetElementType (t));
899 // Loads the proper "1" into the stack based on the type, then it emits the
900 // opcode for the operation requested
902 void LoadOneAndEmitOp (EmitContext ec, Type t)
905 // Measure if getting the typecode and using that is more/less efficient
906 // that comparing types. t.GetTypeCode() is an internal call.
908 ILGenerator ig = ec.ig;
910 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
911 LongConstant.EmitLong (ig, 1);
912 else if (t == TypeManager.double_type)
913 ig.Emit (OpCodes.Ldc_R8, 1.0);
914 else if (t == TypeManager.float_type)
915 ig.Emit (OpCodes.Ldc_R4, 1.0F);
916 else if (t.IsPointer){
917 int n = PtrTypeSize (t);
920 ig.Emit (OpCodes.Sizeof, t);
922 IntConstant.EmitInt (ig, n);
924 ig.Emit (OpCodes.Ldc_I4_1);
927 // Now emit the operation
930 if (t == TypeManager.int32_type ||
931 t == TypeManager.int64_type){
932 if ((mode & Mode.IsDecrement) != 0)
933 ig.Emit (OpCodes.Sub_Ovf);
935 ig.Emit (OpCodes.Add_Ovf);
936 } else if (t == TypeManager.uint32_type ||
937 t == TypeManager.uint64_type){
938 if ((mode & Mode.IsDecrement) != 0)
939 ig.Emit (OpCodes.Sub_Ovf_Un);
941 ig.Emit (OpCodes.Add_Ovf_Un);
943 if ((mode & Mode.IsDecrement) != 0)
944 ig.Emit (OpCodes.Sub_Ovf);
946 ig.Emit (OpCodes.Add_Ovf);
949 if ((mode & Mode.IsDecrement) != 0)
950 ig.Emit (OpCodes.Sub);
952 ig.Emit (OpCodes.Add);
955 if (t == TypeManager.sbyte_type){
957 ig.Emit (OpCodes.Conv_Ovf_I1);
959 ig.Emit (OpCodes.Conv_I1);
960 } else if (t == TypeManager.byte_type){
962 ig.Emit (OpCodes.Conv_Ovf_U1);
964 ig.Emit (OpCodes.Conv_U1);
965 } else if (t == TypeManager.short_type){
967 ig.Emit (OpCodes.Conv_Ovf_I2);
969 ig.Emit (OpCodes.Conv_I2);
970 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
972 ig.Emit (OpCodes.Conv_Ovf_U2);
974 ig.Emit (OpCodes.Conv_U2);
979 void EmitCode (EmitContext ec, bool is_expr)
982 this.is_expr = is_expr;
983 ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
987 public override void Emit (EmitContext ec)
990 // We use recurse to allow ourselfs to be the source
991 // of an assignment. This little hack prevents us from
992 // having to allocate another expression
995 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
997 LoadOneAndEmitOp (ec, expr.Type);
999 ec.ig.Emit (OpCodes.Call, method.Method);
1004 EmitCode (ec, true);
1007 public override void EmitStatement (EmitContext ec)
1009 EmitCode (ec, false);
1014 /// Base class for the `Is' and `As' classes.
1018 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1021 public abstract class Probe : Expression {
1022 public Expression ProbeType;
1023 protected Expression expr;
1024 protected Type probe_type;
1026 public Probe (Expression expr, Expression probe_type, Location l)
1028 ProbeType = probe_type;
1033 public Expression Expr {
1039 public override Expression DoResolve (EmitContext ec)
1041 TypeExpr texpr = ProbeType.ResolveAsTypeTerminal (ec, false);
1044 probe_type = texpr.ResolveType (ec);
1046 CheckObsoleteAttribute (probe_type);
1048 expr = expr.Resolve (ec);
1052 if (expr.Type.IsPointer) {
1053 Report.Error (244, loc, "\"is\" or \"as\" are not valid on pointer types");
1061 /// Implementation of the `is' operator.
1063 public class Is : Probe {
1064 public Is (Expression expr, Expression probe_type, Location l)
1065 : base (expr, probe_type, l)
1070 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1075 public override void Emit (EmitContext ec)
1077 ILGenerator ig = ec.ig;
1082 case Action.AlwaysFalse:
1083 ig.Emit (OpCodes.Pop);
1084 IntConstant.EmitInt (ig, 0);
1086 case Action.AlwaysTrue:
1087 ig.Emit (OpCodes.Pop);
1088 IntConstant.EmitInt (ig, 1);
1090 case Action.LeaveOnStack:
1091 // the `e != null' rule.
1092 ig.Emit (OpCodes.Ldnull);
1093 ig.Emit (OpCodes.Ceq);
1094 ig.Emit (OpCodes.Ldc_I4_0);
1095 ig.Emit (OpCodes.Ceq);
1098 ig.Emit (OpCodes.Isinst, probe_type);
1099 ig.Emit (OpCodes.Ldnull);
1100 ig.Emit (OpCodes.Cgt_Un);
1103 throw new Exception ("never reached");
1106 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
1108 ILGenerator ig = ec.ig;
1111 case Action.AlwaysFalse:
1113 ig.Emit (OpCodes.Br, target);
1116 case Action.AlwaysTrue:
1118 ig.Emit (OpCodes.Br, target);
1121 case Action.LeaveOnStack:
1122 // the `e != null' rule.
1124 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1128 ig.Emit (OpCodes.Isinst, probe_type);
1129 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1132 throw new Exception ("never reached");
1135 public override Expression DoResolve (EmitContext ec)
1137 Expression e = base.DoResolve (ec);
1139 if ((e == null) || (expr == null))
1142 Type etype = expr.Type;
1143 bool warning_always_matches = false;
1144 bool warning_never_matches = false;
1146 type = TypeManager.bool_type;
1147 eclass = ExprClass.Value;
1150 // First case, if at compile time, there is an implicit conversion
1151 // then e != null (objects) or true (value types)
1153 e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1156 if (etype.IsValueType)
1157 action = Action.AlwaysTrue;
1159 action = Action.LeaveOnStack;
1161 warning_always_matches = true;
1162 } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1164 // Second case: explicit reference convresion
1166 if (expr is NullLiteral)
1167 action = Action.AlwaysFalse;
1169 action = Action.Probe;
1171 action = Action.AlwaysFalse;
1172 warning_never_matches = true;
1175 if (warning_always_matches)
1176 Warning (183, "The given expression is always of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1177 else if (warning_never_matches){
1178 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1179 Warning (184, "The given expression is never of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1187 /// Implementation of the `as' operator.
1189 public class As : Probe {
1190 public As (Expression expr, Expression probe_type, Location l)
1191 : base (expr, probe_type, l)
1195 bool do_isinst = false;
1197 public override void Emit (EmitContext ec)
1199 ILGenerator ig = ec.ig;
1204 ig.Emit (OpCodes.Isinst, probe_type);
1207 static void Error_CannotConvertType (Type source, Type target, Location loc)
1210 39, loc, "as operator can not convert from `" +
1211 TypeManager.CSharpName (source) + "' to `" +
1212 TypeManager.CSharpName (target) + "'");
1215 public override Expression DoResolve (EmitContext ec)
1217 Expression e = base.DoResolve (ec);
1223 eclass = ExprClass.Value;
1224 Type etype = expr.Type;
1226 if (TypeManager.IsValueType (probe_type)){
1227 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1228 TypeManager.CSharpName (probe_type) + " is a value type)");
1233 e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1240 if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1245 Error_CannotConvertType (etype, probe_type, loc);
1251 /// This represents a typecast in the source language.
1253 /// FIXME: Cast expressions have an unusual set of parsing
1254 /// rules, we need to figure those out.
1256 public class Cast : Expression {
1257 Expression target_type;
1260 public Cast (Expression cast_type, Expression expr, Location loc)
1262 this.target_type = cast_type;
1267 public Expression TargetType {
1273 public Expression Expr {
1282 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1284 if (!ec.ConstantCheckState)
1287 if ((value < min) || (value > max)) {
1288 Error (221, "Constant value `" + value + "' cannot be converted " +
1289 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1290 "syntax to override)");
1297 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1299 if (!ec.ConstantCheckState)
1303 Error (221, "Constant value `" + value + "' cannot be converted " +
1304 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1305 "syntax to override)");
1312 bool CheckUnsigned (EmitContext ec, long value, Type type)
1314 if (!ec.ConstantCheckState)
1318 Error (221, "Constant value `" + value + "' cannot be converted " +
1319 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1320 "syntax to override)");
1328 /// Attempts to do a compile-time folding of a constant cast.
1330 Expression TryReduce (EmitContext ec, Type target_type)
1332 Expression real_expr = expr;
1333 if (real_expr is EnumConstant)
1334 real_expr = ((EnumConstant) real_expr).Child;
1336 if (real_expr is ByteConstant){
1337 byte v = ((ByteConstant) real_expr).Value;
1339 if (target_type == TypeManager.sbyte_type) {
1340 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1342 return new SByteConstant ((sbyte) v);
1344 if (target_type == TypeManager.short_type)
1345 return new ShortConstant ((short) v);
1346 if (target_type == TypeManager.ushort_type)
1347 return new UShortConstant ((ushort) v);
1348 if (target_type == TypeManager.int32_type)
1349 return new IntConstant ((int) v);
1350 if (target_type == TypeManager.uint32_type)
1351 return new UIntConstant ((uint) v);
1352 if (target_type == TypeManager.int64_type)
1353 return new LongConstant ((long) v);
1354 if (target_type == TypeManager.uint64_type)
1355 return new ULongConstant ((ulong) v);
1356 if (target_type == TypeManager.float_type)
1357 return new FloatConstant ((float) v);
1358 if (target_type == TypeManager.double_type)
1359 return new DoubleConstant ((double) v);
1360 if (target_type == TypeManager.char_type)
1361 return new CharConstant ((char) v);
1362 if (target_type == TypeManager.decimal_type)
1363 return new DecimalConstant ((decimal) v);
1365 if (real_expr is SByteConstant){
1366 sbyte v = ((SByteConstant) real_expr).Value;
1368 if (target_type == TypeManager.byte_type) {
1369 if (!CheckUnsigned (ec, v, target_type))
1371 return new ByteConstant ((byte) v);
1373 if (target_type == TypeManager.short_type)
1374 return new ShortConstant ((short) v);
1375 if (target_type == TypeManager.ushort_type) {
1376 if (!CheckUnsigned (ec, v, target_type))
1378 return new UShortConstant ((ushort) v);
1379 } if (target_type == TypeManager.int32_type)
1380 return new IntConstant ((int) v);
1381 if (target_type == TypeManager.uint32_type) {
1382 if (!CheckUnsigned (ec, v, target_type))
1384 return new UIntConstant ((uint) v);
1385 } if (target_type == TypeManager.int64_type)
1386 return new LongConstant ((long) v);
1387 if (target_type == TypeManager.uint64_type) {
1388 if (!CheckUnsigned (ec, v, target_type))
1390 return new ULongConstant ((ulong) v);
1392 if (target_type == TypeManager.float_type)
1393 return new FloatConstant ((float) v);
1394 if (target_type == TypeManager.double_type)
1395 return new DoubleConstant ((double) v);
1396 if (target_type == TypeManager.char_type) {
1397 if (!CheckUnsigned (ec, v, target_type))
1399 return new CharConstant ((char) v);
1401 if (target_type == TypeManager.decimal_type)
1402 return new DecimalConstant ((decimal) v);
1404 if (real_expr is ShortConstant){
1405 short v = ((ShortConstant) real_expr).Value;
1407 if (target_type == TypeManager.byte_type) {
1408 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1410 return new ByteConstant ((byte) v);
1412 if (target_type == TypeManager.sbyte_type) {
1413 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1415 return new SByteConstant ((sbyte) v);
1417 if (target_type == TypeManager.ushort_type) {
1418 if (!CheckUnsigned (ec, v, target_type))
1420 return new UShortConstant ((ushort) v);
1422 if (target_type == TypeManager.int32_type)
1423 return new IntConstant ((int) v);
1424 if (target_type == TypeManager.uint32_type) {
1425 if (!CheckUnsigned (ec, v, target_type))
1427 return new UIntConstant ((uint) v);
1429 if (target_type == TypeManager.int64_type)
1430 return new LongConstant ((long) v);
1431 if (target_type == TypeManager.uint64_type) {
1432 if (!CheckUnsigned (ec, v, target_type))
1434 return new ULongConstant ((ulong) v);
1436 if (target_type == TypeManager.float_type)
1437 return new FloatConstant ((float) v);
1438 if (target_type == TypeManager.double_type)
1439 return new DoubleConstant ((double) v);
1440 if (target_type == TypeManager.char_type) {
1441 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1443 return new CharConstant ((char) v);
1445 if (target_type == TypeManager.decimal_type)
1446 return new DecimalConstant ((decimal) v);
1448 if (real_expr is UShortConstant){
1449 ushort v = ((UShortConstant) real_expr).Value;
1451 if (target_type == TypeManager.byte_type) {
1452 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1454 return new ByteConstant ((byte) v);
1456 if (target_type == TypeManager.sbyte_type) {
1457 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1459 return new SByteConstant ((sbyte) v);
1461 if (target_type == TypeManager.short_type) {
1462 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1464 return new ShortConstant ((short) v);
1466 if (target_type == TypeManager.int32_type)
1467 return new IntConstant ((int) v);
1468 if (target_type == TypeManager.uint32_type)
1469 return new UIntConstant ((uint) v);
1470 if (target_type == TypeManager.int64_type)
1471 return new LongConstant ((long) v);
1472 if (target_type == TypeManager.uint64_type)
1473 return new ULongConstant ((ulong) v);
1474 if (target_type == TypeManager.float_type)
1475 return new FloatConstant ((float) v);
1476 if (target_type == TypeManager.double_type)
1477 return new DoubleConstant ((double) v);
1478 if (target_type == TypeManager.char_type) {
1479 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1481 return new CharConstant ((char) v);
1483 if (target_type == TypeManager.decimal_type)
1484 return new DecimalConstant ((decimal) v);
1486 if (real_expr is IntConstant){
1487 int v = ((IntConstant) real_expr).Value;
1489 if (target_type == TypeManager.byte_type) {
1490 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1492 return new ByteConstant ((byte) v);
1494 if (target_type == TypeManager.sbyte_type) {
1495 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1497 return new SByteConstant ((sbyte) v);
1499 if (target_type == TypeManager.short_type) {
1500 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1502 return new ShortConstant ((short) v);
1504 if (target_type == TypeManager.ushort_type) {
1505 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1507 return new UShortConstant ((ushort) v);
1509 if (target_type == TypeManager.uint32_type) {
1510 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1512 return new UIntConstant ((uint) v);
1514 if (target_type == TypeManager.int64_type)
1515 return new LongConstant ((long) v);
1516 if (target_type == TypeManager.uint64_type) {
1517 if (!CheckUnsigned (ec, v, target_type))
1519 return new ULongConstant ((ulong) v);
1521 if (target_type == TypeManager.float_type)
1522 return new FloatConstant ((float) v);
1523 if (target_type == TypeManager.double_type)
1524 return new DoubleConstant ((double) v);
1525 if (target_type == TypeManager.char_type) {
1526 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1528 return new CharConstant ((char) v);
1530 if (target_type == TypeManager.decimal_type)
1531 return new DecimalConstant ((decimal) v);
1533 if (real_expr is UIntConstant){
1534 uint v = ((UIntConstant) real_expr).Value;
1536 if (target_type == TypeManager.byte_type) {
1537 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1539 return new ByteConstant ((byte) v);
1541 if (target_type == TypeManager.sbyte_type) {
1542 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1544 return new SByteConstant ((sbyte) v);
1546 if (target_type == TypeManager.short_type) {
1547 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1549 return new ShortConstant ((short) v);
1551 if (target_type == TypeManager.ushort_type) {
1552 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1554 return new UShortConstant ((ushort) v);
1556 if (target_type == TypeManager.int32_type) {
1557 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1559 return new IntConstant ((int) v);
1561 if (target_type == TypeManager.int64_type)
1562 return new LongConstant ((long) v);
1563 if (target_type == TypeManager.uint64_type)
1564 return new ULongConstant ((ulong) v);
1565 if (target_type == TypeManager.float_type)
1566 return new FloatConstant ((float) v);
1567 if (target_type == TypeManager.double_type)
1568 return new DoubleConstant ((double) v);
1569 if (target_type == TypeManager.char_type) {
1570 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1572 return new CharConstant ((char) v);
1574 if (target_type == TypeManager.decimal_type)
1575 return new DecimalConstant ((decimal) v);
1577 if (real_expr is LongConstant){
1578 long v = ((LongConstant) real_expr).Value;
1580 if (target_type == TypeManager.byte_type) {
1581 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1583 return new ByteConstant ((byte) v);
1585 if (target_type == TypeManager.sbyte_type) {
1586 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1588 return new SByteConstant ((sbyte) v);
1590 if (target_type == TypeManager.short_type) {
1591 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1593 return new ShortConstant ((short) v);
1595 if (target_type == TypeManager.ushort_type) {
1596 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1598 return new UShortConstant ((ushort) v);
1600 if (target_type == TypeManager.int32_type) {
1601 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1603 return new IntConstant ((int) v);
1605 if (target_type == TypeManager.uint32_type) {
1606 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1608 return new UIntConstant ((uint) v);
1610 if (target_type == TypeManager.uint64_type) {
1611 if (!CheckUnsigned (ec, v, target_type))
1613 return new ULongConstant ((ulong) v);
1615 if (target_type == TypeManager.float_type)
1616 return new FloatConstant ((float) v);
1617 if (target_type == TypeManager.double_type)
1618 return new DoubleConstant ((double) v);
1619 if (target_type == TypeManager.char_type) {
1620 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1622 return new CharConstant ((char) v);
1624 if (target_type == TypeManager.decimal_type)
1625 return new DecimalConstant ((decimal) v);
1627 if (real_expr is ULongConstant){
1628 ulong v = ((ULongConstant) real_expr).Value;
1630 if (target_type == TypeManager.byte_type) {
1631 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1633 return new ByteConstant ((byte) v);
1635 if (target_type == TypeManager.sbyte_type) {
1636 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1638 return new SByteConstant ((sbyte) v);
1640 if (target_type == TypeManager.short_type) {
1641 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1643 return new ShortConstant ((short) v);
1645 if (target_type == TypeManager.ushort_type) {
1646 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1648 return new UShortConstant ((ushort) v);
1650 if (target_type == TypeManager.int32_type) {
1651 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1653 return new IntConstant ((int) v);
1655 if (target_type == TypeManager.uint32_type) {
1656 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1658 return new UIntConstant ((uint) v);
1660 if (target_type == TypeManager.int64_type) {
1661 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1663 return new LongConstant ((long) v);
1665 if (target_type == TypeManager.float_type)
1666 return new FloatConstant ((float) v);
1667 if (target_type == TypeManager.double_type)
1668 return new DoubleConstant ((double) v);
1669 if (target_type == TypeManager.char_type) {
1670 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1672 return new CharConstant ((char) v);
1674 if (target_type == TypeManager.decimal_type)
1675 return new DecimalConstant ((decimal) v);
1677 if (real_expr is FloatConstant){
1678 float v = ((FloatConstant) real_expr).Value;
1680 if (target_type == TypeManager.byte_type)
1681 return new ByteConstant ((byte) v);
1682 if (target_type == TypeManager.sbyte_type)
1683 return new SByteConstant ((sbyte) v);
1684 if (target_type == TypeManager.short_type)
1685 return new ShortConstant ((short) v);
1686 if (target_type == TypeManager.ushort_type)
1687 return new UShortConstant ((ushort) v);
1688 if (target_type == TypeManager.int32_type)
1689 return new IntConstant ((int) v);
1690 if (target_type == TypeManager.uint32_type)
1691 return new UIntConstant ((uint) v);
1692 if (target_type == TypeManager.int64_type)
1693 return new LongConstant ((long) v);
1694 if (target_type == TypeManager.uint64_type)
1695 return new ULongConstant ((ulong) v);
1696 if (target_type == TypeManager.double_type)
1697 return new DoubleConstant ((double) v);
1698 if (target_type == TypeManager.char_type)
1699 return new CharConstant ((char) v);
1700 if (target_type == TypeManager.decimal_type)
1701 return new DecimalConstant ((decimal) v);
1703 if (real_expr is DoubleConstant){
1704 double v = ((DoubleConstant) real_expr).Value;
1706 if (target_type == TypeManager.byte_type){
1707 return new ByteConstant ((byte) v);
1708 } if (target_type == TypeManager.sbyte_type)
1709 return new SByteConstant ((sbyte) v);
1710 if (target_type == TypeManager.short_type)
1711 return new ShortConstant ((short) v);
1712 if (target_type == TypeManager.ushort_type)
1713 return new UShortConstant ((ushort) v);
1714 if (target_type == TypeManager.int32_type)
1715 return new IntConstant ((int) v);
1716 if (target_type == TypeManager.uint32_type)
1717 return new UIntConstant ((uint) v);
1718 if (target_type == TypeManager.int64_type)
1719 return new LongConstant ((long) v);
1720 if (target_type == TypeManager.uint64_type)
1721 return new ULongConstant ((ulong) v);
1722 if (target_type == TypeManager.float_type)
1723 return new FloatConstant ((float) v);
1724 if (target_type == TypeManager.char_type)
1725 return new CharConstant ((char) v);
1726 if (target_type == TypeManager.decimal_type)
1727 return new DecimalConstant ((decimal) v);
1730 if (real_expr is CharConstant){
1731 char v = ((CharConstant) real_expr).Value;
1733 if (target_type == TypeManager.byte_type) {
1734 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1736 return new ByteConstant ((byte) v);
1738 if (target_type == TypeManager.sbyte_type) {
1739 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1741 return new SByteConstant ((sbyte) v);
1743 if (target_type == TypeManager.short_type) {
1744 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1746 return new ShortConstant ((short) v);
1748 if (target_type == TypeManager.int32_type)
1749 return new IntConstant ((int) v);
1750 if (target_type == TypeManager.uint32_type)
1751 return new UIntConstant ((uint) v);
1752 if (target_type == TypeManager.int64_type)
1753 return new LongConstant ((long) v);
1754 if (target_type == TypeManager.uint64_type)
1755 return new ULongConstant ((ulong) v);
1756 if (target_type == TypeManager.float_type)
1757 return new FloatConstant ((float) v);
1758 if (target_type == TypeManager.double_type)
1759 return new DoubleConstant ((double) v);
1760 if (target_type == TypeManager.char_type) {
1761 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1763 return new CharConstant ((char) v);
1765 if (target_type == TypeManager.decimal_type)
1766 return new DecimalConstant ((decimal) v);
1772 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1774 expr = expr.DoResolveLValue (ec, right_side);
1778 return ResolveRest (ec);
1781 public override Expression DoResolve (EmitContext ec)
1783 expr = expr.Resolve (ec);
1787 return ResolveRest (ec);
1790 Expression ResolveRest (EmitContext ec)
1792 TypeExpr target = target_type.ResolveAsTypeTerminal (ec, false);
1796 type = target.ResolveType (ec);
1798 CheckObsoleteAttribute (type);
1800 if (type.IsAbstract && type.IsSealed) {
1801 Report.Error (716, loc, "Cannot convert to static type '{0}'", TypeManager.CSharpName (type));
1805 eclass = ExprClass.Value;
1807 if (expr is Constant){
1808 Expression e = TryReduce (ec, type);
1814 if (type.IsPointer && !ec.InUnsafe) {
1818 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1822 public override void Emit (EmitContext ec)
1825 // This one will never happen
1827 throw new Exception ("Should not happen");
1832 /// Binary operators
1834 public class Binary : Expression {
1835 public enum Operator : byte {
1836 Multiply, Division, Modulus,
1837 Addition, Subtraction,
1838 LeftShift, RightShift,
1839 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1840 Equality, Inequality,
1850 Expression left, right;
1852 // This must be kept in sync with Operator!!!
1853 public static readonly string [] oper_names;
1857 oper_names = new string [(int) Operator.TOP];
1859 oper_names [(int) Operator.Multiply] = "op_Multiply";
1860 oper_names [(int) Operator.Division] = "op_Division";
1861 oper_names [(int) Operator.Modulus] = "op_Modulus";
1862 oper_names [(int) Operator.Addition] = "op_Addition";
1863 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1864 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1865 oper_names [(int) Operator.RightShift] = "op_RightShift";
1866 oper_names [(int) Operator.LessThan] = "op_LessThan";
1867 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1868 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1869 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1870 oper_names [(int) Operator.Equality] = "op_Equality";
1871 oper_names [(int) Operator.Inequality] = "op_Inequality";
1872 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1873 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1874 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1875 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1876 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1879 public Binary (Operator oper, Expression left, Expression right, Location loc)
1887 public Operator Oper {
1896 public Expression Left {
1905 public Expression Right {
1916 /// Returns a stringified representation of the Operator
1918 static string OperName (Operator oper)
1921 case Operator.Multiply:
1923 case Operator.Division:
1925 case Operator.Modulus:
1927 case Operator.Addition:
1929 case Operator.Subtraction:
1931 case Operator.LeftShift:
1933 case Operator.RightShift:
1935 case Operator.LessThan:
1937 case Operator.GreaterThan:
1939 case Operator.LessThanOrEqual:
1941 case Operator.GreaterThanOrEqual:
1943 case Operator.Equality:
1945 case Operator.Inequality:
1947 case Operator.BitwiseAnd:
1949 case Operator.BitwiseOr:
1951 case Operator.ExclusiveOr:
1953 case Operator.LogicalOr:
1955 case Operator.LogicalAnd:
1959 return oper.ToString ();
1962 public override string ToString ()
1964 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1965 right.ToString () + ")";
1968 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1970 if (expr.Type == target_type)
1973 return Convert.ImplicitConversion (ec, expr, target_type, loc);
1976 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1979 34, loc, "Operator `" + OperName (oper)
1980 + "' is ambiguous on operands of type `"
1981 + TypeManager.CSharpName (l) + "' "
1982 + "and `" + TypeManager.CSharpName (r)
1986 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
1988 if ((l == t) || (r == t))
1991 if (!check_user_conversions)
1994 if (Convert.ImplicitUserConversionExists (ec, l, t))
1996 else if (Convert.ImplicitUserConversionExists (ec, r, t))
2003 // Note that handling the case l == Decimal || r == Decimal
2004 // is taken care of by the Step 1 Operator Overload resolution.
2006 // If `check_user_conv' is true, we also check whether a user-defined conversion
2007 // exists. Note that we only need to do this if both arguments are of a user-defined
2008 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
2009 // so we don't explicitly check for performance reasons.
2011 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
2013 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
2015 // If either operand is of type double, the other operand is
2016 // conveted to type double.
2018 if (r != TypeManager.double_type)
2019 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
2020 if (l != TypeManager.double_type)
2021 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
2023 type = TypeManager.double_type;
2024 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
2026 // if either operand is of type float, the other operand is
2027 // converted to type float.
2029 if (r != TypeManager.double_type)
2030 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
2031 if (l != TypeManager.double_type)
2032 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
2033 type = TypeManager.float_type;
2034 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2038 // If either operand is of type ulong, the other operand is
2039 // converted to type ulong. or an error ocurrs if the other
2040 // operand is of type sbyte, short, int or long
2042 if (l == TypeManager.uint64_type){
2043 if (r != TypeManager.uint64_type){
2044 if (right is IntConstant){
2045 IntConstant ic = (IntConstant) right;
2047 e = Convert.TryImplicitIntConversion (l, ic);
2050 } else if (right is LongConstant){
2051 long ll = ((LongConstant) right).Value;
2054 right = new ULongConstant ((ulong) ll);
2056 e = Convert.ImplicitNumericConversion (ec, right, l, loc);
2063 if (left is IntConstant){
2064 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
2067 } else if (left is LongConstant){
2068 long ll = ((LongConstant) left).Value;
2071 left = new ULongConstant ((ulong) ll);
2073 e = Convert.ImplicitNumericConversion (ec, left, r, loc);
2080 if ((other == TypeManager.sbyte_type) ||
2081 (other == TypeManager.short_type) ||
2082 (other == TypeManager.int32_type) ||
2083 (other == TypeManager.int64_type))
2084 Error_OperatorAmbiguous (loc, oper, l, r);
2086 left = ForceConversion (ec, left, TypeManager.uint64_type);
2087 right = ForceConversion (ec, right, TypeManager.uint64_type);
2089 type = TypeManager.uint64_type;
2090 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2092 // If either operand is of type long, the other operand is converted
2095 if (l != TypeManager.int64_type)
2096 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
2097 if (r != TypeManager.int64_type)
2098 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
2100 type = TypeManager.int64_type;
2101 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2103 // If either operand is of type uint, and the other
2104 // operand is of type sbyte, short or int, othe operands are
2105 // converted to type long (unless we have an int constant).
2109 if (l == TypeManager.uint32_type){
2110 if (right is IntConstant){
2111 IntConstant ic = (IntConstant) right;
2115 right = new UIntConstant ((uint) val);
2122 } else if (r == TypeManager.uint32_type){
2123 if (left is IntConstant){
2124 IntConstant ic = (IntConstant) left;
2128 left = new UIntConstant ((uint) val);
2137 if ((other == TypeManager.sbyte_type) ||
2138 (other == TypeManager.short_type) ||
2139 (other == TypeManager.int32_type)){
2140 left = ForceConversion (ec, left, TypeManager.int64_type);
2141 right = ForceConversion (ec, right, TypeManager.int64_type);
2142 type = TypeManager.int64_type;
2145 // if either operand is of type uint, the other
2146 // operand is converd to type uint
2148 left = ForceConversion (ec, left, TypeManager.uint32_type);
2149 right = ForceConversion (ec, right, TypeManager.uint32_type);
2150 type = TypeManager.uint32_type;
2152 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2153 if (l != TypeManager.decimal_type)
2154 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
2156 if (r != TypeManager.decimal_type)
2157 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
2158 type = TypeManager.decimal_type;
2160 left = ForceConversion (ec, left, TypeManager.int32_type);
2161 right = ForceConversion (ec, right, TypeManager.int32_type);
2163 type = TypeManager.int32_type;
2166 return (left != null) && (right != null);
2169 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2171 Report.Error (19, loc,
2172 "Operator " + name + " cannot be applied to operands of type `" +
2173 TypeManager.CSharpName (l) + "' and `" +
2174 TypeManager.CSharpName (r) + "'");
2177 void Error_OperatorCannotBeApplied ()
2179 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2182 static bool is_unsigned (Type t)
2184 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2185 t == TypeManager.short_type || t == TypeManager.byte_type);
2188 static bool is_user_defined (Type t)
2190 if (t.IsSubclassOf (TypeManager.value_type) &&
2191 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2197 Expression Make32or64 (EmitContext ec, Expression e)
2201 if (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2202 t == TypeManager.int64_type || t == TypeManager.uint64_type)
2204 Expression ee = Convert.ImplicitConversion (ec, e, TypeManager.int32_type, loc);
2207 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint32_type, loc);
2210 ee = Convert.ImplicitConversion (ec, e, TypeManager.int64_type, loc);
2213 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint64_type, loc);
2219 Expression CheckShiftArguments (EmitContext ec)
2223 e = ForceConversion (ec, right, TypeManager.int32_type);
2225 Error_OperatorCannotBeApplied ();
2230 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
2231 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
2232 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
2233 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
2237 if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
2238 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (31), loc);
2239 right = right.DoResolve (ec);
2241 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (63), loc);
2242 right = right.DoResolve (ec);
2247 Error_OperatorCannotBeApplied ();
2251 Expression ResolveOperator (EmitContext ec)
2254 Type r = right.Type;
2257 // Special cases: string comapred to null
2259 if (oper == Operator.Equality || oper == Operator.Inequality){
2260 if ((!TypeManager.IsValueType (l) && r == TypeManager.null_type) ||
2261 (!TypeManager.IsValueType (r) && l == TypeManager.null_type)) {
2262 Type = TypeManager.bool_type;
2268 if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
2269 Type = TypeManager.bool_type;
2276 // Do not perform operator overload resolution when both sides are
2279 if (!(TypeManager.IsPrimitiveType (l) && TypeManager.IsPrimitiveType (r))){
2281 // Step 1: Perform Operator Overload location
2283 Expression left_expr, right_expr;
2285 string op = oper_names [(int) oper];
2287 MethodGroupExpr union;
2288 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2290 right_expr = MemberLookup (
2291 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2292 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2294 union = (MethodGroupExpr) left_expr;
2296 if (union != null) {
2297 ArrayList args = new ArrayList (2);
2298 args.Add (new Argument (left, Argument.AType.Expression));
2299 args.Add (new Argument (right, Argument.AType.Expression));
2301 MethodBase method = Invocation.OverloadResolve (
2302 ec, union, args, true, Location.Null);
2304 if (method != null) {
2305 MethodInfo mi = (MethodInfo) method;
2307 return new BinaryMethod (mi.ReturnType, method, args);
2313 // Step 0: String concatenation (because overloading will get this wrong)
2315 if (oper == Operator.Addition){
2317 // If any of the arguments is a string, cast to string
2320 // Simple constant folding
2321 if (left is StringConstant && right is StringConstant)
2322 return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value);
2324 if (l == TypeManager.string_type || r == TypeManager.string_type) {
2326 if (r == TypeManager.void_type || l == TypeManager.void_type) {
2327 Error_OperatorCannotBeApplied ();
2331 // try to fold it in on the left
2332 if (left is StringConcat) {
2335 // We have to test here for not-null, since we can be doubly-resolved
2336 // take care of not appending twice
2339 type = TypeManager.string_type;
2340 ((StringConcat) left).Append (ec, right);
2341 return left.Resolve (ec);
2347 // Otherwise, start a new concat expression
2348 return new StringConcat (ec, loc, left, right).Resolve (ec);
2352 // Transform a + ( - b) into a - b
2354 if (right is Unary){
2355 Unary right_unary = (Unary) right;
2357 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2358 oper = Operator.Subtraction;
2359 right = right_unary.Expr;
2365 if (oper == Operator.Equality || oper == Operator.Inequality){
2366 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2367 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2368 Error_OperatorCannotBeApplied ();
2372 type = TypeManager.bool_type;
2377 // operator != (object a, object b)
2378 // operator == (object a, object b)
2380 // For this to be used, both arguments have to be reference-types.
2381 // Read the rationale on the spec (14.9.6)
2383 // Also, if at compile time we know that the classes do not inherit
2384 // one from the other, then we catch the error there.
2386 if (!(l.IsValueType || r.IsValueType)){
2387 type = TypeManager.bool_type;
2392 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2396 // Also, a standard conversion must exist from either one
2398 if (!(Convert.ImplicitStandardConversionExists (ec, left, r) ||
2399 Convert.ImplicitStandardConversionExists (ec, right, l))){
2400 Error_OperatorCannotBeApplied ();
2404 // We are going to have to convert to an object to compare
2406 if (l != TypeManager.object_type)
2407 left = new EmptyCast (left, TypeManager.object_type);
2408 if (r != TypeManager.object_type)
2409 right = new EmptyCast (right, TypeManager.object_type);
2412 // FIXME: CSC here catches errors cs254 and cs252
2418 // One of them is a valuetype, but the other one is not.
2420 if (!l.IsValueType || !r.IsValueType) {
2421 Error_OperatorCannotBeApplied ();
2426 // Only perform numeric promotions on:
2427 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2429 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2430 if (l.IsSubclassOf (TypeManager.delegate_type)){
2431 if (((right.eclass == ExprClass.MethodGroup) ||
2432 (r == TypeManager.anonymous_method_type))){
2433 if ((RootContext.Version != LanguageVersion.ISO_1)){
2434 Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2442 if (r.IsSubclassOf (TypeManager.delegate_type)){
2444 ArrayList args = new ArrayList (2);
2446 args = new ArrayList (2);
2447 args.Add (new Argument (left, Argument.AType.Expression));
2448 args.Add (new Argument (right, Argument.AType.Expression));
2450 if (oper == Operator.Addition)
2451 method = TypeManager.delegate_combine_delegate_delegate;
2453 method = TypeManager.delegate_remove_delegate_delegate;
2456 Error_OperatorCannotBeApplied ();
2460 return new BinaryDelegate (l, method, args);
2465 // Pointer arithmetic:
2467 // T* operator + (T* x, int y);
2468 // T* operator + (T* x, uint y);
2469 // T* operator + (T* x, long y);
2470 // T* operator + (T* x, ulong y);
2472 // T* operator + (int y, T* x);
2473 // T* operator + (uint y, T *x);
2474 // T* operator + (long y, T *x);
2475 // T* operator + (ulong y, T *x);
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 // long operator - (T* x, T *y)
2485 if (r.IsPointer && oper == Operator.Subtraction){
2487 return new PointerArithmetic (
2488 false, left, right, TypeManager.int64_type,
2491 Expression t = Make32or64 (ec, right);
2493 return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc).Resolve (ec);
2495 } else if (r.IsPointer && oper == Operator.Addition){
2496 Expression t = Make32or64 (ec, left);
2498 return new PointerArithmetic (true, right, t, r, loc).Resolve (ec);
2503 // Enumeration operators
2505 bool lie = TypeManager.IsEnumType (l);
2506 bool rie = TypeManager.IsEnumType (r);
2510 // U operator - (E e, E f)
2512 if (oper == Operator.Subtraction){
2514 type = TypeManager.EnumToUnderlying (l);
2517 Error_OperatorCannotBeApplied ();
2523 // operator + (E e, U x)
2524 // operator - (E e, U x)
2526 if (oper == Operator.Addition || oper == Operator.Subtraction){
2527 Type enum_type = lie ? l : r;
2528 Type other_type = lie ? r : l;
2529 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2531 if (underlying_type != other_type){
2532 temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
2542 Error_OperatorCannotBeApplied ();
2551 temp = Convert.ImplicitConversion (ec, right, l, loc);
2555 Error_OperatorCannotBeApplied ();
2559 temp = Convert.ImplicitConversion (ec, left, r, loc);
2564 Error_OperatorCannotBeApplied ();
2569 if (oper == Operator.Equality || oper == Operator.Inequality ||
2570 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2571 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2572 if (left.Type != right.Type){
2573 Error_OperatorCannotBeApplied ();
2576 type = TypeManager.bool_type;
2580 if (oper == Operator.BitwiseAnd ||
2581 oper == Operator.BitwiseOr ||
2582 oper == Operator.ExclusiveOr){
2586 Error_OperatorCannotBeApplied ();
2590 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2591 return CheckShiftArguments (ec);
2593 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2594 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2595 type = TypeManager.bool_type;
2600 Error_OperatorCannotBeApplied ();
2604 Expression e = new ConditionalLogicalOperator (
2605 oper == Operator.LogicalAnd, left, right, l, loc);
2606 return e.Resolve (ec);
2610 // operator & (bool x, bool y)
2611 // operator | (bool x, bool y)
2612 // operator ^ (bool x, bool y)
2614 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2615 if (oper == Operator.BitwiseAnd ||
2616 oper == Operator.BitwiseOr ||
2617 oper == Operator.ExclusiveOr){
2624 // Pointer comparison
2626 if (l.IsPointer && r.IsPointer){
2627 if (oper == Operator.Equality || oper == Operator.Inequality ||
2628 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2629 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2630 type = TypeManager.bool_type;
2636 // This will leave left or right set to null if there is an error
2638 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2639 DoNumericPromotions (ec, l, r, check_user_conv);
2640 if (left == null || right == null){
2641 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2646 // reload our cached types if required
2651 if (oper == Operator.BitwiseAnd ||
2652 oper == Operator.BitwiseOr ||
2653 oper == Operator.ExclusiveOr){
2655 if (((l == TypeManager.int32_type) ||
2656 (l == TypeManager.uint32_type) ||
2657 (l == TypeManager.short_type) ||
2658 (l == TypeManager.ushort_type) ||
2659 (l == TypeManager.int64_type) ||
2660 (l == TypeManager.uint64_type))){
2663 Error_OperatorCannotBeApplied ();
2667 Error_OperatorCannotBeApplied ();
2672 if (oper == Operator.Equality ||
2673 oper == Operator.Inequality ||
2674 oper == Operator.LessThanOrEqual ||
2675 oper == Operator.LessThan ||
2676 oper == Operator.GreaterThanOrEqual ||
2677 oper == Operator.GreaterThan){
2678 type = TypeManager.bool_type;
2684 public override Expression DoResolve (EmitContext ec)
2686 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2687 left = ((ParenthesizedExpression) left).Expr;
2688 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2692 if (left.eclass == ExprClass.Type) {
2693 Error (75, "Casting a negative value needs to have the value in parentheses.");
2697 left = left.Resolve (ec);
2702 Constant lc = left as Constant;
2703 if (lc != null && lc.Type == TypeManager.bool_type &&
2704 ((oper == Operator.LogicalAnd && (bool)lc.GetValue () == false) ||
2705 (oper == Operator.LogicalOr && (bool)lc.GetValue () == true))) {
2707 // TODO: make a sense to resolve unreachable expression as we do for statement
2708 Report.Warning (429, 4, loc, "Unreachable expression code detected");
2712 right = right.Resolve (ec);
2716 eclass = ExprClass.Value;
2718 Constant rc = right as Constant;
2719 if (rc != null & lc != null){
2720 Expression e = ConstantFold.BinaryFold (
2721 ec, oper, lc, rc, loc);
2726 return ResolveOperator (ec);
2730 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2731 /// context of a conditional bool expression. This function will return
2732 /// false if it is was possible to use EmitBranchable, or true if it was.
2734 /// The expression's code is generated, and we will generate a branch to `target'
2735 /// if the resulting expression value is equal to isTrue
2737 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2739 ILGenerator ig = ec.ig;
2742 // This is more complicated than it looks, but its just to avoid
2743 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2744 // but on top of that we want for == and != to use a special path
2745 // if we are comparing against null
2747 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
2748 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2751 // put the constant on the rhs, for simplicity
2753 if (left is Constant) {
2754 Expression swap = right;
2759 if (((Constant) right).IsZeroInteger) {
2762 ig.Emit (OpCodes.Brtrue, target);
2764 ig.Emit (OpCodes.Brfalse, target);
2767 } else if (right is BoolConstant) {
2769 if (my_on_true != ((BoolConstant) right).Value)
2770 ig.Emit (OpCodes.Brtrue, target);
2772 ig.Emit (OpCodes.Brfalse, target);
2777 } else if (oper == Operator.LogicalAnd) {
2780 Label tests_end = ig.DefineLabel ();
2782 left.EmitBranchable (ec, tests_end, false);
2783 right.EmitBranchable (ec, target, true);
2784 ig.MarkLabel (tests_end);
2786 left.EmitBranchable (ec, target, false);
2787 right.EmitBranchable (ec, target, false);
2792 } else if (oper == Operator.LogicalOr){
2794 left.EmitBranchable (ec, target, true);
2795 right.EmitBranchable (ec, target, true);
2798 Label tests_end = ig.DefineLabel ();
2799 left.EmitBranchable (ec, tests_end, true);
2800 right.EmitBranchable (ec, target, false);
2801 ig.MarkLabel (tests_end);
2806 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2807 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2808 oper == Operator.Equality || oper == Operator.Inequality)) {
2809 base.EmitBranchable (ec, target, onTrue);
2817 bool isUnsigned = is_unsigned (t) || t == TypeManager.double_type || t == TypeManager.float_type;
2820 case Operator.Equality:
2822 ig.Emit (OpCodes.Beq, target);
2824 ig.Emit (OpCodes.Bne_Un, target);
2827 case Operator.Inequality:
2829 ig.Emit (OpCodes.Bne_Un, target);
2831 ig.Emit (OpCodes.Beq, target);
2834 case Operator.LessThan:
2837 ig.Emit (OpCodes.Blt_Un, target);
2839 ig.Emit (OpCodes.Blt, target);
2842 ig.Emit (OpCodes.Bge_Un, target);
2844 ig.Emit (OpCodes.Bge, target);
2847 case Operator.GreaterThan:
2850 ig.Emit (OpCodes.Bgt_Un, target);
2852 ig.Emit (OpCodes.Bgt, target);
2855 ig.Emit (OpCodes.Ble_Un, target);
2857 ig.Emit (OpCodes.Ble, target);
2860 case Operator.LessThanOrEqual:
2863 ig.Emit (OpCodes.Ble_Un, target);
2865 ig.Emit (OpCodes.Ble, target);
2868 ig.Emit (OpCodes.Bgt_Un, target);
2870 ig.Emit (OpCodes.Bgt, target);
2874 case Operator.GreaterThanOrEqual:
2877 ig.Emit (OpCodes.Bge_Un, target);
2879 ig.Emit (OpCodes.Bge, target);
2882 ig.Emit (OpCodes.Blt_Un, target);
2884 ig.Emit (OpCodes.Blt, target);
2887 Console.WriteLine (oper);
2888 throw new Exception ("what is THAT");
2892 public override void Emit (EmitContext ec)
2894 ILGenerator ig = ec.ig;
2899 // Handle short-circuit operators differently
2902 if (oper == Operator.LogicalAnd) {
2903 Label load_zero = ig.DefineLabel ();
2904 Label end = ig.DefineLabel ();
2906 left.EmitBranchable (ec, load_zero, false);
2908 ig.Emit (OpCodes.Br, end);
2910 ig.MarkLabel (load_zero);
2911 ig.Emit (OpCodes.Ldc_I4_0);
2914 } else if (oper == Operator.LogicalOr) {
2915 Label load_one = ig.DefineLabel ();
2916 Label end = ig.DefineLabel ();
2918 left.EmitBranchable (ec, load_one, true);
2920 ig.Emit (OpCodes.Br, end);
2922 ig.MarkLabel (load_one);
2923 ig.Emit (OpCodes.Ldc_I4_1);
2931 bool isUnsigned = is_unsigned (left.Type);
2934 case Operator.Multiply:
2936 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2937 opcode = OpCodes.Mul_Ovf;
2938 else if (isUnsigned)
2939 opcode = OpCodes.Mul_Ovf_Un;
2941 opcode = OpCodes.Mul;
2943 opcode = OpCodes.Mul;
2947 case Operator.Division:
2949 opcode = OpCodes.Div_Un;
2951 opcode = OpCodes.Div;
2954 case Operator.Modulus:
2956 opcode = OpCodes.Rem_Un;
2958 opcode = OpCodes.Rem;
2961 case Operator.Addition:
2963 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2964 opcode = OpCodes.Add_Ovf;
2965 else if (isUnsigned)
2966 opcode = OpCodes.Add_Ovf_Un;
2968 opcode = OpCodes.Add;
2970 opcode = OpCodes.Add;
2973 case Operator.Subtraction:
2975 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2976 opcode = OpCodes.Sub_Ovf;
2977 else if (isUnsigned)
2978 opcode = OpCodes.Sub_Ovf_Un;
2980 opcode = OpCodes.Sub;
2982 opcode = OpCodes.Sub;
2985 case Operator.RightShift:
2987 opcode = OpCodes.Shr_Un;
2989 opcode = OpCodes.Shr;
2992 case Operator.LeftShift:
2993 opcode = OpCodes.Shl;
2996 case Operator.Equality:
2997 opcode = OpCodes.Ceq;
3000 case Operator.Inequality:
3001 ig.Emit (OpCodes.Ceq);
3002 ig.Emit (OpCodes.Ldc_I4_0);
3004 opcode = OpCodes.Ceq;
3007 case Operator.LessThan:
3009 opcode = OpCodes.Clt_Un;
3011 opcode = OpCodes.Clt;
3014 case Operator.GreaterThan:
3016 opcode = OpCodes.Cgt_Un;
3018 opcode = OpCodes.Cgt;
3021 case Operator.LessThanOrEqual:
3022 Type lt = left.Type;
3024 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
3025 ig.Emit (OpCodes.Cgt_Un);
3027 ig.Emit (OpCodes.Cgt);
3028 ig.Emit (OpCodes.Ldc_I4_0);
3030 opcode = OpCodes.Ceq;
3033 case Operator.GreaterThanOrEqual:
3034 Type le = left.Type;
3036 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3037 ig.Emit (OpCodes.Clt_Un);
3039 ig.Emit (OpCodes.Clt);
3041 ig.Emit (OpCodes.Ldc_I4_0);
3043 opcode = OpCodes.Ceq;
3046 case Operator.BitwiseOr:
3047 opcode = OpCodes.Or;
3050 case Operator.BitwiseAnd:
3051 opcode = OpCodes.And;
3054 case Operator.ExclusiveOr:
3055 opcode = OpCodes.Xor;
3059 throw new Exception ("This should not happen: Operator = "
3060 + oper.ToString ());
3068 // Object created by Binary when the binary operator uses an method instead of being
3069 // a binary operation that maps to a CIL binary operation.
3071 public class BinaryMethod : Expression {
3072 public MethodBase method;
3073 public ArrayList Arguments;
3075 public BinaryMethod (Type t, MethodBase m, ArrayList args)
3080 eclass = ExprClass.Value;
3083 public override Expression DoResolve (EmitContext ec)
3088 public override void Emit (EmitContext ec)
3090 ILGenerator ig = ec.ig;
3092 if (Arguments != null)
3093 Invocation.EmitArguments (ec, method, Arguments, false, null);
3095 if (method is MethodInfo)
3096 ig.Emit (OpCodes.Call, (MethodInfo) method);
3098 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3103 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3104 // b, c, d... may be strings or objects.
3106 public class StringConcat : Expression {
3108 bool invalid = false;
3109 bool emit_conv_done = false;
3111 // Are we also concating objects?
3113 bool is_strings_only = true;
3115 public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
3118 type = TypeManager.string_type;
3119 eclass = ExprClass.Value;
3121 operands = new ArrayList (2);
3126 public override Expression DoResolve (EmitContext ec)
3134 public void Append (EmitContext ec, Expression operand)
3139 if (operand is StringConstant && operands.Count != 0) {
3140 StringConstant last_operand = operands [operands.Count - 1] as StringConstant;
3141 if (last_operand != null) {
3142 operands [operands.Count - 1] = new StringConstant (last_operand.Value + ((StringConstant) operand).Value);
3148 // Conversion to object
3150 if (operand.Type != TypeManager.string_type) {
3151 Expression no = Convert.ImplicitConversion (ec, operand, TypeManager.object_type, loc);
3154 Binary.Error_OperatorCannotBeApplied (loc, "+", TypeManager.string_type, operand.Type);
3160 operands.Add (operand);
3163 public override void Emit (EmitContext ec)
3165 MethodInfo concat_method = null;
3168 // Do conversion to arguments; check for strings only
3171 // This can get called multiple times, so we have to deal with that.
3172 if (!emit_conv_done) {
3173 emit_conv_done = true;
3174 for (int i = 0; i < operands.Count; i ++) {
3175 Expression e = (Expression) operands [i];
3176 is_strings_only &= e.Type == TypeManager.string_type;
3179 for (int i = 0; i < operands.Count; i ++) {
3180 Expression e = (Expression) operands [i];
3182 if (! is_strings_only && e.Type == TypeManager.string_type) {
3183 // need to make sure this is an object, because the EmitParams
3184 // method might look at the type of this expression, see it is a
3185 // string and emit a string [] when we want an object [];
3187 e = new EmptyCast (e, TypeManager.object_type);
3189 operands [i] = new Argument (e, Argument.AType.Expression);
3194 // Find the right method
3196 switch (operands.Count) {
3199 // This should not be possible, because simple constant folding
3200 // is taken care of in the Binary code.
3202 throw new Exception ("how did you get here?");
3205 concat_method = is_strings_only ?
3206 TypeManager.string_concat_string_string :
3207 TypeManager.string_concat_object_object ;
3210 concat_method = is_strings_only ?
3211 TypeManager.string_concat_string_string_string :
3212 TypeManager.string_concat_object_object_object ;
3216 // There is not a 4 param overlaod for object (the one that there is
3217 // is actually a varargs methods, and is only in corlib because it was
3218 // introduced there before.).
3220 if (!is_strings_only)
3223 concat_method = TypeManager.string_concat_string_string_string_string;
3226 concat_method = is_strings_only ?
3227 TypeManager.string_concat_string_dot_dot_dot :
3228 TypeManager.string_concat_object_dot_dot_dot ;
3232 Invocation.EmitArguments (ec, concat_method, operands, false, null);
3233 ec.ig.Emit (OpCodes.Call, concat_method);
3238 // Object created with +/= on delegates
3240 public class BinaryDelegate : Expression {
3244 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3249 eclass = ExprClass.Value;
3252 public override Expression DoResolve (EmitContext ec)
3257 public override void Emit (EmitContext ec)
3259 ILGenerator ig = ec.ig;
3261 Invocation.EmitArguments (ec, method, args, false, null);
3263 ig.Emit (OpCodes.Call, (MethodInfo) method);
3264 ig.Emit (OpCodes.Castclass, type);
3267 public Expression Right {
3269 Argument arg = (Argument) args [1];
3274 public bool IsAddition {
3276 return method == TypeManager.delegate_combine_delegate_delegate;
3282 // User-defined conditional logical operator
3283 public class ConditionalLogicalOperator : Expression {
3284 Expression left, right;
3287 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3290 eclass = ExprClass.Value;
3294 this.is_and = is_and;
3297 protected void Error19 ()
3299 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3302 protected void Error218 ()
3304 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3305 "declarations of operator true and operator false");
3308 Expression op_true, op_false, op;
3309 LocalTemporary left_temp;
3311 public override Expression DoResolve (EmitContext ec)
3314 Expression operator_group;
3316 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3317 if (operator_group == null) {
3322 left_temp = new LocalTemporary (ec, type);
3324 ArrayList arguments = new ArrayList ();
3325 arguments.Add (new Argument (left_temp, Argument.AType.Expression));
3326 arguments.Add (new Argument (right, Argument.AType.Expression));
3327 method = Invocation.OverloadResolve (
3328 ec, (MethodGroupExpr) operator_group, arguments, false, loc)
3330 if (method == null) {
3335 if (method.ReturnType != type) {
3336 Report.Error (217, loc, "In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') " +
3337 "must have the same return type as the type of its 2 parameters", TypeManager.CSharpSignature (method));
3341 op = new StaticCallExpr (method, arguments, loc);
3343 op_true = GetOperatorTrue (ec, left_temp, loc);
3344 op_false = GetOperatorFalse (ec, left_temp, loc);
3345 if ((op_true == null) || (op_false == null)) {
3353 public override void Emit (EmitContext ec)
3355 ILGenerator ig = ec.ig;
3356 Label false_target = ig.DefineLabel ();
3357 Label end_target = ig.DefineLabel ();
3360 left_temp.Store (ec);
3362 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
3363 left_temp.Emit (ec);
3364 ig.Emit (OpCodes.Br, end_target);
3365 ig.MarkLabel (false_target);
3367 ig.MarkLabel (end_target);
3371 public class PointerArithmetic : Expression {
3372 Expression left, right;
3376 // We assume that `l' is always a pointer
3378 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3384 is_add = is_addition;
3387 public override Expression DoResolve (EmitContext ec)
3389 eclass = ExprClass.Variable;
3391 if (left.Type == TypeManager.void_ptr_type) {
3392 Error (242, "The operation in question is undefined on void pointers");
3399 public override void Emit (EmitContext ec)
3401 Type op_type = left.Type;
3402 ILGenerator ig = ec.ig;
3404 // It must be either array or fixed buffer
3405 Type element = TypeManager.HasElementType (op_type) ?
3406 element = TypeManager.GetElementType (op_type) :
3407 element = AttributeTester.GetFixedBuffer (((FieldExpr)left).FieldInfo).ElementType;
3409 int size = GetTypeSize (element);
3410 Type rtype = right.Type;
3412 if (rtype.IsPointer){
3414 // handle (pointer - pointer)
3418 ig.Emit (OpCodes.Sub);
3422 ig.Emit (OpCodes.Sizeof, element);
3424 IntLiteral.EmitInt (ig, size);
3425 ig.Emit (OpCodes.Div);
3427 ig.Emit (OpCodes.Conv_I8);
3430 // handle + and - on (pointer op int)
3433 ig.Emit (OpCodes.Conv_I);
3435 Constant right_const = right as Constant;
3436 if (right_const != null && size != 0) {
3437 Expression ex = ConstantFold.BinaryFold (ec, Binary.Operator.Multiply, new IntConstant (size), right_const, loc);
3445 ig.Emit (OpCodes.Sizeof, element);
3447 IntLiteral.EmitInt (ig, size);
3448 if (rtype == TypeManager.int64_type)
3449 ig.Emit (OpCodes.Conv_I8);
3450 else if (rtype == TypeManager.uint64_type)
3451 ig.Emit (OpCodes.Conv_U8);
3452 ig.Emit (OpCodes.Mul);
3456 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
3457 ig.Emit (OpCodes.Conv_I);
3460 ig.Emit (OpCodes.Add);
3462 ig.Emit (OpCodes.Sub);
3468 /// Implements the ternary conditional operator (?:)
3470 public class Conditional : Expression {
3471 Expression expr, trueExpr, falseExpr;
3473 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3476 this.trueExpr = trueExpr;
3477 this.falseExpr = falseExpr;
3481 public Expression Expr {
3487 public Expression TrueExpr {
3493 public Expression FalseExpr {
3499 public override Expression DoResolve (EmitContext ec)
3501 expr = expr.Resolve (ec);
3506 if (expr.Type != TypeManager.bool_type){
3507 expr = Expression.ResolveBoolean (
3514 trueExpr = trueExpr.Resolve (ec);
3515 falseExpr = falseExpr.Resolve (ec);
3517 if (trueExpr == null || falseExpr == null)
3520 eclass = ExprClass.Value;
3521 if (trueExpr.Type == falseExpr.Type)
3522 type = trueExpr.Type;
3525 Type true_type = trueExpr.Type;
3526 Type false_type = falseExpr.Type;
3529 // First, if an implicit conversion exists from trueExpr
3530 // to falseExpr, then the result type is of type falseExpr.Type
3532 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3535 // Check if both can convert implicitl to each other's type
3537 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3539 "Can not compute type of conditional expression " +
3540 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3541 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3542 "' convert implicitly to each other");
3547 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3551 Error (173, "The type of the conditional expression can " +
3552 "not be computed because there is no implicit conversion" +
3553 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3554 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3559 // Dead code optimalization
3560 if (expr is BoolConstant){
3561 BoolConstant bc = (BoolConstant) expr;
3563 Report.Warning (429, 4, bc.Value ? falseExpr.Location : trueExpr.Location, "Unreachable expression code detected");
3564 return bc.Value ? trueExpr : falseExpr;
3570 public override void Emit (EmitContext ec)
3572 ILGenerator ig = ec.ig;
3573 Label false_target = ig.DefineLabel ();
3574 Label end_target = ig.DefineLabel ();
3576 expr.EmitBranchable (ec, false_target, false);
3578 ig.Emit (OpCodes.Br, end_target);
3579 ig.MarkLabel (false_target);
3580 falseExpr.Emit (ec);
3581 ig.MarkLabel (end_target);
3589 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3590 public readonly string Name;
3591 public readonly Block Block;
3592 public LocalInfo local_info;
3595 LocalTemporary temp;
3597 public LocalVariableReference (Block block, string name, Location l)
3602 eclass = ExprClass.Variable;
3606 // Setting `is_readonly' to false will allow you to create a writable
3607 // reference to a read-only variable. This is used by foreach and using.
3609 public LocalVariableReference (Block block, string name, Location l,
3610 LocalInfo local_info, bool is_readonly)
3611 : this (block, name, l)
3613 this.local_info = local_info;
3614 this.is_readonly = is_readonly;
3617 public VariableInfo VariableInfo {
3619 return local_info.VariableInfo;
3623 public bool IsReadOnly {
3629 protected Expression DoResolveBase (EmitContext ec, Expression lvalue_right_side)
3631 if (local_info == null) {
3632 local_info = Block.GetLocalInfo (Name);
3635 if (lvalue_right_side == EmptyExpression.Null)
3636 local_info.Used = true;
3638 is_readonly = local_info.ReadOnly;
3641 type = local_info.VariableType;
3643 VariableInfo variable_info = local_info.VariableInfo;
3644 if (lvalue_right_side != null){
3646 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3650 if (variable_info != null)
3651 variable_info.SetAssigned (ec);
3654 Expression e = Block.GetConstantExpression (Name);
3656 local_info.Used = true;
3657 eclass = ExprClass.Value;
3658 return e.Resolve (ec);
3661 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3664 if (lvalue_right_side == null)
3665 local_info.Used = true;
3667 if (ec.CurrentAnonymousMethod != null){
3669 // If we are referencing a variable from the external block
3670 // flag it for capturing
3672 if (local_info.Block.Toplevel != ec.CurrentBlock.Toplevel){
3673 if (local_info.AddressTaken){
3674 AnonymousMethod.Error_AddressOfCapturedVar (local_info.Name, loc);
3677 ec.CaptureVariable (local_info);
3684 public override Expression DoResolve (EmitContext ec)
3686 return DoResolveBase (ec, null);
3689 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3691 Expression ret = DoResolveBase (ec, right_side);
3693 CheckObsoleteAttribute (ret.Type);
3698 public bool VerifyFixed (bool is_expression)
3700 return !is_expression || local_info.IsFixed;
3703 public override int GetHashCode()
3705 return Name.GetHashCode ();
3708 public override bool Equals (object obj)
3710 LocalVariableReference lvr = obj as LocalVariableReference;
3714 return Name == lvr.Name && Block == lvr.Block;
3717 public override void Emit (EmitContext ec)
3719 ILGenerator ig = ec.ig;
3721 if (local_info.FieldBuilder == null){
3723 // A local variable on the local CLR stack
3725 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3728 // A local variable captured by anonymous methods.
3731 ec.EmitCapturedVariableInstance (local_info);
3733 ig.Emit (OpCodes.Ldfld, local_info.FieldBuilder);
3737 public void Emit (EmitContext ec, bool leave_copy)
3741 ec.ig.Emit (OpCodes.Dup);
3742 if (local_info.FieldBuilder != null){
3743 temp = new LocalTemporary (ec, Type);
3749 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3751 ILGenerator ig = ec.ig;
3752 prepared = prepare_for_load;
3754 if (local_info.FieldBuilder == null){
3756 // A local variable on the local CLR stack
3758 if (local_info.LocalBuilder == null)
3759 throw new Exception ("This should not happen: both Field and Local are null");
3763 ec.ig.Emit (OpCodes.Dup);
3764 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3767 // A local variable captured by anonymous methods or itereators.
3769 ec.EmitCapturedVariableInstance (local_info);
3771 if (prepare_for_load)
3772 ig.Emit (OpCodes.Dup);
3775 ig.Emit (OpCodes.Dup);
3776 temp = new LocalTemporary (ec, Type);
3779 ig.Emit (OpCodes.Stfld, local_info.FieldBuilder);
3785 public void AddressOf (EmitContext ec, AddressOp mode)
3787 ILGenerator ig = ec.ig;
3789 if (local_info.FieldBuilder == null){
3791 // A local variable on the local CLR stack
3793 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3796 // A local variable captured by anonymous methods or iterators
3798 ec.EmitCapturedVariableInstance (local_info);
3799 ig.Emit (OpCodes.Ldflda, local_info.FieldBuilder);
3803 public override string ToString ()
3805 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3810 /// This represents a reference to a parameter in the intermediate
3813 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3819 public Parameter.Modifier mod;
3820 public bool is_ref, is_out, prepared;
3834 LocalTemporary temp;
3836 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3843 eclass = ExprClass.Variable;
3846 public VariableInfo VariableInfo {
3850 public bool VerifyFixed (bool is_expression)
3852 return !is_expression || TypeManager.IsValueType (type);
3855 public bool IsAssigned (EmitContext ec, Location loc)
3857 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsAssigned (vi))
3860 Report.Error (269, loc,
3861 "Use of unassigned out parameter '{0}'", name);
3865 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3867 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3870 Report.Error (170, loc,
3871 "Use of possibly unassigned field `" + field_name + "'");
3875 public void SetAssigned (EmitContext ec)
3877 if (is_out && ec.DoFlowAnalysis)
3878 ec.CurrentBranching.SetAssigned (vi);
3881 public void SetFieldAssigned (EmitContext ec, string field_name)
3883 if (is_out && ec.DoFlowAnalysis)
3884 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3887 protected void DoResolveBase (EmitContext ec)
3889 type = pars.GetParameterInfo (ec, idx, out mod);
3890 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3891 is_out = (mod & Parameter.Modifier.OUT) != 0;
3892 eclass = ExprClass.Variable;
3895 vi = block.ParameterMap [idx];
3897 if (ec.CurrentAnonymousMethod != null){
3899 Report.Error (1628, Location,
3900 "Can not reference a ref or out parameter in an anonymous method");
3905 // If we are referencing the parameter from the external block
3906 // flag it for capturing
3908 //Console.WriteLine ("Is parameter `{0}' local? {1}", name, block.IsLocalParameter (name));
3909 if (!block.IsLocalParameter (name)){
3910 ec.CaptureParameter (name, type, idx);
3915 public override int GetHashCode()
3917 return name.GetHashCode ();
3920 public override bool Equals (object obj)
3922 ParameterReference pr = obj as ParameterReference;
3926 return name == pr.name && block == pr.block;
3930 // Notice that for ref/out parameters, the type exposed is not the
3931 // same type exposed externally.
3934 // externally we expose "int&"
3935 // here we expose "int".
3937 // We record this in "is_ref". This means that the type system can treat
3938 // the type as it is expected, but when we generate the code, we generate
3939 // the alternate kind of code.
3941 public override Expression DoResolve (EmitContext ec)
3945 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3948 if (ec.RemapToProxy)
3949 return ec.RemapParameter (idx);
3954 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3960 if (ec.RemapToProxy)
3961 return ec.RemapParameterLValue (idx, right_side);
3966 static public void EmitLdArg (ILGenerator ig, int x)
3970 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3971 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3972 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3973 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3974 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3977 ig.Emit (OpCodes.Ldarg, x);
3981 // This method is used by parameters that are references, that are
3982 // being passed as references: we only want to pass the pointer (that
3983 // is already stored in the parameter, not the address of the pointer,
3984 // and not the value of the variable).
3986 public void EmitLoad (EmitContext ec)
3988 ILGenerator ig = ec.ig;
3991 if (!ec.MethodIsStatic)
3995 EmitLdArg (ig, arg_idx);
3998 // FIXME: Review for anonymous methods
4002 public override void Emit (EmitContext ec)
4004 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4005 ec.EmitParameter (name);
4012 public void Emit (EmitContext ec, bool leave_copy)
4014 ILGenerator ig = ec.ig;
4017 if (!ec.MethodIsStatic)
4020 EmitLdArg (ig, arg_idx);
4024 ec.ig.Emit (OpCodes.Dup);
4027 // If we are a reference, we loaded on the stack a pointer
4028 // Now lets load the real value
4030 LoadFromPtr (ig, type);
4034 ec.ig.Emit (OpCodes.Dup);
4037 temp = new LocalTemporary (ec, type);
4043 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
4045 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4046 ec.EmitAssignParameter (name, source, leave_copy, prepare_for_load);
4050 ILGenerator ig = ec.ig;
4053 prepared = prepare_for_load;
4055 if (!ec.MethodIsStatic)
4058 if (is_ref && !prepared)
4059 EmitLdArg (ig, arg_idx);
4064 ec.ig.Emit (OpCodes.Dup);
4068 temp = new LocalTemporary (ec, type);
4072 StoreFromPtr (ig, type);
4078 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
4080 ig.Emit (OpCodes.Starg, arg_idx);
4084 public void AddressOf (EmitContext ec, AddressOp mode)
4086 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4087 ec.EmitAddressOfParameter (name);
4093 if (!ec.MethodIsStatic)
4098 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
4100 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
4103 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
4105 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
4112 /// Used for arguments to New(), Invocation()
4114 public class Argument {
4115 public enum AType : byte {
4122 public readonly AType ArgType;
4123 public Expression Expr;
4125 public Argument (Expression expr, AType type)
4128 this.ArgType = type;
4131 public Argument (Expression expr)
4134 this.ArgType = AType.Expression;
4139 if (ArgType == AType.Ref || ArgType == AType.Out)
4140 return TypeManager.GetReferenceType (Expr.Type);
4146 public Parameter.Modifier GetParameterModifier ()
4150 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
4153 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
4156 return Parameter.Modifier.NONE;
4160 public static string FullDesc (Argument a)
4162 if (a.ArgType == AType.ArgList)
4165 return (a.ArgType == AType.Ref ? "ref " :
4166 (a.ArgType == AType.Out ? "out " : "")) +
4167 TypeManager.CSharpName (a.Expr.Type);
4170 public bool ResolveMethodGroup (EmitContext ec, Location loc)
4172 // FIXME: csc doesn't report any error if you try to use `ref' or
4173 // `out' in a delegate creation expression.
4174 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4181 void Error_LValueRequired (Location loc)
4183 Report.Error (1510, loc, "An lvalue is required as an argument to out or ref");
4186 public bool Resolve (EmitContext ec, Location loc)
4188 if (ArgType == AType.Ref) {
4189 Expr = Expr.Resolve (ec);
4193 if (!ec.IsConstructor) {
4194 FieldExpr fe = Expr as FieldExpr;
4195 if (fe != null && fe.FieldInfo.IsInitOnly) {
4196 if (fe.FieldInfo.IsStatic)
4197 Report.Error (199, loc, "A static readonly field cannot be passed ref or out (except in a static constructor)");
4199 Report.Error (192, loc, "A readonly field cannot be passed ref or out (except in a constructor)");
4203 Expr = Expr.DoResolveLValue (ec, Expr);
4205 Error_LValueRequired (loc);
4206 } else if (ArgType == AType.Out) {
4207 Expr = Expr.DoResolveLValue (ec, EmptyExpression.Null);
4209 Error_LValueRequired (loc);
4212 Expr = Expr.Resolve (ec);
4217 if (ArgType == AType.Expression)
4221 // Catch errors where fields of a MarshalByRefObject are passed as ref or out
4222 // This is only allowed for `this'
4224 FieldExpr fe = Expr as FieldExpr;
4225 if (fe != null && !fe.IsStatic){
4226 Expression instance = fe.InstanceExpression;
4228 if (instance.GetType () != typeof (This)){
4229 if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
4230 Report.SymbolRelatedToPreviousError (fe.InstanceExpression.Type);
4231 Report.Error (197, loc, "Cannot pass '{0}' as ref or out or take its address because it is a member of a marshal-by-reference class",
4239 if (Expr.eclass != ExprClass.Variable){
4241 // We just probe to match the CSC output
4243 if (Expr.eclass == ExprClass.PropertyAccess ||
4244 Expr.eclass == ExprClass.IndexerAccess){
4247 "A property or indexer can not be passed as an out or ref " +
4250 Error_LValueRequired (loc);
4258 public void Emit (EmitContext ec)
4261 // Ref and Out parameters need to have their addresses taken.
4263 // ParameterReferences might already be references, so we want
4264 // to pass just the value
4266 if (ArgType == AType.Ref || ArgType == AType.Out){
4267 AddressOp mode = AddressOp.Store;
4269 if (ArgType == AType.Ref)
4270 mode |= AddressOp.Load;
4272 if (Expr is ParameterReference){
4273 ParameterReference pr = (ParameterReference) Expr;
4279 pr.AddressOf (ec, mode);
4282 if (Expr is IMemoryLocation)
4283 ((IMemoryLocation) Expr).AddressOf (ec, mode);
4286 1510, Expr.Location,
4287 "An lvalue is required as an argument to out or ref");
4297 /// Invocation of methods or delegates.
4299 public class Invocation : ExpressionStatement {
4300 public readonly ArrayList Arguments;
4303 MethodBase method = null;
4306 // arguments is an ArrayList, but we do not want to typecast,
4307 // as it might be null.
4309 // FIXME: only allow expr to be a method invocation or a
4310 // delegate invocation (7.5.5)
4312 public Invocation (Expression expr, ArrayList arguments, Location l)
4315 Arguments = arguments;
4319 public Expression Expr {
4326 /// Determines "better conversion" as specified in 7.4.2.3
4328 /// Returns : p if a->p is better,
4329 /// q if a->q is better,
4330 /// null if neither is better
4332 static Type BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
4334 Type argument_type = a.Type;
4335 Expression argument_expr = a.Expr;
4337 if (argument_type == null)
4338 throw new Exception ("Expression of type " + a.Expr +
4339 " does not resolve its type");
4341 if (p == null || q == null)
4342 throw new InternalErrorException ("BetterConversion Got a null conversion");
4347 if (argument_expr is NullLiteral) {
4349 // If the argument is null and one of the types to compare is 'object' and
4350 // the other is a reference type, we prefer the other.
4352 // This follows from the usual rules:
4353 // * There is an implicit conversion from 'null' to type 'object'
4354 // * There is an implicit conversion from 'null' to any reference type
4355 // * There is an implicit conversion from any reference type to type 'object'
4356 // * There is no implicit conversion from type 'object' to other reference types
4357 // => Conversion of 'null' to a reference type is better than conversion to 'object'
4359 // FIXME: This probably isn't necessary, since the type of a NullLiteral is the
4360 // null type. I think it used to be 'object' and thus needed a special
4361 // case to avoid the immediately following two checks.
4363 if (!p.IsValueType && q == TypeManager.object_type)
4365 if (!q.IsValueType && p == TypeManager.object_type)
4369 if (argument_type == p)
4372 if (argument_type == q)
4375 Expression p_tmp = new EmptyExpression (p);
4376 Expression q_tmp = new EmptyExpression (q);
4378 bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
4379 bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
4381 if (p_to_q && !q_to_p)
4384 if (q_to_p && !p_to_q)
4387 if (p == TypeManager.sbyte_type)
4388 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4389 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4391 if (q == TypeManager.sbyte_type)
4392 if (p == TypeManager.byte_type || p == TypeManager.ushort_type ||
4393 p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4396 if (p == TypeManager.short_type)
4397 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4398 q == TypeManager.uint64_type)
4400 if (q == TypeManager.short_type)
4401 if (p == TypeManager.ushort_type || p == TypeManager.uint32_type ||
4402 p == TypeManager.uint64_type)
4405 if (p == TypeManager.int32_type)
4406 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4408 if (q == TypeManager.int32_type)
4409 if (p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4412 if (p == TypeManager.int64_type)
4413 if (q == TypeManager.uint64_type)
4415 if (q == TypeManager.int64_type)
4416 if (p == TypeManager.uint64_type)
4423 /// Determines "Better function" between candidate
4424 /// and the current best match
4427 /// Returns an integer indicating :
4428 /// false if candidate ain't better
4429 /// true if candidate is better than the current best match
4431 static bool BetterFunction (EmitContext ec, ArrayList args, int argument_count,
4432 MethodBase candidate, bool candidate_params,
4433 MethodBase best, bool best_params, Location loc)
4435 ParameterData candidate_pd = TypeManager.GetParameterData (candidate);
4436 ParameterData best_pd = TypeManager.GetParameterData (best);
4438 bool better_at_least_one = false;
4440 for (int j = 0; j < argument_count; ++j) {
4441 Argument a = (Argument) args [j];
4443 Type ct = TypeManager.TypeToCoreType (candidate_pd.ParameterType (j));
4444 Type bt = TypeManager.TypeToCoreType (best_pd.ParameterType (j));
4446 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4447 if (candidate_params)
4448 ct = TypeManager.GetElementType (ct);
4450 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4452 bt = TypeManager.GetElementType (bt);
4458 Type better = BetterConversion (ec, a, ct, bt, loc);
4460 // for each argument, the conversion to 'ct' should be no worse than
4461 // the conversion to 'bt'.
4465 // for at least one argument, the conversion to 'ct' should be better than
4466 // the conversion to 'bt'.
4468 better_at_least_one = true;
4471 if (better_at_least_one)
4475 // This handles the case
4477 // Add (float f1, float f2, float f3);
4478 // Add (params decimal [] foo);
4480 // The call Add (3, 4, 5) should be ambiguous. Without this check, the
4481 // first candidate would've chosen as better.
4487 // This handles the following cases:
4489 // Trim () is better than Trim (params char[] chars)
4490 // Concat (string s1, string s2, string s3) is better than
4491 // Concat (string s1, params string [] srest)
4493 return !candidate_params && best_params;
4496 static bool IsOverride (MethodBase cand_method, MethodBase base_method)
4498 if (!IsAncestralType (base_method.DeclaringType, cand_method.DeclaringType))
4501 ParameterData cand_pd = TypeManager.GetParameterData (cand_method);
4502 ParameterData base_pd = TypeManager.GetParameterData (base_method);
4504 if (cand_pd.Count != base_pd.Count)
4507 for (int j = 0; j < cand_pd.Count; ++j) {
4508 Parameter.Modifier cm = cand_pd.ParameterModifier (j);
4509 Parameter.Modifier bm = base_pd.ParameterModifier (j);
4510 Type ct = TypeManager.TypeToCoreType (cand_pd.ParameterType (j));
4511 Type bt = TypeManager.TypeToCoreType (base_pd.ParameterType (j));
4513 if (cm != bm || ct != bt)
4520 public static string FullMethodDesc (MethodBase mb)
4522 string ret_type = "";
4527 if (mb is MethodInfo)
4528 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
4530 StringBuilder sb = new StringBuilder (ret_type);
4532 sb.Append (mb.ReflectedType.ToString ());
4534 sb.Append (mb.Name);
4536 ParameterData pd = TypeManager.GetParameterData (mb);
4538 int count = pd.Count;
4541 for (int i = count; i > 0; ) {
4544 sb.Append (pd.ParameterDesc (count - i - 1));
4550 return sb.ToString ();
4553 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4555 MemberInfo [] miset;
4556 MethodGroupExpr union;
4561 return (MethodGroupExpr) mg2;
4564 return (MethodGroupExpr) mg1;
4567 MethodGroupExpr left_set = null, right_set = null;
4568 int length1 = 0, length2 = 0;
4570 left_set = (MethodGroupExpr) mg1;
4571 length1 = left_set.Methods.Length;
4573 right_set = (MethodGroupExpr) mg2;
4574 length2 = right_set.Methods.Length;
4576 ArrayList common = new ArrayList ();
4578 foreach (MethodBase r in right_set.Methods){
4579 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
4583 miset = new MemberInfo [length1 + length2 - common.Count];
4584 left_set.Methods.CopyTo (miset, 0);
4588 foreach (MethodBase r in right_set.Methods) {
4589 if (!common.Contains (r))
4593 union = new MethodGroupExpr (miset, loc);
4598 public static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4599 ArrayList arguments, int arg_count,
4600 ref MethodBase candidate)
4602 return IsParamsMethodApplicable (
4603 ec, me, arguments, arg_count, false, ref candidate) ||
4604 IsParamsMethodApplicable (
4605 ec, me, arguments, arg_count, true, ref candidate);
4610 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4611 ArrayList arguments, int arg_count,
4612 bool do_varargs, ref MethodBase candidate)
4614 return IsParamsMethodApplicable (
4615 ec, arguments, arg_count, candidate, do_varargs);
4619 /// Determines if the candidate method, if a params method, is applicable
4620 /// in its expanded form to the given set of arguments
4622 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
4623 int arg_count, MethodBase candidate,
4626 ParameterData pd = TypeManager.GetParameterData (candidate);
4628 int pd_count = pd.Count;
4632 int count = pd_count - 1;
4634 if (pd.ParameterModifier (count) != Parameter.Modifier.ARGLIST)
4636 if (pd_count != arg_count)
4639 if (pd.ParameterModifier (count) != Parameter.Modifier.PARAMS)
4643 if (count > arg_count)
4646 if (pd_count == 1 && arg_count == 0)
4650 // If we have come this far, the case which
4651 // remains is when the number of parameters is
4652 // less than or equal to the argument count.
4654 for (int i = 0; i < count; ++i) {
4656 Argument a = (Argument) arguments [i];
4658 Parameter.Modifier a_mod = a.GetParameterModifier () &
4659 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4660 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4661 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4663 if (a_mod == p_mod) {
4665 if (a_mod == Parameter.Modifier.NONE)
4666 if (!Convert.ImplicitConversionExists (ec,
4668 pd.ParameterType (i)))
4671 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4672 Type pt = pd.ParameterType (i);
4675 pt = TypeManager.GetReferenceType (pt);
4686 Argument a = (Argument) arguments [count];
4687 if (!(a.Expr is Arglist))
4693 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4695 for (int i = pd_count - 1; i < arg_count; i++) {
4696 Argument a = (Argument) arguments [i];
4698 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4705 public static bool IsApplicable (EmitContext ec, MethodGroupExpr me,
4706 ArrayList arguments, int arg_count,
4707 ref MethodBase candidate)
4709 return IsApplicable (ec, arguments, arg_count, candidate);
4713 /// Determines if the candidate method is applicable (section 14.4.2.1)
4714 /// to the given set of arguments
4716 static bool IsApplicable (EmitContext ec, ArrayList arguments, int arg_count,
4717 MethodBase candidate)
4719 ParameterData pd = TypeManager.GetParameterData (candidate);
4721 if (arg_count != pd.Count)
4724 for (int i = arg_count; i > 0; ) {
4727 Argument a = (Argument) arguments [i];
4729 Parameter.Modifier a_mod = a.GetParameterModifier () &
4730 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4731 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4732 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4735 if (a_mod == p_mod ||
4736 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4737 if (a_mod == Parameter.Modifier.NONE) {
4738 if (!Convert.ImplicitConversionExists (ec,
4740 pd.ParameterType (i)))
4744 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4745 Type pt = pd.ParameterType (i);
4748 pt = TypeManager.GetReferenceType (pt);
4760 static private bool IsAncestralType (Type first_type, Type second_type)
4762 return first_type != second_type &&
4763 (second_type.IsSubclassOf (first_type) ||
4764 TypeManager.ImplementsInterface (second_type, first_type));
4768 /// Find the Applicable Function Members (7.4.2.1)
4770 /// me: Method Group expression with the members to select.
4771 /// it might contain constructors or methods (or anything
4772 /// that maps to a method).
4774 /// Arguments: ArrayList containing resolved Argument objects.
4776 /// loc: The location if we want an error to be reported, or a Null
4777 /// location for "probing" purposes.
4779 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4780 /// that is the best match of me on Arguments.
4783 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4784 ArrayList Arguments, bool may_fail,
4787 MethodBase method = null;
4788 bool method_params = false;
4789 Type applicable_type = null;
4791 ArrayList candidates = new ArrayList (2);
4792 ArrayList candidate_overrides = null;
4795 // Used to keep a map between the candidate
4796 // and whether it is being considered in its
4797 // normal or expanded form
4799 // false is normal form, true is expanded form
4801 Hashtable candidate_to_form = null;
4803 if (Arguments != null)
4804 arg_count = Arguments.Count;
4806 if ((me.Name == "Invoke") &&
4807 TypeManager.IsDelegateType (me.DeclaringType)) {
4808 Error_InvokeOnDelegate (loc);
4812 MethodBase[] methods = me.Methods;
4815 // First we construct the set of applicable methods
4817 bool is_sorted = true;
4818 for (int i = 0; i < methods.Length; i++){
4819 Type decl_type = methods [i].DeclaringType;
4822 // If we have already found an applicable method
4823 // we eliminate all base types (Section 14.5.5.1)
4825 if ((applicable_type != null) &&
4826 IsAncestralType (decl_type, applicable_type))
4830 // Methods marked 'override' don't take part in 'applicable_type'
4831 // computation, nor in the actual overload resolution.
4832 // However, they still need to be emitted instead of a base virtual method.
4833 // We avoid doing the 'applicable' test here, since it'll anyway be applied
4834 // to the base virtual function, and IsOverride is much faster than IsApplicable.
4837 methods [i].IsVirtual &&
4838 (methods [i].Attributes & MethodAttributes.NewSlot) == 0) {
4839 if (candidate_overrides == null)
4840 candidate_overrides = new ArrayList ();
4841 candidate_overrides.Add (methods [i]);
4846 // Check if candidate is applicable (section 14.4.2.1)
4847 // Is candidate applicable in normal form?
4849 bool is_applicable = IsApplicable (
4850 ec, me, Arguments, arg_count, ref methods [i]);
4852 if (!is_applicable &&
4853 (IsParamsMethodApplicable (
4854 ec, me, Arguments, arg_count, ref methods [i]))) {
4855 MethodBase candidate = methods [i];
4856 if (candidate_to_form == null)
4857 candidate_to_form = new PtrHashtable ();
4858 candidate_to_form [candidate] = candidate;
4859 // Candidate is applicable in expanded form
4860 is_applicable = true;
4866 candidates.Add (methods [i]);
4868 if (applicable_type == null)
4869 applicable_type = decl_type;
4870 else if (applicable_type != decl_type) {
4872 if (IsAncestralType (applicable_type, decl_type))
4873 applicable_type = decl_type;
4877 int candidate_top = candidates.Count;
4879 if (applicable_type == null) {
4881 // Okay so we have failed to find anything so we
4882 // return by providing info about the closest match
4884 for (int i = 0; i < methods.Length; ++i) {
4885 MethodBase c = (MethodBase) methods [i];
4886 ParameterData pd = TypeManager.GetParameterData (c);
4888 if (pd.Count != arg_count)
4891 VerifyArgumentsCompat (ec, Arguments, arg_count,
4892 c, false, null, may_fail, loc);
4897 string report_name = me.Name;
4898 if (report_name == ".ctor")
4899 report_name = me.DeclaringType.ToString ();
4901 Error_WrongNumArguments (
4902 loc, report_name, arg_count);
4911 // At this point, applicable_type is _one_ of the most derived types
4912 // in the set of types containing the methods in this MethodGroup.
4913 // Filter the candidates so that they only contain methods from the
4914 // most derived types.
4917 int finalized = 0; // Number of finalized candidates
4920 // Invariant: applicable_type is a most derived type
4922 // We'll try to complete Section 14.5.5.1 for 'applicable_type' by
4923 // eliminating all it's base types. At the same time, we'll also move
4924 // every unrelated type to the end of the array, and pick the next
4925 // 'applicable_type'.
4927 Type next_applicable_type = null;
4928 int j = finalized; // where to put the next finalized candidate
4929 int k = finalized; // where to put the next undiscarded candidate
4930 for (int i = finalized; i < candidate_top; ++i) {
4931 MethodBase candidate = (MethodBase) candidates [i];
4932 Type decl_type = candidate.DeclaringType;
4934 if (decl_type == applicable_type) {
4935 candidates [k++] = candidates [j];
4936 candidates [j++] = candidates [i];
4940 if (IsAncestralType (decl_type, applicable_type))
4943 if (next_applicable_type != null &&
4944 IsAncestralType (decl_type, next_applicable_type))
4947 candidates [k++] = candidates [i];
4949 if (next_applicable_type == null ||
4950 IsAncestralType (next_applicable_type, decl_type))
4951 next_applicable_type = decl_type;
4954 applicable_type = next_applicable_type;
4957 } while (applicable_type != null);
4961 // Now we actually find the best method
4964 method = (MethodBase) candidates [0];
4965 method_params = candidate_to_form != null && candidate_to_form.Contains (method);
4966 for (int ix = 1; ix < candidate_top; ix++){
4967 MethodBase candidate = (MethodBase) candidates [ix];
4969 if (candidate == method)
4972 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4974 if (BetterFunction (ec, Arguments, arg_count,
4975 candidate, cand_params,
4976 method, method_params, loc)) {
4978 method_params = cand_params;
4983 // Now check that there are no ambiguities i.e the selected method
4984 // should be better than all the others
4986 bool ambiguous = false;
4987 for (int ix = 0; ix < candidate_top; ix++){
4988 MethodBase candidate = (MethodBase) candidates [ix];
4990 if (candidate == method)
4993 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4994 if (!BetterFunction (ec, Arguments, arg_count,
4995 method, method_params,
4996 candidate, cand_params,
4998 Report.SymbolRelatedToPreviousError (candidate);
5004 Report.SymbolRelatedToPreviousError (method);
5005 Report.Error (121, loc, "Ambiguous call when selecting function due to implicit casts");
5010 // If the method is a virtual function, pick an override closer to the LHS type.
5012 if (!me.IsBase && method.IsVirtual) {
5013 if ((method.Attributes & MethodAttributes.NewSlot) != MethodAttributes.NewSlot)
5014 throw new InternalErrorException (
5015 "Should not happen. An 'override' method took part in overload resolution: " + method);
5017 if (candidate_overrides != null)
5018 foreach (MethodBase candidate in candidate_overrides) {
5019 if (IsOverride (candidate, method))
5025 // And now check if the arguments are all
5026 // compatible, perform conversions if
5027 // necessary etc. and return if everything is
5030 if (!VerifyArgumentsCompat (ec, Arguments, arg_count, method,
5031 method_params, null, may_fail, loc))
5034 if (method != null) {
5035 IMethodData data = TypeManager.GetMethod (method);
5037 data.SetMemberIsUsed ();
5042 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
5044 if (name == "Finalize" && arg_count == 0) {
5045 Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
5048 Report.Error (1501, loc,
5049 "No overload for method `" + name + "' takes `" +
5050 arg_count + "' arguments");
5054 static void Error_InvokeOnDelegate (Location loc)
5056 Report.Error (1533, loc,
5057 "Invoke cannot be called directly on a delegate");
5060 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
5061 Type delegate_type, string arg_sig, string par_desc)
5063 if (delegate_type == null)
5064 Report.Error (1502, loc,
5065 "The best overloaded match for method '" +
5066 FullMethodDesc (method) +
5067 "' has some invalid arguments");
5069 Report.Error (1594, loc,
5070 "Delegate '" + delegate_type.ToString () +
5071 "' has some invalid arguments.");
5072 Report.Error (1503, loc,
5073 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
5074 idx, arg_sig, par_desc));
5077 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
5078 int arg_count, MethodBase method,
5079 bool chose_params_expanded,
5080 Type delegate_type, bool may_fail,
5083 ParameterData pd = TypeManager.GetParameterData (method);
5084 int pd_count = pd.Count;
5086 for (int j = 0; j < arg_count; j++) {
5087 Argument a = (Argument) Arguments [j];
5088 Expression a_expr = a.Expr;
5089 Type parameter_type = pd.ParameterType (j);
5090 Parameter.Modifier pm = pd.ParameterModifier (j);
5092 if (pm == Parameter.Modifier.PARAMS){
5093 if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
5095 Error_InvalidArguments (
5096 loc, j, method, delegate_type,
5097 Argument.FullDesc (a), pd.ParameterDesc (j));
5101 if (chose_params_expanded)
5102 parameter_type = TypeManager.GetElementType (parameter_type);
5103 } else if (pm == Parameter.Modifier.ARGLIST){
5109 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
5111 Error_InvalidArguments (
5112 loc, j, method, delegate_type,
5113 Argument.FullDesc (a), pd.ParameterDesc (j));
5121 if (!a.Type.Equals (parameter_type)){
5124 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
5128 Error_InvalidArguments (
5129 loc, j, method, delegate_type,
5130 Argument.FullDesc (a), pd.ParameterDesc (j));
5135 // Update the argument with the implicit conversion
5141 if (parameter_type.IsPointer){
5148 Parameter.Modifier a_mod = a.GetParameterModifier () &
5149 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5150 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
5151 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5153 if (a_mod != p_mod &&
5154 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
5156 Report.Error (1502, loc,
5157 "The best overloaded match for method '" + FullMethodDesc (method)+
5158 "' has some invalid arguments");
5159 Report.Error (1503, loc,
5160 "Argument " + (j+1) +
5161 ": Cannot convert from '" + Argument.FullDesc (a)
5162 + "' to '" + pd.ParameterDesc (j) + "'");
5172 public override Expression DoResolve (EmitContext ec)
5175 // First, resolve the expression that is used to
5176 // trigger the invocation
5178 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
5182 if (!(expr is MethodGroupExpr)) {
5183 Type expr_type = expr.Type;
5185 if (expr_type != null){
5186 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
5188 return (new DelegateInvocation (
5189 this.expr, Arguments, loc)).Resolve (ec);
5193 if (!(expr is MethodGroupExpr)){
5194 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup, loc);
5199 // Next, evaluate all the expressions in the argument list
5201 if (Arguments != null){
5202 foreach (Argument a in Arguments){
5203 if (!a.Resolve (ec, loc))
5208 MethodGroupExpr mg = (MethodGroupExpr) expr;
5209 method = OverloadResolve (ec, mg, Arguments, false, loc);
5214 MethodInfo mi = method as MethodInfo;
5216 type = TypeManager.TypeToCoreType (mi.ReturnType);
5217 Expression iexpr = mg.InstanceExpression;
5219 if (iexpr == null ||
5220 iexpr is This || iexpr is EmptyExpression ||
5221 mg.IdenticalTypeName) {
5222 mg.InstanceExpression = null;
5224 MemberExpr.error176 (loc, mi.Name);
5228 if (iexpr == null || iexpr is EmptyExpression) {
5229 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
5235 if (type.IsPointer){
5243 // Only base will allow this invocation to happen.
5245 if (mg.IsBase && method.IsAbstract){
5246 Report.Error (205, loc, "Cannot call an abstract base member: " +
5247 FullMethodDesc (method));
5251 if (method.Name == "Finalize" && Arguments == null) {
5252 Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
5256 if ((method.Attributes & MethodAttributes.SpecialName) != 0) {
5257 if (TypeManager.LookupDeclSpace (method.DeclaringType) != null || TypeManager.IsSpecialMethod (method)) {
5258 Report.Error (571, loc, TypeManager.CSharpSignature (method) + ": can not call operator or accessor");
5263 if (mg.InstanceExpression != null)
5264 mg.InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
5266 eclass = ExprClass.Value;
5271 // Emits the list of arguments as an array
5273 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
5275 ILGenerator ig = ec.ig;
5276 int count = arguments.Count - idx;
5277 Argument a = (Argument) arguments [idx];
5278 Type t = a.Expr.Type;
5280 IntConstant.EmitInt (ig, count);
5281 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
5283 int top = arguments.Count;
5284 for (int j = idx; j < top; j++){
5285 a = (Argument) arguments [j];
5287 ig.Emit (OpCodes.Dup);
5288 IntConstant.EmitInt (ig, j - idx);
5291 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj);
5293 ig.Emit (OpCodes.Ldelema, t);
5298 ig.Emit (OpCodes.Stobj, t);
5305 /// Emits a list of resolved Arguments that are in the arguments
5308 /// The MethodBase argument might be null if the
5309 /// emission of the arguments is known not to contain
5310 /// a `params' field (for example in constructors or other routines
5311 /// that keep their arguments in this structure)
5313 /// if `dup_args' is true, a copy of the arguments will be left
5314 /// on the stack. If `dup_args' is true, you can specify `this_arg'
5315 /// which will be duplicated before any other args. Only EmitCall
5316 /// should be using this interface.
5318 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments, bool dup_args, LocalTemporary this_arg)
5322 pd = TypeManager.GetParameterData (mb);
5326 LocalTemporary [] temps = null;
5329 temps = new LocalTemporary [arguments.Count];
5332 // If we are calling a params method with no arguments, special case it
5334 if (arguments == null){
5335 if (pd != null && pd.Count > 0 &&
5336 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
5337 ILGenerator ig = ec.ig;
5339 IntConstant.EmitInt (ig, 0);
5340 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
5346 int top = arguments.Count;
5348 for (int i = 0; i < top; i++){
5349 Argument a = (Argument) arguments [i];
5352 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
5354 // Special case if we are passing the same data as the
5355 // params argument, do not put it in an array.
5357 if (pd.ParameterType (i) == a.Type)
5360 EmitParams (ec, i, arguments);
5367 ec.ig.Emit (OpCodes.Dup);
5368 (temps [i] = new LocalTemporary (ec, a.Type)).Store (ec);
5373 if (this_arg != null)
5376 for (int i = 0; i < top; i ++)
5377 temps [i].Emit (ec);
5380 if (pd != null && pd.Count > top &&
5381 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
5382 ILGenerator ig = ec.ig;
5384 IntConstant.EmitInt (ig, 0);
5385 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
5389 static Type[] GetVarargsTypes (EmitContext ec, MethodBase mb,
5390 ArrayList arguments)
5392 ParameterData pd = TypeManager.GetParameterData (mb);
5394 if (arguments == null)
5395 return new Type [0];
5397 Argument a = (Argument) arguments [pd.Count - 1];
5398 Arglist list = (Arglist) a.Expr;
5400 return list.ArgumentTypes;
5404 /// This checks the ConditionalAttribute on the method
5406 static bool IsMethodExcluded (MethodBase method, EmitContext ec)
5408 if (method.IsConstructor)
5411 IMethodData md = TypeManager.GetMethod (method);
5413 return md.IsExcluded (ec);
5415 // For some methods (generated by delegate class) GetMethod returns null
5416 // because they are not included in builder_to_method table
5417 if (method.DeclaringType is TypeBuilder)
5420 return AttributeTester.IsConditionalMethodExcluded (method);
5424 /// is_base tells whether we want to force the use of the `call'
5425 /// opcode instead of using callvirt. Call is required to call
5426 /// a specific method, while callvirt will always use the most
5427 /// recent method in the vtable.
5429 /// is_static tells whether this is an invocation on a static method
5431 /// instance_expr is an expression that represents the instance
5432 /// it must be non-null if is_static is false.
5434 /// method is the method to invoke.
5436 /// Arguments is the list of arguments to pass to the method or constructor.
5438 public static void EmitCall (EmitContext ec, bool is_base,
5439 bool is_static, Expression instance_expr,
5440 MethodBase method, ArrayList Arguments, Location loc)
5442 EmitCall (ec, is_base, is_static, instance_expr, method, Arguments, loc, false, false);
5445 // `dup_args' leaves an extra copy of the arguments on the stack
5446 // `omit_args' does not leave any arguments at all.
5447 // So, basically, you could make one call with `dup_args' set to true,
5448 // and then another with `omit_args' set to true, and the two calls
5449 // would have the same set of arguments. However, each argument would
5450 // only have been evaluated once.
5451 public static void EmitCall (EmitContext ec, bool is_base,
5452 bool is_static, Expression instance_expr,
5453 MethodBase method, ArrayList Arguments, Location loc,
5454 bool dup_args, bool omit_args)
5456 ILGenerator ig = ec.ig;
5457 bool struct_call = false;
5458 bool this_call = false;
5459 LocalTemporary this_arg = null;
5461 Type decl_type = method.DeclaringType;
5463 if (!RootContext.StdLib) {
5464 // Replace any calls to the system's System.Array type with calls to
5465 // the newly created one.
5466 if (method == TypeManager.system_int_array_get_length)
5467 method = TypeManager.int_array_get_length;
5468 else if (method == TypeManager.system_int_array_get_rank)
5469 method = TypeManager.int_array_get_rank;
5470 else if (method == TypeManager.system_object_array_clone)
5471 method = TypeManager.object_array_clone;
5472 else if (method == TypeManager.system_int_array_get_length_int)
5473 method = TypeManager.int_array_get_length_int;
5474 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5475 method = TypeManager.int_array_get_lower_bound_int;
5476 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5477 method = TypeManager.int_array_get_upper_bound_int;
5478 else if (method == TypeManager.system_void_array_copyto_array_int)
5479 method = TypeManager.void_array_copyto_array_int;
5482 if (ec.TestObsoleteMethodUsage) {
5484 // This checks ObsoleteAttribute on the method and on the declaring type
5486 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
5488 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
5491 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
5493 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
5497 if (IsMethodExcluded (method, ec))
5501 this_call = instance_expr == null;
5502 if (decl_type.IsValueType || (!this_call && instance_expr.Type.IsValueType))
5506 // If this is ourselves, push "this"
5511 ig.Emit (OpCodes.Ldarg_0);
5515 // Push the instance expression
5517 if (instance_expr.Type.IsValueType) {
5519 // Special case: calls to a function declared in a
5520 // reference-type with a value-type argument need
5521 // to have their value boxed.
5522 if (decl_type.IsValueType) {
5524 // If the expression implements IMemoryLocation, then
5525 // we can optimize and use AddressOf on the
5528 // If not we have to use some temporary storage for
5530 if (instance_expr is IMemoryLocation) {
5531 ((IMemoryLocation)instance_expr).
5532 AddressOf (ec, AddressOp.LoadStore);
5534 LocalTemporary temp = new LocalTemporary (ec, instance_expr.Type);
5535 instance_expr.Emit (ec);
5537 temp.AddressOf (ec, AddressOp.Load);
5540 // avoid the overhead of doing this all the time.
5542 t = TypeManager.GetReferenceType (instance_expr.Type);
5544 instance_expr.Emit (ec);
5545 ig.Emit (OpCodes.Box, instance_expr.Type);
5546 t = TypeManager.object_type;
5549 instance_expr.Emit (ec);
5550 t = instance_expr.Type;
5555 this_arg = new LocalTemporary (ec, t);
5556 ig.Emit (OpCodes.Dup);
5557 this_arg.Store (ec);
5563 EmitArguments (ec, method, Arguments, dup_args, this_arg);
5566 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
5567 call_op = OpCodes.Call;
5569 call_op = OpCodes.Callvirt;
5571 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
5572 Type[] varargs_types = GetVarargsTypes (ec, method, Arguments);
5573 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
5580 // and DoFoo is not virtual, you can omit the callvirt,
5581 // because you don't need the null checking behavior.
5583 if (method is MethodInfo)
5584 ig.Emit (call_op, (MethodInfo) method);
5586 ig.Emit (call_op, (ConstructorInfo) method);
5589 public override void Emit (EmitContext ec)
5591 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5593 EmitCall (ec, mg.IsBase, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5596 public override void EmitStatement (EmitContext ec)
5601 // Pop the return value if there is one
5603 if (method is MethodInfo){
5604 Type ret = ((MethodInfo)method).ReturnType;
5605 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5606 ec.ig.Emit (OpCodes.Pop);
5611 public class InvocationOrCast : ExpressionStatement
5614 Expression argument;
5616 public InvocationOrCast (Expression expr, Expression argument, Location loc)
5619 this.argument = argument;
5623 public override Expression DoResolve (EmitContext ec)
5626 // First try to resolve it as a cast.
5628 TypeExpr te = expr.ResolveAsTypeTerminal (ec, true);
5630 Cast cast = new Cast (te, argument, loc);
5631 return cast.Resolve (ec);
5635 // This can either be a type or a delegate invocation.
5636 // Let's just resolve it and see what we'll get.
5638 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5643 // Ok, so it's a Cast.
5645 if (expr.eclass == ExprClass.Type) {
5646 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
5647 return cast.Resolve (ec);
5651 // It's a delegate invocation.
5653 if (!TypeManager.IsDelegateType (expr.Type)) {
5654 Error (149, "Method name expected");
5658 ArrayList args = new ArrayList ();
5659 args.Add (new Argument (argument, Argument.AType.Expression));
5660 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5661 return invocation.Resolve (ec);
5666 Error (201, "Only assignment, call, increment, decrement and new object " +
5667 "expressions can be used as a statement");
5670 public override ExpressionStatement ResolveStatement (EmitContext ec)
5673 // First try to resolve it as a cast.
5675 TypeExpr te = expr.ResolveAsTypeTerminal (ec, true);
5682 // This can either be a type or a delegate invocation.
5683 // Let's just resolve it and see what we'll get.
5685 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5686 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5692 // It's a delegate invocation.
5694 if (!TypeManager.IsDelegateType (expr.Type)) {
5695 Error (149, "Method name expected");
5699 ArrayList args = new ArrayList ();
5700 args.Add (new Argument (argument, Argument.AType.Expression));
5701 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5702 return invocation.ResolveStatement (ec);
5705 public override void Emit (EmitContext ec)
5707 throw new Exception ("Cannot happen");
5710 public override void EmitStatement (EmitContext ec)
5712 throw new Exception ("Cannot happen");
5717 // This class is used to "disable" the code generation for the
5718 // temporary variable when initializing value types.
5720 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5721 public void AddressOf (EmitContext ec, AddressOp Mode)
5728 /// Implements the new expression
5730 public class New : ExpressionStatement, IMemoryLocation {
5731 public readonly ArrayList Arguments;
5734 // During bootstrap, it contains the RequestedType,
5735 // but if `type' is not null, it *might* contain a NewDelegate
5736 // (because of field multi-initialization)
5738 public Expression RequestedType;
5740 MethodBase method = null;
5743 // If set, the new expression is for a value_target, and
5744 // we will not leave anything on the stack.
5746 Expression value_target;
5747 bool value_target_set = false;
5749 public New (Expression requested_type, ArrayList arguments, Location l)
5751 RequestedType = requested_type;
5752 Arguments = arguments;
5756 public bool SetValueTypeVariable (Expression value)
5758 value_target = value;
5759 value_target_set = true;
5760 if (!(value_target is IMemoryLocation)){
5761 Error_UnexpectedKind ("variable", loc);
5768 // This function is used to disable the following code sequence for
5769 // value type initialization:
5771 // AddressOf (temporary)
5775 // Instead the provide will have provided us with the address on the
5776 // stack to store the results.
5778 static Expression MyEmptyExpression;
5780 public void DisableTemporaryValueType ()
5782 if (MyEmptyExpression == null)
5783 MyEmptyExpression = new EmptyAddressOf ();
5786 // To enable this, look into:
5787 // test-34 and test-89 and self bootstrapping.
5789 // For instance, we can avoid a copy by using `newobj'
5790 // instead of Call + Push-temp on value types.
5791 // value_target = MyEmptyExpression;
5796 /// Converts complex core type syntax like 'new int ()' to simple constant
5798 Expression Constantify (Type t)
5800 if (t == TypeManager.int32_type)
5801 return new IntConstant (0);
5802 if (t == TypeManager.uint32_type)
5803 return new UIntConstant (0);
5804 if (t == TypeManager.int64_type)
5805 return new LongConstant (0);
5806 if (t == TypeManager.uint64_type)
5807 return new ULongConstant (0);
5808 if (t == TypeManager.float_type)
5809 return new FloatConstant (0);
5810 if (t == TypeManager.double_type)
5811 return new DoubleConstant (0);
5812 if (t == TypeManager.short_type)
5813 return new ShortConstant (0);
5814 if (t == TypeManager.ushort_type)
5815 return new UShortConstant (0);
5816 if (t == TypeManager.sbyte_type)
5817 return new SByteConstant (0);
5818 if (t == TypeManager.byte_type)
5819 return new ByteConstant (0);
5820 if (t == TypeManager.char_type)
5821 return new CharConstant ('\0');
5822 if (t == TypeManager.bool_type)
5823 return new BoolConstant (false);
5824 if (t == TypeManager.decimal_type)
5825 return new DecimalConstant (0);
5830 public override Expression DoResolve (EmitContext ec)
5833 // The New DoResolve might be called twice when initializing field
5834 // expressions (see EmitFieldInitializers, the call to
5835 // GetInitializerExpression will perform a resolve on the expression,
5836 // and later the assign will trigger another resolution
5838 // This leads to bugs (#37014)
5841 if (RequestedType is NewDelegate)
5842 return RequestedType;
5846 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec, false);
5850 type = texpr.ResolveType (ec);
5852 if (Arguments == null) {
5853 Expression c = Constantify (type);
5858 CheckObsoleteAttribute (type);
5860 bool IsDelegate = TypeManager.IsDelegateType (type);
5863 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5864 if (RequestedType != null)
5865 if (!(RequestedType is DelegateCreation))
5866 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
5867 return RequestedType;
5870 if (type.IsAbstract && type.IsSealed) {
5871 Report.Error (712, loc, "Cannot create an instance of the static class '{0}'", TypeManager.CSharpName (type));
5875 if (type.IsInterface || type.IsAbstract){
5876 Error (144, "It is not possible to create instances of interfaces or abstract classes");
5880 bool is_struct = type.IsValueType;
5881 eclass = ExprClass.Value;
5884 // SRE returns a match for .ctor () on structs (the object constructor),
5885 // so we have to manually ignore it.
5887 if (is_struct && Arguments == null)
5891 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
5892 ml = MemberLookupFinal (ec, type, type, ".ctor",
5893 MemberTypes.Constructor,
5894 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5899 if (! (ml is MethodGroupExpr)){
5901 ml.Error_UnexpectedKind ("method group", loc);
5907 if (Arguments != null){
5908 foreach (Argument a in Arguments){
5909 if (!a.Resolve (ec, loc))
5914 method = Invocation.OverloadResolve (
5915 ec, (MethodGroupExpr) ml, Arguments, true, loc);
5919 if (method == null) {
5920 if (almostMatchedMembers.Count != 0) {
5921 MemberLookupFailed (ec, type, type, ".ctor", null, true, loc);
5925 if (!is_struct || Arguments.Count > 0) {
5926 Error (1501, String.Format (
5927 "New invocation: Can not find a constructor in `{0}' for this argument list",
5928 TypeManager.CSharpName (type)));
5937 // This DoEmit can be invoked in two contexts:
5938 // * As a mechanism that will leave a value on the stack (new object)
5939 // * As one that wont (init struct)
5941 // You can control whether a value is required on the stack by passing
5942 // need_value_on_stack. The code *might* leave a value on the stack
5943 // so it must be popped manually
5945 // If we are dealing with a ValueType, we have a few
5946 // situations to deal with:
5948 // * The target is a ValueType, and we have been provided
5949 // the instance (this is easy, we are being assigned).
5951 // * The target of New is being passed as an argument,
5952 // to a boxing operation or a function that takes a
5955 // In this case, we need to create a temporary variable
5956 // that is the argument of New.
5958 // Returns whether a value is left on the stack
5960 bool DoEmit (EmitContext ec, bool need_value_on_stack)
5962 bool is_value_type = type.IsValueType;
5963 ILGenerator ig = ec.ig;
5968 // Allow DoEmit() to be called multiple times.
5969 // We need to create a new LocalTemporary each time since
5970 // you can't share LocalBuilders among ILGeneators.
5971 if (!value_target_set)
5972 value_target = new LocalTemporary (ec, type);
5974 ml = (IMemoryLocation) value_target;
5975 ml.AddressOf (ec, AddressOp.Store);
5979 Invocation.EmitArguments (ec, method, Arguments, false, null);
5983 ig.Emit (OpCodes.Initobj, type);
5985 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5986 if (need_value_on_stack){
5987 value_target.Emit (ec);
5992 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
5997 public override void Emit (EmitContext ec)
6002 public override void EmitStatement (EmitContext ec)
6004 if (DoEmit (ec, false))
6005 ec.ig.Emit (OpCodes.Pop);
6008 public void AddressOf (EmitContext ec, AddressOp Mode)
6010 if (!type.IsValueType){
6012 // We throw an exception. So far, I believe we only need to support
6014 // foreach (int j in new StructType ())
6017 throw new Exception ("AddressOf should not be used for classes");
6020 if (!value_target_set)
6021 value_target = new LocalTemporary (ec, type);
6023 IMemoryLocation ml = (IMemoryLocation) value_target;
6024 ml.AddressOf (ec, AddressOp.Store);
6026 Invocation.EmitArguments (ec, method, Arguments, false, null);
6029 ec.ig.Emit (OpCodes.Initobj, type);
6031 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6033 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
6038 /// 14.5.10.2: Represents an array creation expression.
6042 /// There are two possible scenarios here: one is an array creation
6043 /// expression that specifies the dimensions and optionally the
6044 /// initialization data and the other which does not need dimensions
6045 /// specified but where initialization data is mandatory.
6047 public class ArrayCreation : Expression {
6048 Expression requested_base_type;
6049 ArrayList initializers;
6052 // The list of Argument types.
6053 // This is used to construct the `newarray' or constructor signature
6055 ArrayList arguments;
6058 // Method used to create the array object.
6060 MethodBase new_method = null;
6062 Type array_element_type;
6063 Type underlying_type;
6064 bool is_one_dimensional = false;
6065 bool is_builtin_type = false;
6066 bool expect_initializers = false;
6067 int num_arguments = 0;
6071 ArrayList array_data;
6076 // The number of array initializers that we can handle
6077 // via the InitializeArray method - through EmitStaticInitializers
6079 int num_automatic_initializers;
6081 const int max_automatic_initializers = 6;
6083 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
6085 this.requested_base_type = requested_base_type;
6086 this.initializers = initializers;
6090 arguments = new ArrayList ();
6092 foreach (Expression e in exprs) {
6093 arguments.Add (new Argument (e, Argument.AType.Expression));
6098 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
6100 this.requested_base_type = requested_base_type;
6101 this.initializers = initializers;
6105 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
6107 //string tmp = rank.Substring (rank.LastIndexOf ('['));
6109 //dimensions = tmp.Length - 1;
6110 expect_initializers = true;
6113 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
6115 StringBuilder sb = new StringBuilder (rank);
6118 for (int i = 1; i < idx_count; i++)
6123 return new ComposedCast (base_type, sb.ToString (), loc);
6126 void Error_IncorrectArrayInitializer ()
6128 Error (178, "Incorrectly structured array initializer");
6131 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
6133 if (specified_dims) {
6134 Argument a = (Argument) arguments [idx];
6136 if (!a.Resolve (ec, loc))
6139 if (!(a.Expr is Constant)) {
6140 Error (150, "A constant value is expected");
6144 int value = (int) ((Constant) a.Expr).GetValue ();
6146 if (value != probe.Count) {
6147 Error_IncorrectArrayInitializer ();
6151 bounds [idx] = value;
6154 int child_bounds = -1;
6155 foreach (object o in probe) {
6156 if (o is ArrayList) {
6157 int current_bounds = ((ArrayList) o).Count;
6159 if (child_bounds == -1)
6160 child_bounds = current_bounds;
6162 else if (child_bounds != current_bounds){
6163 Error_IncorrectArrayInitializer ();
6166 if (specified_dims && (idx + 1 >= arguments.Count)){
6167 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
6171 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
6175 if (child_bounds != -1){
6176 Error_IncorrectArrayInitializer ();
6180 Expression tmp = (Expression) o;
6181 tmp = tmp.Resolve (ec);
6185 // Console.WriteLine ("I got: " + tmp);
6186 // Handle initialization from vars, fields etc.
6188 Expression conv = Convert.ImplicitConversionRequired (
6189 ec, tmp, underlying_type, loc);
6194 if (conv is StringConstant || conv is DecimalConstant || conv is NullCast) {
6195 // These are subclasses of Constant that can appear as elements of an
6196 // array that cannot be statically initialized (with num_automatic_initializers
6197 // > max_automatic_initializers), so num_automatic_initializers should be left as zero.
6198 array_data.Add (conv);
6199 } else if (conv is Constant) {
6200 // These are the types of Constant that can appear in arrays that can be
6201 // statically allocated.
6202 array_data.Add (conv);
6203 num_automatic_initializers++;
6205 array_data.Add (conv);
6212 public void UpdateIndices (EmitContext ec)
6215 for (ArrayList probe = initializers; probe != null;) {
6216 if (probe.Count > 0 && probe [0] is ArrayList) {
6217 Expression e = new IntConstant (probe.Count);
6218 arguments.Add (new Argument (e, Argument.AType.Expression));
6220 bounds [i++] = probe.Count;
6222 probe = (ArrayList) probe [0];
6225 Expression e = new IntConstant (probe.Count);
6226 arguments.Add (new Argument (e, Argument.AType.Expression));
6228 bounds [i++] = probe.Count;
6235 public bool ValidateInitializers (EmitContext ec, Type array_type)
6237 if (initializers == null) {
6238 if (expect_initializers)
6244 if (underlying_type == null)
6248 // We use this to store all the date values in the order in which we
6249 // will need to store them in the byte blob later
6251 array_data = new ArrayList ();
6252 bounds = new Hashtable ();
6256 if (arguments != null) {
6257 ret = CheckIndices (ec, initializers, 0, true);
6260 arguments = new ArrayList ();
6262 ret = CheckIndices (ec, initializers, 0, false);
6269 if (arguments.Count != dimensions) {
6270 Error_IncorrectArrayInitializer ();
6279 // Creates the type of the array
6281 bool LookupType (EmitContext ec)
6283 StringBuilder array_qualifier = new StringBuilder (rank);
6286 // `In the first form allocates an array instace of the type that results
6287 // from deleting each of the individual expression from the expression list'
6289 if (num_arguments > 0) {
6290 array_qualifier.Append ("[");
6291 for (int i = num_arguments-1; i > 0; i--)
6292 array_qualifier.Append (",");
6293 array_qualifier.Append ("]");
6299 TypeExpr array_type_expr;
6300 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
6301 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec, false);
6302 if (array_type_expr == null)
6305 type = array_type_expr.ResolveType (ec);
6307 if (!type.IsArray) {
6308 Error (622, "Can only use array initializer expressions to assign to array types. Try using a new expression instead.");
6311 underlying_type = TypeManager.GetElementType (type);
6312 dimensions = type.GetArrayRank ();
6317 public override Expression DoResolve (EmitContext ec)
6321 if (!LookupType (ec))
6325 // First step is to validate the initializers and fill
6326 // in any missing bits
6328 if (!ValidateInitializers (ec, type))
6331 if (arguments == null)
6334 arg_count = arguments.Count;
6335 foreach (Argument a in arguments){
6336 if (!a.Resolve (ec, loc))
6339 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
6340 if (real_arg == null)
6347 array_element_type = TypeManager.GetElementType (type);
6349 if (array_element_type.IsAbstract && array_element_type.IsSealed) {
6350 Report.Error (719, loc, "'{0}': array elements cannot be of static type", TypeManager.CSharpName (array_element_type));
6354 if (arg_count == 1) {
6355 is_one_dimensional = true;
6356 eclass = ExprClass.Value;
6360 is_builtin_type = TypeManager.IsBuiltinType (type);
6362 if (is_builtin_type) {
6365 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
6366 AllBindingFlags, loc);
6368 if (!(ml is MethodGroupExpr)) {
6369 ml.Error_UnexpectedKind ("method group", loc);
6374 Error (-6, "New invocation: Can not find a constructor for " +
6375 "this argument list");
6379 new_method = Invocation.OverloadResolve (
6380 ec, (MethodGroupExpr) ml, arguments, false, loc);
6382 if (new_method == null) {
6383 Error (-6, "New invocation: Can not find a constructor for " +
6384 "this argument list");
6388 eclass = ExprClass.Value;
6391 ModuleBuilder mb = CodeGen.Module.Builder;
6392 ArrayList args = new ArrayList ();
6394 if (arguments != null) {
6395 for (int i = 0; i < arg_count; i++)
6396 args.Add (TypeManager.int32_type);
6399 Type [] arg_types = null;
6402 arg_types = new Type [args.Count];
6404 args.CopyTo (arg_types, 0);
6406 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
6409 if (new_method == null) {
6410 Error (-6, "New invocation: Can not find a constructor for " +
6411 "this argument list");
6415 eclass = ExprClass.Value;
6420 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
6425 int count = array_data.Count;
6427 if (underlying_type.IsEnum)
6428 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
6430 factor = GetTypeSize (underlying_type);
6432 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
6434 data = new byte [(count * factor + 4) & ~3];
6437 for (int i = 0; i < count; ++i) {
6438 object v = array_data [i];
6440 if (v is EnumConstant)
6441 v = ((EnumConstant) v).Child;
6443 if (v is Constant && !(v is StringConstant))
6444 v = ((Constant) v).GetValue ();
6450 if (underlying_type == TypeManager.int64_type){
6451 if (!(v is Expression)){
6452 long val = (long) v;
6454 for (int j = 0; j < factor; ++j) {
6455 data [idx + j] = (byte) (val & 0xFF);
6459 } else if (underlying_type == TypeManager.uint64_type){
6460 if (!(v is Expression)){
6461 ulong val = (ulong) v;
6463 for (int j = 0; j < factor; ++j) {
6464 data [idx + j] = (byte) (val & 0xFF);
6468 } else if (underlying_type == TypeManager.float_type) {
6469 if (!(v is Expression)){
6470 element = BitConverter.GetBytes ((float) v);
6472 for (int j = 0; j < factor; ++j)
6473 data [idx + j] = element [j];
6475 } else if (underlying_type == TypeManager.double_type) {
6476 if (!(v is Expression)){
6477 element = BitConverter.GetBytes ((double) v);
6479 for (int j = 0; j < factor; ++j)
6480 data [idx + j] = element [j];
6482 } else if (underlying_type == TypeManager.char_type){
6483 if (!(v is Expression)){
6484 int val = (int) ((char) v);
6486 data [idx] = (byte) (val & 0xff);
6487 data [idx+1] = (byte) (val >> 8);
6489 } else if (underlying_type == TypeManager.short_type){
6490 if (!(v is Expression)){
6491 int val = (int) ((short) v);
6493 data [idx] = (byte) (val & 0xff);
6494 data [idx+1] = (byte) (val >> 8);
6496 } else if (underlying_type == TypeManager.ushort_type){
6497 if (!(v is Expression)){
6498 int val = (int) ((ushort) v);
6500 data [idx] = (byte) (val & 0xff);
6501 data [idx+1] = (byte) (val >> 8);
6503 } else if (underlying_type == TypeManager.int32_type) {
6504 if (!(v is Expression)){
6507 data [idx] = (byte) (val & 0xff);
6508 data [idx+1] = (byte) ((val >> 8) & 0xff);
6509 data [idx+2] = (byte) ((val >> 16) & 0xff);
6510 data [idx+3] = (byte) (val >> 24);
6512 } else if (underlying_type == TypeManager.uint32_type) {
6513 if (!(v is Expression)){
6514 uint val = (uint) v;
6516 data [idx] = (byte) (val & 0xff);
6517 data [idx+1] = (byte) ((val >> 8) & 0xff);
6518 data [idx+2] = (byte) ((val >> 16) & 0xff);
6519 data [idx+3] = (byte) (val >> 24);
6521 } else if (underlying_type == TypeManager.sbyte_type) {
6522 if (!(v is Expression)){
6523 sbyte val = (sbyte) v;
6524 data [idx] = (byte) val;
6526 } else if (underlying_type == TypeManager.byte_type) {
6527 if (!(v is Expression)){
6528 byte val = (byte) v;
6529 data [idx] = (byte) val;
6531 } else if (underlying_type == TypeManager.bool_type) {
6532 if (!(v is Expression)){
6533 bool val = (bool) v;
6534 data [idx] = (byte) (val ? 1 : 0);
6536 } else if (underlying_type == TypeManager.decimal_type){
6537 if (!(v is Expression)){
6538 int [] bits = Decimal.GetBits ((decimal) v);
6541 // FIXME: For some reason, this doesn't work on the MS runtime.
6542 int [] nbits = new int [4];
6543 nbits [0] = bits [3];
6544 nbits [1] = bits [2];
6545 nbits [2] = bits [0];
6546 nbits [3] = bits [1];
6548 for (int j = 0; j < 4; j++){
6549 data [p++] = (byte) (nbits [j] & 0xff);
6550 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6551 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6552 data [p++] = (byte) (nbits [j] >> 24);
6556 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6565 // Emits the initializers for the array
6567 void EmitStaticInitializers (EmitContext ec)
6570 // First, the static data
6573 ILGenerator ig = ec.ig;
6575 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6577 fb = RootContext.MakeStaticData (data);
6579 ig.Emit (OpCodes.Dup);
6580 ig.Emit (OpCodes.Ldtoken, fb);
6581 ig.Emit (OpCodes.Call,
6582 TypeManager.void_initializearray_array_fieldhandle);
6586 // Emits pieces of the array that can not be computed at compile
6587 // time (variables and string locations).
6589 // This always expect the top value on the stack to be the array
6591 void EmitDynamicInitializers (EmitContext ec)
6593 ILGenerator ig = ec.ig;
6594 int dims = bounds.Count;
6595 int [] current_pos = new int [dims];
6596 int top = array_data.Count;
6598 MethodInfo set = null;
6602 ModuleBuilder mb = null;
6603 mb = CodeGen.Module.Builder;
6604 args = new Type [dims + 1];
6607 for (j = 0; j < dims; j++)
6608 args [j] = TypeManager.int32_type;
6610 args [j] = array_element_type;
6612 set = mb.GetArrayMethod (
6614 CallingConventions.HasThis | CallingConventions.Standard,
6615 TypeManager.void_type, args);
6618 for (int i = 0; i < top; i++){
6620 Expression e = null;
6622 if (array_data [i] is Expression)
6623 e = (Expression) array_data [i];
6627 // Basically we do this for string literals and
6628 // other non-literal expressions
6630 if (e is EnumConstant){
6631 e = ((EnumConstant) e).Child;
6634 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6635 num_automatic_initializers <= max_automatic_initializers) {
6636 Type etype = e.Type;
6638 ig.Emit (OpCodes.Dup);
6640 for (int idx = 0; idx < dims; idx++)
6641 IntConstant.EmitInt (ig, current_pos [idx]);
6644 // If we are dealing with a struct, get the
6645 // address of it, so we can store it.
6648 etype.IsSubclassOf (TypeManager.value_type) &&
6649 (!TypeManager.IsBuiltinOrEnum (etype) ||
6650 etype == TypeManager.decimal_type)) {
6655 // Let new know that we are providing
6656 // the address where to store the results
6658 n.DisableTemporaryValueType ();
6661 ig.Emit (OpCodes.Ldelema, etype);
6668 OpCode op = ArrayAccess.GetStoreOpcode (etype, out is_stobj);
6670 ig.Emit (OpCodes.Stobj, etype);
6674 ig.Emit (OpCodes.Call, set);
6682 for (int j = dims - 1; j >= 0; j--){
6684 if (current_pos [j] < (int) bounds [j])
6686 current_pos [j] = 0;
6691 void EmitArrayArguments (EmitContext ec)
6693 ILGenerator ig = ec.ig;
6695 foreach (Argument a in arguments) {
6696 Type atype = a.Type;
6699 if (atype == TypeManager.uint64_type)
6700 ig.Emit (OpCodes.Conv_Ovf_U4);
6701 else if (atype == TypeManager.int64_type)
6702 ig.Emit (OpCodes.Conv_Ovf_I4);
6706 public override void Emit (EmitContext ec)
6708 ILGenerator ig = ec.ig;
6710 EmitArrayArguments (ec);
6711 if (is_one_dimensional)
6712 ig.Emit (OpCodes.Newarr, array_element_type);
6714 if (is_builtin_type)
6715 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6717 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6720 if (initializers != null){
6722 // FIXME: Set this variable correctly.
6724 bool dynamic_initializers = true;
6726 // This will never be true for array types that cannot be statically
6727 // initialized. num_automatic_initializers will always be zero. See
6729 if (num_automatic_initializers > max_automatic_initializers)
6730 EmitStaticInitializers (ec);
6732 if (dynamic_initializers)
6733 EmitDynamicInitializers (ec);
6737 public object EncodeAsAttribute ()
6739 if (!is_one_dimensional){
6740 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6744 if (array_data == null){
6745 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6749 object [] ret = new object [array_data.Count];
6751 foreach (Expression e in array_data){
6754 if (e is NullLiteral)
6757 if (!Attribute.GetAttributeArgumentExpression (e, Location, array_element_type, out v))
6767 /// Represents the `this' construct
6769 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6772 VariableInfo variable_info;
6774 public This (Block block, Location loc)
6780 public This (Location loc)
6785 public VariableInfo VariableInfo {
6786 get { return variable_info; }
6789 public bool VerifyFixed (bool is_expression)
6791 if ((variable_info == null) || (variable_info.LocalInfo == null))
6794 return variable_info.LocalInfo.IsFixed;
6797 public bool ResolveBase (EmitContext ec)
6799 eclass = ExprClass.Variable;
6800 type = ec.ContainerType;
6803 Error (26, "Keyword this not valid in static code");
6807 if ((block != null) && (block.ThisVariable != null))
6808 variable_info = block.ThisVariable.VariableInfo;
6810 if (ec.CurrentAnonymousMethod != null)
6816 public override Expression DoResolve (EmitContext ec)
6818 if (!ResolveBase (ec))
6821 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
6822 Error (188, "The this object cannot be used before all " +
6823 "of its fields are assigned to");
6824 variable_info.SetAssigned (ec);
6828 if (ec.IsFieldInitializer) {
6829 Error (27, "Keyword `this' can't be used outside a constructor, " +
6830 "a method or a property.");
6837 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6839 if (!ResolveBase (ec))
6842 if (variable_info != null)
6843 variable_info.SetAssigned (ec);
6845 if (ec.TypeContainer is Class){
6846 Error (1604, "Cannot assign to 'this' because it is read-only");
6853 public void Emit (EmitContext ec, bool leave_copy)
6857 ec.ig.Emit (OpCodes.Dup);
6860 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
6862 ILGenerator ig = ec.ig;
6864 if (ec.TypeContainer is Struct){
6868 ec.ig.Emit (OpCodes.Dup);
6869 ig.Emit (OpCodes.Stobj, type);
6871 throw new Exception ("how did you get here");
6875 public override void Emit (EmitContext ec)
6877 ILGenerator ig = ec.ig;
6880 if (ec.TypeContainer is Struct)
6881 ig.Emit (OpCodes.Ldobj, type);
6884 public override int GetHashCode()
6886 return block.GetHashCode ();
6889 public override bool Equals (object obj)
6891 This t = obj as This;
6895 return block == t.block;
6898 public void AddressOf (EmitContext ec, AddressOp mode)
6903 // FIGURE OUT WHY LDARG_S does not work
6905 // consider: struct X { int val; int P { set { val = value; }}}
6907 // Yes, this looks very bad. Look at `NOTAS' for
6909 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
6914 /// Represents the `__arglist' construct
6916 public class ArglistAccess : Expression
6918 public ArglistAccess (Location loc)
6923 public bool ResolveBase (EmitContext ec)
6925 eclass = ExprClass.Variable;
6926 type = TypeManager.runtime_argument_handle_type;
6930 public override Expression DoResolve (EmitContext ec)
6932 if (!ResolveBase (ec))
6935 if (ec.IsFieldInitializer || !ec.CurrentBlock.HasVarargs) {
6936 Error (190, "The __arglist construct is valid only within " +
6937 "a variable argument method.");
6944 public override void Emit (EmitContext ec)
6946 ec.ig.Emit (OpCodes.Arglist);
6951 /// Represents the `__arglist (....)' construct
6953 public class Arglist : Expression
6955 public readonly Argument[] Arguments;
6957 public Arglist (Argument[] args, Location l)
6963 public Type[] ArgumentTypes {
6965 Type[] retval = new Type [Arguments.Length];
6966 for (int i = 0; i < Arguments.Length; i++)
6967 retval [i] = Arguments [i].Type;
6972 public override Expression DoResolve (EmitContext ec)
6974 eclass = ExprClass.Variable;
6975 type = TypeManager.runtime_argument_handle_type;
6977 foreach (Argument arg in Arguments) {
6978 if (!arg.Resolve (ec, loc))
6985 public override void Emit (EmitContext ec)
6987 foreach (Argument arg in Arguments)
6993 // This produces the value that renders an instance, used by the iterators code
6995 public class ProxyInstance : Expression, IMemoryLocation {
6996 public override Expression DoResolve (EmitContext ec)
6998 eclass = ExprClass.Variable;
6999 type = ec.ContainerType;
7003 public override void Emit (EmitContext ec)
7005 ec.ig.Emit (OpCodes.Ldarg_0);
7009 public void AddressOf (EmitContext ec, AddressOp mode)
7011 ec.ig.Emit (OpCodes.Ldarg_0);
7016 /// Implements the typeof operator
7018 public class TypeOf : Expression {
7019 public Expression QueriedType;
7020 protected Type typearg;
7022 public TypeOf (Expression queried_type, Location l)
7024 QueriedType = queried_type;
7028 public override Expression DoResolve (EmitContext ec)
7030 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
7034 typearg = texpr.ResolveType (ec);
7036 if (typearg == TypeManager.void_type) {
7037 Error (673, "System.Void cannot be used from C# - " +
7038 "use typeof (void) to get the void type object");
7042 if (typearg.IsPointer && !ec.InUnsafe){
7046 CheckObsoleteAttribute (typearg);
7048 type = TypeManager.type_type;
7049 eclass = ExprClass.Type;
7053 public override void Emit (EmitContext ec)
7055 ec.ig.Emit (OpCodes.Ldtoken, typearg);
7056 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
7059 public Type TypeArg {
7060 get { return typearg; }
7065 /// Implements the `typeof (void)' operator
7067 public class TypeOfVoid : TypeOf {
7068 public TypeOfVoid (Location l) : base (null, l)
7073 public override Expression DoResolve (EmitContext ec)
7075 type = TypeManager.type_type;
7076 typearg = TypeManager.void_type;
7077 eclass = ExprClass.Type;
7083 /// Implements the sizeof expression
7085 public class SizeOf : Expression {
7086 public Expression QueriedType;
7089 public SizeOf (Expression queried_type, Location l)
7091 this.QueriedType = queried_type;
7095 public override Expression DoResolve (EmitContext ec)
7097 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
7101 type_queried = texpr.ResolveType (ec);
7103 int size_of = GetTypeSize (type_queried);
7105 return new IntConstant (size_of);
7109 Report.Error (233, loc, "'{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)",
7110 TypeManager.CSharpName (type_queried));
7114 CheckObsoleteAttribute (type_queried);
7116 if (!TypeManager.IsUnmanagedType (type_queried)){
7117 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
7121 type = TypeManager.int32_type;
7122 eclass = ExprClass.Value;
7126 public override void Emit (EmitContext ec)
7128 int size = GetTypeSize (type_queried);
7131 ec.ig.Emit (OpCodes.Sizeof, type_queried);
7133 IntConstant.EmitInt (ec.ig, size);
7138 /// Implements the member access expression
7140 public class MemberAccess : Expression {
7141 public readonly string Identifier;
7144 public MemberAccess (Expression expr, string id, Location l)
7151 public Expression Expr {
7157 public Expression DoResolve (EmitContext ec, Expression right_side, ResolveFlags flags)
7160 throw new Exception ();
7163 // Resolve the expression with flow analysis turned off, we'll do the definite
7164 // assignment checks later. This is because we don't know yet what the expression
7165 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7166 // definite assignment check on the actual field and not on the whole struct.
7169 SimpleName original = expr as SimpleName;
7170 expr = expr.Resolve (ec, flags | ResolveFlags.Intermediate | ResolveFlags.DisableFlowAnalysis);
7174 if (expr is Namespace) {
7175 Namespace ns = (Namespace) expr;
7176 FullNamedExpression retval = ns.Lookup (ec.DeclSpace, Identifier, loc);
7178 Report.Error (234, loc, "The type or namespace name `{0}' could not be found in namespace `{1}'", Identifier, ns.FullName);
7183 // TODO: I mailed Ravi about this, and apparently we can get rid
7184 // of this and put it in the right place.
7186 // Handle enums here when they are in transit.
7187 // Note that we cannot afford to hit MemberLookup in this case because
7188 // it will fail to find any members at all
7191 Type expr_type = expr.Type;
7192 if (expr is TypeExpr){
7193 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
7194 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", expr_type);
7198 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
7199 Enum en = TypeManager.LookupEnum (expr_type);
7202 object value = en.LookupEnumValue (Identifier, loc);
7205 MemberCore mc = en.GetDefinition (Identifier);
7206 ObsoleteAttribute oa = mc.GetObsoleteAttribute (en);
7208 AttributeTester.Report_ObsoleteMessage (oa, mc.GetSignatureForError (), Location);
7210 oa = en.GetObsoleteAttribute (en);
7212 AttributeTester.Report_ObsoleteMessage (oa, en.GetSignatureForError (), Location);
7215 Constant c = Constantify (value, en.UnderlyingType);
7216 return new EnumConstant (c, expr_type);
7219 CheckObsoleteAttribute (expr_type);
7221 FieldInfo fi = expr_type.GetField (Identifier);
7223 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
7225 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), Location);
7231 if (expr_type.IsPointer){
7232 Error (23, "The `.' operator can not be applied to pointer operands (" +
7233 TypeManager.CSharpName (expr_type) + ")");
7237 Expression member_lookup;
7238 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
7239 if (member_lookup == null)
7242 if (member_lookup is TypeExpr) {
7243 if (!(expr is TypeExpr) &&
7244 (original == null || !original.IdenticalNameAndTypeName (ec, expr, loc))) {
7245 Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
7246 member_lookup.Type + "' instead");
7250 return member_lookup;
7253 MemberExpr me = (MemberExpr) member_lookup;
7254 member_lookup = me.ResolveMemberAccess (ec, expr, loc, original);
7255 if (member_lookup == null)
7258 // The following DoResolve/DoResolveLValue will do the definite assignment
7261 if (right_side != null)
7262 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
7264 member_lookup = member_lookup.DoResolve (ec);
7266 return member_lookup;
7269 public override Expression DoResolve (EmitContext ec)
7271 return DoResolve (ec, null, ResolveFlags.VariableOrValue | ResolveFlags.Type);
7274 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7276 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue | ResolveFlags.Type);
7279 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
7281 return ResolveNamespaceOrType (ec, false);
7284 public FullNamedExpression ResolveNamespaceOrType (EmitContext ec, bool silent)
7286 FullNamedExpression new_expr = expr.ResolveAsTypeStep (ec);
7288 if (new_expr == null)
7291 if (new_expr is Namespace) {
7292 Namespace ns = (Namespace) new_expr;
7293 FullNamedExpression retval = ns.Lookup (ec.DeclSpace, Identifier, loc);
7294 if (!silent && retval == null)
7295 Report.Error (234, loc, "The type or namespace name `{0}' could not be found in namespace `{1}'", Identifier, ns.FullName);
7299 Type expr_type = new_expr.Type;
7301 if (expr_type.IsPointer){
7302 Error (23, "The `.' operator can not be applied to pointer operands (" +
7303 TypeManager.CSharpName (expr_type) + ")");
7307 Expression member_lookup = MemberLookup (ec, expr_type, expr_type, Identifier, loc);
7308 if (member_lookup == null) {
7309 int errors = Report.Errors;
7310 MemberLookupFailed (ec, expr_type, expr_type, Identifier, null, false, loc);
7312 if (!silent && errors == Report.Errors)
7313 Report.Error (234, loc, "The type name `{0}' could not be found in type `{1}'",
7314 Identifier, new_expr.FullName);
7318 if (!(member_lookup is TypeExpr)) {
7319 Report.Error (118, loc, "'{0}.{1}' denotes a '{2}', where a type was expected",
7320 new_expr.FullName, Identifier, member_lookup.ExprClassName ());
7324 member_lookup = member_lookup.Resolve (ec, ResolveFlags.Type);
7325 return (member_lookup as TypeExpr);
7328 public override void Emit (EmitContext ec)
7330 throw new Exception ("Should not happen");
7333 public override string ToString ()
7335 return expr + "." + Identifier;
7340 /// Implements checked expressions
7342 public class CheckedExpr : Expression {
7344 public Expression Expr;
7346 public CheckedExpr (Expression e, Location l)
7352 public override Expression DoResolve (EmitContext ec)
7354 bool last_check = ec.CheckState;
7355 bool last_const_check = ec.ConstantCheckState;
7357 ec.CheckState = true;
7358 ec.ConstantCheckState = true;
7359 Expr = Expr.Resolve (ec);
7360 ec.CheckState = last_check;
7361 ec.ConstantCheckState = last_const_check;
7366 if (Expr is Constant)
7369 eclass = Expr.eclass;
7374 public override void Emit (EmitContext ec)
7376 bool last_check = ec.CheckState;
7377 bool last_const_check = ec.ConstantCheckState;
7379 ec.CheckState = true;
7380 ec.ConstantCheckState = true;
7382 ec.CheckState = last_check;
7383 ec.ConstantCheckState = last_const_check;
7389 /// Implements the unchecked expression
7391 public class UnCheckedExpr : Expression {
7393 public Expression Expr;
7395 public UnCheckedExpr (Expression e, Location l)
7401 public override Expression DoResolve (EmitContext ec)
7403 bool last_check = ec.CheckState;
7404 bool last_const_check = ec.ConstantCheckState;
7406 ec.CheckState = false;
7407 ec.ConstantCheckState = false;
7408 Expr = Expr.Resolve (ec);
7409 ec.CheckState = last_check;
7410 ec.ConstantCheckState = last_const_check;
7415 if (Expr is Constant)
7418 eclass = Expr.eclass;
7423 public override void Emit (EmitContext ec)
7425 bool last_check = ec.CheckState;
7426 bool last_const_check = ec.ConstantCheckState;
7428 ec.CheckState = false;
7429 ec.ConstantCheckState = false;
7431 ec.CheckState = last_check;
7432 ec.ConstantCheckState = last_const_check;
7438 /// An Element Access expression.
7440 /// During semantic analysis these are transformed into
7441 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7443 public class ElementAccess : Expression {
7444 public ArrayList Arguments;
7445 public Expression Expr;
7447 public ElementAccess (Expression e, ArrayList e_list, Location l)
7456 Arguments = new ArrayList ();
7457 foreach (Expression tmp in e_list)
7458 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7462 bool CommonResolve (EmitContext ec)
7464 Expr = Expr.Resolve (ec);
7469 if (Arguments == null)
7472 foreach (Argument a in Arguments){
7473 if (!a.Resolve (ec, loc))
7480 Expression MakePointerAccess (EmitContext ec, Type t)
7482 if (t == TypeManager.void_ptr_type){
7483 Error (242, "The array index operation is not valid for void pointers");
7486 if (Arguments.Count != 1){
7487 Error (196, "A pointer must be indexed by a single value");
7492 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc).Resolve (ec);
7495 return new Indirection (p, loc).Resolve (ec);
7498 public override Expression DoResolve (EmitContext ec)
7500 if (!CommonResolve (ec))
7504 // We perform some simple tests, and then to "split" the emit and store
7505 // code we create an instance of a different class, and return that.
7507 // I am experimenting with this pattern.
7511 if (t == TypeManager.array_type){
7512 Report.Error (21, loc, "Cannot use indexer on System.Array");
7517 return (new ArrayAccess (this, loc)).Resolve (ec);
7519 return MakePointerAccess (ec, Expr.Type);
7521 FieldExpr fe = Expr as FieldExpr;
7523 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
7525 return MakePointerAccess (ec, ff.ElementType);
7528 return (new IndexerAccess (this, loc)).Resolve (ec);
7531 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7533 if (!CommonResolve (ec))
7538 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
7541 return MakePointerAccess (ec, Expr.Type);
7543 FieldExpr fe = Expr as FieldExpr;
7545 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
7547 if (!(fe.InstanceExpression is LocalVariableReference) &&
7548 !(fe.InstanceExpression is This)) {
7549 Error (1708, "Fixed buffers can only be accessed through locals or fields");
7552 // TODO: not sure whether it is correct
7553 // if (!ec.InFixedInitializer) {
7554 // Error (1666, "You cannot use fixed sized buffers contained in unfixed expressions. Try using the fixed statement");
7557 return MakePointerAccess (ec, ff.ElementType);
7560 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
7563 public override void Emit (EmitContext ec)
7565 throw new Exception ("Should never be reached");
7570 /// Implements array access
7572 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7574 // Points to our "data" repository
7578 LocalTemporary temp;
7581 public ArrayAccess (ElementAccess ea_data, Location l)
7584 eclass = ExprClass.Variable;
7588 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7590 return DoResolve (ec);
7593 public override Expression DoResolve (EmitContext ec)
7596 ExprClass eclass = ea.Expr.eclass;
7598 // As long as the type is valid
7599 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7600 eclass == ExprClass.Value)) {
7601 ea.Expr.Error_UnexpectedKind ("variable or value");
7606 Type t = ea.Expr.Type;
7607 if (t.GetArrayRank () != ea.Arguments.Count){
7609 "Incorrect number of indexes for array " +
7610 " expected: " + t.GetArrayRank () + " got: " +
7611 ea.Arguments.Count);
7615 type = TypeManager.GetElementType (t);
7616 if (type.IsPointer && !ec.InUnsafe){
7617 UnsafeError (ea.Location);
7621 foreach (Argument a in ea.Arguments){
7622 Type argtype = a.Type;
7624 if (argtype == TypeManager.int32_type ||
7625 argtype == TypeManager.uint32_type ||
7626 argtype == TypeManager.int64_type ||
7627 argtype == TypeManager.uint64_type) {
7628 Constant c = a.Expr as Constant;
7629 if (c != null && c.IsNegative) {
7630 Report.Warning (251, 2, a.Expr.Location, "Indexing an array with a negative index (array indices always start at zero)");
7636 // Mhm. This is strage, because the Argument.Type is not the same as
7637 // Argument.Expr.Type: the value changes depending on the ref/out setting.
7639 // Wonder if I will run into trouble for this.
7641 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
7646 eclass = ExprClass.Variable;
7652 /// Emits the right opcode to load an object of Type `t'
7653 /// from an array of T
7655 static public void EmitLoadOpcode (ILGenerator ig, Type type)
7657 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7658 ig.Emit (OpCodes.Ldelem_U1);
7659 else if (type == TypeManager.sbyte_type)
7660 ig.Emit (OpCodes.Ldelem_I1);
7661 else if (type == TypeManager.short_type)
7662 ig.Emit (OpCodes.Ldelem_I2);
7663 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7664 ig.Emit (OpCodes.Ldelem_U2);
7665 else if (type == TypeManager.int32_type)
7666 ig.Emit (OpCodes.Ldelem_I4);
7667 else if (type == TypeManager.uint32_type)
7668 ig.Emit (OpCodes.Ldelem_U4);
7669 else if (type == TypeManager.uint64_type)
7670 ig.Emit (OpCodes.Ldelem_I8);
7671 else if (type == TypeManager.int64_type)
7672 ig.Emit (OpCodes.Ldelem_I8);
7673 else if (type == TypeManager.float_type)
7674 ig.Emit (OpCodes.Ldelem_R4);
7675 else if (type == TypeManager.double_type)
7676 ig.Emit (OpCodes.Ldelem_R8);
7677 else if (type == TypeManager.intptr_type)
7678 ig.Emit (OpCodes.Ldelem_I);
7679 else if (TypeManager.IsEnumType (type)){
7680 EmitLoadOpcode (ig, TypeManager.EnumToUnderlying (type));
7681 } else if (type.IsValueType){
7682 ig.Emit (OpCodes.Ldelema, type);
7683 ig.Emit (OpCodes.Ldobj, type);
7685 ig.Emit (OpCodes.Ldelem_Ref);
7689 /// Returns the right opcode to store an object of Type `t'
7690 /// from an array of T.
7692 static public OpCode GetStoreOpcode (Type t, out bool is_stobj)
7694 //Console.WriteLine (new System.Diagnostics.StackTrace ());
7696 t = TypeManager.TypeToCoreType (t);
7697 if (TypeManager.IsEnumType (t))
7698 t = TypeManager.EnumToUnderlying (t);
7699 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
7700 t == TypeManager.bool_type)
7701 return OpCodes.Stelem_I1;
7702 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
7703 t == TypeManager.char_type)
7704 return OpCodes.Stelem_I2;
7705 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
7706 return OpCodes.Stelem_I4;
7707 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
7708 return OpCodes.Stelem_I8;
7709 else if (t == TypeManager.float_type)
7710 return OpCodes.Stelem_R4;
7711 else if (t == TypeManager.double_type)
7712 return OpCodes.Stelem_R8;
7713 else if (t == TypeManager.intptr_type) {
7715 return OpCodes.Stobj;
7716 } else if (t.IsValueType) {
7718 return OpCodes.Stobj;
7720 return OpCodes.Stelem_Ref;
7723 MethodInfo FetchGetMethod ()
7725 ModuleBuilder mb = CodeGen.Module.Builder;
7726 int arg_count = ea.Arguments.Count;
7727 Type [] args = new Type [arg_count];
7730 for (int i = 0; i < arg_count; i++){
7731 //args [i++] = a.Type;
7732 args [i] = TypeManager.int32_type;
7735 get = mb.GetArrayMethod (
7736 ea.Expr.Type, "Get",
7737 CallingConventions.HasThis |
7738 CallingConventions.Standard,
7744 MethodInfo FetchAddressMethod ()
7746 ModuleBuilder mb = CodeGen.Module.Builder;
7747 int arg_count = ea.Arguments.Count;
7748 Type [] args = new Type [arg_count];
7752 ret_type = TypeManager.GetReferenceType (type);
7754 for (int i = 0; i < arg_count; i++){
7755 //args [i++] = a.Type;
7756 args [i] = TypeManager.int32_type;
7759 address = mb.GetArrayMethod (
7760 ea.Expr.Type, "Address",
7761 CallingConventions.HasThis |
7762 CallingConventions.Standard,
7769 // Load the array arguments into the stack.
7771 // If we have been requested to cache the values (cached_locations array
7772 // initialized), then load the arguments the first time and store them
7773 // in locals. otherwise load from local variables.
7775 void LoadArrayAndArguments (EmitContext ec)
7777 ILGenerator ig = ec.ig;
7780 foreach (Argument a in ea.Arguments){
7781 Type argtype = a.Expr.Type;
7785 if (argtype == TypeManager.int64_type)
7786 ig.Emit (OpCodes.Conv_Ovf_I);
7787 else if (argtype == TypeManager.uint64_type)
7788 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7792 public void Emit (EmitContext ec, bool leave_copy)
7794 int rank = ea.Expr.Type.GetArrayRank ();
7795 ILGenerator ig = ec.ig;
7798 LoadArrayAndArguments (ec);
7801 EmitLoadOpcode (ig, type);
7805 method = FetchGetMethod ();
7806 ig.Emit (OpCodes.Call, method);
7809 LoadFromPtr (ec.ig, this.type);
7812 ec.ig.Emit (OpCodes.Dup);
7813 temp = new LocalTemporary (ec, this.type);
7818 public override void Emit (EmitContext ec)
7823 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
7825 int rank = ea.Expr.Type.GetArrayRank ();
7826 ILGenerator ig = ec.ig;
7827 Type t = source.Type;
7828 prepared = prepare_for_load;
7830 if (prepare_for_load) {
7831 AddressOf (ec, AddressOp.LoadStore);
7832 ec.ig.Emit (OpCodes.Dup);
7835 ec.ig.Emit (OpCodes.Dup);
7836 temp = new LocalTemporary (ec, this.type);
7839 StoreFromPtr (ec.ig, t);
7847 LoadArrayAndArguments (ec);
7851 OpCode op = GetStoreOpcode (t, out is_stobj);
7853 // The stobj opcode used by value types will need
7854 // an address on the stack, not really an array/array
7858 ig.Emit (OpCodes.Ldelema, t);
7862 ec.ig.Emit (OpCodes.Dup);
7863 temp = new LocalTemporary (ec, this.type);
7868 ig.Emit (OpCodes.Stobj, t);
7872 ModuleBuilder mb = CodeGen.Module.Builder;
7873 int arg_count = ea.Arguments.Count;
7874 Type [] args = new Type [arg_count + 1];
7879 ec.ig.Emit (OpCodes.Dup);
7880 temp = new LocalTemporary (ec, this.type);
7884 for (int i = 0; i < arg_count; i++){
7885 //args [i++] = a.Type;
7886 args [i] = TypeManager.int32_type;
7889 args [arg_count] = type;
7891 set = mb.GetArrayMethod (
7892 ea.Expr.Type, "Set",
7893 CallingConventions.HasThis |
7894 CallingConventions.Standard,
7895 TypeManager.void_type, args);
7897 ig.Emit (OpCodes.Call, set);
7904 public void AddressOf (EmitContext ec, AddressOp mode)
7906 int rank = ea.Expr.Type.GetArrayRank ();
7907 ILGenerator ig = ec.ig;
7909 LoadArrayAndArguments (ec);
7912 ig.Emit (OpCodes.Ldelema, type);
7914 MethodInfo address = FetchAddressMethod ();
7915 ig.Emit (OpCodes.Call, address);
7922 public ArrayList Properties;
7923 static Hashtable map;
7925 public struct Indexer {
7926 public readonly Type Type;
7927 public readonly MethodInfo Getter, Setter;
7929 public Indexer (Type type, MethodInfo get, MethodInfo set)
7939 map = new Hashtable ();
7944 Properties = new ArrayList ();
7947 void Append (MemberInfo [] mi)
7949 foreach (PropertyInfo property in mi){
7950 MethodInfo get, set;
7952 get = property.GetGetMethod (true);
7953 set = property.GetSetMethod (true);
7954 Properties.Add (new Indexer (property.PropertyType, get, set));
7958 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
7960 string p_name = TypeManager.IndexerPropertyName (lookup_type);
7962 MemberInfo [] mi = TypeManager.MemberLookup (
7963 caller_type, caller_type, lookup_type, MemberTypes.Property,
7964 BindingFlags.Public | BindingFlags.Instance |
7965 BindingFlags.DeclaredOnly, p_name, null);
7967 if (mi == null || mi.Length == 0)
7973 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
7975 Indexers ix = (Indexers) map [lookup_type];
7980 Type copy = lookup_type;
7981 while (copy != TypeManager.object_type && copy != null){
7982 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
7986 ix = new Indexers ();
7991 copy = copy.BaseType;
7994 if (!lookup_type.IsInterface)
7997 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
7998 if (ifaces != null) {
7999 foreach (Type itype in ifaces) {
8000 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
8003 ix = new Indexers ();
8015 /// Expressions that represent an indexer call.
8017 public class IndexerAccess : Expression, IAssignMethod {
8019 // Points to our "data" repository
8021 MethodInfo get, set;
8022 ArrayList set_arguments;
8023 bool is_base_indexer;
8025 protected Type indexer_type;
8026 protected Type current_type;
8027 protected Expression instance_expr;
8028 protected ArrayList arguments;
8030 public IndexerAccess (ElementAccess ea, Location loc)
8031 : this (ea.Expr, false, loc)
8033 this.arguments = ea.Arguments;
8036 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
8039 this.instance_expr = instance_expr;
8040 this.is_base_indexer = is_base_indexer;
8041 this.eclass = ExprClass.Value;
8045 protected virtual bool CommonResolve (EmitContext ec)
8047 indexer_type = instance_expr.Type;
8048 current_type = ec.ContainerType;
8053 public override Expression DoResolve (EmitContext ec)
8055 ArrayList AllGetters = new ArrayList();
8056 if (!CommonResolve (ec))
8060 // Step 1: Query for all `Item' *properties*. Notice
8061 // that the actual methods are pointed from here.
8063 // This is a group of properties, piles of them.
8065 bool found_any = false, found_any_getters = false;
8066 Type lookup_type = indexer_type;
8069 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
8070 if (ilist != null) {
8072 if (ilist.Properties != null) {
8073 foreach (Indexers.Indexer ix in ilist.Properties) {
8074 if (ix.Getter != null)
8075 AllGetters.Add(ix.Getter);
8080 if (AllGetters.Count > 0) {
8081 found_any_getters = true;
8082 get = (MethodInfo) Invocation.OverloadResolve (
8083 ec, new MethodGroupExpr (AllGetters, loc),
8084 arguments, false, loc);
8088 Report.Error (21, loc,
8089 "Type `" + TypeManager.CSharpName (indexer_type) +
8090 "' does not have any indexers defined");
8094 if (!found_any_getters) {
8095 Error (154, "indexer can not be used in this context, because " +
8096 "it lacks a `get' accessor");
8101 Error (1501, "No Overload for method `this' takes `" +
8102 arguments.Count + "' arguments");
8107 // Only base will allow this invocation to happen.
8109 if (get.IsAbstract && this is BaseIndexerAccess){
8110 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
8114 type = get.ReturnType;
8115 if (type.IsPointer && !ec.InUnsafe){
8120 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8122 eclass = ExprClass.IndexerAccess;
8126 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8128 ArrayList AllSetters = new ArrayList();
8129 if (!CommonResolve (ec))
8132 bool found_any = false, found_any_setters = false;
8134 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
8135 if (ilist != null) {
8137 if (ilist.Properties != null) {
8138 foreach (Indexers.Indexer ix in ilist.Properties) {
8139 if (ix.Setter != null)
8140 AllSetters.Add(ix.Setter);
8144 if (AllSetters.Count > 0) {
8145 found_any_setters = true;
8146 set_arguments = (ArrayList) arguments.Clone ();
8147 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
8148 set = (MethodInfo) Invocation.OverloadResolve (
8149 ec, new MethodGroupExpr (AllSetters, loc),
8150 set_arguments, false, loc);
8154 Report.Error (21, loc,
8155 "Type `" + TypeManager.CSharpName (indexer_type) +
8156 "' does not have any indexers defined");
8160 if (!found_any_setters) {
8161 Error (154, "indexer can not be used in this context, because " +
8162 "it lacks a `set' accessor");
8167 Error (1501, "No Overload for method `this' takes `" +
8168 arguments.Count + "' arguments");
8173 // Only base will allow this invocation to happen.
8175 if (set.IsAbstract && this is BaseIndexerAccess){
8176 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
8181 // Now look for the actual match in the list of indexers to set our "return" type
8183 type = TypeManager.void_type; // default value
8184 foreach (Indexers.Indexer ix in ilist.Properties){
8185 if (ix.Setter == set){
8191 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8193 eclass = ExprClass.IndexerAccess;
8197 bool prepared = false;
8198 LocalTemporary temp;
8200 public void Emit (EmitContext ec, bool leave_copy)
8202 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc, prepared, false);
8204 ec.ig.Emit (OpCodes.Dup);
8205 temp = new LocalTemporary (ec, Type);
8211 // source is ignored, because we already have a copy of it from the
8212 // LValue resolution and we have already constructed a pre-cached
8213 // version of the arguments (ea.set_arguments);
8215 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8217 prepared = prepare_for_load;
8218 Argument a = (Argument) set_arguments [set_arguments.Count - 1];
8223 ec.ig.Emit (OpCodes.Dup);
8224 temp = new LocalTemporary (ec, Type);
8227 } else if (leave_copy) {
8228 temp = new LocalTemporary (ec, Type);
8234 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc, false, prepared);
8241 public override void Emit (EmitContext ec)
8248 /// The base operator for method names
8250 public class BaseAccess : Expression {
8253 public BaseAccess (string member, Location l)
8255 this.member = member;
8259 public override Expression DoResolve (EmitContext ec)
8261 Expression c = CommonResolve (ec);
8267 // MethodGroups use this opportunity to flag an error on lacking ()
8269 if (!(c is MethodGroupExpr))
8270 return c.Resolve (ec);
8274 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8276 Expression c = CommonResolve (ec);
8282 // MethodGroups use this opportunity to flag an error on lacking ()
8284 if (! (c is MethodGroupExpr))
8285 return c.DoResolveLValue (ec, right_side);
8290 Expression CommonResolve (EmitContext ec)
8292 Expression member_lookup;
8293 Type current_type = ec.ContainerType;
8294 Type base_type = current_type.BaseType;
8297 Error (1511, "Keyword base is not allowed in static method");
8301 if (ec.IsFieldInitializer){
8302 Error (1512, "Keyword base is not available in the current context");
8306 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type, member,
8307 AllMemberTypes, AllBindingFlags, loc);
8308 if (member_lookup == null) {
8309 MemberLookupFailed (ec, base_type, base_type, member, null, true, loc);
8316 left = new TypeExpression (base_type, loc);
8318 left = ec.GetThis (loc);
8320 MemberExpr me = (MemberExpr) member_lookup;
8322 Expression e = me.ResolveMemberAccess (ec, left, loc, null);
8324 if (e is PropertyExpr) {
8325 PropertyExpr pe = (PropertyExpr) e;
8330 if (e is MethodGroupExpr)
8331 ((MethodGroupExpr) e).IsBase = true;
8336 public override void Emit (EmitContext ec)
8338 throw new Exception ("Should never be called");
8343 /// The base indexer operator
8345 public class BaseIndexerAccess : IndexerAccess {
8346 public BaseIndexerAccess (ArrayList args, Location loc)
8347 : base (null, true, loc)
8349 arguments = new ArrayList ();
8350 foreach (Expression tmp in args)
8351 arguments.Add (new Argument (tmp, Argument.AType.Expression));
8354 protected override bool CommonResolve (EmitContext ec)
8356 instance_expr = ec.GetThis (loc);
8358 current_type = ec.ContainerType.BaseType;
8359 indexer_type = current_type;
8361 foreach (Argument a in arguments){
8362 if (!a.Resolve (ec, loc))
8371 /// This class exists solely to pass the Type around and to be a dummy
8372 /// that can be passed to the conversion functions (this is used by
8373 /// foreach implementation to typecast the object return value from
8374 /// get_Current into the proper type. All code has been generated and
8375 /// we only care about the side effect conversions to be performed
8377 /// This is also now used as a placeholder where a no-action expression
8378 /// is needed (the `New' class).
8380 public class EmptyExpression : Expression {
8381 public static readonly EmptyExpression Null = new EmptyExpression ();
8383 // TODO: should be protected
8384 public EmptyExpression ()
8386 type = TypeManager.object_type;
8387 eclass = ExprClass.Value;
8388 loc = Location.Null;
8391 public EmptyExpression (Type t)
8394 eclass = ExprClass.Value;
8395 loc = Location.Null;
8398 public override Expression DoResolve (EmitContext ec)
8403 public override void Emit (EmitContext ec)
8405 // nothing, as we only exist to not do anything.
8409 // This is just because we might want to reuse this bad boy
8410 // instead of creating gazillions of EmptyExpressions.
8411 // (CanImplicitConversion uses it)
8413 public void SetType (Type t)
8419 public class UserCast : Expression {
8423 public UserCast (MethodInfo method, Expression source, Location l)
8425 this.method = method;
8426 this.source = source;
8427 type = method.ReturnType;
8428 eclass = ExprClass.Value;
8432 public Expression Source {
8438 public override Expression DoResolve (EmitContext ec)
8441 // We are born fully resolved
8446 public override void Emit (EmitContext ec)
8448 ILGenerator ig = ec.ig;
8452 if (method is MethodInfo)
8453 ig.Emit (OpCodes.Call, (MethodInfo) method);
8455 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
8461 // This class is used to "construct" the type during a typecast
8462 // operation. Since the Type.GetType class in .NET can parse
8463 // the type specification, we just use this to construct the type
8464 // one bit at a time.
8466 public class ComposedCast : TypeExpr {
8470 public ComposedCast (Expression left, string dim, Location l)
8477 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
8479 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec, false);
8483 Type ltype = lexpr.ResolveType (ec);
8485 if ((ltype == TypeManager.void_type) && (dim != "*")) {
8486 Report.Error (1547, Location,
8487 "Keyword 'void' cannot be used in this context");
8491 if (dim == "*" && !TypeManager.IsUnmanagedType (ltype)) {
8492 Report.Error (208, loc, "Cannot declare a pointer to a managed type ('{0}')", ltype);
8496 type = TypeManager.GetConstructedType (ltype, dim);
8498 throw new InternalErrorException ("Couldn't create computed type " + ltype + dim);
8501 if (!ec.InUnsafe && type.IsPointer){
8506 if (type.IsArray && (type.GetElementType () == TypeManager.arg_iterator_type ||
8507 type.GetElementType () == TypeManager.typed_reference_type)) {
8508 Report.Error (611, loc, "Array elements cannot be of type '{0}'", TypeManager.CSharpName (type.GetElementType ()));
8512 eclass = ExprClass.Type;
8516 public override string Name {
8522 public override string FullName {
8524 return type.FullName;
8529 public class FixedBufferPtr: Expression {
8532 public FixedBufferPtr (Expression array, Type array_type, Location l)
8537 type = TypeManager.GetPointerType (array_type);
8538 eclass = ExprClass.Value;
8541 public override void Emit(EmitContext ec)
8546 public override Expression DoResolve (EmitContext ec)
8549 // We are born fully resolved
8557 // This class is used to represent the address of an array, used
8558 // only by the Fixed statement, this generates "&a [0]" construct
8559 // for fixed (char *pa = a)
8561 public class ArrayPtr : FixedBufferPtr {
8564 public ArrayPtr (Expression array, Type array_type, Location l):
8565 base (array, array_type, l)
8567 this.array_type = array_type;
8570 public override void Emit (EmitContext ec)
8574 ILGenerator ig = ec.ig;
8575 IntLiteral.EmitInt (ig, 0);
8576 ig.Emit (OpCodes.Ldelema, array_type);
8581 // Used by the fixed statement
8583 public class StringPtr : Expression {
8586 public StringPtr (LocalBuilder b, Location l)
8589 eclass = ExprClass.Value;
8590 type = TypeManager.char_ptr_type;
8594 public override Expression DoResolve (EmitContext ec)
8596 // This should never be invoked, we are born in fully
8597 // initialized state.
8602 public override void Emit (EmitContext ec)
8604 ILGenerator ig = ec.ig;
8606 ig.Emit (OpCodes.Ldloc, b);
8607 ig.Emit (OpCodes.Conv_I);
8608 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
8609 ig.Emit (OpCodes.Add);
8614 // Implements the `stackalloc' keyword
8616 public class StackAlloc : Expression {
8621 public StackAlloc (Expression type, Expression count, Location l)
8628 public override Expression DoResolve (EmitContext ec)
8630 count = count.Resolve (ec);
8634 if (count.Type != TypeManager.int32_type){
8635 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8640 Constant c = count as Constant;
8641 if (c != null && c.IsNegative) {
8642 Report.Error (247, loc, "Cannot use a negative size with stackalloc");
8646 if (ec.InCatch || ec.InFinally) {
8648 "stackalloc can not be used in a catch or finally block");
8652 TypeExpr texpr = t.ResolveAsTypeTerminal (ec, false);
8656 otype = texpr.ResolveType (ec);
8658 if (!TypeManager.VerifyUnManaged (otype, loc))
8661 type = TypeManager.GetPointerType (otype);
8662 eclass = ExprClass.Value;
8667 public override void Emit (EmitContext ec)
8669 int size = GetTypeSize (otype);
8670 ILGenerator ig = ec.ig;
8673 ig.Emit (OpCodes.Sizeof, otype);
8675 IntConstant.EmitInt (ig, size);
8677 ig.Emit (OpCodes.Mul);
8678 ig.Emit (OpCodes.Localloc);