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);
457 type = TypeManager.GetPointerType (Expr.Type);
460 case Operator.Indirection:
466 if (!expr_type.IsPointer){
467 Error (193, "The * or -> operator can only be applied to pointers");
472 // We create an Indirection expression, because
473 // it can implement the IMemoryLocation.
475 return new Indirection (Expr, loc);
477 case Operator.UnaryPlus:
479 // A plus in front of something is just a no-op, so return the child.
483 case Operator.UnaryNegation:
485 // Deals with -literals
486 // int operator- (int x)
487 // long operator- (long x)
488 // float operator- (float f)
489 // double operator- (double d)
490 // decimal operator- (decimal d)
492 Expression expr = null;
495 // transform - - expr into expr
498 Unary unary = (Unary) Expr;
500 if (unary.Oper == Operator.UnaryNegation)
505 // perform numeric promotions to int,
509 // The following is inneficient, because we call
510 // ImplicitConversion too many times.
512 // It is also not clear if we should convert to Float
513 // or Double initially.
515 if (expr_type == TypeManager.uint32_type){
517 // FIXME: handle exception to this rule that
518 // permits the int value -2147483648 (-2^31) to
519 // bt wrote as a decimal interger literal
521 type = TypeManager.int64_type;
522 Expr = Convert.ImplicitConversion (ec, Expr, type, loc);
526 if (expr_type == TypeManager.uint64_type){
528 // FIXME: Handle exception of `long value'
529 // -92233720368547758087 (-2^63) to be wrote as
530 // decimal integer literal.
536 if (expr_type == TypeManager.float_type){
541 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
548 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
555 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.double_type, loc);
566 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
567 TypeManager.CSharpName (expr_type) + "'");
571 public override Expression DoResolve (EmitContext ec)
573 if (Oper == Operator.AddressOf) {
574 Expr = Expr.DoResolveLValue (ec, new EmptyExpression ());
576 if (Expr == null || Expr.eclass != ExprClass.Variable){
577 Error (211, "Cannot take the address of non-variables");
582 Expr = Expr.Resolve (ec);
587 if (TypeManager.IsNullableType (Expr.Type))
588 return new Nullable.LiftedUnaryOperator (Oper, Expr, loc).Resolve (ec);
590 eclass = ExprClass.Value;
591 return ResolveOperator (ec);
594 public override Expression DoResolveLValue (EmitContext ec, Expression right)
596 if (Oper == Operator.Indirection)
597 return DoResolve (ec);
602 public override void Emit (EmitContext ec)
604 ILGenerator ig = ec.ig;
607 case Operator.UnaryPlus:
608 throw new Exception ("This should be caught by Resolve");
610 case Operator.UnaryNegation:
612 ig.Emit (OpCodes.Ldc_I4_0);
613 if (type == TypeManager.int64_type)
614 ig.Emit (OpCodes.Conv_U8);
616 ig.Emit (OpCodes.Sub_Ovf);
619 ig.Emit (OpCodes.Neg);
624 case Operator.LogicalNot:
626 ig.Emit (OpCodes.Ldc_I4_0);
627 ig.Emit (OpCodes.Ceq);
630 case Operator.OnesComplement:
632 ig.Emit (OpCodes.Not);
635 case Operator.AddressOf:
636 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
640 throw new Exception ("This should not happen: Operator = "
645 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
647 if (Oper == Operator.LogicalNot)
648 Expr.EmitBranchable (ec, target, !onTrue);
650 base.EmitBranchable (ec, target, onTrue);
653 public override string ToString ()
655 return "Unary (" + Oper + ", " + Expr + ")";
661 // Unary operators are turned into Indirection expressions
662 // after semantic analysis (this is so we can take the address
663 // of an indirection).
665 public class Indirection : Expression, IMemoryLocation, IAssignMethod, IVariable {
667 LocalTemporary temporary;
670 public Indirection (Expression expr, Location l)
673 type = TypeManager.HasElementType (expr.Type) ? TypeManager.GetElementType (expr.Type) : expr.Type;
674 eclass = ExprClass.Variable;
678 void LoadExprValue (EmitContext ec)
682 public override void Emit (EmitContext ec)
687 LoadFromPtr (ec.ig, Type);
690 public void Emit (EmitContext ec, bool leave_copy)
694 ec.ig.Emit (OpCodes.Dup);
695 temporary = new LocalTemporary (ec, expr.Type);
696 temporary.Store (ec);
700 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
702 prepared = prepare_for_load;
706 if (prepare_for_load)
707 ec.ig.Emit (OpCodes.Dup);
711 ec.ig.Emit (OpCodes.Dup);
712 temporary = new LocalTemporary (ec, expr.Type);
713 temporary.Store (ec);
716 StoreFromPtr (ec.ig, type);
718 if (temporary != null)
722 public void AddressOf (EmitContext ec, AddressOp Mode)
727 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
729 return DoResolve (ec);
732 public override Expression DoResolve (EmitContext ec)
735 // Born fully resolved
740 public override string ToString ()
742 return "*(" + expr + ")";
745 #region IVariable Members
747 public VariableInfo VariableInfo {
753 public bool VerifyFixed (bool is_expression)
762 /// Unary Mutator expressions (pre and post ++ and --)
766 /// UnaryMutator implements ++ and -- expressions. It derives from
767 /// ExpressionStatement becuase the pre/post increment/decrement
768 /// operators can be used in a statement context.
770 /// FIXME: Idea, we could split this up in two classes, one simpler
771 /// for the common case, and one with the extra fields for more complex
772 /// classes (indexers require temporary access; overloaded require method)
775 public class UnaryMutator : ExpressionStatement {
777 public enum Mode : byte {
784 PreDecrement = IsDecrement,
785 PostIncrement = IsPost,
786 PostDecrement = IsPost | IsDecrement
790 bool is_expr = false;
791 bool recurse = false;
796 // This is expensive for the simplest case.
798 StaticCallExpr method;
800 public UnaryMutator (Mode m, Expression e, Location l)
807 static string OperName (Mode mode)
809 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
813 void Error23 (Type t)
816 23, "Operator " + OperName (mode) +
817 " cannot be applied to operand of type `" +
818 TypeManager.CSharpName (t) + "'");
822 /// Returns whether an object of type `t' can be incremented
823 /// or decremented with add/sub (ie, basically whether we can
824 /// use pre-post incr-decr operations on it, but it is not a
825 /// System.Decimal, which we require operator overloading to catch)
827 static bool IsIncrementableNumber (Type t)
829 return (t == TypeManager.sbyte_type) ||
830 (t == TypeManager.byte_type) ||
831 (t == TypeManager.short_type) ||
832 (t == TypeManager.ushort_type) ||
833 (t == TypeManager.int32_type) ||
834 (t == TypeManager.uint32_type) ||
835 (t == TypeManager.int64_type) ||
836 (t == TypeManager.uint64_type) ||
837 (t == TypeManager.char_type) ||
838 (t.IsSubclassOf (TypeManager.enum_type)) ||
839 (t == TypeManager.float_type) ||
840 (t == TypeManager.double_type) ||
841 (t.IsPointer && t != TypeManager.void_ptr_type);
844 Expression ResolveOperator (EmitContext ec)
846 Type expr_type = expr.Type;
849 // Step 1: Perform Operator Overload location
854 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
855 op_name = "op_Increment";
857 op_name = "op_Decrement";
859 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
862 method = StaticCallExpr.MakeSimpleCall (
863 ec, (MethodGroupExpr) mg, expr, loc);
866 } else if (!IsIncrementableNumber (expr_type)) {
867 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
868 TypeManager.CSharpName (expr_type) + "'");
873 // The operand of the prefix/postfix increment decrement operators
874 // should be an expression that is classified as a variable,
875 // a property access or an indexer access
878 if (expr.eclass == ExprClass.Variable){
879 LocalVariableReference var = expr as LocalVariableReference;
880 if ((var != null) && var.IsReadOnly) {
881 Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
884 } else if (expr.eclass == ExprClass.IndexerAccess || expr.eclass == ExprClass.PropertyAccess){
885 expr = expr.ResolveLValue (ec, this);
889 expr.Error_UnexpectedKind ("variable, indexer or property access", loc);
896 public override Expression DoResolve (EmitContext ec)
898 expr = expr.Resolve (ec);
903 eclass = ExprClass.Value;
905 if (TypeManager.IsNullableType (expr.Type))
906 return new Nullable.LiftedUnaryMutator (mode, expr, loc).Resolve (ec);
908 return ResolveOperator (ec);
911 static int PtrTypeSize (Type t)
913 return GetTypeSize (TypeManager.GetElementType (t));
917 // Loads the proper "1" into the stack based on the type, then it emits the
918 // opcode for the operation requested
920 void LoadOneAndEmitOp (EmitContext ec, Type t)
923 // Measure if getting the typecode and using that is more/less efficient
924 // that comparing types. t.GetTypeCode() is an internal call.
926 ILGenerator ig = ec.ig;
928 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
929 LongConstant.EmitLong (ig, 1);
930 else if (t == TypeManager.double_type)
931 ig.Emit (OpCodes.Ldc_R8, 1.0);
932 else if (t == TypeManager.float_type)
933 ig.Emit (OpCodes.Ldc_R4, 1.0F);
934 else if (t.IsPointer){
935 int n = PtrTypeSize (t);
938 ig.Emit (OpCodes.Sizeof, t);
940 IntConstant.EmitInt (ig, n);
942 ig.Emit (OpCodes.Ldc_I4_1);
945 // Now emit the operation
948 if (t == TypeManager.int32_type ||
949 t == TypeManager.int64_type){
950 if ((mode & Mode.IsDecrement) != 0)
951 ig.Emit (OpCodes.Sub_Ovf);
953 ig.Emit (OpCodes.Add_Ovf);
954 } else if (t == TypeManager.uint32_type ||
955 t == TypeManager.uint64_type){
956 if ((mode & Mode.IsDecrement) != 0)
957 ig.Emit (OpCodes.Sub_Ovf_Un);
959 ig.Emit (OpCodes.Add_Ovf_Un);
961 if ((mode & Mode.IsDecrement) != 0)
962 ig.Emit (OpCodes.Sub_Ovf);
964 ig.Emit (OpCodes.Add_Ovf);
967 if ((mode & Mode.IsDecrement) != 0)
968 ig.Emit (OpCodes.Sub);
970 ig.Emit (OpCodes.Add);
973 if (t == TypeManager.sbyte_type){
975 ig.Emit (OpCodes.Conv_Ovf_I1);
977 ig.Emit (OpCodes.Conv_I1);
978 } else if (t == TypeManager.byte_type){
980 ig.Emit (OpCodes.Conv_Ovf_U1);
982 ig.Emit (OpCodes.Conv_U1);
983 } else if (t == TypeManager.short_type){
985 ig.Emit (OpCodes.Conv_Ovf_I2);
987 ig.Emit (OpCodes.Conv_I2);
988 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
990 ig.Emit (OpCodes.Conv_Ovf_U2);
992 ig.Emit (OpCodes.Conv_U2);
997 void EmitCode (EmitContext ec, bool is_expr)
1000 this.is_expr = is_expr;
1001 ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
1004 public override void Emit (EmitContext ec)
1007 // We use recurse to allow ourselfs to be the source
1008 // of an assignment. This little hack prevents us from
1009 // having to allocate another expression
1012 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
1014 LoadOneAndEmitOp (ec, expr.Type);
1016 ec.ig.Emit (OpCodes.Call, method.Method);
1021 EmitCode (ec, true);
1024 public override void EmitStatement (EmitContext ec)
1026 EmitCode (ec, false);
1031 /// Base class for the `Is' and `As' classes.
1035 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1038 public abstract class Probe : Expression {
1039 public Expression ProbeType;
1040 protected Expression expr;
1041 protected Type probe_type;
1043 public Probe (Expression expr, Expression probe_type, Location l)
1045 ProbeType = probe_type;
1050 public Expression Expr {
1056 public override Expression DoResolve (EmitContext ec)
1058 TypeExpr texpr = ProbeType.ResolveAsTypeTerminal (ec);
1061 probe_type = texpr.Type;
1063 CheckObsoleteAttribute (probe_type);
1065 expr = expr.Resolve (ec);
1069 if (expr.Type.IsPointer) {
1070 Report.Error (244, loc, "\"is\" or \"as\" are not valid on pointer types");
1078 /// Implementation of the `is' operator.
1080 public class Is : Probe {
1081 public Is (Expression expr, Expression probe_type, Location l)
1082 : base (expr, probe_type, l)
1087 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1092 public override void Emit (EmitContext ec)
1094 ILGenerator ig = ec.ig;
1099 case Action.AlwaysFalse:
1100 ig.Emit (OpCodes.Pop);
1101 IntConstant.EmitInt (ig, 0);
1103 case Action.AlwaysTrue:
1104 ig.Emit (OpCodes.Pop);
1105 IntConstant.EmitInt (ig, 1);
1107 case Action.LeaveOnStack:
1108 // the `e != null' rule.
1109 ig.Emit (OpCodes.Ldnull);
1110 ig.Emit (OpCodes.Ceq);
1111 ig.Emit (OpCodes.Ldc_I4_0);
1112 ig.Emit (OpCodes.Ceq);
1115 ig.Emit (OpCodes.Isinst, probe_type);
1116 ig.Emit (OpCodes.Ldnull);
1117 ig.Emit (OpCodes.Cgt_Un);
1120 throw new Exception ("never reached");
1123 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
1125 ILGenerator ig = ec.ig;
1128 case Action.AlwaysFalse:
1130 ig.Emit (OpCodes.Br, target);
1133 case Action.AlwaysTrue:
1135 ig.Emit (OpCodes.Br, target);
1138 case Action.LeaveOnStack:
1139 // the `e != null' rule.
1141 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1145 ig.Emit (OpCodes.Isinst, probe_type);
1146 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1149 throw new Exception ("never reached");
1152 public override Expression DoResolve (EmitContext ec)
1154 Expression e = base.DoResolve (ec);
1156 if ((e == null) || (expr == null))
1159 Type etype = expr.Type;
1160 bool warning_always_matches = false;
1161 bool warning_never_matches = false;
1163 type = TypeManager.bool_type;
1164 eclass = ExprClass.Value;
1167 // First case, if at compile time, there is an implicit conversion
1168 // then e != null (objects) or true (value types)
1170 e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1173 if (etype.IsValueType)
1174 action = Action.AlwaysTrue;
1176 action = Action.LeaveOnStack;
1178 warning_always_matches = true;
1179 } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1180 if (etype.IsGenericParameter)
1181 expr = new BoxedCast (expr, etype);
1184 // Second case: explicit reference convresion
1186 if (expr is NullLiteral)
1187 action = Action.AlwaysFalse;
1189 action = Action.Probe;
1191 action = Action.AlwaysFalse;
1192 warning_never_matches = true;
1195 if (warning_always_matches)
1196 Warning (183, "The given expression is always of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1197 else if (warning_never_matches){
1198 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1199 Warning (184, "The given expression is never of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1207 /// Implementation of the `as' operator.
1209 public class As : Probe {
1210 public As (Expression expr, Expression probe_type, Location l)
1211 : base (expr, probe_type, l)
1215 bool do_isinst = false;
1217 public override void Emit (EmitContext ec)
1219 ILGenerator ig = ec.ig;
1224 ig.Emit (OpCodes.Isinst, probe_type);
1227 static void Error_CannotConvertType (Type source, Type target, Location loc)
1230 39, loc, "as operator can not convert from `" +
1231 TypeManager.CSharpName (source) + "' to `" +
1232 TypeManager.CSharpName (target) + "'");
1235 public override Expression DoResolve (EmitContext ec)
1237 Expression e = base.DoResolve (ec);
1243 eclass = ExprClass.Value;
1244 Type etype = expr.Type;
1246 if (TypeManager.IsValueType (probe_type)){
1247 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1248 TypeManager.CSharpName (probe_type) + " is a value type)");
1253 e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1260 if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1261 if (etype.IsGenericParameter)
1262 expr = new BoxedCast (expr, etype);
1268 Error_CannotConvertType (etype, probe_type, loc);
1274 /// This represents a typecast in the source language.
1276 /// FIXME: Cast expressions have an unusual set of parsing
1277 /// rules, we need to figure those out.
1279 public class Cast : Expression {
1280 Expression target_type;
1283 public Cast (Expression cast_type, Expression expr, Location loc)
1285 this.target_type = cast_type;
1290 public Expression TargetType {
1296 public Expression Expr {
1305 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1307 if (!ec.ConstantCheckState)
1310 if ((value < min) || (value > max)) {
1311 Error (221, "Constant value `" + value + "' cannot be converted " +
1312 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1313 "syntax to override)");
1320 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1322 if (!ec.ConstantCheckState)
1326 Error (221, "Constant value `" + value + "' cannot be converted " +
1327 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1328 "syntax to override)");
1335 bool CheckUnsigned (EmitContext ec, long value, Type type)
1337 if (!ec.ConstantCheckState)
1341 Error (221, "Constant value `" + value + "' cannot be converted " +
1342 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1343 "syntax to override)");
1351 /// Attempts to do a compile-time folding of a constant cast.
1353 Expression TryReduce (EmitContext ec, Type target_type)
1355 Expression real_expr = expr;
1356 if (real_expr is EnumConstant)
1357 real_expr = ((EnumConstant) real_expr).Child;
1359 if (real_expr is ByteConstant){
1360 byte v = ((ByteConstant) real_expr).Value;
1362 if (target_type == TypeManager.sbyte_type) {
1363 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1365 return new SByteConstant ((sbyte) v);
1367 if (target_type == TypeManager.short_type)
1368 return new ShortConstant ((short) v);
1369 if (target_type == TypeManager.ushort_type)
1370 return new UShortConstant ((ushort) v);
1371 if (target_type == TypeManager.int32_type)
1372 return new IntConstant ((int) v);
1373 if (target_type == TypeManager.uint32_type)
1374 return new UIntConstant ((uint) v);
1375 if (target_type == TypeManager.int64_type)
1376 return new LongConstant ((long) v);
1377 if (target_type == TypeManager.uint64_type)
1378 return new ULongConstant ((ulong) v);
1379 if (target_type == TypeManager.float_type)
1380 return new FloatConstant ((float) v);
1381 if (target_type == TypeManager.double_type)
1382 return new DoubleConstant ((double) v);
1383 if (target_type == TypeManager.char_type)
1384 return new CharConstant ((char) v);
1385 if (target_type == TypeManager.decimal_type)
1386 return new DecimalConstant ((decimal) v);
1388 if (real_expr is SByteConstant){
1389 sbyte v = ((SByteConstant) real_expr).Value;
1391 if (target_type == TypeManager.byte_type) {
1392 if (!CheckUnsigned (ec, v, target_type))
1394 return new ByteConstant ((byte) v);
1396 if (target_type == TypeManager.short_type)
1397 return new ShortConstant ((short) v);
1398 if (target_type == TypeManager.ushort_type) {
1399 if (!CheckUnsigned (ec, v, target_type))
1401 return new UShortConstant ((ushort) v);
1402 } if (target_type == TypeManager.int32_type)
1403 return new IntConstant ((int) v);
1404 if (target_type == TypeManager.uint32_type) {
1405 if (!CheckUnsigned (ec, v, target_type))
1407 return new UIntConstant ((uint) v);
1408 } if (target_type == TypeManager.int64_type)
1409 return new LongConstant ((long) v);
1410 if (target_type == TypeManager.uint64_type) {
1411 if (!CheckUnsigned (ec, v, target_type))
1413 return new ULongConstant ((ulong) v);
1415 if (target_type == TypeManager.float_type)
1416 return new FloatConstant ((float) v);
1417 if (target_type == TypeManager.double_type)
1418 return new DoubleConstant ((double) v);
1419 if (target_type == TypeManager.char_type) {
1420 if (!CheckUnsigned (ec, v, target_type))
1422 return new CharConstant ((char) v);
1424 if (target_type == TypeManager.decimal_type)
1425 return new DecimalConstant ((decimal) v);
1427 if (real_expr is ShortConstant){
1428 short v = ((ShortConstant) real_expr).Value;
1430 if (target_type == TypeManager.byte_type) {
1431 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1433 return new ByteConstant ((byte) v);
1435 if (target_type == TypeManager.sbyte_type) {
1436 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1438 return new SByteConstant ((sbyte) v);
1440 if (target_type == TypeManager.ushort_type) {
1441 if (!CheckUnsigned (ec, v, target_type))
1443 return new UShortConstant ((ushort) v);
1445 if (target_type == TypeManager.int32_type)
1446 return new IntConstant ((int) v);
1447 if (target_type == TypeManager.uint32_type) {
1448 if (!CheckUnsigned (ec, v, target_type))
1450 return new UIntConstant ((uint) v);
1452 if (target_type == TypeManager.int64_type)
1453 return new LongConstant ((long) v);
1454 if (target_type == TypeManager.uint64_type) {
1455 if (!CheckUnsigned (ec, v, target_type))
1457 return new ULongConstant ((ulong) v);
1459 if (target_type == TypeManager.float_type)
1460 return new FloatConstant ((float) v);
1461 if (target_type == TypeManager.double_type)
1462 return new DoubleConstant ((double) v);
1463 if (target_type == TypeManager.char_type) {
1464 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1466 return new CharConstant ((char) v);
1468 if (target_type == TypeManager.decimal_type)
1469 return new DecimalConstant ((decimal) v);
1471 if (real_expr is UShortConstant){
1472 ushort v = ((UShortConstant) real_expr).Value;
1474 if (target_type == TypeManager.byte_type) {
1475 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1477 return new ByteConstant ((byte) v);
1479 if (target_type == TypeManager.sbyte_type) {
1480 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1482 return new SByteConstant ((sbyte) v);
1484 if (target_type == TypeManager.short_type) {
1485 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1487 return new ShortConstant ((short) v);
1489 if (target_type == TypeManager.int32_type)
1490 return new IntConstant ((int) v);
1491 if (target_type == TypeManager.uint32_type)
1492 return new UIntConstant ((uint) v);
1493 if (target_type == TypeManager.int64_type)
1494 return new LongConstant ((long) v);
1495 if (target_type == TypeManager.uint64_type)
1496 return new ULongConstant ((ulong) v);
1497 if (target_type == TypeManager.float_type)
1498 return new FloatConstant ((float) v);
1499 if (target_type == TypeManager.double_type)
1500 return new DoubleConstant ((double) v);
1501 if (target_type == TypeManager.char_type) {
1502 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1504 return new CharConstant ((char) v);
1506 if (target_type == TypeManager.decimal_type)
1507 return new DecimalConstant ((decimal) v);
1509 if (real_expr is IntConstant){
1510 int v = ((IntConstant) real_expr).Value;
1512 if (target_type == TypeManager.byte_type) {
1513 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1515 return new ByteConstant ((byte) v);
1517 if (target_type == TypeManager.sbyte_type) {
1518 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1520 return new SByteConstant ((sbyte) v);
1522 if (target_type == TypeManager.short_type) {
1523 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1525 return new ShortConstant ((short) v);
1527 if (target_type == TypeManager.ushort_type) {
1528 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1530 return new UShortConstant ((ushort) v);
1532 if (target_type == TypeManager.uint32_type) {
1533 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1535 return new UIntConstant ((uint) v);
1537 if (target_type == TypeManager.int64_type)
1538 return new LongConstant ((long) v);
1539 if (target_type == TypeManager.uint64_type) {
1540 if (!CheckUnsigned (ec, v, target_type))
1542 return new ULongConstant ((ulong) v);
1544 if (target_type == TypeManager.float_type)
1545 return new FloatConstant ((float) v);
1546 if (target_type == TypeManager.double_type)
1547 return new DoubleConstant ((double) v);
1548 if (target_type == TypeManager.char_type) {
1549 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1551 return new CharConstant ((char) v);
1553 if (target_type == TypeManager.decimal_type)
1554 return new DecimalConstant ((decimal) v);
1556 if (real_expr is UIntConstant){
1557 uint v = ((UIntConstant) real_expr).Value;
1559 if (target_type == TypeManager.byte_type) {
1560 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1562 return new ByteConstant ((byte) v);
1564 if (target_type == TypeManager.sbyte_type) {
1565 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1567 return new SByteConstant ((sbyte) v);
1569 if (target_type == TypeManager.short_type) {
1570 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1572 return new ShortConstant ((short) v);
1574 if (target_type == TypeManager.ushort_type) {
1575 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1577 return new UShortConstant ((ushort) v);
1579 if (target_type == TypeManager.int32_type) {
1580 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1582 return new IntConstant ((int) v);
1584 if (target_type == TypeManager.int64_type)
1585 return new LongConstant ((long) v);
1586 if (target_type == TypeManager.uint64_type)
1587 return new ULongConstant ((ulong) v);
1588 if (target_type == TypeManager.float_type)
1589 return new FloatConstant ((float) v);
1590 if (target_type == TypeManager.double_type)
1591 return new DoubleConstant ((double) v);
1592 if (target_type == TypeManager.char_type) {
1593 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1595 return new CharConstant ((char) v);
1597 if (target_type == TypeManager.decimal_type)
1598 return new DecimalConstant ((decimal) v);
1600 if (real_expr is LongConstant){
1601 long v = ((LongConstant) real_expr).Value;
1603 if (target_type == TypeManager.byte_type) {
1604 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1606 return new ByteConstant ((byte) v);
1608 if (target_type == TypeManager.sbyte_type) {
1609 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1611 return new SByteConstant ((sbyte) v);
1613 if (target_type == TypeManager.short_type) {
1614 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1616 return new ShortConstant ((short) v);
1618 if (target_type == TypeManager.ushort_type) {
1619 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1621 return new UShortConstant ((ushort) v);
1623 if (target_type == TypeManager.int32_type) {
1624 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1626 return new IntConstant ((int) v);
1628 if (target_type == TypeManager.uint32_type) {
1629 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1631 return new UIntConstant ((uint) v);
1633 if (target_type == TypeManager.uint64_type) {
1634 if (!CheckUnsigned (ec, v, target_type))
1636 return new ULongConstant ((ulong) v);
1638 if (target_type == TypeManager.float_type)
1639 return new FloatConstant ((float) v);
1640 if (target_type == TypeManager.double_type)
1641 return new DoubleConstant ((double) v);
1642 if (target_type == TypeManager.char_type) {
1643 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1645 return new CharConstant ((char) v);
1647 if (target_type == TypeManager.decimal_type)
1648 return new DecimalConstant ((decimal) v);
1650 if (real_expr is ULongConstant){
1651 ulong v = ((ULongConstant) real_expr).Value;
1653 if (target_type == TypeManager.byte_type) {
1654 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1656 return new ByteConstant ((byte) v);
1658 if (target_type == TypeManager.sbyte_type) {
1659 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1661 return new SByteConstant ((sbyte) v);
1663 if (target_type == TypeManager.short_type) {
1664 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1666 return new ShortConstant ((short) v);
1668 if (target_type == TypeManager.ushort_type) {
1669 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1671 return new UShortConstant ((ushort) v);
1673 if (target_type == TypeManager.int32_type) {
1674 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1676 return new IntConstant ((int) v);
1678 if (target_type == TypeManager.uint32_type) {
1679 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1681 return new UIntConstant ((uint) v);
1683 if (target_type == TypeManager.int64_type) {
1684 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1686 return new LongConstant ((long) v);
1688 if (target_type == TypeManager.float_type)
1689 return new FloatConstant ((float) v);
1690 if (target_type == TypeManager.double_type)
1691 return new DoubleConstant ((double) v);
1692 if (target_type == TypeManager.char_type) {
1693 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1695 return new CharConstant ((char) v);
1697 if (target_type == TypeManager.decimal_type)
1698 return new DecimalConstant ((decimal) v);
1700 if (real_expr is FloatConstant){
1701 float v = ((FloatConstant) real_expr).Value;
1703 if (target_type == TypeManager.byte_type)
1704 return new ByteConstant ((byte) v);
1705 if (target_type == TypeManager.sbyte_type)
1706 return new SByteConstant ((sbyte) v);
1707 if (target_type == TypeManager.short_type)
1708 return new ShortConstant ((short) v);
1709 if (target_type == TypeManager.ushort_type)
1710 return new UShortConstant ((ushort) v);
1711 if (target_type == TypeManager.int32_type)
1712 return new IntConstant ((int) v);
1713 if (target_type == TypeManager.uint32_type)
1714 return new UIntConstant ((uint) v);
1715 if (target_type == TypeManager.int64_type)
1716 return new LongConstant ((long) v);
1717 if (target_type == TypeManager.uint64_type)
1718 return new ULongConstant ((ulong) v);
1719 if (target_type == TypeManager.double_type)
1720 return new DoubleConstant ((double) v);
1721 if (target_type == TypeManager.char_type)
1722 return new CharConstant ((char) v);
1723 if (target_type == TypeManager.decimal_type)
1724 return new DecimalConstant ((decimal) v);
1726 if (real_expr is DoubleConstant){
1727 double v = ((DoubleConstant) real_expr).Value;
1729 if (target_type == TypeManager.byte_type){
1730 return new ByteConstant ((byte) v);
1731 } if (target_type == TypeManager.sbyte_type)
1732 return new SByteConstant ((sbyte) v);
1733 if (target_type == TypeManager.short_type)
1734 return new ShortConstant ((short) v);
1735 if (target_type == TypeManager.ushort_type)
1736 return new UShortConstant ((ushort) v);
1737 if (target_type == TypeManager.int32_type)
1738 return new IntConstant ((int) v);
1739 if (target_type == TypeManager.uint32_type)
1740 return new UIntConstant ((uint) v);
1741 if (target_type == TypeManager.int64_type)
1742 return new LongConstant ((long) v);
1743 if (target_type == TypeManager.uint64_type)
1744 return new ULongConstant ((ulong) v);
1745 if (target_type == TypeManager.float_type)
1746 return new FloatConstant ((float) v);
1747 if (target_type == TypeManager.char_type)
1748 return new CharConstant ((char) v);
1749 if (target_type == TypeManager.decimal_type)
1750 return new DecimalConstant ((decimal) v);
1753 if (real_expr is CharConstant){
1754 char v = ((CharConstant) real_expr).Value;
1756 if (target_type == TypeManager.byte_type) {
1757 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1759 return new ByteConstant ((byte) v);
1761 if (target_type == TypeManager.sbyte_type) {
1762 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1764 return new SByteConstant ((sbyte) v);
1766 if (target_type == TypeManager.short_type) {
1767 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1769 return new ShortConstant ((short) v);
1771 if (target_type == TypeManager.int32_type)
1772 return new IntConstant ((int) v);
1773 if (target_type == TypeManager.uint32_type)
1774 return new UIntConstant ((uint) v);
1775 if (target_type == TypeManager.int64_type)
1776 return new LongConstant ((long) v);
1777 if (target_type == TypeManager.uint64_type)
1778 return new ULongConstant ((ulong) v);
1779 if (target_type == TypeManager.float_type)
1780 return new FloatConstant ((float) v);
1781 if (target_type == TypeManager.double_type)
1782 return new DoubleConstant ((double) v);
1783 if (target_type == TypeManager.char_type) {
1784 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1786 return new CharConstant ((char) v);
1788 if (target_type == TypeManager.decimal_type)
1789 return new DecimalConstant ((decimal) v);
1795 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1797 expr = expr.DoResolveLValue (ec, right_side);
1801 return ResolveRest (ec);
1804 public override Expression DoResolve (EmitContext ec)
1806 expr = expr.Resolve (ec);
1810 return ResolveRest (ec);
1813 Expression ResolveRest (EmitContext ec)
1815 TypeExpr target = target_type.ResolveAsTypeTerminal (ec);
1821 CheckObsoleteAttribute (type);
1823 if (type.IsAbstract && type.IsSealed) {
1824 Report.Error (716, loc, "Cannot convert to static type '{0}'", TypeManager.CSharpName (type));
1828 eclass = ExprClass.Value;
1830 if (expr is Constant){
1831 Expression e = TryReduce (ec, type);
1837 if (type.IsPointer && !ec.InUnsafe) {
1841 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1845 public override void Emit (EmitContext ec)
1848 // This one will never happen
1850 throw new Exception ("Should not happen");
1855 /// Binary operators
1857 public class Binary : Expression {
1858 public enum Operator : byte {
1859 Multiply, Division, Modulus,
1860 Addition, Subtraction,
1861 LeftShift, RightShift,
1862 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1863 Equality, Inequality,
1873 Expression left, right;
1875 // This must be kept in sync with Operator!!!
1876 public static readonly string [] oper_names;
1880 oper_names = new string [(int) Operator.TOP];
1882 oper_names [(int) Operator.Multiply] = "op_Multiply";
1883 oper_names [(int) Operator.Division] = "op_Division";
1884 oper_names [(int) Operator.Modulus] = "op_Modulus";
1885 oper_names [(int) Operator.Addition] = "op_Addition";
1886 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1887 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1888 oper_names [(int) Operator.RightShift] = "op_RightShift";
1889 oper_names [(int) Operator.LessThan] = "op_LessThan";
1890 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1891 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1892 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1893 oper_names [(int) Operator.Equality] = "op_Equality";
1894 oper_names [(int) Operator.Inequality] = "op_Inequality";
1895 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1896 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1897 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1898 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1899 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1902 public Binary (Operator oper, Expression left, Expression right, Location loc)
1910 public Operator Oper {
1919 public Expression Left {
1928 public Expression Right {
1939 /// Returns a stringified representation of the Operator
1941 static string OperName (Operator oper)
1944 case Operator.Multiply:
1946 case Operator.Division:
1948 case Operator.Modulus:
1950 case Operator.Addition:
1952 case Operator.Subtraction:
1954 case Operator.LeftShift:
1956 case Operator.RightShift:
1958 case Operator.LessThan:
1960 case Operator.GreaterThan:
1962 case Operator.LessThanOrEqual:
1964 case Operator.GreaterThanOrEqual:
1966 case Operator.Equality:
1968 case Operator.Inequality:
1970 case Operator.BitwiseAnd:
1972 case Operator.BitwiseOr:
1974 case Operator.ExclusiveOr:
1976 case Operator.LogicalOr:
1978 case Operator.LogicalAnd:
1982 return oper.ToString ();
1985 public override string ToString ()
1987 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1988 right.ToString () + ")";
1991 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1993 if (expr.Type == target_type)
1996 return Convert.ImplicitConversion (ec, expr, target_type, loc);
1999 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
2002 34, loc, "Operator `" + OperName (oper)
2003 + "' is ambiguous on operands of type `"
2004 + TypeManager.CSharpName (l) + "' "
2005 + "and `" + TypeManager.CSharpName (r)
2009 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
2011 if ((l == t) || (r == t))
2014 if (!check_user_conversions)
2017 if (Convert.ImplicitUserConversionExists (ec, l, t))
2019 else if (Convert.ImplicitUserConversionExists (ec, r, t))
2026 // Note that handling the case l == Decimal || r == Decimal
2027 // is taken care of by the Step 1 Operator Overload resolution.
2029 // If `check_user_conv' is true, we also check whether a user-defined conversion
2030 // exists. Note that we only need to do this if both arguments are of a user-defined
2031 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
2032 // so we don't explicitly check for performance reasons.
2034 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
2036 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
2038 // If either operand is of type double, the other operand is
2039 // conveted to type double.
2041 if (r != TypeManager.double_type)
2042 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
2043 if (l != TypeManager.double_type)
2044 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
2046 type = TypeManager.double_type;
2047 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
2049 // if either operand is of type float, the other operand is
2050 // converted to type float.
2052 if (r != TypeManager.double_type)
2053 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
2054 if (l != TypeManager.double_type)
2055 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
2056 type = TypeManager.float_type;
2057 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2061 // If either operand is of type ulong, the other operand is
2062 // converted to type ulong. or an error ocurrs if the other
2063 // operand is of type sbyte, short, int or long
2065 if (l == TypeManager.uint64_type){
2066 if (r != TypeManager.uint64_type){
2067 if (right is IntConstant){
2068 IntConstant ic = (IntConstant) right;
2070 e = Convert.TryImplicitIntConversion (l, ic);
2073 } else if (right is LongConstant){
2074 long ll = ((LongConstant) right).Value;
2077 right = new ULongConstant ((ulong) ll);
2079 e = Convert.ImplicitNumericConversion (ec, right, l, loc);
2086 if (left is IntConstant){
2087 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
2090 } else if (left is LongConstant){
2091 long ll = ((LongConstant) left).Value;
2094 left = new ULongConstant ((ulong) ll);
2096 e = Convert.ImplicitNumericConversion (ec, left, r, loc);
2103 if ((other == TypeManager.sbyte_type) ||
2104 (other == TypeManager.short_type) ||
2105 (other == TypeManager.int32_type) ||
2106 (other == TypeManager.int64_type))
2107 Error_OperatorAmbiguous (loc, oper, l, r);
2109 left = ForceConversion (ec, left, TypeManager.uint64_type);
2110 right = ForceConversion (ec, right, TypeManager.uint64_type);
2112 type = TypeManager.uint64_type;
2113 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2115 // If either operand is of type long, the other operand is converted
2118 if (l != TypeManager.int64_type)
2119 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
2120 if (r != TypeManager.int64_type)
2121 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
2123 type = TypeManager.int64_type;
2124 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2126 // If either operand is of type uint, and the other
2127 // operand is of type sbyte, short or int, othe operands are
2128 // converted to type long (unless we have an int constant).
2132 if (l == TypeManager.uint32_type){
2133 if (right is IntConstant){
2134 IntConstant ic = (IntConstant) right;
2138 right = new UIntConstant ((uint) val);
2145 } else if (r == TypeManager.uint32_type){
2146 if (left is IntConstant){
2147 IntConstant ic = (IntConstant) left;
2151 left = new UIntConstant ((uint) val);
2160 if ((other == TypeManager.sbyte_type) ||
2161 (other == TypeManager.short_type) ||
2162 (other == TypeManager.int32_type)){
2163 left = ForceConversion (ec, left, TypeManager.int64_type);
2164 right = ForceConversion (ec, right, TypeManager.int64_type);
2165 type = TypeManager.int64_type;
2168 // if either operand is of type uint, the other
2169 // operand is converd to type uint
2171 left = ForceConversion (ec, left, TypeManager.uint32_type);
2172 right = ForceConversion (ec, right, TypeManager.uint32_type);
2173 type = TypeManager.uint32_type;
2175 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2176 if (l != TypeManager.decimal_type)
2177 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
2179 if (r != TypeManager.decimal_type)
2180 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
2181 type = TypeManager.decimal_type;
2183 left = ForceConversion (ec, left, TypeManager.int32_type);
2184 right = ForceConversion (ec, right, TypeManager.int32_type);
2186 type = TypeManager.int32_type;
2189 return (left != null) && (right != null);
2192 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2194 Report.Error (19, loc,
2195 "Operator " + name + " cannot be applied to operands of type `" +
2196 TypeManager.CSharpName (l) + "' and `" +
2197 TypeManager.CSharpName (r) + "'");
2200 void Error_OperatorCannotBeApplied ()
2202 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2205 static bool is_unsigned (Type t)
2207 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2208 t == TypeManager.short_type || t == TypeManager.byte_type);
2211 static bool is_user_defined (Type t)
2213 if (t.IsSubclassOf (TypeManager.value_type) &&
2214 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2220 Expression Make32or64 (EmitContext ec, Expression e)
2224 if (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2225 t == TypeManager.int64_type || t == TypeManager.uint64_type)
2227 Expression ee = Convert.ImplicitConversion (ec, e, TypeManager.int32_type, loc);
2230 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint32_type, loc);
2233 ee = Convert.ImplicitConversion (ec, e, TypeManager.int64_type, loc);
2236 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint64_type, loc);
2242 Expression CheckShiftArguments (EmitContext ec)
2246 e = ForceConversion (ec, right, TypeManager.int32_type);
2248 Error_OperatorCannotBeApplied ();
2253 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
2254 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
2255 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
2256 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
2260 if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
2261 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (31), loc);
2262 right = right.DoResolve (ec);
2264 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (63), loc);
2265 right = right.DoResolve (ec);
2270 Error_OperatorCannotBeApplied ();
2274 Expression ResolveOperator (EmitContext ec)
2277 Type r = right.Type;
2280 // Special cases: string or type parameter comapred to null
2282 if (oper == Operator.Equality || oper == Operator.Inequality){
2283 if ((!TypeManager.IsValueType (l) && r == TypeManager.null_type) ||
2284 (!TypeManager.IsValueType (r) && l == TypeManager.null_type)) {
2285 Type = TypeManager.bool_type;
2290 if (l.IsGenericParameter && (right is NullLiteral)) {
2291 if (l.BaseType == TypeManager.value_type) {
2292 Error_OperatorCannotBeApplied ();
2296 left = new BoxedCast (left);
2297 Type = TypeManager.bool_type;
2301 if (r.IsGenericParameter && (left is NullLiteral)) {
2302 if (r.BaseType == TypeManager.value_type) {
2303 Error_OperatorCannotBeApplied ();
2307 right = new BoxedCast (right);
2308 Type = TypeManager.bool_type;
2313 if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
2314 Type = TypeManager.bool_type;
2321 // Do not perform operator overload resolution when both sides are
2324 if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
2326 // Step 1: Perform Operator Overload location
2328 Expression left_expr, right_expr;
2330 string op = oper_names [(int) oper];
2332 MethodGroupExpr union;
2333 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2335 right_expr = MemberLookup (
2336 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2337 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2339 union = (MethodGroupExpr) left_expr;
2341 if (union != null) {
2342 ArrayList args = new ArrayList (2);
2343 args.Add (new Argument (left, Argument.AType.Expression));
2344 args.Add (new Argument (right, Argument.AType.Expression));
2346 MethodBase method = Invocation.OverloadResolve (
2347 ec, union, args, true, Location.Null);
2349 if (method != null) {
2350 MethodInfo mi = (MethodInfo) method;
2352 return new BinaryMethod (mi.ReturnType, method, args);
2358 // Step 0: String concatenation (because overloading will get this wrong)
2360 if (oper == Operator.Addition){
2362 // If any of the arguments is a string, cast to string
2365 // Simple constant folding
2366 if (left is StringConstant && right is StringConstant)
2367 return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value);
2369 if (l == TypeManager.string_type || r == TypeManager.string_type) {
2371 if (r == TypeManager.void_type || l == TypeManager.void_type) {
2372 Error_OperatorCannotBeApplied ();
2376 // try to fold it in on the left
2377 if (left is StringConcat) {
2380 // We have to test here for not-null, since we can be doubly-resolved
2381 // take care of not appending twice
2384 type = TypeManager.string_type;
2385 ((StringConcat) left).Append (ec, right);
2386 return left.Resolve (ec);
2392 // Otherwise, start a new concat expression
2393 return new StringConcat (ec, loc, left, right).Resolve (ec);
2397 // Transform a + ( - b) into a - b
2399 if (right is Unary){
2400 Unary right_unary = (Unary) right;
2402 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2403 oper = Operator.Subtraction;
2404 right = right_unary.Expr;
2410 if (oper == Operator.Equality || oper == Operator.Inequality){
2411 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2412 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2413 Error_OperatorCannotBeApplied ();
2417 type = TypeManager.bool_type;
2421 bool left_is_null = left is NullLiteral;
2422 bool right_is_null = right is NullLiteral;
2423 if (left_is_null || right_is_null) {
2424 if (oper == Operator.Equality)
2425 return new BoolLiteral (left_is_null == right_is_null);
2427 return new BoolLiteral (left_is_null != right_is_null);
2431 // operator != (object a, object b)
2432 // operator == (object a, object b)
2434 // For this to be used, both arguments have to be reference-types.
2435 // Read the rationale on the spec (14.9.6)
2437 // Also, if at compile time we know that the classes do not inherit
2438 // one from the other, then we catch the error there.
2440 if (!(l.IsValueType || r.IsValueType)){
2441 type = TypeManager.bool_type;
2446 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2450 // Also, a standard conversion must exist from either one
2452 if (!(Convert.ImplicitStandardConversionExists (ec, left, r) ||
2453 Convert.ImplicitStandardConversionExists (ec, right, l))){
2454 Error_OperatorCannotBeApplied ();
2458 // We are going to have to convert to an object to compare
2460 if (l != TypeManager.object_type)
2461 left = new EmptyCast (left, TypeManager.object_type);
2462 if (r != TypeManager.object_type)
2463 right = new EmptyCast (right, TypeManager.object_type);
2466 // FIXME: CSC here catches errors cs254 and cs252
2472 // One of them is a valuetype, but the other one is not.
2474 if (!l.IsValueType || !r.IsValueType) {
2475 Error_OperatorCannotBeApplied ();
2480 // Only perform numeric promotions on:
2481 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2483 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2484 if (TypeManager.IsDelegateType (l)){
2485 if (((right.eclass == ExprClass.MethodGroup) ||
2486 (r == TypeManager.anonymous_method_type))){
2487 if ((RootContext.Version != LanguageVersion.ISO_1)){
2488 Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2496 if (TypeManager.IsDelegateType (r)){
2498 ArrayList args = new ArrayList (2);
2500 args = new ArrayList (2);
2501 args.Add (new Argument (left, Argument.AType.Expression));
2502 args.Add (new Argument (right, Argument.AType.Expression));
2504 if (oper == Operator.Addition)
2505 method = TypeManager.delegate_combine_delegate_delegate;
2507 method = TypeManager.delegate_remove_delegate_delegate;
2509 if (!TypeManager.IsEqual (l, r)) {
2510 Error_OperatorCannotBeApplied ();
2514 return new BinaryDelegate (l, method, args);
2519 // Pointer arithmetic:
2521 // T* operator + (T* x, int y);
2522 // T* operator + (T* x, uint y);
2523 // T* operator + (T* x, long y);
2524 // T* operator + (T* x, ulong y);
2526 // T* operator + (int y, T* x);
2527 // T* operator + (uint y, T *x);
2528 // T* operator + (long y, T *x);
2529 // T* operator + (ulong y, T *x);
2531 // T* operator - (T* x, int y);
2532 // T* operator - (T* x, uint y);
2533 // T* operator - (T* x, long y);
2534 // T* operator - (T* x, ulong y);
2536 // long operator - (T* x, T *y)
2539 if (r.IsPointer && oper == Operator.Subtraction){
2541 return new PointerArithmetic (
2542 false, left, right, TypeManager.int64_type,
2545 Expression t = Make32or64 (ec, right);
2547 return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc).Resolve (ec);
2549 } else if (r.IsPointer && oper == Operator.Addition){
2550 Expression t = Make32or64 (ec, left);
2552 return new PointerArithmetic (true, right, t, r, loc).Resolve (ec);
2557 // Enumeration operators
2559 bool lie = TypeManager.IsEnumType (l);
2560 bool rie = TypeManager.IsEnumType (r);
2564 // U operator - (E e, E f)
2566 if (oper == Operator.Subtraction){
2568 type = TypeManager.EnumToUnderlying (l);
2571 Error_OperatorCannotBeApplied ();
2577 // operator + (E e, U x)
2578 // operator - (E e, U x)
2580 if (oper == Operator.Addition || oper == Operator.Subtraction){
2581 Type enum_type = lie ? l : r;
2582 Type other_type = lie ? r : l;
2583 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2585 if (underlying_type != other_type){
2586 temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
2596 Error_OperatorCannotBeApplied ();
2605 temp = Convert.ImplicitConversion (ec, right, l, loc);
2609 Error_OperatorCannotBeApplied ();
2613 temp = Convert.ImplicitConversion (ec, left, r, loc);
2618 Error_OperatorCannotBeApplied ();
2623 if (oper == Operator.Equality || oper == Operator.Inequality ||
2624 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2625 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2626 if (left.Type != right.Type){
2627 Error_OperatorCannotBeApplied ();
2630 type = TypeManager.bool_type;
2634 if (oper == Operator.BitwiseAnd ||
2635 oper == Operator.BitwiseOr ||
2636 oper == Operator.ExclusiveOr){
2640 Error_OperatorCannotBeApplied ();
2644 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2645 return CheckShiftArguments (ec);
2647 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2648 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2649 type = TypeManager.bool_type;
2654 Error_OperatorCannotBeApplied ();
2658 Expression e = new ConditionalLogicalOperator (
2659 oper == Operator.LogicalAnd, left, right, l, loc);
2660 return e.Resolve (ec);
2664 // operator & (bool x, bool y)
2665 // operator | (bool x, bool y)
2666 // operator ^ (bool x, bool y)
2668 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2669 if (oper == Operator.BitwiseAnd ||
2670 oper == Operator.BitwiseOr ||
2671 oper == Operator.ExclusiveOr){
2678 // Pointer comparison
2680 if (l.IsPointer && r.IsPointer){
2681 if (oper == Operator.Equality || oper == Operator.Inequality ||
2682 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2683 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2684 type = TypeManager.bool_type;
2690 // This will leave left or right set to null if there is an error
2692 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2693 DoNumericPromotions (ec, l, r, check_user_conv);
2694 if (left == null || right == null){
2695 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2700 // reload our cached types if required
2705 if (oper == Operator.BitwiseAnd ||
2706 oper == Operator.BitwiseOr ||
2707 oper == Operator.ExclusiveOr){
2709 if (((l == TypeManager.int32_type) ||
2710 (l == TypeManager.uint32_type) ||
2711 (l == TypeManager.short_type) ||
2712 (l == TypeManager.ushort_type) ||
2713 (l == TypeManager.int64_type) ||
2714 (l == TypeManager.uint64_type))){
2717 Error_OperatorCannotBeApplied ();
2721 Error_OperatorCannotBeApplied ();
2726 if (oper == Operator.Equality ||
2727 oper == Operator.Inequality ||
2728 oper == Operator.LessThanOrEqual ||
2729 oper == Operator.LessThan ||
2730 oper == Operator.GreaterThanOrEqual ||
2731 oper == Operator.GreaterThan){
2732 type = TypeManager.bool_type;
2738 public override Expression DoResolve (EmitContext ec)
2740 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2741 left = ((ParenthesizedExpression) left).Expr;
2742 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2746 if (left.eclass == ExprClass.Type) {
2747 Error (75, "Casting a negative value needs to have the value in parentheses.");
2751 left = left.Resolve (ec);
2756 Constant lc = left as Constant;
2757 if (lc != null && lc.Type == TypeManager.bool_type &&
2758 ((oper == Operator.LogicalAnd && (bool)lc.GetValue () == false) ||
2759 (oper == Operator.LogicalOr && (bool)lc.GetValue () == true))) {
2761 // TODO: make a sense to resolve unreachable expression as we do for statement
2762 Report.Warning (429, 4, loc, "Unreachable expression code detected");
2766 right = right.Resolve (ec);
2770 eclass = ExprClass.Value;
2772 Constant rc = right as Constant;
2773 if (rc != null & lc != null){
2774 Expression e = ConstantFold.BinaryFold (
2775 ec, oper, lc, rc, loc);
2780 if (TypeManager.IsNullableType (left.Type) || TypeManager.IsNullableType (right.Type))
2781 return new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
2783 return ResolveOperator (ec);
2787 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2788 /// context of a conditional bool expression. This function will return
2789 /// false if it is was possible to use EmitBranchable, or true if it was.
2791 /// The expression's code is generated, and we will generate a branch to `target'
2792 /// if the resulting expression value is equal to isTrue
2794 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2796 ILGenerator ig = ec.ig;
2799 // This is more complicated than it looks, but its just to avoid
2800 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2801 // but on top of that we want for == and != to use a special path
2802 // if we are comparing against null
2804 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
2805 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2808 // put the constant on the rhs, for simplicity
2810 if (left is Constant) {
2811 Expression swap = right;
2816 if (((Constant) right).IsZeroInteger) {
2819 ig.Emit (OpCodes.Brtrue, target);
2821 ig.Emit (OpCodes.Brfalse, target);
2824 } else if (right is BoolConstant){
2826 if (my_on_true != ((BoolConstant) right).Value)
2827 ig.Emit (OpCodes.Brtrue, target);
2829 ig.Emit (OpCodes.Brfalse, target);
2834 } else if (oper == Operator.LogicalAnd) {
2837 Label tests_end = ig.DefineLabel ();
2839 left.EmitBranchable (ec, tests_end, false);
2840 right.EmitBranchable (ec, target, true);
2841 ig.MarkLabel (tests_end);
2843 left.EmitBranchable (ec, target, false);
2844 right.EmitBranchable (ec, target, false);
2849 } else if (oper == Operator.LogicalOr){
2851 left.EmitBranchable (ec, target, true);
2852 right.EmitBranchable (ec, target, true);
2855 Label tests_end = ig.DefineLabel ();
2856 left.EmitBranchable (ec, tests_end, true);
2857 right.EmitBranchable (ec, target, false);
2858 ig.MarkLabel (tests_end);
2863 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2864 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2865 oper == Operator.Equality || oper == Operator.Inequality)) {
2866 base.EmitBranchable (ec, target, onTrue);
2874 bool isUnsigned = is_unsigned (t) || t == TypeManager.double_type || t == TypeManager.float_type;
2877 case Operator.Equality:
2879 ig.Emit (OpCodes.Beq, target);
2881 ig.Emit (OpCodes.Bne_Un, target);
2884 case Operator.Inequality:
2886 ig.Emit (OpCodes.Bne_Un, target);
2888 ig.Emit (OpCodes.Beq, target);
2891 case Operator.LessThan:
2894 ig.Emit (OpCodes.Blt_Un, target);
2896 ig.Emit (OpCodes.Blt, target);
2899 ig.Emit (OpCodes.Bge_Un, target);
2901 ig.Emit (OpCodes.Bge, target);
2904 case Operator.GreaterThan:
2907 ig.Emit (OpCodes.Bgt_Un, target);
2909 ig.Emit (OpCodes.Bgt, target);
2912 ig.Emit (OpCodes.Ble_Un, target);
2914 ig.Emit (OpCodes.Ble, target);
2917 case Operator.LessThanOrEqual:
2920 ig.Emit (OpCodes.Ble_Un, target);
2922 ig.Emit (OpCodes.Ble, target);
2925 ig.Emit (OpCodes.Bgt_Un, target);
2927 ig.Emit (OpCodes.Bgt, target);
2931 case Operator.GreaterThanOrEqual:
2934 ig.Emit (OpCodes.Bge_Un, target);
2936 ig.Emit (OpCodes.Bge, target);
2939 ig.Emit (OpCodes.Blt_Un, target);
2941 ig.Emit (OpCodes.Blt, target);
2944 Console.WriteLine (oper);
2945 throw new Exception ("what is THAT");
2949 public override void Emit (EmitContext ec)
2951 ILGenerator ig = ec.ig;
2956 // Handle short-circuit operators differently
2959 if (oper == Operator.LogicalAnd) {
2960 Label load_zero = ig.DefineLabel ();
2961 Label end = ig.DefineLabel ();
2963 left.EmitBranchable (ec, load_zero, false);
2965 ig.Emit (OpCodes.Br, end);
2967 ig.MarkLabel (load_zero);
2968 ig.Emit (OpCodes.Ldc_I4_0);
2971 } else if (oper == Operator.LogicalOr) {
2972 Label load_one = ig.DefineLabel ();
2973 Label end = ig.DefineLabel ();
2975 left.EmitBranchable (ec, load_one, true);
2977 ig.Emit (OpCodes.Br, end);
2979 ig.MarkLabel (load_one);
2980 ig.Emit (OpCodes.Ldc_I4_1);
2988 bool isUnsigned = is_unsigned (left.Type);
2991 case Operator.Multiply:
2993 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2994 opcode = OpCodes.Mul_Ovf;
2995 else if (isUnsigned)
2996 opcode = OpCodes.Mul_Ovf_Un;
2998 opcode = OpCodes.Mul;
3000 opcode = OpCodes.Mul;
3004 case Operator.Division:
3006 opcode = OpCodes.Div_Un;
3008 opcode = OpCodes.Div;
3011 case Operator.Modulus:
3013 opcode = OpCodes.Rem_Un;
3015 opcode = OpCodes.Rem;
3018 case Operator.Addition:
3020 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3021 opcode = OpCodes.Add_Ovf;
3022 else if (isUnsigned)
3023 opcode = OpCodes.Add_Ovf_Un;
3025 opcode = OpCodes.Add;
3027 opcode = OpCodes.Add;
3030 case Operator.Subtraction:
3032 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3033 opcode = OpCodes.Sub_Ovf;
3034 else if (isUnsigned)
3035 opcode = OpCodes.Sub_Ovf_Un;
3037 opcode = OpCodes.Sub;
3039 opcode = OpCodes.Sub;
3042 case Operator.RightShift:
3044 opcode = OpCodes.Shr_Un;
3046 opcode = OpCodes.Shr;
3049 case Operator.LeftShift:
3050 opcode = OpCodes.Shl;
3053 case Operator.Equality:
3054 opcode = OpCodes.Ceq;
3057 case Operator.Inequality:
3058 ig.Emit (OpCodes.Ceq);
3059 ig.Emit (OpCodes.Ldc_I4_0);
3061 opcode = OpCodes.Ceq;
3064 case Operator.LessThan:
3066 opcode = OpCodes.Clt_Un;
3068 opcode = OpCodes.Clt;
3071 case Operator.GreaterThan:
3073 opcode = OpCodes.Cgt_Un;
3075 opcode = OpCodes.Cgt;
3078 case Operator.LessThanOrEqual:
3079 Type lt = left.Type;
3081 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
3082 ig.Emit (OpCodes.Cgt_Un);
3084 ig.Emit (OpCodes.Cgt);
3085 ig.Emit (OpCodes.Ldc_I4_0);
3087 opcode = OpCodes.Ceq;
3090 case Operator.GreaterThanOrEqual:
3091 Type le = left.Type;
3093 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3094 ig.Emit (OpCodes.Clt_Un);
3096 ig.Emit (OpCodes.Clt);
3098 ig.Emit (OpCodes.Ldc_I4_0);
3100 opcode = OpCodes.Ceq;
3103 case Operator.BitwiseOr:
3104 opcode = OpCodes.Or;
3107 case Operator.BitwiseAnd:
3108 opcode = OpCodes.And;
3111 case Operator.ExclusiveOr:
3112 opcode = OpCodes.Xor;
3116 throw new Exception ("This should not happen: Operator = "
3117 + oper.ToString ());
3125 // Object created by Binary when the binary operator uses an method instead of being
3126 // a binary operation that maps to a CIL binary operation.
3128 public class BinaryMethod : Expression {
3129 public MethodBase method;
3130 public ArrayList Arguments;
3132 public BinaryMethod (Type t, MethodBase m, ArrayList args)
3137 eclass = ExprClass.Value;
3140 public override Expression DoResolve (EmitContext ec)
3145 public override void Emit (EmitContext ec)
3147 ILGenerator ig = ec.ig;
3149 if (Arguments != null)
3150 Invocation.EmitArguments (ec, method, Arguments, false, null);
3152 if (method is MethodInfo)
3153 ig.Emit (OpCodes.Call, (MethodInfo) method);
3155 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3160 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3161 // b, c, d... may be strings or objects.
3163 public class StringConcat : Expression {
3165 bool invalid = false;
3166 bool emit_conv_done = false;
3168 // Are we also concating objects?
3170 bool is_strings_only = true;
3172 public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
3175 type = TypeManager.string_type;
3176 eclass = ExprClass.Value;
3178 operands = new ArrayList (2);
3183 public override Expression DoResolve (EmitContext ec)
3191 public void Append (EmitContext ec, Expression operand)
3196 if (operand is StringConstant && operands.Count != 0) {
3197 StringConstant last_operand = operands [operands.Count - 1] as StringConstant;
3198 if (last_operand != null) {
3199 operands [operands.Count - 1] = new StringConstant (last_operand.Value + ((StringConstant) operand).Value);
3205 // Conversion to object
3207 if (operand.Type != TypeManager.string_type) {
3208 Expression no = Convert.ImplicitConversion (ec, operand, TypeManager.object_type, loc);
3211 Binary.Error_OperatorCannotBeApplied (loc, "+", TypeManager.string_type, operand.Type);
3217 operands.Add (operand);
3220 public override void Emit (EmitContext ec)
3222 MethodInfo concat_method = null;
3225 // Do conversion to arguments; check for strings only
3228 // This can get called multiple times, so we have to deal with that.
3229 if (!emit_conv_done) {
3230 emit_conv_done = true;
3231 for (int i = 0; i < operands.Count; i ++) {
3232 Expression e = (Expression) operands [i];
3233 is_strings_only &= e.Type == TypeManager.string_type;
3236 for (int i = 0; i < operands.Count; i ++) {
3237 Expression e = (Expression) operands [i];
3239 if (! is_strings_only && e.Type == TypeManager.string_type) {
3240 // need to make sure this is an object, because the EmitParams
3241 // method might look at the type of this expression, see it is a
3242 // string and emit a string [] when we want an object [];
3244 e = new EmptyCast (e, TypeManager.object_type);
3246 operands [i] = new Argument (e, Argument.AType.Expression);
3251 // Find the right method
3253 switch (operands.Count) {
3256 // This should not be possible, because simple constant folding
3257 // is taken care of in the Binary code.
3259 throw new Exception ("how did you get here?");
3262 concat_method = is_strings_only ?
3263 TypeManager.string_concat_string_string :
3264 TypeManager.string_concat_object_object ;
3267 concat_method = is_strings_only ?
3268 TypeManager.string_concat_string_string_string :
3269 TypeManager.string_concat_object_object_object ;
3273 // There is not a 4 param overlaod for object (the one that there is
3274 // is actually a varargs methods, and is only in corlib because it was
3275 // introduced there before.).
3277 if (!is_strings_only)
3280 concat_method = TypeManager.string_concat_string_string_string_string;
3283 concat_method = is_strings_only ?
3284 TypeManager.string_concat_string_dot_dot_dot :
3285 TypeManager.string_concat_object_dot_dot_dot ;
3289 Invocation.EmitArguments (ec, concat_method, operands, false, null);
3290 ec.ig.Emit (OpCodes.Call, concat_method);
3295 // Object created with +/= on delegates
3297 public class BinaryDelegate : Expression {
3301 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3306 eclass = ExprClass.Value;
3309 public override Expression DoResolve (EmitContext ec)
3314 public override void Emit (EmitContext ec)
3316 ILGenerator ig = ec.ig;
3318 Invocation.EmitArguments (ec, method, args, false, null);
3320 ig.Emit (OpCodes.Call, (MethodInfo) method);
3321 ig.Emit (OpCodes.Castclass, type);
3324 public Expression Right {
3326 Argument arg = (Argument) args [1];
3331 public bool IsAddition {
3333 return method == TypeManager.delegate_combine_delegate_delegate;
3339 // User-defined conditional logical operator
3340 public class ConditionalLogicalOperator : Expression {
3341 Expression left, right;
3344 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3347 eclass = ExprClass.Value;
3351 this.is_and = is_and;
3354 protected void Error19 ()
3356 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3359 protected void Error218 ()
3361 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3362 "declarations of operator true and operator false");
3365 Expression op_true, op_false, op;
3366 LocalTemporary left_temp;
3368 public override Expression DoResolve (EmitContext ec)
3371 Expression operator_group;
3373 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3374 if (operator_group == null) {
3379 left_temp = new LocalTemporary (ec, type);
3381 ArrayList arguments = new ArrayList ();
3382 arguments.Add (new Argument (left_temp, Argument.AType.Expression));
3383 arguments.Add (new Argument (right, Argument.AType.Expression));
3384 method = Invocation.OverloadResolve (
3385 ec, (MethodGroupExpr) operator_group, arguments, false, loc)
3387 if (method == null) {
3392 if (method.ReturnType != type) {
3393 Report.Error (217, loc, "In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') " +
3394 "must have the same return type as the type of its 2 parameters", TypeManager.CSharpSignature (method));
3398 op = new StaticCallExpr (method, arguments, loc);
3400 op_true = GetOperatorTrue (ec, left_temp, loc);
3401 op_false = GetOperatorFalse (ec, left_temp, loc);
3402 if ((op_true == null) || (op_false == null)) {
3410 public override void Emit (EmitContext ec)
3412 ILGenerator ig = ec.ig;
3413 Label false_target = ig.DefineLabel ();
3414 Label end_target = ig.DefineLabel ();
3417 left_temp.Store (ec);
3419 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
3420 left_temp.Emit (ec);
3421 ig.Emit (OpCodes.Br, end_target);
3422 ig.MarkLabel (false_target);
3424 ig.MarkLabel (end_target);
3428 public class PointerArithmetic : Expression {
3429 Expression left, right;
3433 // We assume that `l' is always a pointer
3435 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3441 is_add = is_addition;
3444 public override Expression DoResolve (EmitContext ec)
3446 eclass = ExprClass.Variable;
3448 if (left.Type == TypeManager.void_ptr_type) {
3449 Error (242, "The operation in question is undefined on void pointers");
3456 public override void Emit (EmitContext ec)
3458 Type op_type = left.Type;
3459 ILGenerator ig = ec.ig;
3461 // It must be either array or fixed buffer
3462 Type element = TypeManager.HasElementType (op_type) ?
3463 element = TypeManager.GetElementType (op_type) :
3464 element = AttributeTester.GetFixedBuffer (((FieldExpr)left).FieldInfo).ElementType;
3466 int size = GetTypeSize (element);
3467 Type rtype = right.Type;
3469 if (rtype.IsPointer){
3471 // handle (pointer - pointer)
3475 ig.Emit (OpCodes.Sub);
3479 ig.Emit (OpCodes.Sizeof, element);
3481 IntLiteral.EmitInt (ig, size);
3482 ig.Emit (OpCodes.Div);
3484 ig.Emit (OpCodes.Conv_I8);
3487 // handle + and - on (pointer op int)
3490 ig.Emit (OpCodes.Conv_I);
3492 Constant right_const = right as Constant;
3493 if (right_const != null && size != 0) {
3494 Expression ex = ConstantFold.BinaryFold (ec, Binary.Operator.Multiply, new IntConstant (size), right_const, loc);
3502 ig.Emit (OpCodes.Sizeof, element);
3504 IntLiteral.EmitInt (ig, size);
3505 if (rtype == TypeManager.int64_type)
3506 ig.Emit (OpCodes.Conv_I8);
3507 else if (rtype == TypeManager.uint64_type)
3508 ig.Emit (OpCodes.Conv_U8);
3509 ig.Emit (OpCodes.Mul);
3513 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
3514 ig.Emit (OpCodes.Conv_I);
3517 ig.Emit (OpCodes.Add);
3519 ig.Emit (OpCodes.Sub);
3525 /// Implements the ternary conditional operator (?:)
3527 public class Conditional : Expression {
3528 Expression expr, trueExpr, falseExpr;
3530 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3533 this.trueExpr = trueExpr;
3534 this.falseExpr = falseExpr;
3538 public Expression Expr {
3544 public Expression TrueExpr {
3550 public Expression FalseExpr {
3556 public override Expression DoResolve (EmitContext ec)
3558 expr = expr.Resolve (ec);
3563 if (TypeManager.IsNullableType (expr.Type))
3564 return new Nullable.LiftedConditional (expr, trueExpr, falseExpr, loc).Resolve (ec);
3566 if (expr.Type != TypeManager.bool_type){
3567 expr = Expression.ResolveBoolean (
3574 trueExpr = trueExpr.Resolve (ec);
3575 falseExpr = falseExpr.Resolve (ec);
3577 if (trueExpr == null || falseExpr == null)
3580 eclass = ExprClass.Value;
3581 if (trueExpr.Type == falseExpr.Type)
3582 type = trueExpr.Type;
3585 Type true_type = trueExpr.Type;
3586 Type false_type = falseExpr.Type;
3589 // First, if an implicit conversion exists from trueExpr
3590 // to falseExpr, then the result type is of type falseExpr.Type
3592 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3595 // Check if both can convert implicitl to each other's type
3597 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3599 "Can not compute type of conditional expression " +
3600 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3601 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3602 "' convert implicitly to each other");
3607 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3611 Error (173, "The type of the conditional expression can " +
3612 "not be computed because there is no implicit conversion" +
3613 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3614 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3619 // Dead code optimalization
3620 if (expr is BoolConstant){
3621 BoolConstant bc = (BoolConstant) expr;
3623 Report.Warning (429, 4, bc.Value ? falseExpr.Location : trueExpr.Location, "Unreachable expression code detected");
3624 return bc.Value ? trueExpr : falseExpr;
3630 public override void Emit (EmitContext ec)
3632 ILGenerator ig = ec.ig;
3633 Label false_target = ig.DefineLabel ();
3634 Label end_target = ig.DefineLabel ();
3636 expr.EmitBranchable (ec, false_target, false);
3638 ig.Emit (OpCodes.Br, end_target);
3639 ig.MarkLabel (false_target);
3640 falseExpr.Emit (ec);
3641 ig.MarkLabel (end_target);
3649 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3650 public readonly string Name;
3651 public readonly Block Block;
3652 public LocalInfo local_info;
3655 LocalTemporary temp;
3657 public LocalVariableReference (Block block, string name, Location l)
3662 eclass = ExprClass.Variable;
3666 // Setting `is_readonly' to false will allow you to create a writable
3667 // reference to a read-only variable. This is used by foreach and using.
3669 public LocalVariableReference (Block block, string name, Location l,
3670 LocalInfo local_info, bool is_readonly)
3671 : this (block, name, l)
3673 this.local_info = local_info;
3674 this.is_readonly = is_readonly;
3677 public VariableInfo VariableInfo {
3679 return local_info.VariableInfo;
3683 public bool IsReadOnly {
3689 protected Expression DoResolveBase (EmitContext ec, Expression lvalue_right_side)
3691 if (local_info == null) {
3692 local_info = Block.GetLocalInfo (Name);
3695 if (lvalue_right_side == EmptyExpression.Null)
3696 local_info.Used = true;
3698 is_readonly = local_info.ReadOnly;
3701 type = local_info.VariableType;
3703 VariableInfo variable_info = local_info.VariableInfo;
3704 if (lvalue_right_side != null){
3706 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3710 if (variable_info != null)
3711 variable_info.SetAssigned (ec);
3714 Expression e = Block.GetConstantExpression (Name);
3716 local_info.Used = true;
3717 eclass = ExprClass.Value;
3718 return e.Resolve (ec);
3721 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3724 if (lvalue_right_side == null)
3725 local_info.Used = true;
3727 if (ec.CurrentAnonymousMethod != null){
3729 // If we are referencing a variable from the external block
3730 // flag it for capturing
3732 if (local_info.Block.Toplevel != ec.CurrentBlock.Toplevel){
3733 if (local_info.AddressTaken){
3734 AnonymousMethod.Error_AddressOfCapturedVar (local_info.Name, loc);
3737 ec.CaptureVariable (local_info);
3744 public override Expression DoResolve (EmitContext ec)
3746 return DoResolveBase (ec, null);
3749 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3751 Expression ret = DoResolveBase (ec, right_side);
3753 CheckObsoleteAttribute (ret.Type);
3758 public bool VerifyFixed (bool is_expression)
3760 return !is_expression || local_info.IsFixed;
3763 public override void Emit (EmitContext ec)
3765 ILGenerator ig = ec.ig;
3767 if (local_info.FieldBuilder == null){
3769 // A local variable on the local CLR stack
3771 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3774 // A local variable captured by anonymous methods.
3777 ec.EmitCapturedVariableInstance (local_info);
3779 ig.Emit (OpCodes.Ldfld, local_info.FieldBuilder);
3783 public void Emit (EmitContext ec, bool leave_copy)
3787 ec.ig.Emit (OpCodes.Dup);
3788 if (local_info.FieldBuilder != null){
3789 temp = new LocalTemporary (ec, Type);
3795 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3797 ILGenerator ig = ec.ig;
3798 prepared = prepare_for_load;
3800 if (local_info.FieldBuilder == null){
3802 // A local variable on the local CLR stack
3804 if (local_info.LocalBuilder == null)
3805 throw new Exception ("This should not happen: both Field and Local are null");
3809 ec.ig.Emit (OpCodes.Dup);
3810 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3813 // A local variable captured by anonymous methods or itereators.
3815 ec.EmitCapturedVariableInstance (local_info);
3817 if (prepare_for_load)
3818 ig.Emit (OpCodes.Dup);
3821 ig.Emit (OpCodes.Dup);
3822 temp = new LocalTemporary (ec, Type);
3825 ig.Emit (OpCodes.Stfld, local_info.FieldBuilder);
3831 public void AddressOf (EmitContext ec, AddressOp mode)
3833 ILGenerator ig = ec.ig;
3835 if (local_info.FieldBuilder == null){
3837 // A local variable on the local CLR stack
3839 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3842 // A local variable captured by anonymous methods or iterators
3844 ec.EmitCapturedVariableInstance (local_info);
3845 ig.Emit (OpCodes.Ldflda, local_info.FieldBuilder);
3849 public override string ToString ()
3851 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3856 /// This represents a reference to a parameter in the intermediate
3859 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3865 public Parameter.Modifier mod;
3866 public bool is_ref, is_out, prepared;
3880 LocalTemporary temp;
3882 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3889 eclass = ExprClass.Variable;
3892 public VariableInfo VariableInfo {
3896 public bool VerifyFixed (bool is_expression)
3898 return !is_expression || TypeManager.IsValueType (type);
3901 public bool IsAssigned (EmitContext ec, Location loc)
3903 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsAssigned (vi))
3906 Report.Error (165, loc,
3907 "Use of unassigned parameter `" + name + "'");
3911 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3913 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3916 Report.Error (170, loc,
3917 "Use of possibly unassigned field `" + field_name + "'");
3921 public void SetAssigned (EmitContext ec)
3923 if (is_out && ec.DoFlowAnalysis)
3924 ec.CurrentBranching.SetAssigned (vi);
3927 public void SetFieldAssigned (EmitContext ec, string field_name)
3929 if (is_out && ec.DoFlowAnalysis)
3930 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3933 protected void DoResolveBase (EmitContext ec)
3935 type = pars.GetParameterInfo (ec, idx, out mod);
3936 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3937 is_out = (mod & Parameter.Modifier.OUT) != 0;
3938 eclass = ExprClass.Variable;
3941 vi = block.ParameterMap [idx];
3943 if (ec.CurrentAnonymousMethod != null){
3945 Report.Error (1628, Location,
3946 "Can not reference a ref or out parameter in an anonymous method");
3951 // If we are referencing the parameter from the external block
3952 // flag it for capturing
3954 //Console.WriteLine ("Is parameter `{0}' local? {1}", name, block.IsLocalParameter (name));
3955 if (!block.IsLocalParameter (name)){
3956 ec.CaptureParameter (name, type, idx);
3962 // Notice that for ref/out parameters, the type exposed is not the
3963 // same type exposed externally.
3966 // externally we expose "int&"
3967 // here we expose "int".
3969 // We record this in "is_ref". This means that the type system can treat
3970 // the type as it is expected, but when we generate the code, we generate
3971 // the alternate kind of code.
3973 public override Expression DoResolve (EmitContext ec)
3977 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3980 if (ec.RemapToProxy)
3981 return ec.RemapParameter (idx);
3986 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3992 if (ec.RemapToProxy)
3993 return ec.RemapParameterLValue (idx, right_side);
3998 static public void EmitLdArg (ILGenerator ig, int x)
4002 case 0: ig.Emit (OpCodes.Ldarg_0); break;
4003 case 1: ig.Emit (OpCodes.Ldarg_1); break;
4004 case 2: ig.Emit (OpCodes.Ldarg_2); break;
4005 case 3: ig.Emit (OpCodes.Ldarg_3); break;
4006 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
4009 ig.Emit (OpCodes.Ldarg, x);
4013 // This method is used by parameters that are references, that are
4014 // being passed as references: we only want to pass the pointer (that
4015 // is already stored in the parameter, not the address of the pointer,
4016 // and not the value of the variable).
4018 public void EmitLoad (EmitContext ec)
4020 ILGenerator ig = ec.ig;
4023 if (!ec.MethodIsStatic)
4027 EmitLdArg (ig, arg_idx);
4030 // FIXME: Review for anonymous methods
4034 public override void Emit (EmitContext ec)
4036 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4037 ec.EmitParameter (name);
4044 public void Emit (EmitContext ec, bool leave_copy)
4046 ILGenerator ig = ec.ig;
4049 if (!ec.MethodIsStatic)
4052 EmitLdArg (ig, arg_idx);
4056 ec.ig.Emit (OpCodes.Dup);
4059 // If we are a reference, we loaded on the stack a pointer
4060 // Now lets load the real value
4062 LoadFromPtr (ig, type);
4066 ec.ig.Emit (OpCodes.Dup);
4069 temp = new LocalTemporary (ec, type);
4075 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
4077 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4078 ec.EmitAssignParameter (name, source, leave_copy, prepare_for_load);
4082 ILGenerator ig = ec.ig;
4085 prepared = prepare_for_load;
4087 if (!ec.MethodIsStatic)
4090 if (is_ref && !prepared)
4091 EmitLdArg (ig, arg_idx);
4096 ec.ig.Emit (OpCodes.Dup);
4100 temp = new LocalTemporary (ec, type);
4104 StoreFromPtr (ig, type);
4110 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
4112 ig.Emit (OpCodes.Starg, arg_idx);
4116 public void AddressOf (EmitContext ec, AddressOp mode)
4118 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4119 ec.EmitAddressOfParameter (name);
4125 if (!ec.MethodIsStatic)
4130 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
4132 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
4135 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
4137 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
4144 /// Used for arguments to New(), Invocation()
4146 public class Argument {
4147 public enum AType : byte {
4154 public readonly AType ArgType;
4155 public Expression Expr;
4157 public Argument (Expression expr, AType type)
4160 this.ArgType = type;
4163 public Argument (Expression expr)
4166 this.ArgType = AType.Expression;
4171 if (ArgType == AType.Ref || ArgType == AType.Out)
4172 return TypeManager.GetReferenceType (Expr.Type);
4178 public Parameter.Modifier GetParameterModifier ()
4182 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
4185 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
4188 return Parameter.Modifier.NONE;
4192 public static string FullDesc (Argument a)
4194 if (a.ArgType == AType.ArgList)
4197 return (a.ArgType == AType.Ref ? "ref " :
4198 (a.ArgType == AType.Out ? "out " : "")) +
4199 TypeManager.CSharpName (a.Expr.Type);
4202 public bool ResolveMethodGroup (EmitContext ec, Location loc)
4204 SimpleName sn = Expr as SimpleName;
4206 Expr = sn.GetMethodGroup ();
4208 // FIXME: csc doesn't report any error if you try to use `ref' or
4209 // `out' in a delegate creation expression.
4210 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4217 void Error_LValueRequired (Location loc)
4219 Report.Error (1510, loc, "An lvalue is required as an argument to out or ref");
4222 public bool Resolve (EmitContext ec, Location loc)
4224 if (ArgType == AType.Ref) {
4225 Expr = Expr.Resolve (ec);
4229 if (!ec.IsConstructor) {
4230 FieldExpr fe = Expr as FieldExpr;
4231 if (fe != null && fe.FieldInfo.IsInitOnly) {
4232 if (fe.FieldInfo.IsStatic)
4233 Report.Error (199, loc, "A static readonly field cannot be passed ref or out (except in a static constructor)");
4235 Report.Error (192, loc, "A readonly field cannot be passed ref or out (except in a constructor)");
4239 Expr = Expr.DoResolveLValue (ec, Expr);
4241 Error_LValueRequired (loc);
4242 } else if (ArgType == AType.Out) {
4243 Expr = Expr.DoResolveLValue (ec, EmptyExpression.Null);
4245 Error_LValueRequired (loc);
4248 Expr = Expr.Resolve (ec);
4253 if (Expr is IMemberExpr) {
4254 IMemberExpr me = Expr as IMemberExpr;
4257 // This can happen with the following code:
4261 // public Y (X x) {}
4265 // public Z () : base (X) {}
4268 // SimpleNameResolve is conservative about flagging the X as
4269 // an error since it has identical name and type. However,
4270 // because there's no MemberAccess, that is not really justified.
4271 // It is still simpler to fix it here, rather than in SimpleNameResolve.
4273 if (me.IsInstance && me.InstanceExpression == null) {
4274 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
4279 if (ArgType == AType.Expression)
4283 // Catch errors where fields of a MarshalByRefObject are passed as ref or out
4284 // This is only allowed for `this'
4286 FieldExpr fe = Expr as FieldExpr;
4287 if (fe != null && !fe.IsStatic){
4288 Expression instance = fe.InstanceExpression;
4290 if (instance.GetType () != typeof (This)){
4291 if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
4292 Report.SymbolRelatedToPreviousError (fe.InstanceExpression.Type);
4293 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",
4301 if (Expr.eclass != ExprClass.Variable){
4303 // We just probe to match the CSC output
4305 if (Expr.eclass == ExprClass.PropertyAccess ||
4306 Expr.eclass == ExprClass.IndexerAccess){
4309 "A property or indexer can not be passed as an out or ref " +
4312 Error_LValueRequired (loc);
4320 public void Emit (EmitContext ec)
4323 // Ref and Out parameters need to have their addresses taken.
4325 // ParameterReferences might already be references, so we want
4326 // to pass just the value
4328 if (ArgType == AType.Ref || ArgType == AType.Out){
4329 AddressOp mode = AddressOp.Store;
4331 if (ArgType == AType.Ref)
4332 mode |= AddressOp.Load;
4334 if (Expr is ParameterReference){
4335 ParameterReference pr = (ParameterReference) Expr;
4341 pr.AddressOf (ec, mode);
4344 if (Expr is IMemoryLocation)
4345 ((IMemoryLocation) Expr).AddressOf (ec, mode);
4348 1510, Expr.Location,
4349 "An lvalue is required as an argument to out or ref");
4359 /// Invocation of methods or delegates.
4361 public class Invocation : ExpressionStatement {
4362 public readonly ArrayList Arguments;
4365 MethodBase method = null;
4368 // arguments is an ArrayList, but we do not want to typecast,
4369 // as it might be null.
4371 // FIXME: only allow expr to be a method invocation or a
4372 // delegate invocation (7.5.5)
4374 public Invocation (Expression expr, ArrayList arguments, Location l)
4377 Arguments = arguments;
4381 public Expression Expr {
4388 /// Determines "better conversion" as specified in 7.4.2.3
4390 /// Returns : p if a->p is better,
4391 /// q if a->q is better,
4392 /// null if neither is better
4394 static Type BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
4396 Type argument_type = TypeManager.TypeToCoreType (a.Type);
4397 Expression argument_expr = a.Expr;
4399 // p = TypeManager.TypeToCoreType (p);
4400 // q = TypeManager.TypeToCoreType (q);
4402 if (argument_type == null)
4403 throw new Exception ("Expression of type " + a.Expr +
4404 " does not resolve its type");
4406 if (p == null || q == null)
4407 throw new InternalErrorException ("BetterConversion Got a null conversion");
4412 if (argument_expr is NullLiteral) {
4414 // If the argument is null and one of the types to compare is 'object' and
4415 // the other is a reference type, we prefer the other.
4417 // This follows from the usual rules:
4418 // * There is an implicit conversion from 'null' to type 'object'
4419 // * There is an implicit conversion from 'null' to any reference type
4420 // * There is an implicit conversion from any reference type to type 'object'
4421 // * There is no implicit conversion from type 'object' to other reference types
4422 // => Conversion of 'null' to a reference type is better than conversion to 'object'
4424 // FIXME: This probably isn't necessary, since the type of a NullLiteral is the
4425 // null type. I think it used to be 'object' and thus needed a special
4426 // case to avoid the immediately following two checks.
4428 if (!p.IsValueType && q == TypeManager.object_type)
4430 if (!q.IsValueType && p == TypeManager.object_type)
4434 if (argument_type == p)
4437 if (argument_type == q)
4440 Expression p_tmp = new EmptyExpression (p);
4441 Expression q_tmp = new EmptyExpression (q);
4443 bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
4444 bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
4446 if (p_to_q && !q_to_p)
4449 if (q_to_p && !p_to_q)
4452 if (p == TypeManager.sbyte_type)
4453 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4454 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4456 if (q == TypeManager.sbyte_type)
4457 if (p == TypeManager.byte_type || p == TypeManager.ushort_type ||
4458 p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4461 if (p == TypeManager.short_type)
4462 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4463 q == TypeManager.uint64_type)
4466 if (q == TypeManager.short_type)
4467 if (p == TypeManager.ushort_type || p == TypeManager.uint32_type ||
4468 p == TypeManager.uint64_type)
4471 if (p == TypeManager.int32_type)
4472 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4475 if (q == TypeManager.int32_type)
4476 if (p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4479 if (p == TypeManager.int64_type)
4480 if (q == TypeManager.uint64_type)
4482 if (q == TypeManager.int64_type)
4483 if (p == TypeManager.uint64_type)
4490 /// Determines "Better function" between candidate
4491 /// and the current best match
4494 /// Returns a boolean indicating :
4495 /// false if candidate ain't better
4496 /// true if candidate is better than the current best match
4498 static bool BetterFunction (EmitContext ec, ArrayList args, int argument_count,
4499 MethodBase candidate, bool candidate_params,
4500 MethodBase best, bool best_params, Location loc)
4502 ParameterData candidate_pd = TypeManager.GetParameterData (candidate);
4503 ParameterData best_pd = TypeManager.GetParameterData (best);
4505 bool better_at_least_one = false;
4507 for (int j = 0; j < argument_count; ++j) {
4508 Argument a = (Argument) args [j];
4510 Type ct = TypeManager.TypeToCoreType (candidate_pd.ParameterType (j));
4511 Type bt = TypeManager.TypeToCoreType (best_pd.ParameterType (j));
4513 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4514 if (candidate_params)
4515 ct = TypeManager.GetElementType (ct);
4517 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4519 bt = TypeManager.GetElementType (bt);
4525 Type better = BetterConversion (ec, a, ct, bt, loc);
4526 // for each argument, the conversion to 'ct' should be no worse than
4527 // the conversion to 'bt'.
4531 // for at least one argument, the conversion to 'ct' should be better than
4532 // the conversion to 'bt'.
4534 better_at_least_one = true;
4537 if (better_at_least_one)
4544 // If two methods have equal parameter types, but
4545 // only one of them is generic, the non-generic one wins.
4547 if (TypeManager.IsGenericMethod (best) && !TypeManager.IsGenericMethod (candidate))
4549 else if (!TypeManager.IsGenericMethod (best) && TypeManager.IsGenericMethod (candidate))
4553 // Note that this is not just an optimization. This handles the case
4554 // This handles the case
4556 // Add (float f1, float f2, float f3);
4557 // Add (params decimal [] foo);
4559 // The call Add (3, 4, 5) should be ambiguous. Without this check, the
4560 // first candidate would've chosen as better.
4563 // This handles the following cases:
4565 // Trim () is better than Trim (params char[] chars)
4566 // Concat (string s1, string s2, string s3) is better than
4567 // Concat (string s1, params string [] srest)
4569 return !candidate_params && best_params;
4572 static bool IsOverride (MethodBase cand_method, MethodBase base_method)
4574 if (!IsAncestralType (base_method.DeclaringType, cand_method.DeclaringType))
4577 ParameterData cand_pd = TypeManager.GetParameterData (cand_method);
4578 ParameterData base_pd = TypeManager.GetParameterData (base_method);
4580 if (cand_pd.Count != base_pd.Count)
4583 for (int j = 0; j < cand_pd.Count; ++j) {
4584 Parameter.Modifier cm = cand_pd.ParameterModifier (j);
4585 Parameter.Modifier bm = base_pd.ParameterModifier (j);
4586 Type ct = TypeManager.TypeToCoreType (cand_pd.ParameterType (j));
4587 Type bt = TypeManager.TypeToCoreType (base_pd.ParameterType (j));
4589 if (cm != bm || ct != bt)
4596 public static string FullMethodDesc (MethodBase mb)
4598 string ret_type = "";
4603 if (mb is MethodInfo)
4604 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
4606 StringBuilder sb = new StringBuilder (ret_type);
4608 sb.Append (mb.ReflectedType.ToString ());
4610 sb.Append (mb.Name);
4612 ParameterData pd = TypeManager.GetParameterData (mb);
4614 int count = pd.Count;
4617 for (int i = count; i > 0; ) {
4620 sb.Append (pd.ParameterDesc (count - i - 1));
4626 return sb.ToString ();
4629 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4631 MemberInfo [] miset;
4632 MethodGroupExpr union;
4637 return (MethodGroupExpr) mg2;
4640 return (MethodGroupExpr) mg1;
4643 MethodGroupExpr left_set = null, right_set = null;
4644 int length1 = 0, length2 = 0;
4646 left_set = (MethodGroupExpr) mg1;
4647 length1 = left_set.Methods.Length;
4649 right_set = (MethodGroupExpr) mg2;
4650 length2 = right_set.Methods.Length;
4652 ArrayList common = new ArrayList ();
4654 foreach (MethodBase r in right_set.Methods){
4655 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
4659 miset = new MemberInfo [length1 + length2 - common.Count];
4660 left_set.Methods.CopyTo (miset, 0);
4664 foreach (MethodBase r in right_set.Methods) {
4665 if (!common.Contains (r))
4669 union = new MethodGroupExpr (miset, loc);
4674 public static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4675 ArrayList arguments, int arg_count,
4676 ref MethodBase candidate)
4678 return IsParamsMethodApplicable (
4679 ec, me, arguments, arg_count, false, ref candidate) ||
4680 IsParamsMethodApplicable (
4681 ec, me, arguments, arg_count, true, ref candidate);
4686 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4687 ArrayList arguments, int arg_count,
4688 bool do_varargs, ref MethodBase candidate)
4690 if (!me.HasTypeArguments &&
4691 !TypeManager.InferParamsTypeArguments (ec, arguments, ref candidate))
4694 return IsParamsMethodApplicable (
4695 ec, arguments, arg_count, candidate, do_varargs);
4699 /// Determines if the candidate method, if a params method, is applicable
4700 /// in its expanded form to the given set of arguments
4702 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
4703 int arg_count, MethodBase candidate,
4706 ParameterData pd = TypeManager.GetParameterData (candidate);
4708 int pd_count = pd.Count;
4713 int count = pd_count - 1;
4715 if (pd.ParameterModifier (count) != Parameter.Modifier.ARGLIST)
4717 if (pd_count != arg_count)
4720 if (pd.ParameterModifier (count) != Parameter.Modifier.PARAMS)
4724 if (count > arg_count)
4727 if (pd_count == 1 && arg_count == 0)
4731 // If we have come this far, the case which
4732 // remains is when the number of parameters is
4733 // less than or equal to the argument count.
4735 for (int i = 0; i < count; ++i) {
4737 Argument a = (Argument) arguments [i];
4739 Parameter.Modifier a_mod = a.GetParameterModifier () &
4740 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4741 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4742 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4744 if (a_mod == p_mod) {
4746 if (a_mod == Parameter.Modifier.NONE)
4747 if (!Convert.ImplicitConversionExists (ec,
4749 pd.ParameterType (i)))
4752 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4753 Type pt = pd.ParameterType (i);
4756 pt = TypeManager.GetReferenceType (pt);
4767 Argument a = (Argument) arguments [count];
4768 if (!(a.Expr is Arglist))
4774 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4776 for (int i = pd_count - 1; i < arg_count; i++) {
4777 Argument a = (Argument) arguments [i];
4779 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4786 public static bool IsApplicable (EmitContext ec, MethodGroupExpr me,
4787 ArrayList arguments, int arg_count,
4788 ref MethodBase candidate)
4790 if (!me.HasTypeArguments &&
4791 !TypeManager.InferTypeArguments (ec, arguments, ref candidate))
4794 return IsApplicable (ec, arguments, arg_count, candidate);
4798 /// Determines if the candidate method is applicable (section 14.4.2.1)
4799 /// to the given set of arguments
4801 static bool IsApplicable (EmitContext ec, ArrayList arguments, int arg_count,
4802 MethodBase candidate)
4804 ParameterData pd = TypeManager.GetParameterData (candidate);
4806 if (arg_count != pd.Count)
4809 for (int i = arg_count; i > 0; ) {
4812 Argument a = (Argument) arguments [i];
4814 Parameter.Modifier a_mod = a.GetParameterModifier () &
4815 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4816 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4817 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4820 if (a_mod == p_mod ||
4821 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4822 if (a_mod == Parameter.Modifier.NONE) {
4823 if (!Convert.ImplicitConversionExists (ec,
4825 pd.ParameterType (i)))
4829 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4830 Type pt = pd.ParameterType (i);
4833 pt = TypeManager.GetReferenceType (pt);
4845 static private bool IsAncestralType (Type first_type, Type second_type)
4847 return first_type != second_type &&
4848 (second_type.IsSubclassOf (first_type) ||
4849 TypeManager.ImplementsInterface (second_type, first_type));
4853 /// Find the Applicable Function Members (7.4.2.1)
4855 /// me: Method Group expression with the members to select.
4856 /// it might contain constructors or methods (or anything
4857 /// that maps to a method).
4859 /// Arguments: ArrayList containing resolved Argument objects.
4861 /// loc: The location if we want an error to be reported, or a Null
4862 /// location for "probing" purposes.
4864 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4865 /// that is the best match of me on Arguments.
4868 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4869 ArrayList Arguments, bool may_fail,
4872 MethodBase method = null;
4873 bool method_params = false;
4874 Type applicable_type = null;
4876 ArrayList candidates = new ArrayList ();
4877 ArrayList candidate_overrides = new ArrayList ();
4880 // Used to keep a map between the candidate
4881 // and whether it is being considered in its
4882 // normal or expanded form
4884 // false is normal form, true is expanded form
4886 Hashtable candidate_to_form = null;
4888 if (Arguments != null)
4889 arg_count = Arguments.Count;
4891 if ((me.Name == "Invoke") &&
4892 TypeManager.IsDelegateType (me.DeclaringType)) {
4893 Error_InvokeOnDelegate (loc);
4897 MethodBase[] methods = me.Methods;
4900 // First we construct the set of applicable methods
4902 bool is_sorted = true;
4903 for (int i = 0; i < methods.Length; i++){
4904 Type decl_type = methods [i].DeclaringType;
4907 // If we have already found an applicable method
4908 // we eliminate all base types (Section 14.5.5.1)
4910 if ((applicable_type != null) &&
4911 IsAncestralType (decl_type, applicable_type))
4915 // Methods marked 'override' don't take part in 'applicable_type'
4916 // computation, nor in the actual overload resolution.
4917 // However, they still need to be emitted instead of a base virtual method.
4918 // We avoid doing the 'applicable' test here, since it'll anyway be applied
4919 // to the base virtual function, and IsOverride is much faster than IsApplicable.
4922 methods [i].IsVirtual &&
4923 (methods [i].Attributes & MethodAttributes.NewSlot) == 0) {
4924 candidate_overrides.Add (methods [i]);
4929 // Check if candidate is applicable (section 14.4.2.1)
4930 // Is candidate applicable in normal form?
4932 bool is_applicable = IsApplicable (
4933 ec, me, Arguments, arg_count, ref methods [i]);
4935 if (!is_applicable &&
4936 (IsParamsMethodApplicable (
4937 ec, me, Arguments, arg_count, ref methods [i]))) {
4938 MethodBase candidate = methods [i];
4939 if (candidate_to_form == null)
4940 candidate_to_form = new PtrHashtable ();
4941 candidate_to_form [candidate] = candidate;
4942 // Candidate is applicable in expanded form
4943 is_applicable = true;
4949 candidates.Add (methods [i]);
4951 if (applicable_type == null)
4952 applicable_type = decl_type;
4953 else if (applicable_type != decl_type) {
4955 if (IsAncestralType (applicable_type, decl_type))
4956 applicable_type = decl_type;
4960 int candidate_top = candidates.Count;
4962 if (applicable_type == null) {
4964 // Okay so we have failed to find anything so we
4965 // return by providing info about the closest match
4967 for (int i = 0; i < methods.Length; ++i) {
4968 MethodBase c = (MethodBase) methods [i];
4969 ParameterData pd = TypeManager.GetParameterData (c);
4971 if (pd.Count != arg_count)
4974 if (!TypeManager.InferTypeArguments (ec, Arguments, ref c))
4977 VerifyArgumentsCompat (ec, Arguments, arg_count,
4978 c, false, null, may_fail, loc);
4983 string report_name = me.Name;
4984 if (report_name == ".ctor")
4985 report_name = me.DeclaringType.ToString ();
4987 for (int i = 0; i < methods.Length; ++i) {
4988 MethodBase c = methods [i];
4989 ParameterData pd = TypeManager.GetParameterData (c);
4991 if (pd.Count != arg_count)
4994 if (TypeManager.InferTypeArguments (ec, Arguments, ref c))
4998 411, loc, "The type arguments for " +
4999 "method `{0}' cannot be infered from " +
5000 "the usage. Try specifying the type " +
5001 "arguments explicitly.", report_name);
5005 Error_WrongNumArguments (
5006 loc, report_name, arg_count);
5015 // At this point, applicable_type is _one_ of the most derived types
5016 // in the set of types containing the methods in this MethodGroup.
5017 // Filter the candidates so that they only contain methods from the
5018 // most derived types.
5021 int finalized = 0; // Number of finalized candidates
5024 // Invariant: applicable_type is a most derived type
5026 // We'll try to complete Section 14.5.5.1 for 'applicable_type' by
5027 // eliminating all it's base types. At the same time, we'll also move
5028 // every unrelated type to the end of the array, and pick the next
5029 // 'applicable_type'.
5031 Type next_applicable_type = null;
5032 int j = finalized; // where to put the next finalized candidate
5033 int k = finalized; // where to put the next undiscarded candidate
5034 for (int i = finalized; i < candidate_top; ++i) {
5035 MethodBase candidate = (MethodBase) candidates [i];
5036 Type decl_type = candidate.DeclaringType;
5038 if (decl_type == applicable_type) {
5039 candidates [k++] = candidates [j];
5040 candidates [j++] = candidates [i];
5044 if (IsAncestralType (decl_type, applicable_type))
5047 if (next_applicable_type != null &&
5048 IsAncestralType (decl_type, next_applicable_type))
5051 candidates [k++] = candidates [i];
5053 if (next_applicable_type == null ||
5054 IsAncestralType (next_applicable_type, decl_type))
5055 next_applicable_type = decl_type;
5058 applicable_type = next_applicable_type;
5061 } while (applicable_type != null);
5065 // Now we actually find the best method
5068 method = (MethodBase) candidates [0];
5069 method_params = candidate_to_form != null && candidate_to_form.Contains (method);
5070 for (int ix = 1; ix < candidate_top; ix++){
5071 MethodBase candidate = (MethodBase) candidates [ix];
5073 if (candidate == method)
5076 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
5078 if (BetterFunction (ec, Arguments, arg_count,
5079 candidate, cand_params,
5080 method, method_params, loc)) {
5082 method_params = cand_params;
5087 // Now check that there are no ambiguities i.e the selected method
5088 // should be better than all the others
5090 bool ambiguous = false;
5091 for (int ix = 0; ix < candidate_top; ix++){
5092 MethodBase candidate = (MethodBase) candidates [ix];
5094 if (candidate == method)
5097 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
5098 if (!BetterFunction (ec, Arguments, arg_count,
5099 method, method_params,
5100 candidate, cand_params,
5102 Report.SymbolRelatedToPreviousError (candidate);
5108 Report.SymbolRelatedToPreviousError (method);
5109 Report.Error (121, loc, "Ambiguous call when selecting function due to implicit casts");
5114 // If the method is a virtual function, pick an override closer to the LHS type.
5116 if (!me.IsBase && method.IsVirtual) {
5117 if ((method.Attributes & MethodAttributes.NewSlot) != MethodAttributes.NewSlot)
5118 throw new InternalErrorException (
5119 "Should not happen. An 'override' method took part in overload resolution: " + method);
5121 foreach (MethodBase candidate in candidate_overrides) {
5122 if (IsOverride (candidate, method))
5128 // And now check if the arguments are all
5129 // compatible, perform conversions if
5130 // necessary etc. and return if everything is
5133 if (!VerifyArgumentsCompat (ec, Arguments, arg_count, method,
5134 method_params, null, may_fail, loc))
5140 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
5142 Report.Error (1501, loc,
5143 "No overload for method `" + name + "' takes `" +
5144 arg_count + "' arguments");
5147 static void Error_InvokeOnDelegate (Location loc)
5149 Report.Error (1533, loc,
5150 "Invoke cannot be called directly on a delegate");
5153 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
5154 Type delegate_type, string arg_sig, string par_desc)
5156 if (delegate_type == null)
5157 Report.Error (1502, loc,
5158 "The best overloaded match for method '" +
5159 FullMethodDesc (method) +
5160 "' has some invalid arguments");
5162 Report.Error (1594, loc,
5163 "Delegate '" + delegate_type.ToString () +
5164 "' has some invalid arguments.");
5165 Report.Error (1503, loc,
5166 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
5167 idx, arg_sig, par_desc));
5170 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
5171 int arg_count, MethodBase method,
5172 bool chose_params_expanded,
5173 Type delegate_type, bool may_fail,
5176 ParameterData pd = TypeManager.GetParameterData (method);
5177 int pd_count = pd.Count;
5179 for (int j = 0; j < arg_count; j++) {
5180 Argument a = (Argument) Arguments [j];
5181 Expression a_expr = a.Expr;
5182 Type parameter_type = pd.ParameterType (j);
5183 Parameter.Modifier pm = pd.ParameterModifier (j);
5185 if (pm == Parameter.Modifier.PARAMS){
5186 if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
5188 Error_InvalidArguments (
5189 loc, j, method, delegate_type,
5190 Argument.FullDesc (a), pd.ParameterDesc (j));
5194 if (chose_params_expanded)
5195 parameter_type = TypeManager.GetElementType (parameter_type);
5196 } else if (pm == Parameter.Modifier.ARGLIST){
5202 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
5204 Error_InvalidArguments (
5205 loc, j, method, delegate_type,
5206 Argument.FullDesc (a), pd.ParameterDesc (j));
5214 if (!TypeManager.IsEqual (a.Type, parameter_type)){
5217 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
5221 Error_InvalidArguments (
5222 loc, j, method, delegate_type,
5223 Argument.FullDesc (a), pd.ParameterDesc (j));
5228 // Update the argument with the implicit conversion
5234 if (parameter_type.IsPointer){
5241 Parameter.Modifier a_mod = a.GetParameterModifier () &
5242 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5243 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
5244 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5246 if (a_mod != p_mod &&
5247 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
5249 Report.Error (1502, loc,
5250 "The best overloaded match for method '" + FullMethodDesc (method)+
5251 "' has some invalid arguments");
5252 Report.Error (1503, loc,
5253 "Argument " + (j+1) +
5254 ": Cannot convert from '" + Argument.FullDesc (a)
5255 + "' to '" + pd.ParameterDesc (j) + "'");
5265 public override Expression DoResolve (EmitContext ec)
5268 // First, resolve the expression that is used to
5269 // trigger the invocation
5271 SimpleName sn = expr as SimpleName;
5273 expr = sn.GetMethodGroup ();
5275 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
5279 if (!(expr is MethodGroupExpr)) {
5280 Type expr_type = expr.Type;
5282 if (expr_type != null){
5283 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
5285 return (new DelegateInvocation (
5286 this.expr, Arguments, loc)).Resolve (ec);
5290 if (!(expr is MethodGroupExpr)){
5291 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup, loc);
5296 // Next, evaluate all the expressions in the argument list
5298 if (Arguments != null){
5299 foreach (Argument a in Arguments){
5300 if (!a.Resolve (ec, loc))
5305 MethodGroupExpr mg = (MethodGroupExpr) expr;
5306 method = OverloadResolve (ec, mg, Arguments, false, loc);
5311 MethodInfo mi = method as MethodInfo;
5313 type = TypeManager.TypeToCoreType (mi.ReturnType);
5314 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null)) {
5315 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
5319 Expression iexpr = mg.InstanceExpression;
5320 if (mi.IsStatic && (iexpr != null) && !(iexpr is This)) {
5321 if (mg.IdenticalTypeName)
5322 mg.InstanceExpression = null;
5324 MemberAccess.error176 (loc, mi.Name);
5330 if (type.IsPointer){
5338 // Only base will allow this invocation to happen.
5340 if (mg.IsBase && method.IsAbstract){
5341 Report.Error (205, loc, "Cannot call an abstract base member: " +
5342 FullMethodDesc (method));
5346 if (method.Name == "Finalize" && Arguments == null) {
5348 Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
5350 Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
5354 if ((method.Attributes & MethodAttributes.SpecialName) != 0){
5355 if (TypeManager.LookupDeclSpace (method.DeclaringType) != null || TypeManager.IsSpecialMethod (method)) {
5356 Report.Error (571, loc, TypeManager.CSharpSignature (method) + ": can not call operator or accessor");
5361 if (mg.InstanceExpression != null)
5362 mg.InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
5364 eclass = ExprClass.Value;
5369 // Emits the list of arguments as an array
5371 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
5373 ILGenerator ig = ec.ig;
5374 int count = arguments.Count - idx;
5375 Argument a = (Argument) arguments [idx];
5376 Type t = a.Expr.Type;
5378 IntConstant.EmitInt (ig, count);
5379 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
5381 int top = arguments.Count;
5382 for (int j = idx; j < top; j++){
5383 a = (Argument) arguments [j];
5385 ig.Emit (OpCodes.Dup);
5386 IntConstant.EmitInt (ig, j - idx);
5388 bool is_stobj, has_type_arg;
5389 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj, out has_type_arg);
5391 ig.Emit (OpCodes.Ldelema, t);
5403 /// Emits a list of resolved Arguments that are in the arguments
5406 /// The MethodBase argument might be null if the
5407 /// emission of the arguments is known not to contain
5408 /// a `params' field (for example in constructors or other routines
5409 /// that keep their arguments in this structure)
5411 /// if `dup_args' is true, a copy of the arguments will be left
5412 /// on the stack. If `dup_args' is true, you can specify `this_arg'
5413 /// which will be duplicated before any other args. Only EmitCall
5414 /// should be using this interface.
5416 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments, bool dup_args, LocalTemporary this_arg)
5420 pd = TypeManager.GetParameterData (mb);
5424 LocalTemporary [] temps = null;
5427 temps = new LocalTemporary [arguments.Count];
5430 // If we are calling a params method with no arguments, special case it
5432 if (arguments == null){
5433 if (pd != null && pd.Count > 0 &&
5434 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
5435 ILGenerator ig = ec.ig;
5437 IntConstant.EmitInt (ig, 0);
5438 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
5444 int top = arguments.Count;
5446 for (int i = 0; i < top; i++){
5447 Argument a = (Argument) arguments [i];
5450 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
5452 // Special case if we are passing the same data as the
5453 // params argument, do not put it in an array.
5455 if (pd.ParameterType (i) == a.Type)
5458 EmitParams (ec, i, arguments);
5465 ec.ig.Emit (OpCodes.Dup);
5466 (temps [i] = new LocalTemporary (ec, a.Type)).Store (ec);
5471 if (this_arg != null)
5474 for (int i = 0; i < top; i ++)
5475 temps [i].Emit (ec);
5478 if (pd != null && pd.Count > top &&
5479 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
5480 ILGenerator ig = ec.ig;
5482 IntConstant.EmitInt (ig, 0);
5483 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
5487 static Type[] GetVarargsTypes (EmitContext ec, MethodBase mb,
5488 ArrayList arguments)
5490 ParameterData pd = TypeManager.GetParameterData (mb);
5492 if (arguments == null)
5493 return new Type [0];
5495 Argument a = (Argument) arguments [pd.Count - 1];
5496 Arglist list = (Arglist) a.Expr;
5498 return list.ArgumentTypes;
5502 /// This checks the ConditionalAttribute on the method
5504 static bool IsMethodExcluded (MethodBase method, EmitContext ec)
5506 if (method.IsConstructor)
5509 IMethodData md = TypeManager.GetMethod (method);
5511 return md.IsExcluded (ec);
5513 // For some methods (generated by delegate class) GetMethod returns null
5514 // because they are not included in builder_to_method table
5515 if (method.DeclaringType is TypeBuilder)
5518 return AttributeTester.IsConditionalMethodExcluded (method);
5522 /// is_base tells whether we want to force the use of the `call'
5523 /// opcode instead of using callvirt. Call is required to call
5524 /// a specific method, while callvirt will always use the most
5525 /// recent method in the vtable.
5527 /// is_static tells whether this is an invocation on a static method
5529 /// instance_expr is an expression that represents the instance
5530 /// it must be non-null if is_static is false.
5532 /// method is the method to invoke.
5534 /// Arguments is the list of arguments to pass to the method or constructor.
5536 public static void EmitCall (EmitContext ec, bool is_base,
5537 bool is_static, Expression instance_expr,
5538 MethodBase method, ArrayList Arguments, Location loc)
5540 EmitCall (ec, is_base, is_static, instance_expr, method, Arguments, loc, false, false);
5543 // `dup_args' leaves an extra copy of the arguments on the stack
5544 // `omit_args' does not leave any arguments at all.
5545 // So, basically, you could make one call with `dup_args' set to true,
5546 // and then another with `omit_args' set to true, and the two calls
5547 // would have the same set of arguments. However, each argument would
5548 // only have been evaluated once.
5549 public static void EmitCall (EmitContext ec, bool is_base,
5550 bool is_static, Expression instance_expr,
5551 MethodBase method, ArrayList Arguments, Location loc,
5552 bool dup_args, bool omit_args)
5554 ILGenerator ig = ec.ig;
5555 bool struct_call = false;
5556 bool this_call = false;
5557 LocalTemporary this_arg = null;
5559 Type decl_type = method.DeclaringType;
5561 if (!RootContext.StdLib) {
5562 // Replace any calls to the system's System.Array type with calls to
5563 // the newly created one.
5564 if (method == TypeManager.system_int_array_get_length)
5565 method = TypeManager.int_array_get_length;
5566 else if (method == TypeManager.system_int_array_get_rank)
5567 method = TypeManager.int_array_get_rank;
5568 else if (method == TypeManager.system_object_array_clone)
5569 method = TypeManager.object_array_clone;
5570 else if (method == TypeManager.system_int_array_get_length_int)
5571 method = TypeManager.int_array_get_length_int;
5572 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5573 method = TypeManager.int_array_get_lower_bound_int;
5574 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5575 method = TypeManager.int_array_get_upper_bound_int;
5576 else if (method == TypeManager.system_void_array_copyto_array_int)
5577 method = TypeManager.void_array_copyto_array_int;
5580 if (ec.TestObsoleteMethodUsage) {
5582 // This checks ObsoleteAttribute on the method and on the declaring type
5584 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
5586 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
5588 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
5590 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
5594 if (IsMethodExcluded (method, ec))
5598 this_call = instance_expr == null;
5599 if (decl_type.IsValueType || (!this_call && instance_expr.Type.IsValueType))
5603 // If this is ourselves, push "this"
5608 ig.Emit (OpCodes.Ldarg_0);
5611 Type iexpr_type = instance_expr.Type;
5614 // Push the instance expression
5616 if (TypeManager.IsValueType (iexpr_type)) {
5618 // Special case: calls to a function declared in a
5619 // reference-type with a value-type argument need
5620 // to have their value boxed.
5621 if (decl_type.IsValueType ||
5622 iexpr_type.IsGenericParameter) {
5624 // If the expression implements IMemoryLocation, then
5625 // we can optimize and use AddressOf on the
5628 // If not we have to use some temporary storage for
5630 if (instance_expr is IMemoryLocation) {
5631 ((IMemoryLocation)instance_expr).
5632 AddressOf (ec, AddressOp.LoadStore);
5634 LocalTemporary temp = new LocalTemporary (ec, iexpr_type);
5635 instance_expr.Emit (ec);
5637 temp.AddressOf (ec, AddressOp.Load);
5640 // avoid the overhead of doing this all the time.
5642 t = TypeManager.GetReferenceType (iexpr_type);
5644 instance_expr.Emit (ec);
5645 ig.Emit (OpCodes.Box, instance_expr.Type);
5646 t = TypeManager.object_type;
5649 instance_expr.Emit (ec);
5650 t = instance_expr.Type;
5655 this_arg = new LocalTemporary (ec, t);
5656 ig.Emit (OpCodes.Dup);
5657 this_arg.Store (ec);
5663 EmitArguments (ec, method, Arguments, dup_args, this_arg);
5665 if ((instance_expr != null) && (instance_expr.Type.IsGenericParameter))
5666 ig.Emit (OpCodes.Constrained, instance_expr.Type);
5669 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
5670 call_op = OpCodes.Call;
5672 call_op = OpCodes.Callvirt;
5674 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
5675 Type[] varargs_types = GetVarargsTypes (ec, method, Arguments);
5676 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
5683 // and DoFoo is not virtual, you can omit the callvirt,
5684 // because you don't need the null checking behavior.
5686 if (method is MethodInfo)
5687 ig.Emit (call_op, (MethodInfo) method);
5689 ig.Emit (call_op, (ConstructorInfo) method);
5692 public override void Emit (EmitContext ec)
5694 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5696 EmitCall (ec, mg.IsBase, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5699 public override void EmitStatement (EmitContext ec)
5704 // Pop the return value if there is one
5706 if (method is MethodInfo){
5707 Type ret = ((MethodInfo)method).ReturnType;
5708 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5709 ec.ig.Emit (OpCodes.Pop);
5714 public class InvocationOrCast : ExpressionStatement
5717 Expression argument;
5719 public InvocationOrCast (Expression expr, Expression argument, Location loc)
5722 this.argument = argument;
5726 public override Expression DoResolve (EmitContext ec)
5729 // First try to resolve it as a cast.
5731 TypeExpr te = expr.ResolveAsTypeStep (ec) as TypeExpr;
5732 if ((te != null) && (te.eclass == ExprClass.Type)) {
5733 Cast cast = new Cast (te, argument, loc);
5734 return cast.Resolve (ec);
5738 // This can either be a type or a delegate invocation.
5739 // Let's just resolve it and see what we'll get.
5741 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5746 // Ok, so it's a Cast.
5748 if (expr.eclass == ExprClass.Type) {
5749 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
5750 return cast.Resolve (ec);
5754 // It's a delegate invocation.
5756 if (!TypeManager.IsDelegateType (expr.Type)) {
5757 Error (149, "Method name expected");
5761 ArrayList args = new ArrayList ();
5762 args.Add (new Argument (argument, Argument.AType.Expression));
5763 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5764 return invocation.Resolve (ec);
5769 Error (201, "Only assignment, call, increment, decrement and new object " +
5770 "expressions can be used as a statement");
5773 public override ExpressionStatement ResolveStatement (EmitContext ec)
5776 // First try to resolve it as a cast.
5778 TypeExpr te = expr.ResolveAsTypeStep (ec) as TypeExpr;
5779 if ((te != null) && (te.eclass == ExprClass.Type)) {
5785 // This can either be a type or a delegate invocation.
5786 // Let's just resolve it and see what we'll get.
5788 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5789 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5795 // It's a delegate invocation.
5797 if (!TypeManager.IsDelegateType (expr.Type)) {
5798 Error (149, "Method name expected");
5802 ArrayList args = new ArrayList ();
5803 args.Add (new Argument (argument, Argument.AType.Expression));
5804 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5805 return invocation.ResolveStatement (ec);
5808 public override void Emit (EmitContext ec)
5810 throw new Exception ("Cannot happen");
5813 public override void EmitStatement (EmitContext ec)
5815 throw new Exception ("Cannot happen");
5820 // This class is used to "disable" the code generation for the
5821 // temporary variable when initializing value types.
5823 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5824 public void AddressOf (EmitContext ec, AddressOp Mode)
5831 /// Implements the new expression
5833 public class New : ExpressionStatement, IMemoryLocation {
5834 public readonly ArrayList Arguments;
5837 // During bootstrap, it contains the RequestedType,
5838 // but if `type' is not null, it *might* contain a NewDelegate
5839 // (because of field multi-initialization)
5841 public Expression RequestedType;
5843 MethodBase method = null;
5846 // If set, the new expression is for a value_target, and
5847 // we will not leave anything on the stack.
5849 Expression value_target;
5850 bool value_target_set = false;
5851 bool is_type_parameter = false;
5853 public New (Expression requested_type, ArrayList arguments, Location l)
5855 RequestedType = requested_type;
5856 Arguments = arguments;
5860 public bool SetValueTypeVariable (Expression value)
5862 value_target = value;
5863 value_target_set = true;
5864 if (!(value_target is IMemoryLocation)){
5865 Error_UnexpectedKind ("variable", loc);
5872 // This function is used to disable the following code sequence for
5873 // value type initialization:
5875 // AddressOf (temporary)
5879 // Instead the provide will have provided us with the address on the
5880 // stack to store the results.
5882 static Expression MyEmptyExpression;
5884 public void DisableTemporaryValueType ()
5886 if (MyEmptyExpression == null)
5887 MyEmptyExpression = new EmptyAddressOf ();
5890 // To enable this, look into:
5891 // test-34 and test-89 and self bootstrapping.
5893 // For instance, we can avoid a copy by using `newobj'
5894 // instead of Call + Push-temp on value types.
5895 // value_target = MyEmptyExpression;
5900 /// Converts complex core type syntax like 'new int ()' to simple constant
5902 Expression Constantify (Type t)
5904 if (t == TypeManager.int32_type)
5905 return new IntConstant (0);
5906 if (t == TypeManager.uint32_type)
5907 return new UIntConstant (0);
5908 if (t == TypeManager.int64_type)
5909 return new LongConstant (0);
5910 if (t == TypeManager.uint64_type)
5911 return new ULongConstant (0);
5912 if (t == TypeManager.float_type)
5913 return new FloatConstant (0);
5914 if (t == TypeManager.double_type)
5915 return new DoubleConstant (0);
5916 if (t == TypeManager.short_type)
5917 return new ShortConstant (0);
5918 if (t == TypeManager.ushort_type)
5919 return new UShortConstant (0);
5920 if (t == TypeManager.sbyte_type)
5921 return new SByteConstant (0);
5922 if (t == TypeManager.byte_type)
5923 return new ByteConstant (0);
5924 if (t == TypeManager.char_type)
5925 return new CharConstant ('\0');
5926 if (t == TypeManager.bool_type)
5927 return new BoolConstant (false);
5928 if (t == TypeManager.decimal_type)
5929 return new DecimalConstant (0);
5934 public override Expression DoResolve (EmitContext ec)
5937 // The New DoResolve might be called twice when initializing field
5938 // expressions (see EmitFieldInitializers, the call to
5939 // GetInitializerExpression will perform a resolve on the expression,
5940 // and later the assign will trigger another resolution
5942 // This leads to bugs (#37014)
5945 if (RequestedType is NewDelegate)
5946 return RequestedType;
5950 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec);
5954 if (Arguments == null) {
5955 Expression c = Constantify (type);
5964 CheckObsoleteAttribute (type);
5966 bool IsDelegate = TypeManager.IsDelegateType (type);
5969 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5970 if (RequestedType != null)
5971 if (!(RequestedType is DelegateCreation))
5972 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
5973 return RequestedType;
5976 if (type.IsGenericParameter) {
5977 if (!TypeManager.HasConstructorConstraint (type)) {
5978 Error (304, String.Format (
5979 "Cannot create an instance of the " +
5980 "variable type '{0}' because it " +
5981 "doesn't have the new() constraint",
5986 if ((Arguments != null) && (Arguments.Count != 0)) {
5987 Error (417, String.Format (
5988 "`{0}': cannot provide arguments " +
5989 "when creating an instance of a " +
5990 "variable type.", type));
5994 is_type_parameter = true;
5995 eclass = ExprClass.Value;
5999 if (type.IsInterface || type.IsAbstract){
6000 Error (144, "It is not possible to create instances of interfaces or abstract classes");
6004 if (type.IsAbstract && type.IsSealed) {
6005 Report.Error (712, loc, "Cannot create an instance of the static class '{0}'", TypeManager.CSharpName (type));
6009 bool is_struct = type.IsValueType;
6010 eclass = ExprClass.Value;
6013 // SRE returns a match for .ctor () on structs (the object constructor),
6014 // so we have to manually ignore it.
6016 if (is_struct && Arguments == null)
6020 ml = MemberLookupFinal (ec, type, type, ".ctor",
6021 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
6022 MemberTypes.Constructor,
6023 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
6028 if (! (ml is MethodGroupExpr)){
6030 ml.Error_UnexpectedKind ("method group", loc);
6036 if (Arguments != null){
6037 foreach (Argument a in Arguments){
6038 if (!a.Resolve (ec, loc))
6043 method = Invocation.OverloadResolve (
6044 ec, (MethodGroupExpr) ml, Arguments, true, loc);
6048 if (method == null) {
6049 if (almostMatchedMembers.Count != 0) {
6050 MemberLookupFailed (ec, type, type, ".ctor", null, true, loc);
6054 if (!is_struct || Arguments.Count > 0) {
6055 Error (1501, String.Format (
6056 "New invocation: Can not find a constructor in `{0}' for this argument list",
6057 TypeManager.CSharpName (type)));
6065 bool DoEmitTypeParameter (EmitContext ec)
6067 ILGenerator ig = ec.ig;
6069 ig.Emit (OpCodes.Ldtoken, type);
6070 ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6071 ig.Emit (OpCodes.Call, TypeManager.activator_create_instance);
6072 ig.Emit (OpCodes.Unbox_Any, type);
6078 // This DoEmit can be invoked in two contexts:
6079 // * As a mechanism that will leave a value on the stack (new object)
6080 // * As one that wont (init struct)
6082 // You can control whether a value is required on the stack by passing
6083 // need_value_on_stack. The code *might* leave a value on the stack
6084 // so it must be popped manually
6086 // If we are dealing with a ValueType, we have a few
6087 // situations to deal with:
6089 // * The target is a ValueType, and we have been provided
6090 // the instance (this is easy, we are being assigned).
6092 // * The target of New is being passed as an argument,
6093 // to a boxing operation or a function that takes a
6096 // In this case, we need to create a temporary variable
6097 // that is the argument of New.
6099 // Returns whether a value is left on the stack
6101 bool DoEmit (EmitContext ec, bool need_value_on_stack)
6103 bool is_value_type = TypeManager.IsValueType (type);
6104 ILGenerator ig = ec.ig;
6109 // Allow DoEmit() to be called multiple times.
6110 // We need to create a new LocalTemporary each time since
6111 // you can't share LocalBuilders among ILGeneators.
6112 if (!value_target_set)
6113 value_target = new LocalTemporary (ec, type);
6115 ml = (IMemoryLocation) value_target;
6116 ml.AddressOf (ec, AddressOp.Store);
6120 Invocation.EmitArguments (ec, method, Arguments, false, null);
6124 ig.Emit (OpCodes.Initobj, type);
6126 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6127 if (need_value_on_stack){
6128 value_target.Emit (ec);
6133 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
6138 public override void Emit (EmitContext ec)
6140 if (is_type_parameter)
6141 DoEmitTypeParameter (ec);
6146 public override void EmitStatement (EmitContext ec)
6148 if (is_type_parameter)
6149 throw new InvalidOperationException ();
6151 if (DoEmit (ec, false))
6152 ec.ig.Emit (OpCodes.Pop);
6155 public void AddressOf (EmitContext ec, AddressOp Mode)
6157 if (is_type_parameter)
6158 throw new InvalidOperationException ();
6160 if (!type.IsValueType){
6162 // We throw an exception. So far, I believe we only need to support
6164 // foreach (int j in new StructType ())
6167 throw new Exception ("AddressOf should not be used for classes");
6170 if (!value_target_set)
6171 value_target = new LocalTemporary (ec, type);
6173 IMemoryLocation ml = (IMemoryLocation) value_target;
6174 ml.AddressOf (ec, AddressOp.Store);
6176 Invocation.EmitArguments (ec, method, Arguments, false, null);
6179 ec.ig.Emit (OpCodes.Initobj, type);
6181 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6183 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
6188 /// 14.5.10.2: Represents an array creation expression.
6192 /// There are two possible scenarios here: one is an array creation
6193 /// expression that specifies the dimensions and optionally the
6194 /// initialization data and the other which does not need dimensions
6195 /// specified but where initialization data is mandatory.
6197 public class ArrayCreation : Expression {
6198 Expression requested_base_type;
6199 ArrayList initializers;
6202 // The list of Argument types.
6203 // This is used to construct the `newarray' or constructor signature
6205 ArrayList arguments;
6208 // Method used to create the array object.
6210 MethodBase new_method = null;
6212 Type array_element_type;
6213 Type underlying_type;
6214 bool is_one_dimensional = false;
6215 bool is_builtin_type = false;
6216 bool expect_initializers = false;
6217 int num_arguments = 0;
6221 ArrayList array_data;
6226 // The number of array initializers that we can handle
6227 // via the InitializeArray method - through EmitStaticInitializers
6229 int num_automatic_initializers;
6231 const int max_automatic_initializers = 6;
6233 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
6235 this.requested_base_type = requested_base_type;
6236 this.initializers = initializers;
6240 arguments = new ArrayList ();
6242 foreach (Expression e in exprs) {
6243 arguments.Add (new Argument (e, Argument.AType.Expression));
6248 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
6250 this.requested_base_type = requested_base_type;
6251 this.initializers = initializers;
6255 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
6257 //string tmp = rank.Substring (rank.LastIndexOf ('['));
6259 //dimensions = tmp.Length - 1;
6260 expect_initializers = true;
6263 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
6265 StringBuilder sb = new StringBuilder (rank);
6268 for (int i = 1; i < idx_count; i++)
6273 return new ComposedCast (base_type, sb.ToString (), loc);
6276 void Error_IncorrectArrayInitializer ()
6278 Error (178, "Incorrectly structured array initializer");
6281 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
6283 if (specified_dims) {
6284 Argument a = (Argument) arguments [idx];
6286 if (!a.Resolve (ec, loc))
6289 if (!(a.Expr is Constant)) {
6290 Error (150, "A constant value is expected");
6294 int value = (int) ((Constant) a.Expr).GetValue ();
6296 if (value != probe.Count) {
6297 Error_IncorrectArrayInitializer ();
6301 bounds [idx] = value;
6304 int child_bounds = -1;
6305 foreach (object o in probe) {
6306 if (o is ArrayList) {
6307 int current_bounds = ((ArrayList) o).Count;
6309 if (child_bounds == -1)
6310 child_bounds = current_bounds;
6312 else if (child_bounds != current_bounds){
6313 Error_IncorrectArrayInitializer ();
6316 if (specified_dims && (idx + 1 >= arguments.Count)){
6317 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
6321 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
6325 if (child_bounds != -1){
6326 Error_IncorrectArrayInitializer ();
6330 Expression tmp = (Expression) o;
6331 tmp = tmp.Resolve (ec);
6335 // Console.WriteLine ("I got: " + tmp);
6336 // Handle initialization from vars, fields etc.
6338 Expression conv = Convert.ImplicitConversionRequired (
6339 ec, tmp, underlying_type, loc);
6344 if (conv is StringConstant || conv is DecimalConstant || conv is NullCast) {
6345 // These are subclasses of Constant that can appear as elements of an
6346 // array that cannot be statically initialized (with num_automatic_initializers
6347 // > max_automatic_initializers), so num_automatic_initializers should be left as zero.
6348 array_data.Add (conv);
6349 } else if (conv is Constant) {
6350 // These are the types of Constant that can appear in arrays that can be
6351 // statically allocated.
6352 array_data.Add (conv);
6353 num_automatic_initializers++;
6355 array_data.Add (conv);
6362 public void UpdateIndices (EmitContext ec)
6365 for (ArrayList probe = initializers; probe != null;) {
6366 if (probe.Count > 0 && probe [0] is ArrayList) {
6367 Expression e = new IntConstant (probe.Count);
6368 arguments.Add (new Argument (e, Argument.AType.Expression));
6370 bounds [i++] = probe.Count;
6372 probe = (ArrayList) probe [0];
6375 Expression e = new IntConstant (probe.Count);
6376 arguments.Add (new Argument (e, Argument.AType.Expression));
6378 bounds [i++] = probe.Count;
6385 public bool ValidateInitializers (EmitContext ec, Type array_type)
6387 if (initializers == null) {
6388 if (expect_initializers)
6394 if (underlying_type == null)
6398 // We use this to store all the date values in the order in which we
6399 // will need to store them in the byte blob later
6401 array_data = new ArrayList ();
6402 bounds = new Hashtable ();
6406 if (arguments != null) {
6407 ret = CheckIndices (ec, initializers, 0, true);
6410 arguments = new ArrayList ();
6412 ret = CheckIndices (ec, initializers, 0, false);
6419 if (arguments.Count != dimensions) {
6420 Error_IncorrectArrayInitializer ();
6429 // Converts `source' to an int, uint, long or ulong.
6431 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
6435 bool old_checked = ec.CheckState;
6436 ec.CheckState = true;
6438 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
6439 if (target == null){
6440 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
6441 if (target == null){
6442 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
6443 if (target == null){
6444 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
6446 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
6450 ec.CheckState = old_checked;
6453 // Only positive constants are allowed at compile time
6455 if (target is Constant){
6456 if (target is IntConstant){
6457 if (((IntConstant) target).Value < 0){
6458 Expression.Error_NegativeArrayIndex (loc);
6463 if (target is LongConstant){
6464 if (((LongConstant) target).Value < 0){
6465 Expression.Error_NegativeArrayIndex (loc);
6476 // Creates the type of the array
6478 bool LookupType (EmitContext ec)
6480 StringBuilder array_qualifier = new StringBuilder (rank);
6483 // `In the first form allocates an array instace of the type that results
6484 // from deleting each of the individual expression from the expression list'
6486 if (num_arguments > 0) {
6487 array_qualifier.Append ("[");
6488 for (int i = num_arguments-1; i > 0; i--)
6489 array_qualifier.Append (",");
6490 array_qualifier.Append ("]");
6496 TypeExpr array_type_expr;
6497 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
6498 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec);
6499 if (array_type_expr == null)
6502 type = array_type_expr.Type;
6504 if (!type.IsArray) {
6505 Error (622, "Can only use array initializer expressions to assign to array types. Try using a new expression instead.");
6508 underlying_type = TypeManager.GetElementType (type);
6509 dimensions = type.GetArrayRank ();
6514 public override Expression DoResolve (EmitContext ec)
6518 if (!LookupType (ec))
6522 // First step is to validate the initializers and fill
6523 // in any missing bits
6525 if (!ValidateInitializers (ec, type))
6528 if (arguments == null)
6531 arg_count = arguments.Count;
6532 foreach (Argument a in arguments){
6533 if (!a.Resolve (ec, loc))
6536 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
6537 if (real_arg == null)
6544 array_element_type = TypeManager.GetElementType (type);
6546 if (array_element_type.IsAbstract && array_element_type.IsSealed) {
6547 Report.Error (719, loc, "'{0}': array elements cannot be of static type", TypeManager.CSharpName (array_element_type));
6551 if (arg_count == 1) {
6552 is_one_dimensional = true;
6553 eclass = ExprClass.Value;
6557 is_builtin_type = TypeManager.IsBuiltinType (type);
6559 if (is_builtin_type) {
6562 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
6563 AllBindingFlags, loc);
6565 if (!(ml is MethodGroupExpr)) {
6566 ml.Error_UnexpectedKind ("method group", loc);
6571 Error (-6, "New invocation: Can not find a constructor for " +
6572 "this argument list");
6576 new_method = Invocation.OverloadResolve (
6577 ec, (MethodGroupExpr) ml, arguments, false, loc);
6579 if (new_method == null) {
6580 Error (-6, "New invocation: Can not find a constructor for " +
6581 "this argument list");
6585 eclass = ExprClass.Value;
6588 ModuleBuilder mb = CodeGen.Module.Builder;
6589 ArrayList args = new ArrayList ();
6591 if (arguments != null) {
6592 for (int i = 0; i < arg_count; i++)
6593 args.Add (TypeManager.int32_type);
6596 Type [] arg_types = null;
6599 arg_types = new Type [args.Count];
6601 args.CopyTo (arg_types, 0);
6603 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
6606 if (new_method == null) {
6607 Error (-6, "New invocation: Can not find a constructor for " +
6608 "this argument list");
6612 eclass = ExprClass.Value;
6617 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
6622 int count = array_data.Count;
6624 if (underlying_type.IsEnum)
6625 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
6627 factor = GetTypeSize (underlying_type);
6629 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
6631 data = new byte [(count * factor + 4) & ~3];
6634 for (int i = 0; i < count; ++i) {
6635 object v = array_data [i];
6637 if (v is EnumConstant)
6638 v = ((EnumConstant) v).Child;
6640 if (v is Constant && !(v is StringConstant))
6641 v = ((Constant) v).GetValue ();
6647 if (underlying_type == TypeManager.int64_type){
6648 if (!(v is Expression)){
6649 long val = (long) v;
6651 for (int j = 0; j < factor; ++j) {
6652 data [idx + j] = (byte) (val & 0xFF);
6656 } else if (underlying_type == TypeManager.uint64_type){
6657 if (!(v is Expression)){
6658 ulong val = (ulong) v;
6660 for (int j = 0; j < factor; ++j) {
6661 data [idx + j] = (byte) (val & 0xFF);
6665 } else if (underlying_type == TypeManager.float_type) {
6666 if (!(v is Expression)){
6667 element = BitConverter.GetBytes ((float) v);
6669 for (int j = 0; j < factor; ++j)
6670 data [idx + j] = element [j];
6672 } else if (underlying_type == TypeManager.double_type) {
6673 if (!(v is Expression)){
6674 element = BitConverter.GetBytes ((double) v);
6676 for (int j = 0; j < factor; ++j)
6677 data [idx + j] = element [j];
6679 } else if (underlying_type == TypeManager.char_type){
6680 if (!(v is Expression)){
6681 int val = (int) ((char) v);
6683 data [idx] = (byte) (val & 0xff);
6684 data [idx+1] = (byte) (val >> 8);
6686 } else if (underlying_type == TypeManager.short_type){
6687 if (!(v is Expression)){
6688 int val = (int) ((short) v);
6690 data [idx] = (byte) (val & 0xff);
6691 data [idx+1] = (byte) (val >> 8);
6693 } else if (underlying_type == TypeManager.ushort_type){
6694 if (!(v is Expression)){
6695 int val = (int) ((ushort) v);
6697 data [idx] = (byte) (val & 0xff);
6698 data [idx+1] = (byte) (val >> 8);
6700 } else if (underlying_type == TypeManager.int32_type) {
6701 if (!(v is Expression)){
6704 data [idx] = (byte) (val & 0xff);
6705 data [idx+1] = (byte) ((val >> 8) & 0xff);
6706 data [idx+2] = (byte) ((val >> 16) & 0xff);
6707 data [idx+3] = (byte) (val >> 24);
6709 } else if (underlying_type == TypeManager.uint32_type) {
6710 if (!(v is Expression)){
6711 uint val = (uint) v;
6713 data [idx] = (byte) (val & 0xff);
6714 data [idx+1] = (byte) ((val >> 8) & 0xff);
6715 data [idx+2] = (byte) ((val >> 16) & 0xff);
6716 data [idx+3] = (byte) (val >> 24);
6718 } else if (underlying_type == TypeManager.sbyte_type) {
6719 if (!(v is Expression)){
6720 sbyte val = (sbyte) v;
6721 data [idx] = (byte) val;
6723 } else if (underlying_type == TypeManager.byte_type) {
6724 if (!(v is Expression)){
6725 byte val = (byte) v;
6726 data [idx] = (byte) val;
6728 } else if (underlying_type == TypeManager.bool_type) {
6729 if (!(v is Expression)){
6730 bool val = (bool) v;
6731 data [idx] = (byte) (val ? 1 : 0);
6733 } else if (underlying_type == TypeManager.decimal_type){
6734 if (!(v is Expression)){
6735 int [] bits = Decimal.GetBits ((decimal) v);
6738 // FIXME: For some reason, this doesn't work on the MS runtime.
6739 int [] nbits = new int [4];
6740 nbits [0] = bits [3];
6741 nbits [1] = bits [2];
6742 nbits [2] = bits [0];
6743 nbits [3] = bits [1];
6745 for (int j = 0; j < 4; j++){
6746 data [p++] = (byte) (nbits [j] & 0xff);
6747 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6748 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6749 data [p++] = (byte) (nbits [j] >> 24);
6753 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6762 // Emits the initializers for the array
6764 void EmitStaticInitializers (EmitContext ec)
6767 // First, the static data
6770 ILGenerator ig = ec.ig;
6772 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6774 fb = RootContext.MakeStaticData (data);
6776 ig.Emit (OpCodes.Dup);
6777 ig.Emit (OpCodes.Ldtoken, fb);
6778 ig.Emit (OpCodes.Call,
6779 TypeManager.void_initializearray_array_fieldhandle);
6783 // Emits pieces of the array that can not be computed at compile
6784 // time (variables and string locations).
6786 // This always expect the top value on the stack to be the array
6788 void EmitDynamicInitializers (EmitContext ec)
6790 ILGenerator ig = ec.ig;
6791 int dims = bounds.Count;
6792 int [] current_pos = new int [dims];
6793 int top = array_data.Count;
6795 MethodInfo set = null;
6799 ModuleBuilder mb = null;
6800 mb = CodeGen.Module.Builder;
6801 args = new Type [dims + 1];
6804 for (j = 0; j < dims; j++)
6805 args [j] = TypeManager.int32_type;
6807 args [j] = array_element_type;
6809 set = mb.GetArrayMethod (
6811 CallingConventions.HasThis | CallingConventions.Standard,
6812 TypeManager.void_type, args);
6815 for (int i = 0; i < top; i++){
6817 Expression e = null;
6819 if (array_data [i] is Expression)
6820 e = (Expression) array_data [i];
6824 // Basically we do this for string literals and
6825 // other non-literal expressions
6827 if (e is EnumConstant){
6828 e = ((EnumConstant) e).Child;
6831 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6832 num_automatic_initializers <= max_automatic_initializers) {
6833 Type etype = e.Type;
6835 ig.Emit (OpCodes.Dup);
6837 for (int idx = 0; idx < dims; idx++)
6838 IntConstant.EmitInt (ig, current_pos [idx]);
6841 // If we are dealing with a struct, get the
6842 // address of it, so we can store it.
6844 if ((dims == 1) && etype.IsValueType &&
6845 (!TypeManager.IsBuiltinOrEnum (etype) ||
6846 etype == TypeManager.decimal_type)) {
6851 // Let new know that we are providing
6852 // the address where to store the results
6854 n.DisableTemporaryValueType ();
6857 ig.Emit (OpCodes.Ldelema, etype);
6863 bool is_stobj, has_type_arg;
6864 OpCode op = ArrayAccess.GetStoreOpcode (
6865 etype, out is_stobj,
6868 ig.Emit (OpCodes.Stobj, etype);
6869 else if (has_type_arg)
6870 ig.Emit (op, etype);
6874 ig.Emit (OpCodes.Call, set);
6881 for (int j = dims - 1; j >= 0; j--){
6883 if (current_pos [j] < (int) bounds [j])
6885 current_pos [j] = 0;
6890 void EmitArrayArguments (EmitContext ec)
6892 ILGenerator ig = ec.ig;
6894 foreach (Argument a in arguments) {
6895 Type atype = a.Type;
6898 if (atype == TypeManager.uint64_type)
6899 ig.Emit (OpCodes.Conv_Ovf_U4);
6900 else if (atype == TypeManager.int64_type)
6901 ig.Emit (OpCodes.Conv_Ovf_I4);
6905 public override void Emit (EmitContext ec)
6907 ILGenerator ig = ec.ig;
6909 EmitArrayArguments (ec);
6910 if (is_one_dimensional)
6911 ig.Emit (OpCodes.Newarr, array_element_type);
6913 if (is_builtin_type)
6914 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6916 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6919 if (initializers != null){
6921 // FIXME: Set this variable correctly.
6923 bool dynamic_initializers = true;
6925 // This will never be true for array types that cannot be statically
6926 // initialized. num_automatic_initializers will always be zero. See
6928 if (num_automatic_initializers > max_automatic_initializers)
6929 EmitStaticInitializers (ec);
6931 if (dynamic_initializers)
6932 EmitDynamicInitializers (ec);
6936 public object EncodeAsAttribute ()
6938 if (!is_one_dimensional){
6939 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6943 if (array_data == null){
6944 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6948 object [] ret = new object [array_data.Count];
6950 foreach (Expression e in array_data){
6953 if (e is NullLiteral)
6956 if (!Attribute.GetAttributeArgumentExpression (e, Location, array_element_type, out v))
6966 /// Represents the `this' construct
6968 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6971 VariableInfo variable_info;
6973 public This (Block block, Location loc)
6979 public This (Location loc)
6984 public VariableInfo VariableInfo {
6985 get { return variable_info; }
6988 public bool VerifyFixed (bool is_expression)
6990 if ((variable_info == null) || (variable_info.LocalInfo == null))
6993 return variable_info.LocalInfo.IsFixed;
6996 public bool ResolveBase (EmitContext ec)
6998 eclass = ExprClass.Variable;
7000 if (ec.TypeContainer.CurrentType != null)
7001 type = ec.TypeContainer.CurrentType;
7003 type = ec.ContainerType;
7006 Error (26, "Keyword this not valid in static code");
7010 if ((block != null) && (block.ThisVariable != null))
7011 variable_info = block.ThisVariable.VariableInfo;
7013 if (ec.CurrentAnonymousMethod != null)
7019 public override Expression DoResolve (EmitContext ec)
7021 if (!ResolveBase (ec))
7024 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
7025 Error (188, "The this object cannot be used before all " +
7026 "of its fields are assigned to");
7027 variable_info.SetAssigned (ec);
7031 if (ec.IsFieldInitializer) {
7032 Error (27, "Keyword `this' can't be used outside a constructor, " +
7033 "a method or a property.");
7040 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
7042 if (!ResolveBase (ec))
7045 if (variable_info != null)
7046 variable_info.SetAssigned (ec);
7048 if (ec.TypeContainer is Class){
7049 Error (1604, "Cannot assign to `this'");
7056 public void Emit (EmitContext ec, bool leave_copy)
7060 ec.ig.Emit (OpCodes.Dup);
7063 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
7065 ILGenerator ig = ec.ig;
7067 if (ec.TypeContainer is Struct){
7071 ec.ig.Emit (OpCodes.Dup);
7072 ig.Emit (OpCodes.Stobj, type);
7074 throw new Exception ("how did you get here");
7078 public override void Emit (EmitContext ec)
7080 ILGenerator ig = ec.ig;
7083 if (ec.TypeContainer is Struct)
7084 ig.Emit (OpCodes.Ldobj, type);
7087 public void AddressOf (EmitContext ec, AddressOp mode)
7092 // FIGURE OUT WHY LDARG_S does not work
7094 // consider: struct X { int val; int P { set { val = value; }}}
7096 // Yes, this looks very bad. Look at `NOTAS' for
7098 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
7103 /// Represents the `__arglist' construct
7105 public class ArglistAccess : Expression
7107 public ArglistAccess (Location loc)
7112 public bool ResolveBase (EmitContext ec)
7114 eclass = ExprClass.Variable;
7115 type = TypeManager.runtime_argument_handle_type;
7119 public override Expression DoResolve (EmitContext ec)
7121 if (!ResolveBase (ec))
7124 if (ec.IsFieldInitializer || !ec.CurrentBlock.HasVarargs) {
7125 Error (190, "The __arglist construct is valid only within " +
7126 "a variable argument method.");
7133 public override void Emit (EmitContext ec)
7135 ec.ig.Emit (OpCodes.Arglist);
7140 /// Represents the `__arglist (....)' construct
7142 public class Arglist : Expression
7144 public readonly Argument[] Arguments;
7146 public Arglist (Argument[] args, Location l)
7152 public Type[] ArgumentTypes {
7154 Type[] retval = new Type [Arguments.Length];
7155 for (int i = 0; i < Arguments.Length; i++)
7156 retval [i] = Arguments [i].Type;
7161 public override Expression DoResolve (EmitContext ec)
7163 eclass = ExprClass.Variable;
7164 type = TypeManager.runtime_argument_handle_type;
7166 foreach (Argument arg in Arguments) {
7167 if (!arg.Resolve (ec, loc))
7174 public override void Emit (EmitContext ec)
7176 foreach (Argument arg in Arguments)
7182 // This produces the value that renders an instance, used by the iterators code
7184 public class ProxyInstance : Expression, IMemoryLocation {
7185 public override Expression DoResolve (EmitContext ec)
7187 eclass = ExprClass.Variable;
7188 type = ec.ContainerType;
7192 public override void Emit (EmitContext ec)
7194 ec.ig.Emit (OpCodes.Ldarg_0);
7198 public void AddressOf (EmitContext ec, AddressOp mode)
7200 ec.ig.Emit (OpCodes.Ldarg_0);
7205 /// Implements the typeof operator
7207 public class TypeOf : Expression {
7208 public Expression QueriedType;
7209 protected Type typearg;
7211 public TypeOf (Expression queried_type, Location l)
7213 QueriedType = queried_type;
7217 public override Expression DoResolve (EmitContext ec)
7219 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec);
7223 typearg = texpr.Type;
7225 if (typearg == TypeManager.void_type) {
7226 Error (673, "System.Void cannot be used from C# - " +
7227 "use typeof (void) to get the void type object");
7231 if (typearg.IsPointer && !ec.InUnsafe){
7235 CheckObsoleteAttribute (typearg);
7237 type = TypeManager.type_type;
7238 eclass = ExprClass.Type;
7242 public override void Emit (EmitContext ec)
7244 ec.ig.Emit (OpCodes.Ldtoken, typearg);
7245 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
7248 public Type TypeArg {
7249 get { return typearg; }
7254 /// Implements the `typeof (void)' operator
7256 public class TypeOfVoid : TypeOf {
7257 public TypeOfVoid (Location l) : base (null, l)
7262 public override Expression DoResolve (EmitContext ec)
7264 type = TypeManager.type_type;
7265 typearg = TypeManager.void_type;
7266 eclass = ExprClass.Type;
7272 /// Implements the sizeof expression
7274 public class SizeOf : Expression {
7275 public Expression QueriedType;
7278 public SizeOf (Expression queried_type, Location l)
7280 this.QueriedType = queried_type;
7284 public override Expression DoResolve (EmitContext ec)
7288 233, loc, "Sizeof may only be used in an unsafe context " +
7289 "(consider using System.Runtime.InteropServices.Marshal.SizeOf");
7293 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec);
7297 if (texpr is TypeParameterExpr){
7298 ((TypeParameterExpr)texpr).Error_CannotUseAsUnmanagedType (loc);
7302 type_queried = texpr.Type;
7304 CheckObsoleteAttribute (type_queried);
7306 if (!TypeManager.IsUnmanagedType (type_queried)){
7307 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
7311 type = TypeManager.int32_type;
7312 eclass = ExprClass.Value;
7316 public override void Emit (EmitContext ec)
7318 int size = GetTypeSize (type_queried);
7321 ec.ig.Emit (OpCodes.Sizeof, type_queried);
7323 IntConstant.EmitInt (ec.ig, size);
7328 /// Implements the member access expression
7330 public class MemberAccess : Expression {
7331 public string Identifier;
7332 protected Expression expr;
7333 protected TypeArguments args;
7335 public MemberAccess (Expression expr, string id, Location l)
7342 public MemberAccess (Expression expr, string id, TypeArguments args,
7344 : this (expr, id, l)
7349 public Expression Expr {
7355 public static void error176 (Location loc, string name)
7357 Report.Error (176, loc, "Static member `" +
7358 name + "' cannot be accessed " +
7359 "with an instance reference, qualify with a " +
7360 "type name instead");
7363 public static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Expression left, Location loc)
7365 SimpleName sn = left_original as SimpleName;
7366 return sn != null && sn.IdenticalNameAndTypeName (ec, left, loc);
7369 // TODO: possible optimalization
7370 // Cache resolved constant result in FieldBuilder <-> expresion map
7371 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
7372 Expression left, Location loc,
7373 Expression left_original)
7375 bool left_is_type, left_is_explicit;
7377 // If `left' is null, then we're called from SimpleNameResolve and this is
7378 // a member in the currently defining class.
7380 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
7381 left_is_explicit = false;
7383 // Implicitly default to `this' unless we're static.
7384 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
7385 left = ec.GetThis (loc);
7387 left_is_type = left is TypeExpr;
7388 left_is_explicit = true;
7391 if (member_lookup is FieldExpr){
7392 FieldExpr fe = (FieldExpr) member_lookup;
7393 FieldInfo fi = fe.FieldInfo.Mono_GetGenericFieldDefinition ();
7394 Type decl_type = fi.DeclaringType;
7396 bool is_emitted = fi is FieldBuilder;
7397 Type t = fi.FieldType;
7400 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
7404 if (!c.LookupConstantValue (out o))
7407 object real_value = ((Constant) c.Expr).GetValue ();
7409 Expression exp = Constantify (real_value, t);
7411 if (left_is_explicit && !left_is_type && !IdenticalNameAndTypeName (ec, left_original, left, loc)) {
7412 Report.SymbolRelatedToPreviousError (c);
7413 error176 (loc, c.GetSignatureForError ());
7421 // IsInitOnly is because of MS compatibility, I don't know why but they emit decimal constant as InitOnly
7422 if (fi.IsInitOnly && !is_emitted && t == TypeManager.decimal_type) {
7423 object[] attrs = fi.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
7424 if (attrs.Length == 1)
7425 return new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
7432 o = TypeManager.GetValue ((FieldBuilder) fi);
7434 o = fi.GetValue (fi);
7436 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
7437 if (left_is_explicit && !left_is_type &&
7438 !IdenticalNameAndTypeName (ec, left_original, member_lookup, loc)) {
7439 error176 (loc, fe.FieldInfo.Name);
7443 Expression enum_member = MemberLookup (
7444 ec, decl_type, "value__", MemberTypes.Field,
7445 AllBindingFlags, loc);
7447 Enum en = TypeManager.LookupEnum (decl_type);
7451 c = Constantify (o, en.UnderlyingType);
7453 c = Constantify (o, enum_member.Type);
7455 return new EnumConstant (c, decl_type);
7458 Expression exp = Constantify (o, t);
7460 if (left_is_explicit && !left_is_type) {
7461 error176 (loc, fe.FieldInfo.Name);
7468 if (t.IsPointer && !ec.InUnsafe){
7474 if (member_lookup is EventExpr) {
7475 EventExpr ee = (EventExpr) member_lookup;
7478 // If the event is local to this class, we transform ourselves into
7482 if (ee.EventInfo.DeclaringType == ec.ContainerType ||
7483 TypeManager.IsNestedChildOf(ec.ContainerType, ee.EventInfo.DeclaringType)) {
7484 MemberInfo mi = GetFieldFromEvent (ee);
7488 // If this happens, then we have an event with its own
7489 // accessors and private field etc so there's no need
7490 // to transform ourselves.
7492 ee.InstanceExpression = left;
7496 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
7499 Report.Error (-200, loc, "Internal error!!");
7503 if (!left_is_explicit)
7506 ee.InstanceExpression = left;
7508 return ResolveMemberAccess (ec, ml, left, loc, left_original);
7512 if (member_lookup is IMemberExpr) {
7513 IMemberExpr me = (IMemberExpr) member_lookup;
7514 MethodGroupExpr mg = me as MethodGroupExpr;
7517 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
7518 mg.IsExplicitImpl = left_is_explicit;
7521 if ((ec.IsFieldInitializer || ec.IsStatic) &&
7522 IdenticalNameAndTypeName (ec, left_original, member_lookup, loc))
7523 return member_lookup;
7525 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
7530 if (!me.IsInstance){
7531 if (IdenticalNameAndTypeName (ec, left_original, left, loc))
7532 return member_lookup;
7534 if (left_is_explicit) {
7535 error176 (loc, me.Name);
7541 // Since we can not check for instance objects in SimpleName,
7542 // becaue of the rule that allows types and variables to share
7543 // the name (as long as they can be de-ambiguated later, see
7544 // IdenticalNameAndTypeName), we have to check whether left
7545 // is an instance variable in a static context
7547 // However, if the left-hand value is explicitly given, then
7548 // it is already our instance expression, so we aren't in
7552 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
7553 IMemberExpr mexp = (IMemberExpr) left;
7555 if (!mexp.IsStatic){
7556 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
7561 if ((mg != null) && IdenticalNameAndTypeName (ec, left_original, left, loc))
7562 mg.IdenticalTypeName = true;
7564 me.InstanceExpression = left;
7567 return member_lookup;
7570 Console.WriteLine ("Left is: " + left);
7571 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
7572 Environment.Exit (1);
7576 public virtual Expression DoResolve (EmitContext ec, Expression right_side,
7580 throw new Exception ();
7583 // Resolve the expression with flow analysis turned off, we'll do the definite
7584 // assignment checks later. This is because we don't know yet what the expression
7585 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7586 // definite assignment check on the actual field and not on the whole struct.
7589 Expression original = expr;
7590 expr = expr.Resolve (ec, flags | ResolveFlags.Intermediate | ResolveFlags.DisableFlowAnalysis);
7594 if (expr is Namespace) {
7595 Namespace ns = (Namespace) expr;
7596 string lookup_id = MemberName.MakeName (Identifier, args);
7597 FullNamedExpression retval = ns.Lookup (ec.DeclSpace, lookup_id, loc);
7598 if ((retval != null) && (args != null))
7599 retval = new ConstructedType (retval, args, loc).ResolveAsTypeStep (ec);
7601 Report.Error (234, loc, "The type or namespace name `{0}' could not be found in namespace `{1}'", Identifier, ns.FullName);
7606 // TODO: I mailed Ravi about this, and apparently we can get rid
7607 // of this and put it in the right place.
7609 // Handle enums here when they are in transit.
7610 // Note that we cannot afford to hit MemberLookup in this case because
7611 // it will fail to find any members at all
7615 if (expr is TypeExpr){
7616 expr_type = expr.Type;
7618 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
7619 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", expr_type);
7623 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
7624 Enum en = TypeManager.LookupEnum (expr_type);
7627 object value = en.LookupEnumValue (ec, Identifier, loc);
7630 MemberCore mc = en.GetDefinition (Identifier);
7631 ObsoleteAttribute oa = mc.GetObsoleteAttribute (en);
7633 AttributeTester.Report_ObsoleteMessage (oa, mc.GetSignatureForError (), Location);
7635 oa = en.GetObsoleteAttribute (en);
7637 AttributeTester.Report_ObsoleteMessage (oa, en.GetSignatureForError (), Location);
7640 Constant c = Constantify (value, en.UnderlyingType);
7641 return new EnumConstant (c, expr_type);
7644 CheckObsoleteAttribute (expr_type);
7646 FieldInfo fi = expr_type.GetField (Identifier);
7648 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
7650 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), Location);
7655 expr_type = expr.Type;
7657 if (expr_type.IsPointer){
7658 Error (23, "The `.' operator can not be applied to pointer operands (" +
7659 TypeManager.CSharpName (expr_type) + ")");
7663 Expression member_lookup;
7664 member_lookup = MemberLookup (
7665 ec, expr_type, expr_type, Identifier, loc);
7666 if ((member_lookup == null) && (args != null)) {
7667 string lookup_id = MemberName.MakeName (Identifier, args);
7668 member_lookup = MemberLookup (
7669 ec, expr_type, expr_type, lookup_id, loc);
7671 if (member_lookup == null) {
7672 MemberLookupFailed (
7673 ec, expr_type, expr_type, Identifier, null, false, loc);
7677 if (member_lookup is TypeExpr) {
7678 if (!(expr is TypeExpr) &&
7679 !IdenticalNameAndTypeName (ec, original, expr, loc)) {
7680 Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
7681 member_lookup.Type + "' instead");
7685 return member_lookup;
7689 string full_name = expr_type + "." + Identifier;
7691 if (member_lookup is FieldExpr) {
7692 Report.Error (307, loc, "The field `{0}' cannot " +
7693 "be used with type arguments", full_name);
7695 } else if (member_lookup is EventExpr) {
7696 Report.Error (307, loc, "The event `{0}' cannot " +
7697 "be used with type arguments", full_name);
7699 } else if (member_lookup is PropertyExpr) {
7700 Report.Error (307, loc, "The property `{0}' cannot " +
7701 "be used with type arguments", full_name);
7706 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
7707 if (member_lookup == null)
7711 MethodGroupExpr mg = member_lookup as MethodGroupExpr;
7713 throw new InternalErrorException ();
7715 return mg.ResolveGeneric (ec, args);
7718 // The following DoResolve/DoResolveLValue will do the definite assignment
7721 if (right_side != null)
7722 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
7724 member_lookup = member_lookup.DoResolve (ec);
7726 return member_lookup;
7729 public override Expression DoResolve (EmitContext ec)
7731 return DoResolve (ec, null, ResolveFlags.VariableOrValue | ResolveFlags.Type);
7734 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7736 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue | ResolveFlags.Type);
7739 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
7741 return ResolveNamespaceOrType (ec, false);
7744 public FullNamedExpression ResolveNamespaceOrType (EmitContext ec, bool silent)
7746 FullNamedExpression new_expr = expr.ResolveAsTypeStep (ec);
7748 if (new_expr == null)
7751 string lookup_id = MemberName.MakeName (Identifier, args);
7753 if (new_expr is Namespace) {
7754 Namespace ns = (Namespace) new_expr;
7755 FullNamedExpression retval = ns.Lookup (ec.DeclSpace, lookup_id, loc);
7756 if ((retval != null) && (args != null))
7757 retval = new ConstructedType (retval, args, loc).ResolveAsTypeStep (ec);
7758 if (!silent && retval == null)
7759 Report.Error (234, loc, "The type or namespace name `{0}' could not be found in namespace `{1}'", Identifier, ns.FullName);
7763 TypeExpr tnew_expr = new_expr.ResolveAsTypeTerminal (ec);
7764 if (tnew_expr == null)
7767 Type expr_type = tnew_expr.Type;
7769 if (expr_type.IsPointer){
7770 Error (23, "The `.' operator can not be applied to pointer operands (" +
7771 TypeManager.CSharpName (expr_type) + ")");
7775 Expression member_lookup = MemberLookup (ec, expr_type, expr_type, lookup_id, loc);
7776 if (member_lookup == null) {
7777 int errors = Report.Errors;
7778 MemberLookupFailed (ec, expr_type, expr_type, lookup_id, null, false, loc);
7780 if (!silent && errors == Report.Errors)
7781 Report.Error (234, loc, "The type name `{0}' could not be found in type `{1}'",
7782 lookup_id, new_expr.FullName);
7786 if (!(member_lookup is TypeExpr)) {
7787 Report.Error (118, loc, "'{0}.{1}' denotes a '{2}', where a type was expected",
7788 new_expr.FullName, lookup_id, member_lookup.ExprClassName ());
7792 TypeExpr texpr = member_lookup.ResolveAsTypeTerminal (ec);
7796 TypeArguments the_args = args;
7797 if (TypeManager.HasGenericArguments (expr_type)) {
7798 Type[] decl_args = TypeManager.GetTypeArguments (expr_type);
7800 TypeArguments new_args = new TypeArguments (loc);
7801 foreach (Type decl in decl_args)
7802 new_args.Add (new TypeExpression (decl, loc));
7805 new_args.Add (args);
7807 the_args = new_args;
7810 if (the_args != null) {
7811 ConstructedType ctype = new ConstructedType (texpr.Type, the_args, loc);
7812 return ctype.ResolveAsTypeStep (ec);
7818 public override void Emit (EmitContext ec)
7820 throw new Exception ("Should not happen");
7823 public override string ToString ()
7825 return expr + "." + MemberName.MakeName (Identifier, args);
7830 /// Implements checked expressions
7832 public class CheckedExpr : Expression {
7834 public Expression Expr;
7836 public CheckedExpr (Expression e, Location l)
7842 public override Expression DoResolve (EmitContext ec)
7844 bool last_check = ec.CheckState;
7845 bool last_const_check = ec.ConstantCheckState;
7847 ec.CheckState = true;
7848 ec.ConstantCheckState = true;
7849 Expr = Expr.Resolve (ec);
7850 ec.CheckState = last_check;
7851 ec.ConstantCheckState = last_const_check;
7856 if (Expr is Constant)
7859 eclass = Expr.eclass;
7864 public override void Emit (EmitContext ec)
7866 bool last_check = ec.CheckState;
7867 bool last_const_check = ec.ConstantCheckState;
7869 ec.CheckState = true;
7870 ec.ConstantCheckState = true;
7872 ec.CheckState = last_check;
7873 ec.ConstantCheckState = last_const_check;
7879 /// Implements the unchecked expression
7881 public class UnCheckedExpr : Expression {
7883 public Expression Expr;
7885 public UnCheckedExpr (Expression e, Location l)
7891 public override Expression DoResolve (EmitContext ec)
7893 bool last_check = ec.CheckState;
7894 bool last_const_check = ec.ConstantCheckState;
7896 ec.CheckState = false;
7897 ec.ConstantCheckState = false;
7898 Expr = Expr.Resolve (ec);
7899 ec.CheckState = last_check;
7900 ec.ConstantCheckState = last_const_check;
7905 if (Expr is Constant)
7908 eclass = Expr.eclass;
7913 public override void Emit (EmitContext ec)
7915 bool last_check = ec.CheckState;
7916 bool last_const_check = ec.ConstantCheckState;
7918 ec.CheckState = false;
7919 ec.ConstantCheckState = false;
7921 ec.CheckState = last_check;
7922 ec.ConstantCheckState = last_const_check;
7928 /// An Element Access expression.
7930 /// During semantic analysis these are transformed into
7931 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7933 public class ElementAccess : Expression {
7934 public ArrayList Arguments;
7935 public Expression Expr;
7937 public ElementAccess (Expression e, ArrayList e_list, Location l)
7946 Arguments = new ArrayList ();
7947 foreach (Expression tmp in e_list)
7948 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7952 bool CommonResolve (EmitContext ec)
7954 Expr = Expr.Resolve (ec);
7959 if (Arguments == null)
7962 foreach (Argument a in Arguments){
7963 if (!a.Resolve (ec, loc))
7970 Expression MakePointerAccess (EmitContext ec, Type t)
7972 if (t == TypeManager.void_ptr_type){
7973 Error (242, "The array index operation is not valid for void pointers");
7976 if (Arguments.Count != 1){
7977 Error (196, "A pointer must be indexed by a single value");
7982 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc).Resolve (ec);
7985 return new Indirection (p, loc).Resolve (ec);
7988 public override Expression DoResolve (EmitContext ec)
7990 if (!CommonResolve (ec))
7994 // We perform some simple tests, and then to "split" the emit and store
7995 // code we create an instance of a different class, and return that.
7997 // I am experimenting with this pattern.
8001 if (t == TypeManager.array_type){
8002 Report.Error (21, loc, "Cannot use indexer on System.Array");
8007 return (new ArrayAccess (this, loc)).Resolve (ec);
8009 return MakePointerAccess (ec, Expr.Type);
8011 FieldExpr fe = Expr as FieldExpr;
8013 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
8015 return MakePointerAccess (ec, ff.ElementType);
8018 return (new IndexerAccess (this, loc)).Resolve (ec);
8021 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8023 if (!CommonResolve (ec))
8028 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
8031 return MakePointerAccess (ec, Expr.Type);
8033 FieldExpr fe = Expr as FieldExpr;
8035 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
8037 // TODO: not sure whether it is correct
8038 // if (!ec.InFixedInitializer) {
8039 // if (!ec.InFixedInitializer) {
8040 // Error (1666, "You cannot use fixed sized buffers contained in unfixed expressions. Try using the fixed statement.");
8043 return MakePointerAccess (ec, ff.ElementType);
8046 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
8049 public override void Emit (EmitContext ec)
8051 throw new Exception ("Should never be reached");
8056 /// Implements array access
8058 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
8060 // Points to our "data" repository
8064 LocalTemporary temp;
8067 public ArrayAccess (ElementAccess ea_data, Location l)
8070 eclass = ExprClass.Variable;
8074 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8076 return DoResolve (ec);
8079 public override Expression DoResolve (EmitContext ec)
8082 ExprClass eclass = ea.Expr.eclass;
8084 // As long as the type is valid
8085 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
8086 eclass == ExprClass.Value)) {
8087 ea.Expr.Error_UnexpectedKind ("variable or value");
8092 Type t = ea.Expr.Type;
8093 if (t.GetArrayRank () != ea.Arguments.Count){
8095 "Incorrect number of indexes for array " +
8096 " expected: " + t.GetArrayRank () + " got: " +
8097 ea.Arguments.Count);
8101 type = TypeManager.GetElementType (t);
8102 if (type.IsPointer && !ec.InUnsafe){
8103 UnsafeError (ea.Location);
8107 foreach (Argument a in ea.Arguments){
8108 Type argtype = a.Type;
8110 if (argtype == TypeManager.int32_type ||
8111 argtype == TypeManager.uint32_type ||
8112 argtype == TypeManager.int64_type ||
8113 argtype == TypeManager.uint64_type) {
8114 Constant c = a.Expr as Constant;
8115 if (c != null && c.IsNegative) {
8116 Report.Warning (251, 2, a.Expr.Location, "Indexing an array with a negative index (array indices always start at zero)");
8122 // Mhm. This is strage, because the Argument.Type is not the same as
8123 // Argument.Expr.Type: the value changes depending on the ref/out setting.
8125 // Wonder if I will run into trouble for this.
8127 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
8132 eclass = ExprClass.Variable;
8138 /// Emits the right opcode to load an object of Type `t'
8139 /// from an array of T
8141 static public void EmitLoadOpcode (ILGenerator ig, Type type)
8143 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
8144 ig.Emit (OpCodes.Ldelem_U1);
8145 else if (type == TypeManager.sbyte_type)
8146 ig.Emit (OpCodes.Ldelem_I1);
8147 else if (type == TypeManager.short_type)
8148 ig.Emit (OpCodes.Ldelem_I2);
8149 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
8150 ig.Emit (OpCodes.Ldelem_U2);
8151 else if (type == TypeManager.int32_type)
8152 ig.Emit (OpCodes.Ldelem_I4);
8153 else if (type == TypeManager.uint32_type)
8154 ig.Emit (OpCodes.Ldelem_U4);
8155 else if (type == TypeManager.uint64_type)
8156 ig.Emit (OpCodes.Ldelem_I8);
8157 else if (type == TypeManager.int64_type)
8158 ig.Emit (OpCodes.Ldelem_I8);
8159 else if (type == TypeManager.float_type)
8160 ig.Emit (OpCodes.Ldelem_R4);
8161 else if (type == TypeManager.double_type)
8162 ig.Emit (OpCodes.Ldelem_R8);
8163 else if (type == TypeManager.intptr_type)
8164 ig.Emit (OpCodes.Ldelem_I);
8165 else if (TypeManager.IsEnumType (type)){
8166 EmitLoadOpcode (ig, TypeManager.EnumToUnderlying (type));
8167 } else if (type.IsValueType){
8168 ig.Emit (OpCodes.Ldelema, type);
8169 ig.Emit (OpCodes.Ldobj, type);
8170 } else if (type.IsGenericParameter)
8171 ig.Emit (OpCodes.Ldelem_Any, type);
8173 ig.Emit (OpCodes.Ldelem_Ref);
8177 /// Returns the right opcode to store an object of Type `t'
8178 /// from an array of T.
8180 static public OpCode GetStoreOpcode (Type t, out bool is_stobj, out bool has_type_arg)
8182 //Console.WriteLine (new System.Diagnostics.StackTrace ());
8183 has_type_arg = false; is_stobj = false;
8184 t = TypeManager.TypeToCoreType (t);
8185 if (TypeManager.IsEnumType (t))
8186 t = TypeManager.EnumToUnderlying (t);
8187 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
8188 t == TypeManager.bool_type)
8189 return OpCodes.Stelem_I1;
8190 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
8191 t == TypeManager.char_type)
8192 return OpCodes.Stelem_I2;
8193 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
8194 return OpCodes.Stelem_I4;
8195 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
8196 return OpCodes.Stelem_I8;
8197 else if (t == TypeManager.float_type)
8198 return OpCodes.Stelem_R4;
8199 else if (t == TypeManager.double_type)
8200 return OpCodes.Stelem_R8;
8201 else if (t == TypeManager.intptr_type) {
8202 has_type_arg = true;
8204 return OpCodes.Stobj;
8205 } else if (t.IsValueType) {
8206 has_type_arg = true;
8208 return OpCodes.Stobj;
8209 } else if (t.IsGenericParameter) {
8210 has_type_arg = true;
8211 return OpCodes.Stelem_Any;
8213 return OpCodes.Stelem_Ref;
8216 MethodInfo FetchGetMethod ()
8218 ModuleBuilder mb = CodeGen.Module.Builder;
8219 int arg_count = ea.Arguments.Count;
8220 Type [] args = new Type [arg_count];
8223 for (int i = 0; i < arg_count; i++){
8224 //args [i++] = a.Type;
8225 args [i] = TypeManager.int32_type;
8228 get = mb.GetArrayMethod (
8229 ea.Expr.Type, "Get",
8230 CallingConventions.HasThis |
8231 CallingConventions.Standard,
8237 MethodInfo FetchAddressMethod ()
8239 ModuleBuilder mb = CodeGen.Module.Builder;
8240 int arg_count = ea.Arguments.Count;
8241 Type [] args = new Type [arg_count];
8245 ret_type = TypeManager.GetReferenceType (type);
8247 for (int i = 0; i < arg_count; i++){
8248 //args [i++] = a.Type;
8249 args [i] = TypeManager.int32_type;
8252 address = mb.GetArrayMethod (
8253 ea.Expr.Type, "Address",
8254 CallingConventions.HasThis |
8255 CallingConventions.Standard,
8262 // Load the array arguments into the stack.
8264 // If we have been requested to cache the values (cached_locations array
8265 // initialized), then load the arguments the first time and store them
8266 // in locals. otherwise load from local variables.
8268 void LoadArrayAndArguments (EmitContext ec)
8270 ILGenerator ig = ec.ig;
8273 foreach (Argument a in ea.Arguments){
8274 Type argtype = a.Expr.Type;
8278 if (argtype == TypeManager.int64_type)
8279 ig.Emit (OpCodes.Conv_Ovf_I);
8280 else if (argtype == TypeManager.uint64_type)
8281 ig.Emit (OpCodes.Conv_Ovf_I_Un);
8285 public void Emit (EmitContext ec, bool leave_copy)
8287 int rank = ea.Expr.Type.GetArrayRank ();
8288 ILGenerator ig = ec.ig;
8291 LoadArrayAndArguments (ec);
8294 EmitLoadOpcode (ig, type);
8298 method = FetchGetMethod ();
8299 ig.Emit (OpCodes.Call, method);
8302 LoadFromPtr (ec.ig, this.type);
8305 ec.ig.Emit (OpCodes.Dup);
8306 temp = new LocalTemporary (ec, this.type);
8311 public override void Emit (EmitContext ec)
8316 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8318 int rank = ea.Expr.Type.GetArrayRank ();
8319 ILGenerator ig = ec.ig;
8320 Type t = source.Type;
8321 prepared = prepare_for_load;
8323 if (prepare_for_load) {
8324 AddressOf (ec, AddressOp.LoadStore);
8325 ec.ig.Emit (OpCodes.Dup);
8328 ec.ig.Emit (OpCodes.Dup);
8329 temp = new LocalTemporary (ec, this.type);
8332 StoreFromPtr (ec.ig, t);
8340 LoadArrayAndArguments (ec);
8343 bool is_stobj, has_type_arg;
8344 OpCode op = GetStoreOpcode (t, out is_stobj, out has_type_arg);
8347 // The stobj opcode used by value types will need
8348 // an address on the stack, not really an array/array
8352 ig.Emit (OpCodes.Ldelema, t);
8356 ec.ig.Emit (OpCodes.Dup);
8357 temp = new LocalTemporary (ec, this.type);
8362 ig.Emit (OpCodes.Stobj, t);
8363 else if (has_type_arg)
8368 ModuleBuilder mb = CodeGen.Module.Builder;
8369 int arg_count = ea.Arguments.Count;
8370 Type [] args = new Type [arg_count + 1];
8375 ec.ig.Emit (OpCodes.Dup);
8376 temp = new LocalTemporary (ec, this.type);
8380 for (int i = 0; i < arg_count; i++){
8381 //args [i++] = a.Type;
8382 args [i] = TypeManager.int32_type;
8385 args [arg_count] = type;
8387 set = mb.GetArrayMethod (
8388 ea.Expr.Type, "Set",
8389 CallingConventions.HasThis |
8390 CallingConventions.Standard,
8391 TypeManager.void_type, args);
8393 ig.Emit (OpCodes.Call, set);
8400 public void AddressOf (EmitContext ec, AddressOp mode)
8402 int rank = ea.Expr.Type.GetArrayRank ();
8403 ILGenerator ig = ec.ig;
8405 LoadArrayAndArguments (ec);
8408 ig.Emit (OpCodes.Ldelema, type);
8410 MethodInfo address = FetchAddressMethod ();
8411 ig.Emit (OpCodes.Call, address);
8418 public ArrayList Properties;
8419 static Hashtable map;
8421 public struct Indexer {
8422 public readonly Type Type;
8423 public readonly MethodInfo Getter, Setter;
8425 public Indexer (Type type, MethodInfo get, MethodInfo set)
8435 map = new Hashtable ();
8440 Properties = new ArrayList ();
8443 void Append (MemberInfo [] mi)
8445 foreach (PropertyInfo property in mi){
8446 MethodInfo get, set;
8448 get = property.GetGetMethod (true);
8449 set = property.GetSetMethod (true);
8450 Properties.Add (new Indexer (property.PropertyType, get, set));
8454 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
8456 string p_name = TypeManager.IndexerPropertyName (lookup_type);
8458 MemberInfo [] mi = TypeManager.MemberLookup (
8459 caller_type, caller_type, lookup_type, MemberTypes.Property,
8460 BindingFlags.Public | BindingFlags.Instance |
8461 BindingFlags.DeclaredOnly, p_name, null);
8463 if (mi == null || mi.Length == 0)
8469 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
8471 Indexers ix = (Indexers) map [lookup_type];
8476 Type copy = lookup_type;
8477 while (copy != TypeManager.object_type && copy != null){
8478 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
8482 ix = new Indexers ();
8487 copy = copy.BaseType;
8490 if (!lookup_type.IsInterface)
8493 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
8494 if (ifaces != null) {
8495 foreach (Type itype in ifaces) {
8496 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
8499 ix = new Indexers ();
8511 /// Expressions that represent an indexer call.
8513 public class IndexerAccess : Expression, IAssignMethod {
8515 // Points to our "data" repository
8517 MethodInfo get, set;
8518 ArrayList set_arguments;
8519 bool is_base_indexer;
8521 protected Type indexer_type;
8522 protected Type current_type;
8523 protected Expression instance_expr;
8524 protected ArrayList arguments;
8526 public IndexerAccess (ElementAccess ea, Location loc)
8527 : this (ea.Expr, false, loc)
8529 this.arguments = ea.Arguments;
8532 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
8535 this.instance_expr = instance_expr;
8536 this.is_base_indexer = is_base_indexer;
8537 this.eclass = ExprClass.Value;
8541 protected virtual bool CommonResolve (EmitContext ec)
8543 indexer_type = instance_expr.Type;
8544 current_type = ec.ContainerType;
8549 public override Expression DoResolve (EmitContext ec)
8551 ArrayList AllGetters = new ArrayList();
8552 if (!CommonResolve (ec))
8556 // Step 1: Query for all `Item' *properties*. Notice
8557 // that the actual methods are pointed from here.
8559 // This is a group of properties, piles of them.
8561 bool found_any = false, found_any_getters = false;
8562 Type lookup_type = indexer_type;
8565 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
8566 if (ilist != null) {
8568 if (ilist.Properties != null) {
8569 foreach (Indexers.Indexer ix in ilist.Properties) {
8570 if (ix.Getter != null)
8571 AllGetters.Add(ix.Getter);
8576 if (AllGetters.Count > 0) {
8577 found_any_getters = true;
8578 get = (MethodInfo) Invocation.OverloadResolve (
8579 ec, new MethodGroupExpr (AllGetters, loc),
8580 arguments, false, loc);
8584 Report.Error (21, loc,
8585 "Type `" + TypeManager.CSharpName (indexer_type) +
8586 "' does not have any indexers defined");
8590 if (!found_any_getters) {
8591 Error (154, "indexer can not be used in this context, because " +
8592 "it lacks a `get' accessor");
8597 Error (1501, "No Overload for method `this' takes `" +
8598 arguments.Count + "' arguments");
8603 // Only base will allow this invocation to happen.
8605 if (get.IsAbstract && this is BaseIndexerAccess){
8606 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
8610 type = get.ReturnType;
8611 if (type.IsPointer && !ec.InUnsafe){
8616 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8618 eclass = ExprClass.IndexerAccess;
8622 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8624 ArrayList AllSetters = new ArrayList();
8625 if (!CommonResolve (ec))
8628 bool found_any = false, found_any_setters = false;
8630 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
8631 if (ilist != null) {
8633 if (ilist.Properties != null) {
8634 foreach (Indexers.Indexer ix in ilist.Properties) {
8635 if (ix.Setter != null)
8636 AllSetters.Add(ix.Setter);
8640 if (AllSetters.Count > 0) {
8641 found_any_setters = true;
8642 set_arguments = (ArrayList) arguments.Clone ();
8643 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
8644 set = (MethodInfo) Invocation.OverloadResolve (
8645 ec, new MethodGroupExpr (AllSetters, loc),
8646 set_arguments, false, loc);
8650 Report.Error (21, loc,
8651 "Type `" + TypeManager.CSharpName (indexer_type) +
8652 "' does not have any indexers defined");
8656 if (!found_any_setters) {
8657 Error (154, "indexer can not be used in this context, because " +
8658 "it lacks a `set' accessor");
8663 Error (1501, "No Overload for method `this' takes `" +
8664 arguments.Count + "' arguments");
8669 // Only base will allow this invocation to happen.
8671 if (set.IsAbstract && this is BaseIndexerAccess){
8672 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
8677 // Now look for the actual match in the list of indexers to set our "return" type
8679 type = TypeManager.void_type; // default value
8680 foreach (Indexers.Indexer ix in ilist.Properties){
8681 if (ix.Setter == set){
8687 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8689 eclass = ExprClass.IndexerAccess;
8693 bool prepared = false;
8694 LocalTemporary temp;
8696 public void Emit (EmitContext ec, bool leave_copy)
8698 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc, prepared, false);
8700 ec.ig.Emit (OpCodes.Dup);
8701 temp = new LocalTemporary (ec, Type);
8707 // source is ignored, because we already have a copy of it from the
8708 // LValue resolution and we have already constructed a pre-cached
8709 // version of the arguments (ea.set_arguments);
8711 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8713 prepared = prepare_for_load;
8714 Argument a = (Argument) set_arguments [set_arguments.Count - 1];
8719 ec.ig.Emit (OpCodes.Dup);
8720 temp = new LocalTemporary (ec, Type);
8723 } else if (leave_copy) {
8724 temp = new LocalTemporary (ec, Type);
8730 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc, false, prepared);
8737 public override void Emit (EmitContext ec)
8744 /// The base operator for method names
8746 public class BaseAccess : Expression {
8749 public BaseAccess (string member, Location l)
8751 this.member = member;
8755 public override Expression DoResolve (EmitContext ec)
8757 Expression c = CommonResolve (ec);
8763 // MethodGroups use this opportunity to flag an error on lacking ()
8765 if (!(c is MethodGroupExpr))
8766 return c.Resolve (ec);
8770 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8772 Expression c = CommonResolve (ec);
8778 // MethodGroups use this opportunity to flag an error on lacking ()
8780 if (! (c is MethodGroupExpr))
8781 return c.DoResolveLValue (ec, right_side);
8786 Expression CommonResolve (EmitContext ec)
8788 Expression member_lookup;
8789 Type current_type = ec.ContainerType;
8790 Type base_type = current_type.BaseType;
8794 Error (1511, "Keyword base is not allowed in static method");
8798 if (ec.IsFieldInitializer){
8799 Error (1512, "Keyword base is not available in the current context");
8803 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type,
8804 member, AllMemberTypes, AllBindingFlags,
8806 if (member_lookup == null) {
8807 MemberLookupFailed (ec, base_type, base_type, member, null, true, loc);
8814 left = new TypeExpression (base_type, loc);
8816 left = ec.GetThis (loc);
8818 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
8820 if (e is PropertyExpr){
8821 PropertyExpr pe = (PropertyExpr) e;
8826 if (e is MethodGroupExpr)
8827 ((MethodGroupExpr) e).IsBase = true;
8832 public override void Emit (EmitContext ec)
8834 throw new Exception ("Should never be called");
8839 /// The base indexer operator
8841 public class BaseIndexerAccess : IndexerAccess {
8842 public BaseIndexerAccess (ArrayList args, Location loc)
8843 : base (null, true, loc)
8845 arguments = new ArrayList ();
8846 foreach (Expression tmp in args)
8847 arguments.Add (new Argument (tmp, Argument.AType.Expression));
8850 protected override bool CommonResolve (EmitContext ec)
8852 instance_expr = ec.GetThis (loc);
8854 current_type = ec.ContainerType.BaseType;
8855 indexer_type = current_type;
8857 foreach (Argument a in arguments){
8858 if (!a.Resolve (ec, loc))
8867 /// This class exists solely to pass the Type around and to be a dummy
8868 /// that can be passed to the conversion functions (this is used by
8869 /// foreach implementation to typecast the object return value from
8870 /// get_Current into the proper type. All code has been generated and
8871 /// we only care about the side effect conversions to be performed
8873 /// This is also now used as a placeholder where a no-action expression
8874 /// is needed (the `New' class).
8876 public class EmptyExpression : Expression {
8877 public static readonly EmptyExpression Null = new EmptyExpression ();
8879 // TODO: should be protected
8880 public EmptyExpression ()
8882 type = TypeManager.object_type;
8883 eclass = ExprClass.Value;
8884 loc = Location.Null;
8887 public EmptyExpression (Type t)
8890 eclass = ExprClass.Value;
8891 loc = Location.Null;
8894 public override Expression DoResolve (EmitContext ec)
8899 public override void Emit (EmitContext ec)
8901 // nothing, as we only exist to not do anything.
8905 // This is just because we might want to reuse this bad boy
8906 // instead of creating gazillions of EmptyExpressions.
8907 // (CanImplicitConversion uses it)
8909 public void SetType (Type t)
8915 public class UserCast : Expression {
8919 public UserCast (MethodInfo method, Expression source, Location l)
8921 this.method = method;
8922 this.source = source;
8923 type = method.ReturnType;
8924 eclass = ExprClass.Value;
8928 public Expression Source {
8934 public override Expression DoResolve (EmitContext ec)
8937 // We are born fully resolved
8942 public override void Emit (EmitContext ec)
8944 ILGenerator ig = ec.ig;
8948 if (method is MethodInfo)
8949 ig.Emit (OpCodes.Call, (MethodInfo) method);
8951 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
8957 // This class is used to "construct" the type during a typecast
8958 // operation. Since the Type.GetType class in .NET can parse
8959 // the type specification, we just use this to construct the type
8960 // one bit at a time.
8962 public class ComposedCast : TypeExpr {
8966 public ComposedCast (Expression left, string dim, Location l)
8973 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
8975 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec);
8979 Type ltype = lexpr.Type;
8981 if ((ltype == TypeManager.void_type) && (dim != "*")) {
8982 Report.Error (1547, Location,
8983 "Keyword 'void' cannot be used in this context");
8987 if ((dim.Length > 0) && (dim [0] == '?')) {
8988 TypeExpr nullable = new NullableType (left, loc);
8990 nullable = new ComposedCast (nullable, dim.Substring (1), loc);
8991 return nullable.ResolveAsTypeTerminal (ec);
8995 while ((pos < dim.Length) && (dim [pos] == '[')) {
8998 if (dim [pos] == ']') {
8999 ltype = ltype.MakeArrayType ();
9002 if (pos < dim.Length)
9006 eclass = ExprClass.Type;
9011 while (dim [pos] == ',') {
9015 if ((dim [pos] != ']') || (pos != dim.Length-1))
9018 type = ltype.MakeArrayType (rank + 1);
9019 eclass = ExprClass.Type;
9025 // ltype.Fullname is already fully qualified, so we can skip
9026 // a lot of probes, and go directly to TypeManager.LookupType
9028 string fname = ltype.FullName != null ? ltype.FullName : ltype.Name;
9029 string cname = fname + dim;
9030 type = TypeManager.LookupTypeDirect (cname);
9033 // For arrays of enumerations we are having a problem
9034 // with the direct lookup. Need to investigate.
9036 // For now, fall back to the full lookup in that case.
9038 FullNamedExpression e = ec.DeclSpace.LookupType (
9039 cname, loc, /*ignore_cs0104=*/ false);
9041 Report.Error (246, loc, "Cannot find type `" + cname + "'");
9045 type = ((TypeExpr) e).ResolveType (ec);
9053 if (!ec.InUnsafe && type.IsPointer){
9058 if (type.IsArray && (type.GetElementType () == TypeManager.arg_iterator_type ||
9059 type.GetElementType () == TypeManager.typed_reference_type)) {
9060 Report.Error (611, loc, "Array elements cannot be of type '{0}'", TypeManager.CSharpName (type.GetElementType ()));
9064 eclass = ExprClass.Type;
9068 public override string Name {
9074 public override string FullName {
9076 return type.FullName;
9081 public class FixedBufferPtr: Expression {
9084 public FixedBufferPtr (Expression array, Type array_type, Location l)
9089 type = TypeManager.GetPointerType (array_type);
9090 eclass = ExprClass.Value;
9093 public override void Emit(EmitContext ec)
9098 public override Expression DoResolve (EmitContext ec)
9101 // We are born fully resolved
9109 // This class is used to represent the address of an array, used
9110 // only by the Fixed statement, this generates "&a [0]" construct
9111 // for fixed (char *pa = a)
9113 public class ArrayPtr : FixedBufferPtr {
9116 public ArrayPtr (Expression array, Type array_type, Location l):
9117 base (array, array_type, l)
9119 this.array_type = array_type;
9122 public override void Emit (EmitContext ec)
9126 ILGenerator ig = ec.ig;
9127 IntLiteral.EmitInt (ig, 0);
9128 ig.Emit (OpCodes.Ldelema, array_type);
9133 // Used by the fixed statement
9135 public class StringPtr : Expression {
9138 public StringPtr (LocalBuilder b, Location l)
9141 eclass = ExprClass.Value;
9142 type = TypeManager.char_ptr_type;
9146 public override Expression DoResolve (EmitContext ec)
9148 // This should never be invoked, we are born in fully
9149 // initialized state.
9154 public override void Emit (EmitContext ec)
9156 ILGenerator ig = ec.ig;
9158 ig.Emit (OpCodes.Ldloc, b);
9159 ig.Emit (OpCodes.Conv_I);
9160 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
9161 ig.Emit (OpCodes.Add);
9166 // Implements the `stackalloc' keyword
9168 public class StackAlloc : Expression {
9173 public StackAlloc (Expression type, Expression count, Location l)
9180 public override Expression DoResolve (EmitContext ec)
9182 count = count.Resolve (ec);
9186 if (count.Type != TypeManager.int32_type){
9187 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
9192 Constant c = count as Constant;
9193 if (c != null && c.IsNegative) {
9194 Report.Error (247, loc, "Cannot use a negative size with stackalloc");
9198 if (ec.CurrentBranching.InCatch () ||
9199 ec.CurrentBranching.InFinally (true)) {
9201 "stackalloc can not be used in a catch or finally block");
9205 TypeExpr texpr = t.ResolveAsTypeTerminal (ec);
9211 if (!TypeManager.VerifyUnManaged (otype, loc))
9214 type = TypeManager.GetPointerType (otype);
9215 eclass = ExprClass.Value;
9220 public override void Emit (EmitContext ec)
9222 int size = GetTypeSize (otype);
9223 ILGenerator ig = ec.ig;
9226 ig.Emit (OpCodes.Sizeof, otype);
9228 IntConstant.EmitInt (ig, size);
9230 ig.Emit (OpCodes.Mul);
9231 ig.Emit (OpCodes.Localloc);