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);
51 ec.ig.Emit (OpCodes.Call, mi);
55 static public Expression 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 (ec, (MethodGroupExpr) mg, args, loc);
74 return new StaticCallExpr ((MethodInfo) method, args, loc);
77 public override void EmitStatement (EmitContext ec)
80 if (TypeManager.TypeToCoreType (type) != TypeManager.void_type)
81 ec.ig.Emit (OpCodes.Pop);
85 public class ParenthesizedExpression : Expression
87 public Expression Expr;
89 public ParenthesizedExpression (Expression expr, Location loc)
95 public override Expression DoResolve (EmitContext ec)
97 Expr = Expr.Resolve (ec);
101 public override void Emit (EmitContext ec)
103 throw new Exception ("Should not happen");
108 /// Unary expressions.
112 /// Unary implements unary expressions. It derives from
113 /// ExpressionStatement becuase the pre/post increment/decrement
114 /// operators can be used in a statement context.
116 public class Unary : Expression {
117 public enum Operator : byte {
118 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
119 Indirection, AddressOf, TOP
122 public Operator Oper;
123 public Expression Expr;
125 public Unary (Operator op, Expression expr, Location loc)
133 /// Returns a stringified representation of the Operator
135 static public string OperName (Operator oper)
138 case Operator.UnaryPlus:
140 case Operator.UnaryNegation:
142 case Operator.LogicalNot:
144 case Operator.OnesComplement:
146 case Operator.AddressOf:
148 case Operator.Indirection:
152 return oper.ToString ();
155 public static readonly string [] oper_names;
159 oper_names = new string [(int)Operator.TOP];
161 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
162 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
163 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
164 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
165 oper_names [(int) Operator.Indirection] = "op_Indirection";
166 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
169 void Error23 (Type t)
172 23, "Operator " + OperName (Oper) +
173 " cannot be applied to operand of type `" +
174 TypeManager.CSharpName (t) + "'");
178 /// The result has been already resolved:
180 /// FIXME: a minus constant -128 sbyte cant be turned into a
183 static Expression TryReduceNegative (Constant expr)
187 if (expr is IntConstant)
188 e = new IntConstant (-((IntConstant) expr).Value);
189 else if (expr is UIntConstant){
190 uint value = ((UIntConstant) expr).Value;
192 if (value < 2147483649)
193 return new IntConstant (-(int)value);
195 e = new LongConstant (-value);
197 else if (expr is LongConstant)
198 e = new LongConstant (-((LongConstant) expr).Value);
199 else if (expr is ULongConstant){
200 ulong value = ((ULongConstant) expr).Value;
202 if (value < 9223372036854775809)
203 return new LongConstant(-(long)value);
205 else if (expr is FloatConstant)
206 e = new FloatConstant (-((FloatConstant) expr).Value);
207 else if (expr is DoubleConstant)
208 e = new DoubleConstant (-((DoubleConstant) expr).Value);
209 else if (expr is DecimalConstant)
210 e = new DecimalConstant (-((DecimalConstant) expr).Value);
211 else if (expr is ShortConstant)
212 e = new IntConstant (-((ShortConstant) expr).Value);
213 else if (expr is UShortConstant)
214 e = new IntConstant (-((UShortConstant) expr).Value);
219 // This routine will attempt to simplify the unary expression when the
220 // argument is a constant. The result is returned in `result' and the
221 // function returns true or false depending on whether a reduction
222 // was performed or not
224 bool Reduce (EmitContext ec, Constant e, out Expression result)
226 Type expr_type = e.Type;
229 case Operator.UnaryPlus:
233 case Operator.UnaryNegation:
234 result = TryReduceNegative (e);
237 case Operator.LogicalNot:
238 if (expr_type != TypeManager.bool_type) {
244 BoolConstant b = (BoolConstant) e;
245 result = new BoolConstant (!(b.Value));
248 case Operator.OnesComplement:
249 if (!((expr_type == TypeManager.int32_type) ||
250 (expr_type == TypeManager.uint32_type) ||
251 (expr_type == TypeManager.int64_type) ||
252 (expr_type == TypeManager.uint64_type) ||
253 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
256 if (Convert.ImplicitConversionExists (ec, e, TypeManager.int32_type)){
257 result = new Cast (new TypeExpression (TypeManager.int32_type, loc), e, loc);
258 result = result.Resolve (ec);
259 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint32_type)){
260 result = new Cast (new TypeExpression (TypeManager.uint32_type, loc), e, loc);
261 result = result.Resolve (ec);
262 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.int64_type)){
263 result = new Cast (new TypeExpression (TypeManager.int64_type, loc), e, loc);
264 result = result.Resolve (ec);
265 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint64_type)){
266 result = new Cast (new TypeExpression (TypeManager.uint64_type, loc), e, loc);
267 result = result.Resolve (ec);
270 if (result == null || !(result is Constant)){
276 expr_type = result.Type;
277 e = (Constant) result;
280 if (e is EnumConstant){
281 EnumConstant enum_constant = (EnumConstant) e;
284 if (Reduce (ec, enum_constant.Child, out reduced)){
285 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
293 if (expr_type == TypeManager.int32_type){
294 result = new IntConstant (~ ((IntConstant) e).Value);
295 } else if (expr_type == TypeManager.uint32_type){
296 result = new UIntConstant (~ ((UIntConstant) e).Value);
297 } else if (expr_type == TypeManager.int64_type){
298 result = new LongConstant (~ ((LongConstant) e).Value);
299 } else if (expr_type == TypeManager.uint64_type){
300 result = new ULongConstant (~ ((ULongConstant) e).Value);
308 case Operator.AddressOf:
312 case Operator.Indirection:
316 throw new Exception ("Can not constant fold: " + Oper.ToString());
319 Expression ResolveOperator (EmitContext ec)
321 Type expr_type = Expr.Type;
324 // Step 1: Perform Operator Overload location
329 op_name = oper_names [(int) Oper];
331 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
334 Expression e = StaticCallExpr.MakeSimpleCall (
335 ec, (MethodGroupExpr) mg, Expr, loc);
345 // Only perform numeric promotions on:
348 if (expr_type == null)
352 // Step 2: Default operations on CLI native types.
355 // Attempt to use a constant folding operation.
356 if (Expr is Constant){
359 if (Reduce (ec, (Constant) Expr, out result))
364 case Operator.LogicalNot:
365 if (expr_type != TypeManager.bool_type) {
366 Expr = ResolveBoolean (ec, Expr, loc);
373 type = TypeManager.bool_type;
376 case Operator.OnesComplement:
377 if (!((expr_type == TypeManager.int32_type) ||
378 (expr_type == TypeManager.uint32_type) ||
379 (expr_type == TypeManager.int64_type) ||
380 (expr_type == TypeManager.uint64_type) ||
381 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
384 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
386 type = TypeManager.int32_type;
389 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint32_type, loc);
391 type = TypeManager.uint32_type;
394 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
396 type = TypeManager.int64_type;
399 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint64_type, loc);
401 type = TypeManager.uint64_type;
410 case Operator.AddressOf:
411 if (Expr.eclass != ExprClass.Variable){
412 Error (211, "Cannot take the address of non-variables");
421 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
425 IVariable variable = Expr as IVariable;
426 if (!ec.InFixedInitializer && ((variable == null) || !variable.VerifyFixed (false))) {
427 Error (212, "You can only take the address of an unfixed expression inside " +
428 "of a fixed statement initializer");
432 if (ec.InFixedInitializer && ((variable != null) && variable.VerifyFixed (false))) {
433 Error (213, "You can not fix an already fixed expression");
437 // According to the specs, a variable is considered definitely assigned if you take
439 if ((variable != null) && (variable.VariableInfo != null))
440 variable.VariableInfo.SetAssigned (ec);
442 type = TypeManager.GetPointerType (Expr.Type);
445 case Operator.Indirection:
451 if (!expr_type.IsPointer){
452 Error (193, "The * or -> operator can only be applied to pointers");
457 // We create an Indirection expression, because
458 // it can implement the IMemoryLocation.
460 return new Indirection (Expr, loc);
462 case Operator.UnaryPlus:
464 // A plus in front of something is just a no-op, so return the child.
468 case Operator.UnaryNegation:
470 // Deals with -literals
471 // int operator- (int x)
472 // long operator- (long x)
473 // float operator- (float f)
474 // double operator- (double d)
475 // decimal operator- (decimal d)
477 Expression expr = null;
480 // transform - - expr into expr
483 Unary unary = (Unary) Expr;
485 if (unary.Oper == Operator.UnaryNegation)
490 // perform numeric promotions to int,
494 // The following is inneficient, because we call
495 // ImplicitConversion too many times.
497 // It is also not clear if we should convert to Float
498 // or Double initially.
500 if (expr_type == TypeManager.uint32_type){
502 // FIXME: handle exception to this rule that
503 // permits the int value -2147483648 (-2^31) to
504 // bt wrote as a decimal interger literal
506 type = TypeManager.int64_type;
507 Expr = Convert.ImplicitConversion (ec, Expr, type, loc);
511 if (expr_type == TypeManager.uint64_type){
513 // FIXME: Handle exception of `long value'
514 // -92233720368547758087 (-2^63) to be wrote as
515 // decimal integer literal.
521 if (expr_type == TypeManager.float_type){
526 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
533 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
540 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.double_type, loc);
551 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
552 TypeManager.CSharpName (expr_type) + "'");
556 public override Expression DoResolve (EmitContext ec)
558 if (Oper == Operator.AddressOf)
559 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
561 Expr = Expr.Resolve (ec);
566 eclass = ExprClass.Value;
567 return ResolveOperator (ec);
570 public override Expression DoResolveLValue (EmitContext ec, Expression right)
572 if (Oper == Operator.Indirection)
573 return base.DoResolveLValue (ec, right);
575 Error (131, "The left-hand side of an assignment must be a " +
576 "variable, property or indexer");
580 public override void Emit (EmitContext ec)
582 ILGenerator ig = ec.ig;
585 case Operator.UnaryPlus:
586 throw new Exception ("This should be caught by Resolve");
588 case Operator.UnaryNegation:
590 ig.Emit (OpCodes.Ldc_I4_0);
591 if (type == TypeManager.int64_type)
592 ig.Emit (OpCodes.Conv_U8);
594 ig.Emit (OpCodes.Sub_Ovf);
597 ig.Emit (OpCodes.Neg);
602 case Operator.LogicalNot:
604 ig.Emit (OpCodes.Ldc_I4_0);
605 ig.Emit (OpCodes.Ceq);
608 case Operator.OnesComplement:
610 ig.Emit (OpCodes.Not);
613 case Operator.AddressOf:
614 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
618 throw new Exception ("This should not happen: Operator = "
623 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
625 if (Oper == Operator.LogicalNot)
626 Expr.EmitBranchable (ec, target, !onTrue);
628 base.EmitBranchable (ec, target, onTrue);
631 public override string ToString ()
633 return "Unary (" + Oper + ", " + Expr + ")";
639 // Unary operators are turned into Indirection expressions
640 // after semantic analysis (this is so we can take the address
641 // of an indirection).
643 public class Indirection : Expression, IMemoryLocation, IAssignMethod {
645 LocalTemporary temporary;
648 public Indirection (Expression expr, Location l)
651 this.type = TypeManager.GetElementType (expr.Type);
652 eclass = ExprClass.Variable;
656 void LoadExprValue (EmitContext ec)
660 public override void Emit (EmitContext ec)
662 ILGenerator ig = ec.ig;
664 if (temporary != null){
665 if (have_temporary) {
669 ec.ig.Emit (OpCodes.Dup);
670 temporary.Store (ec);
671 have_temporary = true;
676 LoadFromPtr (ig, Type);
679 public void EmitAssign (EmitContext ec, Expression source)
681 if (temporary != null){
686 ec.ig.Emit (OpCodes.Dup);
687 temporary.Store (ec);
688 have_temporary = true;
694 StoreFromPtr (ec.ig, type);
697 public void AddressOf (EmitContext ec, AddressOp Mode)
699 if (temporary != null){
705 ec.ig.Emit (OpCodes.Dup);
706 temporary.Store (ec);
707 have_temporary = true;
712 public override Expression DoResolve (EmitContext ec)
715 // Born fully resolved
720 public new void CacheTemporaries (EmitContext ec)
722 temporary = new LocalTemporary (ec, expr.Type);
725 public override string ToString ()
727 return "*(" + expr + ")";
732 /// Unary Mutator expressions (pre and post ++ and --)
736 /// UnaryMutator implements ++ and -- expressions. It derives from
737 /// ExpressionStatement becuase the pre/post increment/decrement
738 /// operators can be used in a statement context.
740 /// FIXME: Idea, we could split this up in two classes, one simpler
741 /// for the common case, and one with the extra fields for more complex
742 /// classes (indexers require temporary access; overloaded require method)
745 public class UnaryMutator : ExpressionStatement {
747 public enum Mode : byte {
754 PreDecrement = IsDecrement,
755 PostIncrement = IsPost,
756 PostDecrement = IsPost | IsDecrement
761 LocalTemporary temp_storage;
764 // This is expensive for the simplest case.
768 public UnaryMutator (Mode m, Expression e, Location l)
775 static string OperName (Mode mode)
777 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
781 void Error23 (Type t)
784 23, "Operator " + OperName (mode) +
785 " cannot be applied to operand of type `" +
786 TypeManager.CSharpName (t) + "'");
790 /// Returns whether an object of type `t' can be incremented
791 /// or decremented with add/sub (ie, basically whether we can
792 /// use pre-post incr-decr operations on it, but it is not a
793 /// System.Decimal, which we require operator overloading to catch)
795 static bool IsIncrementableNumber (Type t)
797 return (t == TypeManager.sbyte_type) ||
798 (t == TypeManager.byte_type) ||
799 (t == TypeManager.short_type) ||
800 (t == TypeManager.ushort_type) ||
801 (t == TypeManager.int32_type) ||
802 (t == TypeManager.uint32_type) ||
803 (t == TypeManager.int64_type) ||
804 (t == TypeManager.uint64_type) ||
805 (t == TypeManager.char_type) ||
806 (t.IsSubclassOf (TypeManager.enum_type)) ||
807 (t == TypeManager.float_type) ||
808 (t == TypeManager.double_type) ||
809 (t.IsPointer && t != TypeManager.void_ptr_type);
812 Expression ResolveOperator (EmitContext ec)
814 Type expr_type = expr.Type;
817 // Step 1: Perform Operator Overload location
822 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
823 op_name = "op_Increment";
825 op_name = "op_Decrement";
827 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
829 if (mg == null && expr_type.BaseType != null)
830 mg = MemberLookup (ec, expr_type.BaseType, op_name,
831 MemberTypes.Method, AllBindingFlags, loc);
834 method = StaticCallExpr.MakeSimpleCall (
835 ec, (MethodGroupExpr) mg, expr, loc);
842 // The operand of the prefix/postfix increment decrement operators
843 // should be an expression that is classified as a variable,
844 // a property access or an indexer access
847 if (expr.eclass == ExprClass.Variable){
848 LocalVariableReference var = expr as LocalVariableReference;
849 if ((var != null) && var.IsReadOnly)
850 Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
851 if (IsIncrementableNumber (expr_type) ||
852 expr_type == TypeManager.decimal_type){
855 } else if (expr.eclass == ExprClass.IndexerAccess){
856 IndexerAccess ia = (IndexerAccess) expr;
858 temp_storage = new LocalTemporary (ec, expr.Type);
860 expr = ia.ResolveLValue (ec, temp_storage);
865 } else if (expr.eclass == ExprClass.PropertyAccess){
866 PropertyExpr pe = (PropertyExpr) expr;
868 if (pe.VerifyAssignable ())
873 expr.Error_UnexpectedKind ("variable, indexer or property access");
877 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
878 TypeManager.CSharpName (expr_type) + "'");
882 public override Expression DoResolve (EmitContext ec)
884 expr = expr.Resolve (ec);
889 eclass = ExprClass.Value;
890 return ResolveOperator (ec);
893 static int PtrTypeSize (Type t)
895 return GetTypeSize (TypeManager.GetElementType (t));
899 // Loads the proper "1" into the stack based on the type, then it emits the
900 // opcode for the operation requested
902 void LoadOneAndEmitOp (EmitContext ec, Type t)
905 // Measure if getting the typecode and using that is more/less efficient
906 // that comparing types. t.GetTypeCode() is an internal call.
908 ILGenerator ig = ec.ig;
910 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
911 LongConstant.EmitLong (ig, 1);
912 else if (t == TypeManager.double_type)
913 ig.Emit (OpCodes.Ldc_R8, 1.0);
914 else if (t == TypeManager.float_type)
915 ig.Emit (OpCodes.Ldc_R4, 1.0F);
916 else if (t.IsPointer){
917 int n = PtrTypeSize (t);
920 ig.Emit (OpCodes.Sizeof, t);
922 IntConstant.EmitInt (ig, n);
924 ig.Emit (OpCodes.Ldc_I4_1);
927 // Now emit the operation
930 if (t == TypeManager.int32_type ||
931 t == TypeManager.int64_type){
932 if ((mode & Mode.IsDecrement) != 0)
933 ig.Emit (OpCodes.Sub_Ovf);
935 ig.Emit (OpCodes.Add_Ovf);
936 } else if (t == TypeManager.uint32_type ||
937 t == TypeManager.uint64_type){
938 if ((mode & Mode.IsDecrement) != 0)
939 ig.Emit (OpCodes.Sub_Ovf_Un);
941 ig.Emit (OpCodes.Add_Ovf_Un);
943 if ((mode & Mode.IsDecrement) != 0)
944 ig.Emit (OpCodes.Sub_Ovf);
946 ig.Emit (OpCodes.Add_Ovf);
949 if ((mode & Mode.IsDecrement) != 0)
950 ig.Emit (OpCodes.Sub);
952 ig.Emit (OpCodes.Add);
955 if (t == TypeManager.sbyte_type){
957 ig.Emit (OpCodes.Conv_Ovf_I1);
959 ig.Emit (OpCodes.Conv_I1);
960 } else if (t == TypeManager.byte_type){
962 ig.Emit (OpCodes.Conv_Ovf_U1);
964 ig.Emit (OpCodes.Conv_U1);
965 } else if (t == TypeManager.short_type){
967 ig.Emit (OpCodes.Conv_Ovf_I2);
969 ig.Emit (OpCodes.Conv_I2);
970 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
972 ig.Emit (OpCodes.Conv_Ovf_U2);
974 ig.Emit (OpCodes.Conv_U2);
979 static EmptyExpression empty_expr;
981 void EmitCode (EmitContext ec, bool is_expr)
983 ILGenerator ig = ec.ig;
984 IAssignMethod ia = (IAssignMethod) expr;
985 Type expr_type = expr.Type;
987 ia.CacheTemporaries (ec);
990 // NOTE: We should probably handle three cases:
992 // * method invocation required.
993 // * direct stack manipulation possible
994 // * the object requires an "instance" field
996 if (temp_storage == null){
998 // Temporary improvement: if we are dealing with something that does
999 // not require complicated instance setup, avoid using a temporary
1001 // For now: only localvariables when not remapped
1004 if (method == null &&
1005 ((expr is LocalVariableReference) ||(expr is FieldExpr && ((FieldExpr) expr).FieldInfo.IsStatic))){
1006 if (empty_expr == null)
1007 empty_expr = new EmptyExpression ();
1010 case Mode.PreIncrement:
1011 case Mode.PreDecrement:
1014 LoadOneAndEmitOp (ec, expr_type);
1016 ig.Emit (OpCodes.Dup);
1017 ia.EmitAssign (ec, empty_expr);
1020 case Mode.PostIncrement:
1021 case Mode.PostDecrement:
1024 ig.Emit (OpCodes.Dup);
1026 LoadOneAndEmitOp (ec, expr_type);
1027 ia.EmitAssign (ec, empty_expr);
1032 temp_storage = new LocalTemporary (ec, expr_type);
1036 case Mode.PreIncrement:
1037 case Mode.PreDecrement:
1038 if (method == null){
1041 LoadOneAndEmitOp (ec, expr_type);
1045 temp_storage.Store (ec);
1046 ia.EmitAssign (ec, temp_storage);
1048 temp_storage.Emit (ec);
1051 case Mode.PostIncrement:
1052 case Mode.PostDecrement:
1056 if (method == null){
1060 ig.Emit (OpCodes.Dup);
1062 LoadOneAndEmitOp (ec, expr_type);
1067 temp_storage.Store (ec);
1068 ia.EmitAssign (ec, temp_storage);
1072 temp_storage.Release (ec);
1075 public override void Emit (EmitContext ec)
1077 EmitCode (ec, true);
1081 public override void EmitStatement (EmitContext ec)
1083 EmitCode (ec, false);
1089 /// Base class for the `Is' and `As' classes.
1093 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1096 public abstract class Probe : Expression {
1097 public readonly Expression ProbeType;
1098 protected Expression expr;
1099 protected Type probe_type;
1101 public Probe (Expression expr, Expression probe_type, Location l)
1103 ProbeType = probe_type;
1108 public Expression Expr {
1114 public override Expression DoResolve (EmitContext ec)
1116 probe_type = ec.DeclSpace.ResolveType (ProbeType, false, loc);
1118 if (probe_type == null)
1121 CheckObsoleteAttribute (probe_type);
1123 expr = expr.Resolve (ec);
1132 /// Implementation of the `is' operator.
1134 public class Is : Probe {
1135 public Is (Expression expr, Expression probe_type, Location l)
1136 : base (expr, probe_type, l)
1141 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1146 public override void Emit (EmitContext ec)
1148 ILGenerator ig = ec.ig;
1153 case Action.AlwaysFalse:
1154 ig.Emit (OpCodes.Pop);
1155 IntConstant.EmitInt (ig, 0);
1157 case Action.AlwaysTrue:
1158 ig.Emit (OpCodes.Pop);
1159 IntConstant.EmitInt (ig, 1);
1161 case Action.LeaveOnStack:
1162 // the `e != null' rule.
1163 ig.Emit (OpCodes.Ldnull);
1164 ig.Emit (OpCodes.Ceq);
1165 ig.Emit (OpCodes.Ldc_I4_0);
1166 ig.Emit (OpCodes.Ceq);
1169 ig.Emit (OpCodes.Isinst, probe_type);
1170 ig.Emit (OpCodes.Ldnull);
1171 ig.Emit (OpCodes.Cgt_Un);
1174 throw new Exception ("never reached");
1177 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
1179 ILGenerator ig = ec.ig;
1182 case Action.AlwaysFalse:
1184 ig.Emit (OpCodes.Br, target);
1187 case Action.AlwaysTrue:
1189 ig.Emit (OpCodes.Br, target);
1192 case Action.LeaveOnStack:
1193 // the `e != null' rule.
1195 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1199 ig.Emit (OpCodes.Isinst, probe_type);
1200 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1203 throw new Exception ("never reached");
1206 public override Expression DoResolve (EmitContext ec)
1208 Expression e = base.DoResolve (ec);
1210 if ((e == null) || (expr == null))
1213 Type etype = expr.Type;
1214 bool warning_always_matches = false;
1215 bool warning_never_matches = false;
1217 type = TypeManager.bool_type;
1218 eclass = ExprClass.Value;
1221 // First case, if at compile time, there is an implicit conversion
1222 // then e != null (objects) or true (value types)
1224 e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1227 if (etype.IsValueType)
1228 action = Action.AlwaysTrue;
1230 action = Action.LeaveOnStack;
1232 warning_always_matches = true;
1233 } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1235 // Second case: explicit reference convresion
1237 if (expr is NullLiteral)
1238 action = Action.AlwaysFalse;
1240 action = Action.Probe;
1242 action = Action.AlwaysFalse;
1243 warning_never_matches = true;
1246 if (RootContext.WarningLevel >= 1){
1247 if (warning_always_matches)
1248 Warning (183, "The expression is always of type `" +
1249 TypeManager.CSharpName (probe_type) + "'");
1250 else if (warning_never_matches){
1251 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1253 "The expression is never of type `" +
1254 TypeManager.CSharpName (probe_type) + "'");
1263 /// Implementation of the `as' operator.
1265 public class As : Probe {
1266 public As (Expression expr, Expression probe_type, Location l)
1267 : base (expr, probe_type, l)
1271 bool do_isinst = false;
1273 public override void Emit (EmitContext ec)
1275 ILGenerator ig = ec.ig;
1280 ig.Emit (OpCodes.Isinst, probe_type);
1283 static void Error_CannotConvertType (Type source, Type target, Location loc)
1286 39, loc, "as operator can not convert from `" +
1287 TypeManager.CSharpName (source) + "' to `" +
1288 TypeManager.CSharpName (target) + "'");
1291 public override Expression DoResolve (EmitContext ec)
1293 Expression e = base.DoResolve (ec);
1299 eclass = ExprClass.Value;
1300 Type etype = expr.Type;
1302 if (TypeManager.IsValueType (probe_type)){
1303 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1304 TypeManager.CSharpName (probe_type) + " is a value type)");
1309 e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1316 if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1321 Error_CannotConvertType (etype, probe_type, loc);
1327 /// This represents a typecast in the source language.
1329 /// FIXME: Cast expressions have an unusual set of parsing
1330 /// rules, we need to figure those out.
1332 public class Cast : Expression {
1333 Expression target_type;
1336 public Cast (Expression cast_type, Expression expr, Location loc)
1338 this.target_type = cast_type;
1343 public Expression TargetType {
1349 public Expression Expr {
1358 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1360 if (!ec.ConstantCheckState)
1363 if ((value < min) || (value > max)) {
1364 Error (221, "Constant value `" + value + "' cannot be converted " +
1365 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1366 "syntax to override)");
1373 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1375 if (!ec.ConstantCheckState)
1379 Error (221, "Constant value `" + value + "' cannot be converted " +
1380 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1381 "syntax to override)");
1388 bool CheckUnsigned (EmitContext ec, long value, Type type)
1390 if (!ec.ConstantCheckState)
1394 Error (221, "Constant value `" + value + "' cannot be converted " +
1395 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1396 "syntax to override)");
1404 /// Attempts to do a compile-time folding of a constant cast.
1406 Expression TryReduce (EmitContext ec, Type target_type)
1408 Expression real_expr = expr;
1409 if (real_expr is EnumConstant)
1410 real_expr = ((EnumConstant) real_expr).Child;
1412 if (real_expr is ByteConstant){
1413 byte v = ((ByteConstant) real_expr).Value;
1415 if (target_type == TypeManager.sbyte_type) {
1416 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1418 return new SByteConstant ((sbyte) v);
1420 if (target_type == TypeManager.short_type)
1421 return new ShortConstant ((short) v);
1422 if (target_type == TypeManager.ushort_type)
1423 return new UShortConstant ((ushort) v);
1424 if (target_type == TypeManager.int32_type)
1425 return new IntConstant ((int) v);
1426 if (target_type == TypeManager.uint32_type)
1427 return new UIntConstant ((uint) v);
1428 if (target_type == TypeManager.int64_type)
1429 return new LongConstant ((long) v);
1430 if (target_type == TypeManager.uint64_type)
1431 return new ULongConstant ((ulong) v);
1432 if (target_type == TypeManager.float_type)
1433 return new FloatConstant ((float) v);
1434 if (target_type == TypeManager.double_type)
1435 return new DoubleConstant ((double) v);
1436 if (target_type == TypeManager.char_type)
1437 return new CharConstant ((char) v);
1438 if (target_type == TypeManager.decimal_type)
1439 return new DecimalConstant ((decimal) v);
1441 if (real_expr is SByteConstant){
1442 sbyte v = ((SByteConstant) real_expr).Value;
1444 if (target_type == TypeManager.byte_type) {
1445 if (!CheckUnsigned (ec, v, target_type))
1447 return new ByteConstant ((byte) v);
1449 if (target_type == TypeManager.short_type)
1450 return new ShortConstant ((short) v);
1451 if (target_type == TypeManager.ushort_type) {
1452 if (!CheckUnsigned (ec, v, target_type))
1454 return new UShortConstant ((ushort) v);
1455 } if (target_type == TypeManager.int32_type)
1456 return new IntConstant ((int) v);
1457 if (target_type == TypeManager.uint32_type) {
1458 if (!CheckUnsigned (ec, v, target_type))
1460 return new UIntConstant ((uint) v);
1461 } if (target_type == TypeManager.int64_type)
1462 return new LongConstant ((long) v);
1463 if (target_type == TypeManager.uint64_type) {
1464 if (!CheckUnsigned (ec, v, target_type))
1466 return new ULongConstant ((ulong) v);
1468 if (target_type == TypeManager.float_type)
1469 return new FloatConstant ((float) v);
1470 if (target_type == TypeManager.double_type)
1471 return new DoubleConstant ((double) v);
1472 if (target_type == TypeManager.char_type) {
1473 if (!CheckUnsigned (ec, v, target_type))
1475 return new CharConstant ((char) v);
1477 if (target_type == TypeManager.decimal_type)
1478 return new DecimalConstant ((decimal) v);
1480 if (real_expr is ShortConstant){
1481 short v = ((ShortConstant) real_expr).Value;
1483 if (target_type == TypeManager.byte_type) {
1484 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1486 return new ByteConstant ((byte) v);
1488 if (target_type == TypeManager.sbyte_type) {
1489 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1491 return new SByteConstant ((sbyte) v);
1493 if (target_type == TypeManager.ushort_type) {
1494 if (!CheckUnsigned (ec, v, target_type))
1496 return new UShortConstant ((ushort) v);
1498 if (target_type == TypeManager.int32_type)
1499 return new IntConstant ((int) v);
1500 if (target_type == TypeManager.uint32_type) {
1501 if (!CheckUnsigned (ec, v, target_type))
1503 return new UIntConstant ((uint) v);
1505 if (target_type == TypeManager.int64_type)
1506 return new LongConstant ((long) v);
1507 if (target_type == TypeManager.uint64_type) {
1508 if (!CheckUnsigned (ec, v, target_type))
1510 return new ULongConstant ((ulong) v);
1512 if (target_type == TypeManager.float_type)
1513 return new FloatConstant ((float) v);
1514 if (target_type == TypeManager.double_type)
1515 return new DoubleConstant ((double) v);
1516 if (target_type == TypeManager.char_type) {
1517 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1519 return new CharConstant ((char) v);
1521 if (target_type == TypeManager.decimal_type)
1522 return new DecimalConstant ((decimal) v);
1524 if (real_expr is UShortConstant){
1525 ushort v = ((UShortConstant) real_expr).Value;
1527 if (target_type == TypeManager.byte_type) {
1528 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1530 return new ByteConstant ((byte) v);
1532 if (target_type == TypeManager.sbyte_type) {
1533 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1535 return new SByteConstant ((sbyte) v);
1537 if (target_type == TypeManager.short_type) {
1538 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1540 return new ShortConstant ((short) v);
1542 if (target_type == TypeManager.int32_type)
1543 return new IntConstant ((int) v);
1544 if (target_type == TypeManager.uint32_type)
1545 return new UIntConstant ((uint) v);
1546 if (target_type == TypeManager.int64_type)
1547 return new LongConstant ((long) v);
1548 if (target_type == TypeManager.uint64_type)
1549 return new ULongConstant ((ulong) v);
1550 if (target_type == TypeManager.float_type)
1551 return new FloatConstant ((float) v);
1552 if (target_type == TypeManager.double_type)
1553 return new DoubleConstant ((double) v);
1554 if (target_type == TypeManager.char_type) {
1555 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1557 return new CharConstant ((char) v);
1559 if (target_type == TypeManager.decimal_type)
1560 return new DecimalConstant ((decimal) v);
1562 if (real_expr is IntConstant){
1563 int v = ((IntConstant) real_expr).Value;
1565 if (target_type == TypeManager.byte_type) {
1566 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1568 return new ByteConstant ((byte) v);
1570 if (target_type == TypeManager.sbyte_type) {
1571 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1573 return new SByteConstant ((sbyte) v);
1575 if (target_type == TypeManager.short_type) {
1576 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1578 return new ShortConstant ((short) v);
1580 if (target_type == TypeManager.ushort_type) {
1581 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1583 return new UShortConstant ((ushort) v);
1585 if (target_type == TypeManager.uint32_type) {
1586 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1588 return new UIntConstant ((uint) v);
1590 if (target_type == TypeManager.int64_type)
1591 return new LongConstant ((long) v);
1592 if (target_type == TypeManager.uint64_type) {
1593 if (!CheckUnsigned (ec, v, target_type))
1595 return new ULongConstant ((ulong) v);
1597 if (target_type == TypeManager.float_type)
1598 return new FloatConstant ((float) v);
1599 if (target_type == TypeManager.double_type)
1600 return new DoubleConstant ((double) v);
1601 if (target_type == TypeManager.char_type) {
1602 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1604 return new CharConstant ((char) v);
1606 if (target_type == TypeManager.decimal_type)
1607 return new DecimalConstant ((decimal) v);
1609 if (real_expr is UIntConstant){
1610 uint v = ((UIntConstant) real_expr).Value;
1612 if (target_type == TypeManager.byte_type) {
1613 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1615 return new ByteConstant ((byte) v);
1617 if (target_type == TypeManager.sbyte_type) {
1618 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1620 return new SByteConstant ((sbyte) v);
1622 if (target_type == TypeManager.short_type) {
1623 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1625 return new ShortConstant ((short) v);
1627 if (target_type == TypeManager.ushort_type) {
1628 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1630 return new UShortConstant ((ushort) v);
1632 if (target_type == TypeManager.int32_type) {
1633 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1635 return new IntConstant ((int) v);
1637 if (target_type == TypeManager.int64_type)
1638 return new LongConstant ((long) v);
1639 if (target_type == TypeManager.uint64_type)
1640 return new ULongConstant ((ulong) v);
1641 if (target_type == TypeManager.float_type)
1642 return new FloatConstant ((float) v);
1643 if (target_type == TypeManager.double_type)
1644 return new DoubleConstant ((double) v);
1645 if (target_type == TypeManager.char_type) {
1646 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1648 return new CharConstant ((char) v);
1650 if (target_type == TypeManager.decimal_type)
1651 return new DecimalConstant ((decimal) v);
1653 if (real_expr is LongConstant){
1654 long v = ((LongConstant) real_expr).Value;
1656 if (target_type == TypeManager.byte_type) {
1657 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1659 return new ByteConstant ((byte) v);
1661 if (target_type == TypeManager.sbyte_type) {
1662 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1664 return new SByteConstant ((sbyte) v);
1666 if (target_type == TypeManager.short_type) {
1667 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1669 return new ShortConstant ((short) v);
1671 if (target_type == TypeManager.ushort_type) {
1672 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1674 return new UShortConstant ((ushort) v);
1676 if (target_type == TypeManager.int32_type) {
1677 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1679 return new IntConstant ((int) v);
1681 if (target_type == TypeManager.uint32_type) {
1682 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1684 return new UIntConstant ((uint) v);
1686 if (target_type == TypeManager.uint64_type) {
1687 if (!CheckUnsigned (ec, v, target_type))
1689 return new ULongConstant ((ulong) v);
1691 if (target_type == TypeManager.float_type)
1692 return new FloatConstant ((float) v);
1693 if (target_type == TypeManager.double_type)
1694 return new DoubleConstant ((double) v);
1695 if (target_type == TypeManager.char_type) {
1696 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1698 return new CharConstant ((char) v);
1700 if (target_type == TypeManager.decimal_type)
1701 return new DecimalConstant ((decimal) v);
1703 if (real_expr is ULongConstant){
1704 ulong v = ((ULongConstant) real_expr).Value;
1706 if (target_type == TypeManager.byte_type) {
1707 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1709 return new ByteConstant ((byte) v);
1711 if (target_type == TypeManager.sbyte_type) {
1712 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1714 return new SByteConstant ((sbyte) v);
1716 if (target_type == TypeManager.short_type) {
1717 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1719 return new ShortConstant ((short) v);
1721 if (target_type == TypeManager.ushort_type) {
1722 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1724 return new UShortConstant ((ushort) v);
1726 if (target_type == TypeManager.int32_type) {
1727 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1729 return new IntConstant ((int) v);
1731 if (target_type == TypeManager.uint32_type) {
1732 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1734 return new UIntConstant ((uint) v);
1736 if (target_type == TypeManager.int64_type) {
1737 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1739 return new LongConstant ((long) v);
1741 if (target_type == TypeManager.float_type)
1742 return new FloatConstant ((float) v);
1743 if (target_type == TypeManager.double_type)
1744 return new DoubleConstant ((double) v);
1745 if (target_type == TypeManager.char_type) {
1746 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1748 return new CharConstant ((char) v);
1750 if (target_type == TypeManager.decimal_type)
1751 return new DecimalConstant ((decimal) v);
1753 if (real_expr is FloatConstant){
1754 float v = ((FloatConstant) real_expr).Value;
1756 if (target_type == TypeManager.byte_type)
1757 return new ByteConstant ((byte) v);
1758 if (target_type == TypeManager.sbyte_type)
1759 return new SByteConstant ((sbyte) v);
1760 if (target_type == TypeManager.short_type)
1761 return new ShortConstant ((short) v);
1762 if (target_type == TypeManager.ushort_type)
1763 return new UShortConstant ((ushort) v);
1764 if (target_type == TypeManager.int32_type)
1765 return new IntConstant ((int) v);
1766 if (target_type == TypeManager.uint32_type)
1767 return new UIntConstant ((uint) v);
1768 if (target_type == TypeManager.int64_type)
1769 return new LongConstant ((long) v);
1770 if (target_type == TypeManager.uint64_type)
1771 return new ULongConstant ((ulong) v);
1772 if (target_type == TypeManager.double_type)
1773 return new DoubleConstant ((double) v);
1774 if (target_type == TypeManager.char_type)
1775 return new CharConstant ((char) v);
1776 if (target_type == TypeManager.decimal_type)
1777 return new DecimalConstant ((decimal) v);
1779 if (real_expr is DoubleConstant){
1780 double v = ((DoubleConstant) real_expr).Value;
1782 if (target_type == TypeManager.byte_type){
1783 return new ByteConstant ((byte) v);
1784 } if (target_type == TypeManager.sbyte_type)
1785 return new SByteConstant ((sbyte) v);
1786 if (target_type == TypeManager.short_type)
1787 return new ShortConstant ((short) v);
1788 if (target_type == TypeManager.ushort_type)
1789 return new UShortConstant ((ushort) v);
1790 if (target_type == TypeManager.int32_type)
1791 return new IntConstant ((int) v);
1792 if (target_type == TypeManager.uint32_type)
1793 return new UIntConstant ((uint) v);
1794 if (target_type == TypeManager.int64_type)
1795 return new LongConstant ((long) v);
1796 if (target_type == TypeManager.uint64_type)
1797 return new ULongConstant ((ulong) v);
1798 if (target_type == TypeManager.float_type)
1799 return new FloatConstant ((float) v);
1800 if (target_type == TypeManager.char_type)
1801 return new CharConstant ((char) v);
1802 if (target_type == TypeManager.decimal_type)
1803 return new DecimalConstant ((decimal) v);
1806 if (real_expr is CharConstant){
1807 char v = ((CharConstant) real_expr).Value;
1809 if (target_type == TypeManager.byte_type) {
1810 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1812 return new ByteConstant ((byte) v);
1814 if (target_type == TypeManager.sbyte_type) {
1815 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1817 return new SByteConstant ((sbyte) v);
1819 if (target_type == TypeManager.short_type) {
1820 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1822 return new ShortConstant ((short) v);
1824 if (target_type == TypeManager.int32_type)
1825 return new IntConstant ((int) v);
1826 if (target_type == TypeManager.uint32_type)
1827 return new UIntConstant ((uint) v);
1828 if (target_type == TypeManager.int64_type)
1829 return new LongConstant ((long) v);
1830 if (target_type == TypeManager.uint64_type)
1831 return new ULongConstant ((ulong) v);
1832 if (target_type == TypeManager.float_type)
1833 return new FloatConstant ((float) v);
1834 if (target_type == TypeManager.double_type)
1835 return new DoubleConstant ((double) v);
1836 if (target_type == TypeManager.char_type) {
1837 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1839 return new CharConstant ((char) v);
1841 if (target_type == TypeManager.decimal_type)
1842 return new DecimalConstant ((decimal) v);
1848 public override Expression DoResolve (EmitContext ec)
1850 expr = expr.Resolve (ec);
1854 type = ec.DeclSpace.ResolveType (target_type, false, Location);
1859 CheckObsoleteAttribute (type);
1861 eclass = ExprClass.Value;
1863 if (expr is Constant){
1864 Expression e = TryReduce (ec, type);
1870 if (type.IsPointer && !ec.InUnsafe) {
1874 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1878 public override void Emit (EmitContext ec)
1881 // This one will never happen
1883 throw new Exception ("Should not happen");
1888 /// Binary operators
1890 public class Binary : Expression {
1891 public enum Operator : byte {
1892 Multiply, Division, Modulus,
1893 Addition, Subtraction,
1894 LeftShift, RightShift,
1895 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1896 Equality, Inequality,
1906 Expression left, right;
1908 // This must be kept in sync with Operator!!!
1909 public static readonly string [] oper_names;
1913 oper_names = new string [(int) Operator.TOP];
1915 oper_names [(int) Operator.Multiply] = "op_Multiply";
1916 oper_names [(int) Operator.Division] = "op_Division";
1917 oper_names [(int) Operator.Modulus] = "op_Modulus";
1918 oper_names [(int) Operator.Addition] = "op_Addition";
1919 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1920 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1921 oper_names [(int) Operator.RightShift] = "op_RightShift";
1922 oper_names [(int) Operator.LessThan] = "op_LessThan";
1923 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1924 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1925 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1926 oper_names [(int) Operator.Equality] = "op_Equality";
1927 oper_names [(int) Operator.Inequality] = "op_Inequality";
1928 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1929 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1930 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1931 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1932 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1935 public Binary (Operator oper, Expression left, Expression right, Location loc)
1943 public Operator Oper {
1952 public Expression Left {
1961 public Expression Right {
1972 /// Returns a stringified representation of the Operator
1974 static string OperName (Operator oper)
1977 case Operator.Multiply:
1979 case Operator.Division:
1981 case Operator.Modulus:
1983 case Operator.Addition:
1985 case Operator.Subtraction:
1987 case Operator.LeftShift:
1989 case Operator.RightShift:
1991 case Operator.LessThan:
1993 case Operator.GreaterThan:
1995 case Operator.LessThanOrEqual:
1997 case Operator.GreaterThanOrEqual:
1999 case Operator.Equality:
2001 case Operator.Inequality:
2003 case Operator.BitwiseAnd:
2005 case Operator.BitwiseOr:
2007 case Operator.ExclusiveOr:
2009 case Operator.LogicalOr:
2011 case Operator.LogicalAnd:
2015 return oper.ToString ();
2018 public override string ToString ()
2020 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
2021 right.ToString () + ")";
2024 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
2026 if (expr.Type == target_type)
2029 return Convert.ImplicitConversion (ec, expr, target_type, loc);
2032 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
2035 34, loc, "Operator `" + OperName (oper)
2036 + "' is ambiguous on operands of type `"
2037 + TypeManager.CSharpName (l) + "' "
2038 + "and `" + TypeManager.CSharpName (r)
2042 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
2044 if ((l == t) || (r == t))
2047 if (!check_user_conversions)
2050 if (Convert.ImplicitUserConversionExists (ec, l, t))
2052 else if (Convert.ImplicitUserConversionExists (ec, r, t))
2059 // Note that handling the case l == Decimal || r == Decimal
2060 // is taken care of by the Step 1 Operator Overload resolution.
2062 // If `check_user_conv' is true, we also check whether a user-defined conversion
2063 // exists. Note that we only need to do this if both arguments are of a user-defined
2064 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
2065 // so we don't explicitly check for performance reasons.
2067 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
2069 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
2071 // If either operand is of type double, the other operand is
2072 // conveted to type double.
2074 if (r != TypeManager.double_type)
2075 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
2076 if (l != TypeManager.double_type)
2077 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
2079 type = TypeManager.double_type;
2080 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
2082 // if either operand is of type float, the other operand is
2083 // converted to type float.
2085 if (r != TypeManager.double_type)
2086 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
2087 if (l != TypeManager.double_type)
2088 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
2089 type = TypeManager.float_type;
2090 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2094 // If either operand is of type ulong, the other operand is
2095 // converted to type ulong. or an error ocurrs if the other
2096 // operand is of type sbyte, short, int or long
2098 if (l == TypeManager.uint64_type){
2099 if (r != TypeManager.uint64_type){
2100 if (right is IntConstant){
2101 IntConstant ic = (IntConstant) right;
2103 e = Convert.TryImplicitIntConversion (l, ic);
2106 } else if (right is LongConstant){
2107 long ll = ((LongConstant) right).Value;
2110 right = new ULongConstant ((ulong) ll);
2112 e = Convert.ImplicitNumericConversion (ec, right, l, loc);
2119 if (left is IntConstant){
2120 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
2123 } else if (left is LongConstant){
2124 long ll = ((LongConstant) left).Value;
2127 left = new ULongConstant ((ulong) ll);
2129 e = Convert.ImplicitNumericConversion (ec, left, r, loc);
2136 if ((other == TypeManager.sbyte_type) ||
2137 (other == TypeManager.short_type) ||
2138 (other == TypeManager.int32_type) ||
2139 (other == TypeManager.int64_type))
2140 Error_OperatorAmbiguous (loc, oper, l, r);
2142 left = ForceConversion (ec, left, TypeManager.uint64_type);
2143 right = ForceConversion (ec, right, TypeManager.uint64_type);
2145 type = TypeManager.uint64_type;
2146 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2148 // If either operand is of type long, the other operand is converted
2151 if (l != TypeManager.int64_type)
2152 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
2153 if (r != TypeManager.int64_type)
2154 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
2156 type = TypeManager.int64_type;
2157 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2159 // If either operand is of type uint, and the other
2160 // operand is of type sbyte, short or int, othe operands are
2161 // converted to type long (unless we have an int constant).
2165 if (l == TypeManager.uint32_type){
2166 if (right is IntConstant){
2167 IntConstant ic = (IntConstant) right;
2171 right = new UIntConstant ((uint) val);
2178 } else if (r == TypeManager.uint32_type){
2179 if (left is IntConstant){
2180 IntConstant ic = (IntConstant) left;
2184 left = new UIntConstant ((uint) val);
2193 if ((other == TypeManager.sbyte_type) ||
2194 (other == TypeManager.short_type) ||
2195 (other == TypeManager.int32_type)){
2196 left = ForceConversion (ec, left, TypeManager.int64_type);
2197 right = ForceConversion (ec, right, TypeManager.int64_type);
2198 type = TypeManager.int64_type;
2201 // if either operand is of type uint, the other
2202 // operand is converd to type uint
2204 left = ForceConversion (ec, left, TypeManager.uint32_type);
2205 right = ForceConversion (ec, right, TypeManager.uint32_type);
2206 type = TypeManager.uint32_type;
2208 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2209 if (l != TypeManager.decimal_type)
2210 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
2212 if (r != TypeManager.decimal_type)
2213 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
2214 type = TypeManager.decimal_type;
2216 left = ForceConversion (ec, left, TypeManager.int32_type);
2217 right = ForceConversion (ec, right, TypeManager.int32_type);
2219 type = TypeManager.int32_type;
2222 return (left != null) && (right != null);
2225 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2227 Report.Error (19, loc,
2228 "Operator " + name + " cannot be applied to operands of type `" +
2229 TypeManager.CSharpName (l) + "' and `" +
2230 TypeManager.CSharpName (r) + "'");
2233 void Error_OperatorCannotBeApplied ()
2235 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2238 static bool is_unsigned (Type t)
2240 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2241 t == TypeManager.short_type || t == TypeManager.byte_type);
2244 static bool is_user_defined (Type t)
2246 if (t.IsSubclassOf (TypeManager.value_type) &&
2247 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2253 Expression Make32or64 (EmitContext ec, Expression e)
2257 if (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2258 t == TypeManager.int64_type || t == TypeManager.uint64_type)
2260 Expression ee = Convert.ImplicitConversion (ec, e, TypeManager.int32_type, loc);
2263 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint32_type, loc);
2266 ee = Convert.ImplicitConversion (ec, e, TypeManager.int64_type, loc);
2269 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint64_type, loc);
2275 Expression CheckShiftArguments (EmitContext ec)
2279 e = ForceConversion (ec, right, TypeManager.int32_type);
2281 Error_OperatorCannotBeApplied ();
2286 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
2287 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
2288 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
2289 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
2293 if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
2294 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (31), loc);
2295 right = right.DoResolve (ec);
2297 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (63), loc);
2298 right = right.DoResolve (ec);
2303 Error_OperatorCannotBeApplied ();
2307 Expression ResolveOperator (EmitContext ec)
2310 Type r = right.Type;
2313 // Special cases: string comapred to null
2315 if (oper == Operator.Equality || oper == Operator.Inequality){
2316 if ((l == TypeManager.string_type && (right is NullLiteral)) ||
2317 (r == TypeManager.string_type && (left is NullLiteral))){
2318 Type = TypeManager.bool_type;
2324 if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
2325 Type = TypeManager.bool_type;
2332 // Do not perform operator overload resolution when both sides are
2335 if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
2337 // Step 1: Perform Operator Overload location
2339 Expression left_expr, right_expr;
2341 string op = oper_names [(int) oper];
2343 MethodGroupExpr union;
2344 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2346 right_expr = MemberLookup (
2347 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2348 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2350 union = (MethodGroupExpr) left_expr;
2352 if (union != null) {
2353 ArrayList args = new ArrayList (2);
2354 args.Add (new Argument (left, Argument.AType.Expression));
2355 args.Add (new Argument (right, Argument.AType.Expression));
2357 MethodBase method = Invocation.OverloadResolve (ec, union, args, Location.Null);
2358 if (method != null) {
2359 MethodInfo mi = (MethodInfo) method;
2361 return new BinaryMethod (mi.ReturnType, method, args);
2367 // Step 0: String concatenation (because overloading will get this wrong)
2369 if (oper == Operator.Addition){
2371 // If any of the arguments is a string, cast to string
2374 // Simple constant folding
2375 if (left is StringConstant && right is StringConstant)
2376 return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value);
2378 if (l == TypeManager.string_type || r == TypeManager.string_type) {
2380 if (r == TypeManager.void_type || l == TypeManager.void_type) {
2381 Error_OperatorCannotBeApplied ();
2385 // try to fold it in on the left
2386 if (left is StringConcat) {
2389 // We have to test here for not-null, since we can be doubly-resolved
2390 // take care of not appending twice
2393 type = TypeManager.string_type;
2394 ((StringConcat) left).Append (ec, right);
2395 return left.Resolve (ec);
2401 // Otherwise, start a new concat expression
2402 return new StringConcat (ec, loc, left, right).Resolve (ec);
2406 // Transform a + ( - b) into a - b
2408 if (right is Unary){
2409 Unary right_unary = (Unary) right;
2411 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2412 oper = Operator.Subtraction;
2413 right = right_unary.Expr;
2419 if (oper == Operator.Equality || oper == Operator.Inequality){
2420 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2421 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2422 Error_OperatorCannotBeApplied ();
2426 type = TypeManager.bool_type;
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 (left, r) ||
2453 Convert.ImplicitStandardConversionExists (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 (l.IsSubclassOf (TypeManager.delegate_type)){
2485 if (right.eclass == ExprClass.MethodGroup && RootContext.V2){
2486 Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2493 if (r.IsSubclassOf (TypeManager.delegate_type)){
2495 ArrayList args = new ArrayList (2);
2497 args = new ArrayList (2);
2498 args.Add (new Argument (left, Argument.AType.Expression));
2499 args.Add (new Argument (right, Argument.AType.Expression));
2501 if (oper == Operator.Addition)
2502 method = TypeManager.delegate_combine_delegate_delegate;
2504 method = TypeManager.delegate_remove_delegate_delegate;
2507 Error_OperatorCannotBeApplied ();
2511 return new BinaryDelegate (l, method, args);
2516 // Pointer arithmetic:
2518 // T* operator + (T* x, int y);
2519 // T* operator + (T* x, uint y);
2520 // T* operator + (T* x, long y);
2521 // T* operator + (T* x, ulong y);
2523 // T* operator + (int y, T* x);
2524 // T* operator + (uint y, T *x);
2525 // T* operator + (long y, T *x);
2526 // T* operator + (ulong y, T *x);
2528 // T* operator - (T* x, int y);
2529 // T* operator - (T* x, uint y);
2530 // T* operator - (T* x, long y);
2531 // T* operator - (T* x, ulong y);
2533 // long operator - (T* x, T *y)
2536 if (r.IsPointer && oper == Operator.Subtraction){
2538 return new PointerArithmetic (
2539 false, left, right, TypeManager.int64_type,
2542 Expression t = Make32or64 (ec, right);
2544 return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc).Resolve (ec);
2546 } else if (r.IsPointer && oper == Operator.Addition){
2547 Expression t = Make32or64 (ec, left);
2549 return new PointerArithmetic (true, right, t, r, loc).Resolve (ec);
2554 // Enumeration operators
2556 bool lie = TypeManager.IsEnumType (l);
2557 bool rie = TypeManager.IsEnumType (r);
2561 // U operator - (E e, E f)
2563 if (oper == Operator.Subtraction){
2565 type = TypeManager.EnumToUnderlying (l);
2568 Error_OperatorCannotBeApplied ();
2574 // operator + (E e, U x)
2575 // operator - (E e, U x)
2577 if (oper == Operator.Addition || oper == Operator.Subtraction){
2578 Type enum_type = lie ? l : r;
2579 Type other_type = lie ? r : l;
2580 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2582 if (underlying_type != other_type){
2583 temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
2593 Error_OperatorCannotBeApplied ();
2602 temp = Convert.ImplicitConversion (ec, right, l, loc);
2606 Error_OperatorCannotBeApplied ();
2610 temp = Convert.ImplicitConversion (ec, left, r, loc);
2615 Error_OperatorCannotBeApplied ();
2620 if (oper == Operator.Equality || oper == Operator.Inequality ||
2621 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2622 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2623 if (left.Type != right.Type){
2624 Error_OperatorCannotBeApplied ();
2627 type = TypeManager.bool_type;
2631 if (oper == Operator.BitwiseAnd ||
2632 oper == Operator.BitwiseOr ||
2633 oper == Operator.ExclusiveOr){
2637 Error_OperatorCannotBeApplied ();
2641 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2642 return CheckShiftArguments (ec);
2644 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2645 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2646 type = TypeManager.bool_type;
2651 Error_OperatorCannotBeApplied ();
2655 Expression e = new ConditionalLogicalOperator (
2656 oper == Operator.LogicalAnd, left, right, l, loc);
2657 return e.Resolve (ec);
2661 // operator & (bool x, bool y)
2662 // operator | (bool x, bool y)
2663 // operator ^ (bool x, bool y)
2665 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2666 if (oper == Operator.BitwiseAnd ||
2667 oper == Operator.BitwiseOr ||
2668 oper == Operator.ExclusiveOr){
2675 // Pointer comparison
2677 if (l.IsPointer && r.IsPointer){
2678 if (oper == Operator.Equality || oper == Operator.Inequality ||
2679 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2680 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2681 type = TypeManager.bool_type;
2687 // This will leave left or right set to null if there is an error
2689 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2690 DoNumericPromotions (ec, l, r, check_user_conv);
2691 if (left == null || right == null){
2692 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2697 // reload our cached types if required
2702 if (oper == Operator.BitwiseAnd ||
2703 oper == Operator.BitwiseOr ||
2704 oper == Operator.ExclusiveOr){
2706 if (((l == TypeManager.int32_type) ||
2707 (l == TypeManager.uint32_type) ||
2708 (l == TypeManager.short_type) ||
2709 (l == TypeManager.ushort_type) ||
2710 (l == TypeManager.int64_type) ||
2711 (l == TypeManager.uint64_type))){
2714 Error_OperatorCannotBeApplied ();
2718 Error_OperatorCannotBeApplied ();
2723 if (oper == Operator.Equality ||
2724 oper == Operator.Inequality ||
2725 oper == Operator.LessThanOrEqual ||
2726 oper == Operator.LessThan ||
2727 oper == Operator.GreaterThanOrEqual ||
2728 oper == Operator.GreaterThan){
2729 type = TypeManager.bool_type;
2735 public override Expression DoResolve (EmitContext ec)
2737 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2738 left = ((ParenthesizedExpression) left).Expr;
2739 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2743 if (left.eclass == ExprClass.Type) {
2744 Error (75, "Casting a negative value needs to have the value in parentheses.");
2748 left = left.Resolve (ec);
2749 right = right.Resolve (ec);
2751 if (left == null || right == null)
2754 eclass = ExprClass.Value;
2756 Constant rc = right as Constant;
2757 Constant lc = left as Constant;
2759 if (rc != null & lc != null){
2760 Expression e = ConstantFold.BinaryFold (
2761 ec, oper, lc, rc, loc);
2766 return ResolveOperator (ec);
2770 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2771 /// context of a conditional bool expression. This function will return
2772 /// false if it is was possible to use EmitBranchable, or true if it was.
2774 /// The expression's code is generated, and we will generate a branch to `target'
2775 /// if the resulting expression value is equal to isTrue
2777 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2779 ILGenerator ig = ec.ig;
2782 // This is more complicated than it looks, but its just to avoid
2783 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2784 // but on top of that we want for == and != to use a special path
2785 // if we are comparing against null
2787 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
2788 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2791 // put the constant on the rhs, for simplicity
2793 if (left is Constant) {
2794 Expression swap = right;
2799 if (((Constant) right).IsZeroInteger) {
2802 ig.Emit (OpCodes.Brtrue, target);
2804 ig.Emit (OpCodes.Brfalse, target);
2807 } else if (right is BoolConstant) {
2809 if (my_on_true != ((BoolConstant) right).Value)
2810 ig.Emit (OpCodes.Brtrue, target);
2812 ig.Emit (OpCodes.Brfalse, target);
2817 } else if (oper == Operator.LogicalAnd) {
2820 Label tests_end = ig.DefineLabel ();
2822 left.EmitBranchable (ec, tests_end, false);
2823 right.EmitBranchable (ec, target, true);
2824 ig.MarkLabel (tests_end);
2826 left.EmitBranchable (ec, target, false);
2827 right.EmitBranchable (ec, target, false);
2832 } else if (oper == Operator.LogicalOr){
2834 left.EmitBranchable (ec, target, true);
2835 right.EmitBranchable (ec, target, true);
2838 Label tests_end = ig.DefineLabel ();
2839 left.EmitBranchable (ec, tests_end, true);
2840 right.EmitBranchable (ec, target, false);
2841 ig.MarkLabel (tests_end);
2846 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2847 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2848 oper == Operator.Equality || oper == Operator.Inequality)) {
2849 base.EmitBranchable (ec, target, onTrue);
2857 bool isUnsigned = is_unsigned (t) || t == TypeManager.double_type || t == TypeManager.float_type;
2860 case Operator.Equality:
2862 ig.Emit (OpCodes.Beq, target);
2864 ig.Emit (OpCodes.Bne_Un, target);
2867 case Operator.Inequality:
2869 ig.Emit (OpCodes.Bne_Un, target);
2871 ig.Emit (OpCodes.Beq, target);
2874 case Operator.LessThan:
2877 ig.Emit (OpCodes.Blt_Un, target);
2879 ig.Emit (OpCodes.Blt, target);
2882 ig.Emit (OpCodes.Bge_Un, target);
2884 ig.Emit (OpCodes.Bge, target);
2887 case Operator.GreaterThan:
2890 ig.Emit (OpCodes.Bgt_Un, target);
2892 ig.Emit (OpCodes.Bgt, target);
2895 ig.Emit (OpCodes.Ble_Un, target);
2897 ig.Emit (OpCodes.Ble, target);
2900 case Operator.LessThanOrEqual:
2903 ig.Emit (OpCodes.Ble_Un, target);
2905 ig.Emit (OpCodes.Ble, target);
2908 ig.Emit (OpCodes.Bgt_Un, target);
2910 ig.Emit (OpCodes.Bgt, target);
2914 case Operator.GreaterThanOrEqual:
2917 ig.Emit (OpCodes.Bge_Un, target);
2919 ig.Emit (OpCodes.Bge, target);
2922 ig.Emit (OpCodes.Blt_Un, target);
2924 ig.Emit (OpCodes.Blt, target);
2927 Console.WriteLine (oper);
2928 throw new Exception ("what is THAT");
2932 public override void Emit (EmitContext ec)
2934 ILGenerator ig = ec.ig;
2939 // Handle short-circuit operators differently
2942 if (oper == Operator.LogicalAnd) {
2943 Label load_zero = ig.DefineLabel ();
2944 Label end = ig.DefineLabel ();
2946 left.EmitBranchable (ec, load_zero, false);
2948 ig.Emit (OpCodes.Br, end);
2950 ig.MarkLabel (load_zero);
2951 ig.Emit (OpCodes.Ldc_I4_0);
2954 } else if (oper == Operator.LogicalOr) {
2955 Label load_one = ig.DefineLabel ();
2956 Label end = ig.DefineLabel ();
2958 left.EmitBranchable (ec, load_one, true);
2960 ig.Emit (OpCodes.Br, end);
2962 ig.MarkLabel (load_one);
2963 ig.Emit (OpCodes.Ldc_I4_1);
2971 bool isUnsigned = is_unsigned (left.Type);
2974 case Operator.Multiply:
2976 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2977 opcode = OpCodes.Mul_Ovf;
2978 else if (isUnsigned)
2979 opcode = OpCodes.Mul_Ovf_Un;
2981 opcode = OpCodes.Mul;
2983 opcode = OpCodes.Mul;
2987 case Operator.Division:
2989 opcode = OpCodes.Div_Un;
2991 opcode = OpCodes.Div;
2994 case Operator.Modulus:
2996 opcode = OpCodes.Rem_Un;
2998 opcode = OpCodes.Rem;
3001 case Operator.Addition:
3003 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3004 opcode = OpCodes.Add_Ovf;
3005 else if (isUnsigned)
3006 opcode = OpCodes.Add_Ovf_Un;
3008 opcode = OpCodes.Add;
3010 opcode = OpCodes.Add;
3013 case Operator.Subtraction:
3015 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3016 opcode = OpCodes.Sub_Ovf;
3017 else if (isUnsigned)
3018 opcode = OpCodes.Sub_Ovf_Un;
3020 opcode = OpCodes.Sub;
3022 opcode = OpCodes.Sub;
3025 case Operator.RightShift:
3027 opcode = OpCodes.Shr_Un;
3029 opcode = OpCodes.Shr;
3032 case Operator.LeftShift:
3033 opcode = OpCodes.Shl;
3036 case Operator.Equality:
3037 opcode = OpCodes.Ceq;
3040 case Operator.Inequality:
3041 ig.Emit (OpCodes.Ceq);
3042 ig.Emit (OpCodes.Ldc_I4_0);
3044 opcode = OpCodes.Ceq;
3047 case Operator.LessThan:
3049 opcode = OpCodes.Clt_Un;
3051 opcode = OpCodes.Clt;
3054 case Operator.GreaterThan:
3056 opcode = OpCodes.Cgt_Un;
3058 opcode = OpCodes.Cgt;
3061 case Operator.LessThanOrEqual:
3062 Type lt = left.Type;
3064 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
3065 ig.Emit (OpCodes.Cgt_Un);
3067 ig.Emit (OpCodes.Cgt);
3068 ig.Emit (OpCodes.Ldc_I4_0);
3070 opcode = OpCodes.Ceq;
3073 case Operator.GreaterThanOrEqual:
3074 Type le = left.Type;
3076 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3077 ig.Emit (OpCodes.Clt_Un);
3079 ig.Emit (OpCodes.Clt);
3081 ig.Emit (OpCodes.Ldc_I4_0);
3083 opcode = OpCodes.Ceq;
3086 case Operator.BitwiseOr:
3087 opcode = OpCodes.Or;
3090 case Operator.BitwiseAnd:
3091 opcode = OpCodes.And;
3094 case Operator.ExclusiveOr:
3095 opcode = OpCodes.Xor;
3099 throw new Exception ("This should not happen: Operator = "
3100 + oper.ToString ());
3108 // Object created by Binary when the binary operator uses an method instead of being
3109 // a binary operation that maps to a CIL binary operation.
3111 public class BinaryMethod : Expression {
3112 public MethodBase method;
3113 public ArrayList Arguments;
3115 public BinaryMethod (Type t, MethodBase m, ArrayList args)
3120 eclass = ExprClass.Value;
3123 public override Expression DoResolve (EmitContext ec)
3128 public override void Emit (EmitContext ec)
3130 ILGenerator ig = ec.ig;
3132 if (Arguments != null)
3133 Invocation.EmitArguments (ec, method, Arguments);
3135 if (method is MethodInfo)
3136 ig.Emit (OpCodes.Call, (MethodInfo) method);
3138 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3143 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3144 // b, c, d... may be strings or objects.
3146 public class StringConcat : Expression {
3148 bool invalid = false;
3151 public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
3154 type = TypeManager.string_type;
3155 eclass = ExprClass.Value;
3157 operands = new ArrayList (2);
3162 public override Expression DoResolve (EmitContext ec)
3170 public void Append (EmitContext ec, Expression operand)
3175 if (operand is StringConstant && operands.Count != 0) {
3176 StringConstant last_operand = operands [operands.Count - 1] as StringConstant;
3177 if (last_operand != null) {
3178 operands [operands.Count - 1] = new StringConstant (last_operand.Value + ((StringConstant) operand).Value);
3184 // Conversion to object
3186 if (operand.Type != TypeManager.string_type) {
3187 Expression no = Convert.ImplicitConversion (ec, operand, TypeManager.object_type, loc);
3190 Binary.Error_OperatorCannotBeApplied (loc, "+", TypeManager.string_type, operand.Type);
3196 operands.Add (operand);
3199 public override void Emit (EmitContext ec)
3201 MethodInfo concat_method = null;
3204 // Are we also concating objects?
3206 bool is_strings_only = true;
3209 // Do conversion to arguments; check for strings only
3211 for (int i = 0; i < operands.Count; i ++) {
3212 Expression e = (Expression) operands [i];
3213 is_strings_only &= e.Type == TypeManager.string_type;
3216 for (int i = 0; i < operands.Count; i ++) {
3217 Expression e = (Expression) operands [i];
3219 if (! is_strings_only && e.Type == TypeManager.string_type) {
3220 // need to make sure this is an object, because the EmitParams
3221 // method might look at the type of this expression, see it is a
3222 // string and emit a string [] when we want an object [];
3224 e = Convert.ImplicitConversion (ec, e, TypeManager.object_type, loc);
3226 operands [i] = new Argument (e, Argument.AType.Expression);
3230 // Find the right method
3232 switch (operands.Count) {
3235 // This should not be possible, because simple constant folding
3236 // is taken care of in the Binary code.
3238 throw new Exception ("how did you get here?");
3241 concat_method = is_strings_only ?
3242 TypeManager.string_concat_string_string :
3243 TypeManager.string_concat_object_object ;
3246 concat_method = is_strings_only ?
3247 TypeManager.string_concat_string_string_string :
3248 TypeManager.string_concat_object_object_object ;
3252 // There is not a 4 param overlaod for object (the one that there is
3253 // is actually a varargs methods, and is only in corlib because it was
3254 // introduced there before.).
3256 if (!is_strings_only)
3259 concat_method = TypeManager.string_concat_string_string_string_string;
3262 concat_method = is_strings_only ?
3263 TypeManager.string_concat_string_dot_dot_dot :
3264 TypeManager.string_concat_object_dot_dot_dot ;
3268 Invocation.EmitArguments (ec, concat_method, operands);
3269 ec.ig.Emit (OpCodes.Call, concat_method);
3274 // Object created with +/= on delegates
3276 public class BinaryDelegate : Expression {
3280 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3285 eclass = ExprClass.Value;
3288 public override Expression DoResolve (EmitContext ec)
3293 public override void Emit (EmitContext ec)
3295 ILGenerator ig = ec.ig;
3297 Invocation.EmitArguments (ec, method, args);
3299 ig.Emit (OpCodes.Call, (MethodInfo) method);
3300 ig.Emit (OpCodes.Castclass, type);
3303 public Expression Right {
3305 Argument arg = (Argument) args [1];
3310 public bool IsAddition {
3312 return method == TypeManager.delegate_combine_delegate_delegate;
3318 // User-defined conditional logical operator
3319 public class ConditionalLogicalOperator : Expression {
3320 Expression left, right;
3323 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3326 eclass = ExprClass.Value;
3330 this.is_and = is_and;
3333 protected void Error19 ()
3335 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3338 protected void Error218 ()
3340 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3341 "declarations of operator true and operator false");
3344 Expression op_true, op_false, op;
3345 LocalTemporary left_temp;
3347 public override Expression DoResolve (EmitContext ec)
3350 Expression operator_group;
3352 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3353 if (operator_group == null) {
3358 left_temp = new LocalTemporary (ec, type);
3360 ArrayList arguments = new ArrayList ();
3361 arguments.Add (new Argument (left_temp, Argument.AType.Expression));
3362 arguments.Add (new Argument (right, Argument.AType.Expression));
3363 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) operator_group, arguments, loc) as MethodInfo;
3364 if ((method == null) || (method.ReturnType != type)) {
3369 op = new StaticCallExpr (method, arguments, loc);
3371 op_true = GetOperatorTrue (ec, left_temp, loc);
3372 op_false = GetOperatorFalse (ec, left_temp, loc);
3373 if ((op_true == null) || (op_false == null)) {
3381 public override void Emit (EmitContext ec)
3383 ILGenerator ig = ec.ig;
3384 Label false_target = ig.DefineLabel ();
3385 Label end_target = ig.DefineLabel ();
3387 ig.Emit (OpCodes.Nop);
3390 left_temp.Store (ec);
3392 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
3393 left_temp.Emit (ec);
3394 ig.Emit (OpCodes.Br, end_target);
3395 ig.MarkLabel (false_target);
3397 ig.MarkLabel (end_target);
3399 ig.Emit (OpCodes.Nop);
3403 public class PointerArithmetic : Expression {
3404 Expression left, right;
3408 // We assume that `l' is always a pointer
3410 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3416 is_add = is_addition;
3419 public override Expression DoResolve (EmitContext ec)
3421 eclass = ExprClass.Variable;
3423 if (left.Type == TypeManager.void_ptr_type) {
3424 Error (242, "The operation in question is undefined on void pointers");
3431 public override void Emit (EmitContext ec)
3433 Type op_type = left.Type;
3434 ILGenerator ig = ec.ig;
3435 Type element = TypeManager.GetElementType (op_type);
3436 int size = GetTypeSize (element);
3437 Type rtype = right.Type;
3439 if (rtype.IsPointer){
3441 // handle (pointer - pointer)
3445 ig.Emit (OpCodes.Sub);
3449 ig.Emit (OpCodes.Sizeof, element);
3451 IntLiteral.EmitInt (ig, size);
3452 ig.Emit (OpCodes.Div);
3454 ig.Emit (OpCodes.Conv_I8);
3457 // handle + and - on (pointer op int)
3460 ig.Emit (OpCodes.Conv_I);
3464 ig.Emit (OpCodes.Sizeof, element);
3466 IntLiteral.EmitInt (ig, size);
3467 if (rtype == TypeManager.int64_type)
3468 ig.Emit (OpCodes.Conv_I8);
3469 else if (rtype == TypeManager.uint64_type)
3470 ig.Emit (OpCodes.Conv_U8);
3471 ig.Emit (OpCodes.Mul);
3474 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
3475 ig.Emit (OpCodes.Conv_I);
3478 ig.Emit (OpCodes.Add);
3480 ig.Emit (OpCodes.Sub);
3486 /// Implements the ternary conditional operator (?:)
3488 public class Conditional : Expression {
3489 Expression expr, trueExpr, falseExpr;
3491 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3494 this.trueExpr = trueExpr;
3495 this.falseExpr = falseExpr;
3499 public Expression Expr {
3505 public Expression TrueExpr {
3511 public Expression FalseExpr {
3517 public override Expression DoResolve (EmitContext ec)
3519 expr = expr.Resolve (ec);
3524 if (expr.Type != TypeManager.bool_type){
3525 expr = Expression.ResolveBoolean (
3532 trueExpr = trueExpr.Resolve (ec);
3533 falseExpr = falseExpr.Resolve (ec);
3535 if (trueExpr == null || falseExpr == null)
3538 eclass = ExprClass.Value;
3539 if (trueExpr.Type == falseExpr.Type)
3540 type = trueExpr.Type;
3543 Type true_type = trueExpr.Type;
3544 Type false_type = falseExpr.Type;
3546 if (trueExpr is NullLiteral){
3549 } else if (falseExpr is NullLiteral){
3555 // First, if an implicit conversion exists from trueExpr
3556 // to falseExpr, then the result type is of type falseExpr.Type
3558 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3561 // Check if both can convert implicitl to each other's type
3563 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3565 "Can not compute type of conditional expression " +
3566 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3567 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3568 "' convert implicitly to each other");
3573 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3577 Error (173, "The type of the conditional expression can " +
3578 "not be computed because there is no implicit conversion" +
3579 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3580 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3585 if (expr is BoolConstant){
3586 BoolConstant bc = (BoolConstant) expr;
3597 public override void Emit (EmitContext ec)
3599 ILGenerator ig = ec.ig;
3600 Label false_target = ig.DefineLabel ();
3601 Label end_target = ig.DefineLabel ();
3603 expr.EmitBranchable (ec, false_target, false);
3605 ig.Emit (OpCodes.Br, end_target);
3606 ig.MarkLabel (false_target);
3607 falseExpr.Emit (ec);
3608 ig.MarkLabel (end_target);
3616 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3617 public readonly string Name;
3618 public readonly Block Block;
3619 LocalInfo local_info;
3622 public LocalVariableReference (Block block, string name, Location l)
3627 eclass = ExprClass.Variable;
3630 // Setting `is_readonly' to false will allow you to create a writable
3631 // reference to a read-only variable. This is used by foreach and using.
3632 public LocalVariableReference (Block block, string name, Location l,
3633 LocalInfo local_info, bool is_readonly)
3634 : this (block, name, l)
3636 this.local_info = local_info;
3637 this.is_readonly = is_readonly;
3640 public VariableInfo VariableInfo {
3641 get { return local_info.VariableInfo; }
3644 public bool IsReadOnly {
3650 protected void DoResolveBase (EmitContext ec)
3652 if (local_info == null) {
3653 local_info = Block.GetLocalInfo (Name);
3654 is_readonly = local_info.ReadOnly;
3657 type = local_info.VariableType;
3659 if (ec.InAnonymousMethod)
3660 Block.LiftVariable (local_info);
3664 protected Expression DoResolve (EmitContext ec, bool is_lvalue)
3666 Expression e = Block.GetConstantExpression (Name);
3668 local_info.Used = true;
3669 eclass = ExprClass.Value;
3670 return e.Resolve (ec);
3673 VariableInfo variable_info = local_info.VariableInfo;
3674 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3678 local_info.Used = true;
3680 if (local_info.LocalBuilder == null)
3681 return ec.RemapLocal (local_info);
3686 public override Expression DoResolve (EmitContext ec)
3690 return DoResolve (ec, false);
3693 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3697 VariableInfo variable_info = local_info.VariableInfo;
3698 if (variable_info != null)
3699 variable_info.SetAssigned (ec);
3701 Expression e = DoResolve (ec, true);
3707 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3711 CheckObsoleteAttribute (e.Type);
3713 if (local_info.LocalBuilder == null)
3714 return ec.RemapLocalLValue (local_info, right_side);
3719 public bool VerifyFixed (bool is_expression)
3721 return !is_expression || local_info.IsFixed;
3724 public override void Emit (EmitContext ec)
3726 ILGenerator ig = ec.ig;
3728 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3731 public void EmitAssign (EmitContext ec, Expression source)
3733 ILGenerator ig = ec.ig;
3736 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3739 public void AddressOf (EmitContext ec, AddressOp mode)
3741 ILGenerator ig = ec.ig;
3743 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3746 public override string ToString ()
3748 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3753 /// This represents a reference to a parameter in the intermediate
3756 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3762 public Parameter.Modifier mod;
3763 public bool is_ref, is_out;
3765 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3772 eclass = ExprClass.Variable;
3775 public VariableInfo VariableInfo {
3779 public bool VerifyFixed (bool is_expression)
3781 return !is_expression || TypeManager.IsValueType (type);
3784 public bool IsAssigned (EmitContext ec, Location loc)
3786 if (!ec.DoFlowAnalysis || !is_out ||
3787 ec.CurrentBranching.IsAssigned (vi))
3790 Report.Error (165, loc,
3791 "Use of unassigned parameter `" + name + "'");
3795 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3797 if (!ec.DoFlowAnalysis || !is_out ||
3798 ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3801 Report.Error (170, loc,
3802 "Use of possibly unassigned field `" + field_name + "'");
3806 public void SetAssigned (EmitContext ec)
3808 if (is_out && ec.DoFlowAnalysis)
3809 ec.CurrentBranching.SetAssigned (vi);
3812 public void SetFieldAssigned (EmitContext ec, string field_name)
3814 if (is_out && ec.DoFlowAnalysis)
3815 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3818 protected void DoResolveBase (EmitContext ec)
3820 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
3821 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3822 is_out = (mod & Parameter.Modifier.OUT) != 0;
3823 eclass = ExprClass.Variable;
3826 vi = block.ParameterMap [idx];
3830 // Notice that for ref/out parameters, the type exposed is not the
3831 // same type exposed externally.
3834 // externally we expose "int&"
3835 // here we expose "int".
3837 // We record this in "is_ref". This means that the type system can treat
3838 // the type as it is expected, but when we generate the code, we generate
3839 // the alternate kind of code.
3841 public override Expression DoResolve (EmitContext ec)
3845 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3848 if (ec.RemapToProxy)
3849 return ec.RemapParameter (idx);
3854 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3860 if (ec.RemapToProxy)
3861 return ec.RemapParameterLValue (idx, right_side);
3866 static public void EmitLdArg (ILGenerator ig, int x)
3870 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3871 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3872 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3873 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3874 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3877 ig.Emit (OpCodes.Ldarg, x);
3881 // This method is used by parameters that are references, that are
3882 // being passed as references: we only want to pass the pointer (that
3883 // is already stored in the parameter, not the address of the pointer,
3884 // and not the value of the variable).
3886 public void EmitLoad (EmitContext ec)
3888 ILGenerator ig = ec.ig;
3894 EmitLdArg (ig, arg_idx);
3897 public override void Emit (EmitContext ec)
3899 ILGenerator ig = ec.ig;
3906 EmitLdArg (ig, arg_idx);
3912 // If we are a reference, we loaded on the stack a pointer
3913 // Now lets load the real value
3915 LoadFromPtr (ig, type);
3918 public void EmitAssign (EmitContext ec, Expression source)
3920 ILGenerator ig = ec.ig;
3928 EmitLdArg (ig, arg_idx);
3933 StoreFromPtr (ig, type);
3936 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
3938 ig.Emit (OpCodes.Starg, arg_idx);
3942 public void AddressOf (EmitContext ec, AddressOp mode)
3951 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
3953 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
3956 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
3958 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
3965 /// Used for arguments to New(), Invocation()
3967 public class Argument {
3968 public enum AType : byte {
3975 public readonly AType ArgType;
3976 public Expression Expr;
3978 public Argument (Expression expr, AType type)
3981 this.ArgType = type;
3986 if (ArgType == AType.Ref || ArgType == AType.Out)
3987 return TypeManager.GetReferenceType (Expr.Type);
3993 public Parameter.Modifier GetParameterModifier ()
3997 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
4000 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
4003 return Parameter.Modifier.NONE;
4007 public static string FullDesc (Argument a)
4009 if (a.ArgType == AType.ArgList)
4012 return (a.ArgType == AType.Ref ? "ref " :
4013 (a.ArgType == AType.Out ? "out " : "")) +
4014 TypeManager.CSharpName (a.Expr.Type);
4017 public bool ResolveMethodGroup (EmitContext ec, Location loc)
4019 // FIXME: csc doesn't report any error if you try to use `ref' or
4020 // `out' in a delegate creation expression.
4021 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4028 public bool Resolve (EmitContext ec, Location loc)
4030 if (ArgType == AType.Ref) {
4031 Expr = Expr.Resolve (ec);
4035 Expr = Expr.ResolveLValue (ec, Expr);
4036 } else if (ArgType == AType.Out)
4037 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
4039 Expr = Expr.Resolve (ec);
4044 if (ArgType == AType.Expression)
4048 // Catch errors where fields of a MarshalByRefObject are passed as ref or out
4049 // This is only allowed for `this'
4051 FieldExpr fe = Expr as FieldExpr;
4052 if (fe != null && !fe.IsStatic){
4053 Expression instance = fe.InstanceExpression;
4055 if (instance.GetType () != typeof (This)){
4056 if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
4057 Report.Error (197, loc,
4058 "Can not pass a type that derives from MarshalByRefObject with out or ref");
4065 if (Expr.eclass != ExprClass.Variable){
4067 // We just probe to match the CSC output
4069 if (Expr.eclass == ExprClass.PropertyAccess ||
4070 Expr.eclass == ExprClass.IndexerAccess){
4073 "A property or indexer can not be passed as an out or ref " +
4078 "An lvalue is required as an argument to out or ref");
4086 public void Emit (EmitContext ec)
4089 // Ref and Out parameters need to have their addresses taken.
4091 // ParameterReferences might already be references, so we want
4092 // to pass just the value
4094 if (ArgType == AType.Ref || ArgType == AType.Out){
4095 AddressOp mode = AddressOp.Store;
4097 if (ArgType == AType.Ref)
4098 mode |= AddressOp.Load;
4100 if (Expr is ParameterReference){
4101 ParameterReference pr = (ParameterReference) Expr;
4107 pr.AddressOf (ec, mode);
4110 ((IMemoryLocation)Expr).AddressOf (ec, mode);
4118 /// Invocation of methods or delegates.
4120 public class Invocation : ExpressionStatement {
4121 public readonly ArrayList Arguments;
4124 MethodBase method = null;
4127 static Hashtable method_parameter_cache;
4129 static Invocation ()
4131 method_parameter_cache = new PtrHashtable ();
4135 // arguments is an ArrayList, but we do not want to typecast,
4136 // as it might be null.
4138 // FIXME: only allow expr to be a method invocation or a
4139 // delegate invocation (7.5.5)
4141 public Invocation (Expression expr, ArrayList arguments, Location l)
4144 Arguments = arguments;
4148 public Expression Expr {
4155 /// Returns the Parameters (a ParameterData interface) for the
4158 public static ParameterData GetParameterData (MethodBase mb)
4160 object pd = method_parameter_cache [mb];
4164 return (ParameterData) pd;
4167 ip = TypeManager.LookupParametersByBuilder (mb);
4169 method_parameter_cache [mb] = ip;
4171 return (ParameterData) ip;
4173 ReflectionParameters rp = new ReflectionParameters (mb);
4174 method_parameter_cache [mb] = rp;
4176 return (ParameterData) rp;
4181 /// Determines "better conversion" as specified in 7.4.2.3
4183 /// Returns : 1 if a->p is better
4184 /// 0 if a->q or neither is better
4186 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
4188 Type argument_type = a.Type;
4189 Expression argument_expr = a.Expr;
4191 if (argument_type == null)
4192 throw new Exception ("Expression of type " + a.Expr +
4193 " does not resolve its type");
4196 // This is a special case since csc behaves this way.
4198 if (argument_expr is NullLiteral &&
4199 p == TypeManager.string_type &&
4200 q == TypeManager.object_type)
4202 else if (argument_expr is NullLiteral &&
4203 p == TypeManager.object_type &&
4204 q == TypeManager.string_type)
4208 // csc behaves this way so we emulate it. Basically, if the argument
4209 // is null and one of the types to compare is 'object' and the other
4210 // is a reference type, we prefer the other.
4212 // I can't find this anywhere in the spec but we can interpret this
4213 // to mean that null can be of any type you wish in such a context
4215 if (p != null && q != null) {
4216 if (argument_expr is NullLiteral &&
4218 q == TypeManager.object_type)
4220 else if (argument_expr is NullLiteral &&
4222 p == TypeManager.object_type)
4229 if (argument_type == p)
4232 if (argument_type == q)
4236 Expression tmp = Convert.ImplicitConversion (ec, argument_expr, p, loc);
4244 Expression p_tmp = new EmptyExpression (p);
4245 Expression q_tmp = new EmptyExpression (q);
4247 if (Convert.ImplicitConversionExists (ec, p_tmp, q) == true &&
4248 Convert.ImplicitConversionExists (ec, q_tmp, p) == false)
4251 if (p == TypeManager.sbyte_type)
4252 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4253 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4256 if (p == TypeManager.short_type)
4257 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4258 q == TypeManager.uint64_type)
4261 if (p == TypeManager.int32_type)
4262 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4265 if (p == TypeManager.int64_type)
4266 if (q == TypeManager.uint64_type)
4273 /// Determines "Better function" between candidate
4274 /// and the current best match
4277 /// Returns an integer indicating :
4278 /// 0 if candidate ain't better
4279 /// 1 if candidate is better than the current best match
4281 static int BetterFunction (EmitContext ec, ArrayList args,
4282 MethodBase candidate, bool candidate_params,
4283 MethodBase best, bool best_params,
4286 ParameterData candidate_pd = GetParameterData (candidate);
4287 ParameterData best_pd;
4293 argument_count = args.Count;
4295 int cand_count = candidate_pd.Count;
4298 // If there is no best method, than this one
4299 // is better, however, if we already found a
4300 // best method, we cant tell. This happens
4311 // interface IFooBar : IFoo, IBar {}
4313 // We cant tell if IFoo.DoIt is better than IBar.DoIt
4315 // However, we have to consider that
4316 // Trim (); is better than Trim (params char[] chars);
4318 if (cand_count == 0 && argument_count == 0)
4319 return best == null || best_params ? 1 : 0;
4321 if ((candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS) &&
4322 (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.ARGLIST))
4323 if (cand_count != argument_count)
4329 if (argument_count == 0 && cand_count == 1 &&
4330 candidate_pd.ParameterModifier (cand_count - 1) == Parameter.Modifier.PARAMS)
4333 for (int j = 0; j < argument_count; ++j) {
4335 Argument a = (Argument) args [j];
4336 Type t = candidate_pd.ParameterType (j);
4338 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4339 if (candidate_params)
4340 t = TypeManager.GetElementType (t);
4342 x = BetterConversion (ec, a, t, null, loc);
4354 best_pd = GetParameterData (best);
4356 int rating1 = 0, rating2 = 0;
4358 for (int j = 0; j < argument_count; ++j) {
4361 Argument a = (Argument) args [j];
4363 Type ct = candidate_pd.ParameterType (j);
4364 Type bt = best_pd.ParameterType (j);
4366 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4367 if (candidate_params)
4368 ct = TypeManager.GetElementType (ct);
4370 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4372 bt = TypeManager.GetElementType (bt);
4374 x = BetterConversion (ec, a, ct, bt, loc);
4375 y = BetterConversion (ec, a, bt, ct, loc);
4385 // If a method (in the normal form) with the
4386 // same signature as the expanded form of the
4387 // current best params method already exists,
4388 // the expanded form is not applicable so we
4389 // force it to select the candidate
4391 if (!candidate_params && best_params && cand_count == argument_count)
4394 if (rating1 > rating2)
4400 public static string FullMethodDesc (MethodBase mb)
4402 string ret_type = "";
4407 if (mb is MethodInfo)
4408 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
4410 StringBuilder sb = new StringBuilder (ret_type);
4412 sb.Append (mb.ReflectedType.ToString ());
4414 sb.Append (mb.Name);
4416 ParameterData pd = GetParameterData (mb);
4418 int count = pd.Count;
4421 for (int i = count; i > 0; ) {
4424 sb.Append (pd.ParameterDesc (count - i - 1));
4430 return sb.ToString ();
4433 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4435 MemberInfo [] miset;
4436 MethodGroupExpr union;
4441 return (MethodGroupExpr) mg2;
4444 return (MethodGroupExpr) mg1;
4447 MethodGroupExpr left_set = null, right_set = null;
4448 int length1 = 0, length2 = 0;
4450 left_set = (MethodGroupExpr) mg1;
4451 length1 = left_set.Methods.Length;
4453 right_set = (MethodGroupExpr) mg2;
4454 length2 = right_set.Methods.Length;
4456 ArrayList common = new ArrayList ();
4458 foreach (MethodBase r in right_set.Methods){
4459 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
4463 miset = new MemberInfo [length1 + length2 - common.Count];
4464 left_set.Methods.CopyTo (miset, 0);
4468 foreach (MethodBase r in right_set.Methods) {
4469 if (!common.Contains (r))
4473 union = new MethodGroupExpr (miset, loc);
4479 /// Determines if the candidate method, if a params method, is applicable
4480 /// in its expanded form to the given set of arguments
4482 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
4483 MethodBase candidate, bool do_varargs)
4487 if (arguments == null)
4490 arg_count = arguments.Count;
4492 ParameterData pd = GetParameterData (candidate);
4494 int pd_count = pd.Count;
4498 int count = pd_count - 1;
4500 if (pd.ParameterModifier (count) != Parameter.Modifier.ARGLIST)
4502 if (pd_count != arg_count)
4505 if (pd.ParameterModifier (count) != Parameter.Modifier.PARAMS)
4509 if (count > arg_count)
4512 if (pd_count == 1 && arg_count == 0)
4516 // If we have come this far, the case which
4517 // remains is when the number of parameters is
4518 // less than or equal to the argument count.
4520 for (int i = 0; i < count; ++i) {
4522 Argument a = (Argument) arguments [i];
4524 Parameter.Modifier a_mod = a.GetParameterModifier () &
4525 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4526 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4527 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4529 if (a_mod == p_mod) {
4531 if (a_mod == Parameter.Modifier.NONE)
4532 if (!Convert.ImplicitConversionExists (ec,
4534 pd.ParameterType (i)))
4537 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4538 Type pt = pd.ParameterType (i);
4541 pt = TypeManager.GetReferenceType (pt);
4552 Argument a = (Argument) arguments [count];
4553 if (!(a.Expr is Arglist))
4559 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4561 for (int i = pd_count - 1; i < arg_count; i++) {
4562 Argument a = (Argument) arguments [i];
4564 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4572 /// Determines if the candidate method is applicable (section 14.4.2.1)
4573 /// to the given set of arguments
4575 static bool IsApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
4579 if (arguments == null)
4582 arg_count = arguments.Count;
4585 ParameterData pd = GetParameterData (candidate);
4587 if (arg_count != pd.Count)
4590 for (int i = arg_count; i > 0; ) {
4593 Argument a = (Argument) arguments [i];
4595 Parameter.Modifier a_mod = a.GetParameterModifier () &
4596 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4597 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4598 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4601 if (a_mod == p_mod ||
4602 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4603 if (a_mod == Parameter.Modifier.NONE) {
4604 if (!Convert.ImplicitConversionExists (ec,
4606 pd.ParameterType (i)))
4610 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4611 Type pt = pd.ParameterType (i);
4614 pt = TypeManager.GetReferenceType (pt);
4627 /// Find the Applicable Function Members (7.4.2.1)
4629 /// me: Method Group expression with the members to select.
4630 /// it might contain constructors or methods (or anything
4631 /// that maps to a method).
4633 /// Arguments: ArrayList containing resolved Argument objects.
4635 /// loc: The location if we want an error to be reported, or a Null
4636 /// location for "probing" purposes.
4638 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4639 /// that is the best match of me on Arguments.
4642 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4643 ArrayList Arguments, Location loc)
4645 MethodBase method = null;
4646 Type applicable_type = null;
4648 ArrayList candidates = new ArrayList ();
4651 // Used to keep a map between the candidate
4652 // and whether it is being considered in its
4653 // normal or expanded form
4655 // false is normal form, true is expanded form
4657 Hashtable candidate_to_form = null;
4661 // First we construct the set of applicable methods
4663 // We start at the top of the type hierarchy and
4664 // go down to find applicable methods
4666 applicable_type = me.DeclaringType;
4668 if (me.Name == "Invoke" && TypeManager.IsDelegateType (applicable_type)) {
4669 Error_InvokeOnDelegate (loc);
4673 bool found_applicable = false;
4675 foreach (MethodBase candidate in me.Methods){
4676 Type decl_type = candidate.DeclaringType;
4679 // If we have already found an applicable method
4680 // we eliminate all base types (Section 14.5.5.1)
4682 if (decl_type != applicable_type &&
4683 (applicable_type.IsSubclassOf (decl_type) ||
4684 TypeManager.ImplementsInterface (applicable_type, decl_type)) &&
4689 // Check if candidate is applicable (section 14.4.2.1)
4690 if (IsApplicable (ec, Arguments, candidate)) {
4691 // Candidate is applicable in normal form
4692 candidates.Add (candidate);
4693 applicable_type = candidate.DeclaringType;
4694 found_applicable = true;
4695 } else if (IsParamsMethodApplicable (ec, Arguments, candidate, false)) {
4696 if (candidate_to_form == null)
4697 candidate_to_form = new PtrHashtable ();
4699 // Candidate is applicable in expanded form
4700 candidates.Add (candidate);
4701 applicable_type = candidate.DeclaringType;
4702 found_applicable = true;
4703 candidate_to_form [candidate] = candidate;
4704 } else if (IsParamsMethodApplicable (ec, Arguments, candidate, true)) {
4705 if (candidate_to_form == null)
4706 candidate_to_form = new PtrHashtable ();
4708 // Candidate is applicable in expanded form
4709 candidates.Add (candidate);
4710 applicable_type = candidate.DeclaringType;
4711 found_applicable = true;
4712 candidate_to_form [candidate] = candidate;
4718 // Now we actually find the best method
4720 int candidate_top = candidates.Count;
4721 for (int ix = 0; ix < candidate_top; ix++){
4722 MethodBase candidate = (MethodBase) candidates [ix];
4724 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4725 bool method_params = false;
4728 method_params = candidate_to_form != null && candidate_to_form.Contains (method);
4730 int x = BetterFunction (ec, Arguments,
4731 candidate, cand_params,
4732 method, method_params,
4741 if (Arguments == null)
4744 argument_count = Arguments.Count;
4747 if (method == null) {
4749 // Okay so we have failed to find anything so we
4750 // return by providing info about the closest match
4752 for (int i = 0; i < me.Methods.Length; ++i) {
4754 MethodBase c = (MethodBase) me.Methods [i];
4755 ParameterData pd = GetParameterData (c);
4757 if (pd.Count != argument_count)
4760 VerifyArgumentsCompat (ec, Arguments, argument_count, c, false,
4765 if (!Location.IsNull (loc)) {
4766 string report_name = me.Name;
4767 if (report_name == ".ctor")
4768 report_name = me.DeclaringType.ToString ();
4770 Error_WrongNumArguments (loc, report_name, argument_count);
4777 // Now check that there are no ambiguities i.e the selected method
4778 // should be better than all the others
4780 bool best_params = candidate_to_form != null && candidate_to_form.Contains (method);
4782 for (int ix = 0; ix < candidate_top; ix++){
4783 MethodBase candidate = (MethodBase) candidates [ix];
4785 if (candidate == method)
4789 // If a normal method is applicable in
4790 // the sense that it has the same
4791 // number of arguments, then the
4792 // expanded params method is never
4793 // applicable so we debar the params
4796 // if ((IsParamsMethodApplicable (ec, Arguments, candidate) &&
4797 // IsApplicable (ec, Arguments, method)))
4800 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
4801 int x = BetterFunction (ec, Arguments,
4802 method, best_params,
4803 candidate, cand_params,
4809 "Ambiguous call when selecting function due to implicit casts");
4815 // And now check if the arguments are all
4816 // compatible, perform conversions if
4817 // necessary etc. and return if everything is
4820 if (!VerifyArgumentsCompat (ec, Arguments, argument_count, method,
4821 best_params, null, loc))
4827 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
4829 Report.Error (1501, loc,
4830 "No overload for method `" + name + "' takes `" +
4831 arg_count + "' arguments");
4834 static void Error_InvokeOnDelegate (Location loc)
4836 Report.Error (1533, loc,
4837 "Invoke cannot be called directly on a delegate");
4840 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
4841 Type delegate_type, string arg_sig, string par_desc)
4843 if (delegate_type == null)
4844 Report.Error (1502, loc,
4845 "The best overloaded match for method '" +
4846 FullMethodDesc (method) +
4847 "' has some invalid arguments");
4849 Report.Error (1594, loc,
4850 "Delegate '" + delegate_type.ToString () +
4851 "' has some invalid arguments.");
4852 Report.Error (1503, loc,
4853 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
4854 idx, arg_sig, par_desc));
4857 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
4860 bool chose_params_expanded,
4864 ParameterData pd = GetParameterData (method);
4865 int pd_count = pd.Count;
4867 for (int j = 0; j < argument_count; j++) {
4868 Argument a = (Argument) Arguments [j];
4869 Expression a_expr = a.Expr;
4870 Type parameter_type = pd.ParameterType (j);
4871 Parameter.Modifier pm = pd.ParameterModifier (j);
4873 if (pm == Parameter.Modifier.PARAMS){
4874 if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
4875 if (!Location.IsNull (loc))
4876 Error_InvalidArguments (
4877 loc, j, method, delegate_type,
4878 Argument.FullDesc (a), pd.ParameterDesc (j));
4882 if (chose_params_expanded)
4883 parameter_type = TypeManager.GetElementType (parameter_type);
4884 } else if (pm == Parameter.Modifier.ARGLIST){
4890 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
4891 if (!Location.IsNull (loc))
4892 Error_InvalidArguments (
4893 loc, j, method, delegate_type,
4894 Argument.FullDesc (a), pd.ParameterDesc (j));
4902 if (a.Type != parameter_type){
4905 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
4908 if (!Location.IsNull (loc))
4909 Error_InvalidArguments (
4910 loc, j, method, delegate_type,
4911 Argument.FullDesc (a), pd.ParameterDesc (j));
4916 // Update the argument with the implicit conversion
4922 Parameter.Modifier a_mod = a.GetParameterModifier () &
4923 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4924 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
4925 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4927 if (a_mod != p_mod &&
4928 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
4929 if (!Location.IsNull (loc)) {
4930 Report.Error (1502, loc,
4931 "The best overloaded match for method '" + FullMethodDesc (method)+
4932 "' has some invalid arguments");
4933 Report.Error (1503, loc,
4934 "Argument " + (j+1) +
4935 ": Cannot convert from '" + Argument.FullDesc (a)
4936 + "' to '" + pd.ParameterDesc (j) + "'");
4946 public override Expression DoResolve (EmitContext ec)
4949 // First, resolve the expression that is used to
4950 // trigger the invocation
4952 if (expr is BaseAccess)
4955 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4959 if (!(expr is MethodGroupExpr)) {
4960 Type expr_type = expr.Type;
4962 if (expr_type != null){
4963 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
4965 return (new DelegateInvocation (
4966 this.expr, Arguments, loc)).Resolve (ec);
4970 if (!(expr is MethodGroupExpr)){
4971 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup);
4976 // Next, evaluate all the expressions in the argument list
4978 if (Arguments != null){
4979 foreach (Argument a in Arguments){
4980 if (!a.Resolve (ec, loc))
4985 MethodGroupExpr mg = (MethodGroupExpr) expr;
4986 method = OverloadResolve (ec, mg, Arguments, loc);
4988 if (method == null){
4990 "Could not find any applicable function for this argument list");
4994 MethodInfo mi = method as MethodInfo;
4996 type = TypeManager.TypeToCoreType (mi.ReturnType);
4997 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null)) {
4998 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
5002 Expression iexpr = mg.InstanceExpression;
5003 if (mi.IsStatic && (iexpr != null) && !(iexpr is This)) {
5004 if (mg.IdenticalTypeName)
5005 mg.InstanceExpression = null;
5007 MemberAccess.error176 (loc, mi.Name);
5013 if (type.IsPointer){
5021 // Only base will allow this invocation to happen.
5023 if (is_base && method.IsAbstract){
5024 Report.Error (205, loc, "Cannot call an abstract base member: " +
5025 FullMethodDesc (method));
5029 if ((method.Attributes & MethodAttributes.SpecialName) != 0){
5030 if (TypeManager.IsSpecialMethod (method))
5031 Report.Error (571, loc, method.Name + ": can not call operator or accessor");
5034 eclass = ExprClass.Value;
5039 // Emits the list of arguments as an array
5041 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
5043 ILGenerator ig = ec.ig;
5044 int count = arguments.Count - idx;
5045 Argument a = (Argument) arguments [idx];
5046 Type t = a.Expr.Type;
5048 IntConstant.EmitInt (ig, count);
5049 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
5051 int top = arguments.Count;
5052 for (int j = idx; j < top; j++){
5053 a = (Argument) arguments [j];
5055 ig.Emit (OpCodes.Dup);
5056 IntConstant.EmitInt (ig, j - idx);
5059 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj);
5061 ig.Emit (OpCodes.Ldelema, t);
5066 ig.Emit (OpCodes.Stobj, t);
5073 /// Emits a list of resolved Arguments that are in the arguments
5076 /// The MethodBase argument might be null if the
5077 /// emission of the arguments is known not to contain
5078 /// a `params' field (for example in constructors or other routines
5079 /// that keep their arguments in this structure)
5081 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
5085 pd = GetParameterData (mb);
5090 // If we are calling a params method with no arguments, special case it
5092 if (arguments == null){
5093 if (pd != null && pd.Count > 0 &&
5094 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
5095 ILGenerator ig = ec.ig;
5097 IntConstant.EmitInt (ig, 0);
5098 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
5104 int top = arguments.Count;
5106 for (int i = 0; i < top; i++){
5107 Argument a = (Argument) arguments [i];
5110 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
5112 // Special case if we are passing the same data as the
5113 // params argument, do not put it in an array.
5115 if (pd.ParameterType (i) == a.Type)
5118 EmitParams (ec, i, arguments);
5126 if (pd != null && pd.Count > top &&
5127 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
5128 ILGenerator ig = ec.ig;
5130 IntConstant.EmitInt (ig, 0);
5131 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
5135 static Type[] GetVarargsTypes (EmitContext ec, MethodBase mb,
5136 ArrayList arguments)
5138 ParameterData pd = GetParameterData (mb);
5140 if (arguments == null)
5141 return new Type [0];
5143 Argument a = (Argument) arguments [pd.Count - 1];
5144 Arglist list = (Arglist) a.Expr;
5146 return list.ArgumentTypes;
5150 /// This checks the ConditionalAttribute on the method
5152 static bool IsMethodExcluded (MethodBase method, EmitContext ec)
5154 if (method.IsConstructor)
5157 IMethodData md = TypeManager.GetMethod (method);
5159 return md.IsExcluded (ec);
5161 // For some methods (generated by delegate class) GetMethod returns null
5162 // because they are not included in builder_to_method table
5163 if (method.DeclaringType is TypeBuilder)
5166 return AttributeTester.IsConditionalMethodExcluded (method);
5170 /// is_base tells whether we want to force the use of the `call'
5171 /// opcode instead of using callvirt. Call is required to call
5172 /// a specific method, while callvirt will always use the most
5173 /// recent method in the vtable.
5175 /// is_static tells whether this is an invocation on a static method
5177 /// instance_expr is an expression that represents the instance
5178 /// it must be non-null if is_static is false.
5180 /// method is the method to invoke.
5182 /// Arguments is the list of arguments to pass to the method or constructor.
5184 public static void EmitCall (EmitContext ec, bool is_base,
5185 bool is_static, Expression instance_expr,
5186 MethodBase method, ArrayList Arguments, Location loc)
5188 ILGenerator ig = ec.ig;
5189 bool struct_call = false;
5190 bool this_call = false;
5192 Type decl_type = method.DeclaringType;
5194 if (!RootContext.StdLib) {
5195 // Replace any calls to the system's System.Array type with calls to
5196 // the newly created one.
5197 if (method == TypeManager.system_int_array_get_length)
5198 method = TypeManager.int_array_get_length;
5199 else if (method == TypeManager.system_int_array_get_rank)
5200 method = TypeManager.int_array_get_rank;
5201 else if (method == TypeManager.system_object_array_clone)
5202 method = TypeManager.object_array_clone;
5203 else if (method == TypeManager.system_int_array_get_length_int)
5204 method = TypeManager.int_array_get_length_int;
5205 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5206 method = TypeManager.int_array_get_lower_bound_int;
5207 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5208 method = TypeManager.int_array_get_upper_bound_int;
5209 else if (method == TypeManager.system_void_array_copyto_array_int)
5210 method = TypeManager.void_array_copyto_array_int;
5214 // This checks ObsoleteAttribute on the method and on the declaring type
5216 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
5218 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
5221 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
5223 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
5226 if (IsMethodExcluded (method, ec))
5230 if (decl_type.IsValueType)
5233 // If this is ourselves, push "this"
5235 if (instance_expr == null) {
5237 ig.Emit (OpCodes.Ldarg_0);
5240 // Push the instance expression
5242 if (instance_expr.Type.IsValueType){
5244 // Special case: calls to a function declared in a
5245 // reference-type with a value-type argument need
5246 // to have their value boxed.
5249 if (decl_type.IsValueType){
5251 // If the expression implements IMemoryLocation, then
5252 // we can optimize and use AddressOf on the
5255 // If not we have to use some temporary storage for
5257 if (instance_expr is IMemoryLocation){
5258 ((IMemoryLocation)instance_expr).
5259 AddressOf (ec, AddressOp.LoadStore);
5262 Type t = instance_expr.Type;
5264 instance_expr.Emit (ec);
5265 LocalBuilder temp = ig.DeclareLocal (t);
5266 ig.Emit (OpCodes.Stloc, temp);
5267 ig.Emit (OpCodes.Ldloca, temp);
5270 instance_expr.Emit (ec);
5271 ig.Emit (OpCodes.Box, instance_expr.Type);
5274 instance_expr.Emit (ec);
5278 EmitArguments (ec, method, Arguments);
5281 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
5282 call_op = OpCodes.Call;
5284 call_op = OpCodes.Callvirt;
5286 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
5287 Type[] varargs_types = GetVarargsTypes (ec, method, Arguments);
5288 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
5295 // and DoFoo is not virtual, you can omit the callvirt,
5296 // because you don't need the null checking behavior.
5298 if (method is MethodInfo)
5299 ig.Emit (call_op, (MethodInfo) method);
5301 ig.Emit (call_op, (ConstructorInfo) method);
5304 public override void Emit (EmitContext ec)
5306 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5308 EmitCall (ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5311 public override void EmitStatement (EmitContext ec)
5316 // Pop the return value if there is one
5318 if (method is MethodInfo){
5319 Type ret = ((MethodInfo)method).ReturnType;
5320 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5321 ec.ig.Emit (OpCodes.Pop);
5326 public class InvocationOrCast : ExpressionStatement
5329 Expression argument;
5331 public InvocationOrCast (Expression expr, Expression argument, Location loc)
5334 this.argument = argument;
5338 public override Expression DoResolve (EmitContext ec)
5341 // First try to resolve it as a cast.
5343 type = ec.DeclSpace.ResolveType (expr, true, loc);
5345 Cast cast = new Cast (new TypeExpression (type, loc), argument, loc);
5346 return cast.Resolve (ec);
5350 // This can either be a type or a delegate invocation.
5351 // Let's just resolve it and see what we'll get.
5353 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5358 // Ok, so it's a Cast.
5360 if (expr.eclass == ExprClass.Type) {
5361 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
5362 return cast.Resolve (ec);
5366 // It's a delegate invocation.
5368 if (!TypeManager.IsDelegateType (expr.Type)) {
5369 Error (149, "Method name expected");
5373 ArrayList args = new ArrayList ();
5374 args.Add (new Argument (argument, Argument.AType.Expression));
5375 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5376 return invocation.Resolve (ec);
5381 Error (201, "Only assignment, call, increment, decrement and new object " +
5382 "expressions can be used as a statement");
5385 public override ExpressionStatement ResolveStatement (EmitContext ec)
5388 // First try to resolve it as a cast.
5390 type = ec.DeclSpace.ResolveType (expr, true, loc);
5397 // This can either be a type or a delegate invocation.
5398 // Let's just resolve it and see what we'll get.
5400 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5401 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5407 // It's a delegate invocation.
5409 if (!TypeManager.IsDelegateType (expr.Type)) {
5410 Error (149, "Method name expected");
5414 ArrayList args = new ArrayList ();
5415 args.Add (new Argument (argument, Argument.AType.Expression));
5416 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5417 return invocation.ResolveStatement (ec);
5420 public override void Emit (EmitContext ec)
5422 throw new Exception ("Cannot happen");
5425 public override void EmitStatement (EmitContext ec)
5427 throw new Exception ("Cannot happen");
5432 // This class is used to "disable" the code generation for the
5433 // temporary variable when initializing value types.
5435 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5436 public void AddressOf (EmitContext ec, AddressOp Mode)
5443 /// Implements the new expression
5445 public class New : ExpressionStatement, IMemoryLocation {
5446 public readonly ArrayList Arguments;
5449 // During bootstrap, it contains the RequestedType,
5450 // but if `type' is not null, it *might* contain a NewDelegate
5451 // (because of field multi-initialization)
5453 public Expression RequestedType;
5455 MethodBase method = null;
5458 // If set, the new expression is for a value_target, and
5459 // we will not leave anything on the stack.
5461 Expression value_target;
5462 bool value_target_set = false;
5464 public New (Expression requested_type, ArrayList arguments, Location l)
5466 RequestedType = requested_type;
5467 Arguments = arguments;
5471 public bool SetValueTypeVariable (Expression value)
5473 value_target = value;
5474 value_target_set = true;
5475 if (!(value_target is IMemoryLocation)){
5476 Error_UnexpectedKind ("variable");
5483 // This function is used to disable the following code sequence for
5484 // value type initialization:
5486 // AddressOf (temporary)
5490 // Instead the provide will have provided us with the address on the
5491 // stack to store the results.
5493 static Expression MyEmptyExpression;
5495 public void DisableTemporaryValueType ()
5497 if (MyEmptyExpression == null)
5498 MyEmptyExpression = new EmptyAddressOf ();
5501 // To enable this, look into:
5502 // test-34 and test-89 and self bootstrapping.
5504 // For instance, we can avoid a copy by using `newobj'
5505 // instead of Call + Push-temp on value types.
5506 // value_target = MyEmptyExpression;
5509 public override Expression DoResolve (EmitContext ec)
5512 // The New DoResolve might be called twice when initializing field
5513 // expressions (see EmitFieldInitializers, the call to
5514 // GetInitializerExpression will perform a resolve on the expression,
5515 // and later the assign will trigger another resolution
5517 // This leads to bugs (#37014)
5520 if (RequestedType is NewDelegate)
5521 return RequestedType;
5525 type = ec.DeclSpace.ResolveType (RequestedType, false, loc);
5530 CheckObsoleteAttribute (type);
5532 bool IsDelegate = TypeManager.IsDelegateType (type);
5535 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5536 if (RequestedType != null)
5537 if (!(RequestedType is NewDelegate))
5538 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
5539 return RequestedType;
5542 if (type.IsInterface || type.IsAbstract){
5543 Error (144, "It is not possible to create instances of interfaces or abstract classes");
5547 bool is_struct = type.IsValueType;
5548 eclass = ExprClass.Value;
5551 // SRE returns a match for .ctor () on structs (the object constructor),
5552 // so we have to manually ignore it.
5554 if (is_struct && Arguments == null)
5558 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
5559 ml = MemberLookupFinal (ec, type, type, ".ctor",
5560 MemberTypes.Constructor,
5561 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5566 if (! (ml is MethodGroupExpr)){
5568 ml.Error_UnexpectedKind ("method group");
5574 if (Arguments != null){
5575 foreach (Argument a in Arguments){
5576 if (!a.Resolve (ec, loc))
5581 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
5585 if (method == null) {
5586 if (!is_struct || Arguments.Count > 0) {
5587 Error (1501, String.Format (
5588 "New invocation: Can not find a constructor in `{0}' for this argument list",
5589 TypeManager.CSharpName (type)));
5598 // This DoEmit can be invoked in two contexts:
5599 // * As a mechanism that will leave a value on the stack (new object)
5600 // * As one that wont (init struct)
5602 // You can control whether a value is required on the stack by passing
5603 // need_value_on_stack. The code *might* leave a value on the stack
5604 // so it must be popped manually
5606 // If we are dealing with a ValueType, we have a few
5607 // situations to deal with:
5609 // * The target is a ValueType, and we have been provided
5610 // the instance (this is easy, we are being assigned).
5612 // * The target of New is being passed as an argument,
5613 // to a boxing operation or a function that takes a
5616 // In this case, we need to create a temporary variable
5617 // that is the argument of New.
5619 // Returns whether a value is left on the stack
5621 bool DoEmit (EmitContext ec, bool need_value_on_stack)
5623 bool is_value_type = type.IsValueType;
5624 ILGenerator ig = ec.ig;
5629 // Allow DoEmit() to be called multiple times.
5630 // We need to create a new LocalTemporary each time since
5631 // you can't share LocalBuilders among ILGeneators.
5632 if (!value_target_set)
5633 value_target = new LocalTemporary (ec, type);
5635 ml = (IMemoryLocation) value_target;
5636 ml.AddressOf (ec, AddressOp.Store);
5640 Invocation.EmitArguments (ec, method, Arguments);
5644 ig.Emit (OpCodes.Initobj, type);
5646 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5647 if (need_value_on_stack){
5648 value_target.Emit (ec);
5653 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
5658 public override void Emit (EmitContext ec)
5663 public override void EmitStatement (EmitContext ec)
5665 if (DoEmit (ec, false))
5666 ec.ig.Emit (OpCodes.Pop);
5669 public void AddressOf (EmitContext ec, AddressOp Mode)
5671 if (!type.IsValueType){
5673 // We throw an exception. So far, I believe we only need to support
5675 // foreach (int j in new StructType ())
5678 throw new Exception ("AddressOf should not be used for classes");
5681 if (!value_target_set)
5682 value_target = new LocalTemporary (ec, type);
5684 IMemoryLocation ml = (IMemoryLocation) value_target;
5685 ml.AddressOf (ec, AddressOp.Store);
5687 Invocation.EmitArguments (ec, method, Arguments);
5690 ec.ig.Emit (OpCodes.Initobj, type);
5692 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5694 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
5699 /// 14.5.10.2: Represents an array creation expression.
5703 /// There are two possible scenarios here: one is an array creation
5704 /// expression that specifies the dimensions and optionally the
5705 /// initialization data and the other which does not need dimensions
5706 /// specified but where initialization data is mandatory.
5708 public class ArrayCreation : Expression {
5709 Expression requested_base_type;
5710 ArrayList initializers;
5713 // The list of Argument types.
5714 // This is used to construct the `newarray' or constructor signature
5716 ArrayList arguments;
5719 // Method used to create the array object.
5721 MethodBase new_method = null;
5723 Type array_element_type;
5724 Type underlying_type;
5725 bool is_one_dimensional = false;
5726 bool is_builtin_type = false;
5727 bool expect_initializers = false;
5728 int num_arguments = 0;
5732 ArrayList array_data;
5737 // The number of array initializers that we can handle
5738 // via the InitializeArray method - through EmitStaticInitializers
5740 int num_automatic_initializers;
5742 const int max_automatic_initializers = 6;
5744 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
5746 this.requested_base_type = requested_base_type;
5747 this.initializers = initializers;
5751 arguments = new ArrayList ();
5753 foreach (Expression e in exprs) {
5754 arguments.Add (new Argument (e, Argument.AType.Expression));
5759 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
5761 this.requested_base_type = requested_base_type;
5762 this.initializers = initializers;
5766 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
5768 //string tmp = rank.Substring (rank.LastIndexOf ('['));
5770 //dimensions = tmp.Length - 1;
5771 expect_initializers = true;
5774 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
5776 StringBuilder sb = new StringBuilder (rank);
5779 for (int i = 1; i < idx_count; i++)
5784 return new ComposedCast (base_type, sb.ToString (), loc);
5787 void Error_IncorrectArrayInitializer ()
5789 Error (178, "Incorrectly structured array initializer");
5792 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
5794 if (specified_dims) {
5795 Argument a = (Argument) arguments [idx];
5797 if (!a.Resolve (ec, loc))
5800 if (!(a.Expr is Constant)) {
5801 Error (150, "A constant value is expected");
5805 int value = (int) ((Constant) a.Expr).GetValue ();
5807 if (value != probe.Count) {
5808 Error_IncorrectArrayInitializer ();
5812 bounds [idx] = value;
5815 int child_bounds = -1;
5816 foreach (object o in probe) {
5817 if (o is ArrayList) {
5818 int current_bounds = ((ArrayList) o).Count;
5820 if (child_bounds == -1)
5821 child_bounds = current_bounds;
5823 else if (child_bounds != current_bounds){
5824 Error_IncorrectArrayInitializer ();
5827 if (specified_dims && (idx + 1 >= arguments.Count)){
5828 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
5832 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
5836 if (child_bounds != -1){
5837 Error_IncorrectArrayInitializer ();
5841 Expression tmp = (Expression) o;
5842 tmp = tmp.Resolve (ec);
5846 // Console.WriteLine ("I got: " + tmp);
5847 // Handle initialization from vars, fields etc.
5849 Expression conv = Convert.ImplicitConversionRequired (
5850 ec, tmp, underlying_type, loc);
5855 if (conv is StringConstant || conv is DecimalConstant || conv is NullCast) {
5856 // These are subclasses of Constant that can appear as elements of an
5857 // array that cannot be statically initialized (with num_automatic_initializers
5858 // > max_automatic_initializers), so num_automatic_initializers should be left as zero.
5859 array_data.Add (conv);
5860 } else if (conv is Constant) {
5861 // These are the types of Constant that can appear in arrays that can be
5862 // statically allocated.
5863 array_data.Add (conv);
5864 num_automatic_initializers++;
5866 array_data.Add (conv);
5873 public void UpdateIndices (EmitContext ec)
5876 for (ArrayList probe = initializers; probe != null;) {
5877 if (probe.Count > 0 && probe [0] is ArrayList) {
5878 Expression e = new IntConstant (probe.Count);
5879 arguments.Add (new Argument (e, Argument.AType.Expression));
5881 bounds [i++] = probe.Count;
5883 probe = (ArrayList) probe [0];
5886 Expression e = new IntConstant (probe.Count);
5887 arguments.Add (new Argument (e, Argument.AType.Expression));
5889 bounds [i++] = probe.Count;
5896 public bool ValidateInitializers (EmitContext ec, Type array_type)
5898 if (initializers == null) {
5899 if (expect_initializers)
5905 if (underlying_type == null)
5909 // We use this to store all the date values in the order in which we
5910 // will need to store them in the byte blob later
5912 array_data = new ArrayList ();
5913 bounds = new Hashtable ();
5917 if (arguments != null) {
5918 ret = CheckIndices (ec, initializers, 0, true);
5921 arguments = new ArrayList ();
5923 ret = CheckIndices (ec, initializers, 0, false);
5930 if (arguments.Count != dimensions) {
5931 Error_IncorrectArrayInitializer ();
5939 void Error_NegativeArrayIndex ()
5941 Error (284, "Can not create array with a negative size");
5945 // Converts `source' to an int, uint, long or ulong.
5947 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
5951 bool old_checked = ec.CheckState;
5952 ec.CheckState = true;
5954 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
5955 if (target == null){
5956 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
5957 if (target == null){
5958 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
5959 if (target == null){
5960 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
5962 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
5966 ec.CheckState = old_checked;
5969 // Only positive constants are allowed at compile time
5971 if (target is Constant){
5972 if (target is IntConstant){
5973 if (((IntConstant) target).Value < 0){
5974 Error_NegativeArrayIndex ();
5979 if (target is LongConstant){
5980 if (((LongConstant) target).Value < 0){
5981 Error_NegativeArrayIndex ();
5992 // Creates the type of the array
5994 bool LookupType (EmitContext ec)
5996 StringBuilder array_qualifier = new StringBuilder (rank);
5999 // `In the first form allocates an array instace of the type that results
6000 // from deleting each of the individual expression from the expression list'
6002 if (num_arguments > 0) {
6003 array_qualifier.Append ("[");
6004 for (int i = num_arguments-1; i > 0; i--)
6005 array_qualifier.Append (",");
6006 array_qualifier.Append ("]");
6012 Expression array_type_expr;
6013 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
6014 type = ec.DeclSpace.ResolveType (array_type_expr, false, loc);
6019 if (!type.IsArray) {
6020 Error (622, "Can only use array initializer expressions to assign to array types. Try using a new expression instead.");
6023 underlying_type = TypeManager.GetElementType (type);
6024 dimensions = type.GetArrayRank ();
6029 public override Expression DoResolve (EmitContext ec)
6033 if (!LookupType (ec))
6037 // First step is to validate the initializers and fill
6038 // in any missing bits
6040 if (!ValidateInitializers (ec, type))
6043 if (arguments == null)
6046 arg_count = arguments.Count;
6047 foreach (Argument a in arguments){
6048 if (!a.Resolve (ec, loc))
6051 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
6052 if (real_arg == null)
6059 array_element_type = TypeManager.GetElementType (type);
6061 if (arg_count == 1) {
6062 is_one_dimensional = true;
6063 eclass = ExprClass.Value;
6067 is_builtin_type = TypeManager.IsBuiltinType (type);
6069 if (is_builtin_type) {
6072 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
6073 AllBindingFlags, loc);
6075 if (!(ml is MethodGroupExpr)) {
6076 ml.Error_UnexpectedKind ("method group");
6081 Error (-6, "New invocation: Can not find a constructor for " +
6082 "this argument list");
6086 new_method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, arguments, loc);
6088 if (new_method == null) {
6089 Error (-6, "New invocation: Can not find a constructor for " +
6090 "this argument list");
6094 eclass = ExprClass.Value;
6097 ModuleBuilder mb = CodeGen.Module.Builder;
6098 ArrayList args = new ArrayList ();
6100 if (arguments != null) {
6101 for (int i = 0; i < arg_count; i++)
6102 args.Add (TypeManager.int32_type);
6105 Type [] arg_types = null;
6108 arg_types = new Type [args.Count];
6110 args.CopyTo (arg_types, 0);
6112 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
6115 if (new_method == null) {
6116 Error (-6, "New invocation: Can not find a constructor for " +
6117 "this argument list");
6121 eclass = ExprClass.Value;
6126 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
6131 int count = array_data.Count;
6133 if (underlying_type.IsEnum)
6134 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
6136 factor = GetTypeSize (underlying_type);
6138 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
6140 data = new byte [(count * factor + 4) & ~3];
6143 for (int i = 0; i < count; ++i) {
6144 object v = array_data [i];
6146 if (v is EnumConstant)
6147 v = ((EnumConstant) v).Child;
6149 if (v is Constant && !(v is StringConstant))
6150 v = ((Constant) v).GetValue ();
6156 if (underlying_type == TypeManager.int64_type){
6157 if (!(v is Expression)){
6158 long val = (long) v;
6160 for (int j = 0; j < factor; ++j) {
6161 data [idx + j] = (byte) (val & 0xFF);
6165 } else if (underlying_type == TypeManager.uint64_type){
6166 if (!(v is Expression)){
6167 ulong val = (ulong) v;
6169 for (int j = 0; j < factor; ++j) {
6170 data [idx + j] = (byte) (val & 0xFF);
6174 } else if (underlying_type == TypeManager.float_type) {
6175 if (!(v is Expression)){
6176 element = BitConverter.GetBytes ((float) v);
6178 for (int j = 0; j < factor; ++j)
6179 data [idx + j] = element [j];
6181 } else if (underlying_type == TypeManager.double_type) {
6182 if (!(v is Expression)){
6183 element = BitConverter.GetBytes ((double) v);
6185 for (int j = 0; j < factor; ++j)
6186 data [idx + j] = element [j];
6188 } else if (underlying_type == TypeManager.char_type){
6189 if (!(v is Expression)){
6190 int val = (int) ((char) v);
6192 data [idx] = (byte) (val & 0xff);
6193 data [idx+1] = (byte) (val >> 8);
6195 } else if (underlying_type == TypeManager.short_type){
6196 if (!(v is Expression)){
6197 int val = (int) ((short) v);
6199 data [idx] = (byte) (val & 0xff);
6200 data [idx+1] = (byte) (val >> 8);
6202 } else if (underlying_type == TypeManager.ushort_type){
6203 if (!(v is Expression)){
6204 int val = (int) ((ushort) v);
6206 data [idx] = (byte) (val & 0xff);
6207 data [idx+1] = (byte) (val >> 8);
6209 } else if (underlying_type == TypeManager.int32_type) {
6210 if (!(v is Expression)){
6213 data [idx] = (byte) (val & 0xff);
6214 data [idx+1] = (byte) ((val >> 8) & 0xff);
6215 data [idx+2] = (byte) ((val >> 16) & 0xff);
6216 data [idx+3] = (byte) (val >> 24);
6218 } else if (underlying_type == TypeManager.uint32_type) {
6219 if (!(v is Expression)){
6220 uint val = (uint) v;
6222 data [idx] = (byte) (val & 0xff);
6223 data [idx+1] = (byte) ((val >> 8) & 0xff);
6224 data [idx+2] = (byte) ((val >> 16) & 0xff);
6225 data [idx+3] = (byte) (val >> 24);
6227 } else if (underlying_type == TypeManager.sbyte_type) {
6228 if (!(v is Expression)){
6229 sbyte val = (sbyte) v;
6230 data [idx] = (byte) val;
6232 } else if (underlying_type == TypeManager.byte_type) {
6233 if (!(v is Expression)){
6234 byte val = (byte) v;
6235 data [idx] = (byte) val;
6237 } else if (underlying_type == TypeManager.bool_type) {
6238 if (!(v is Expression)){
6239 bool val = (bool) v;
6240 data [idx] = (byte) (val ? 1 : 0);
6242 } else if (underlying_type == TypeManager.decimal_type){
6243 if (!(v is Expression)){
6244 int [] bits = Decimal.GetBits ((decimal) v);
6247 // FIXME: For some reason, this doesn't work on the MS runtime.
6248 int [] nbits = new int [4];
6249 nbits [0] = bits [3];
6250 nbits [1] = bits [2];
6251 nbits [2] = bits [0];
6252 nbits [3] = bits [1];
6254 for (int j = 0; j < 4; j++){
6255 data [p++] = (byte) (nbits [j] & 0xff);
6256 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6257 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6258 data [p++] = (byte) (nbits [j] >> 24);
6262 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6271 // Emits the initializers for the array
6273 void EmitStaticInitializers (EmitContext ec)
6276 // First, the static data
6279 ILGenerator ig = ec.ig;
6281 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6283 fb = RootContext.MakeStaticData (data);
6285 ig.Emit (OpCodes.Dup);
6286 ig.Emit (OpCodes.Ldtoken, fb);
6287 ig.Emit (OpCodes.Call,
6288 TypeManager.void_initializearray_array_fieldhandle);
6292 // Emits pieces of the array that can not be computed at compile
6293 // time (variables and string locations).
6295 // This always expect the top value on the stack to be the array
6297 void EmitDynamicInitializers (EmitContext ec)
6299 ILGenerator ig = ec.ig;
6300 int dims = bounds.Count;
6301 int [] current_pos = new int [dims];
6302 int top = array_data.Count;
6304 MethodInfo set = null;
6308 ModuleBuilder mb = null;
6309 mb = CodeGen.Module.Builder;
6310 args = new Type [dims + 1];
6313 for (j = 0; j < dims; j++)
6314 args [j] = TypeManager.int32_type;
6316 args [j] = array_element_type;
6318 set = mb.GetArrayMethod (
6320 CallingConventions.HasThis | CallingConventions.Standard,
6321 TypeManager.void_type, args);
6324 for (int i = 0; i < top; i++){
6326 Expression e = null;
6328 if (array_data [i] is Expression)
6329 e = (Expression) array_data [i];
6333 // Basically we do this for string literals and
6334 // other non-literal expressions
6336 if (e is EnumConstant){
6337 e = ((EnumConstant) e).Child;
6340 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6341 num_automatic_initializers <= max_automatic_initializers) {
6342 Type etype = e.Type;
6344 ig.Emit (OpCodes.Dup);
6346 for (int idx = 0; idx < dims; idx++)
6347 IntConstant.EmitInt (ig, current_pos [idx]);
6350 // If we are dealing with a struct, get the
6351 // address of it, so we can store it.
6354 etype.IsSubclassOf (TypeManager.value_type) &&
6355 (!TypeManager.IsBuiltinOrEnum (etype) ||
6356 etype == TypeManager.decimal_type)) {
6361 // Let new know that we are providing
6362 // the address where to store the results
6364 n.DisableTemporaryValueType ();
6367 ig.Emit (OpCodes.Ldelema, etype);
6373 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
6375 ig.Emit (OpCodes.Call, set);
6383 for (int j = dims - 1; j >= 0; j--){
6385 if (current_pos [j] < (int) bounds [j])
6387 current_pos [j] = 0;
6392 void EmitArrayArguments (EmitContext ec)
6394 ILGenerator ig = ec.ig;
6396 foreach (Argument a in arguments) {
6397 Type atype = a.Type;
6400 if (atype == TypeManager.uint64_type)
6401 ig.Emit (OpCodes.Conv_Ovf_U4);
6402 else if (atype == TypeManager.int64_type)
6403 ig.Emit (OpCodes.Conv_Ovf_I4);
6407 public override void Emit (EmitContext ec)
6409 ILGenerator ig = ec.ig;
6411 EmitArrayArguments (ec);
6412 if (is_one_dimensional)
6413 ig.Emit (OpCodes.Newarr, array_element_type);
6415 if (is_builtin_type)
6416 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6418 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6421 if (initializers != null){
6423 // FIXME: Set this variable correctly.
6425 bool dynamic_initializers = true;
6427 // This will never be true for array types that cannot be statically
6428 // initialized. num_automatic_initializers will always be zero. See
6430 if (num_automatic_initializers > max_automatic_initializers)
6431 EmitStaticInitializers (ec);
6433 if (dynamic_initializers)
6434 EmitDynamicInitializers (ec);
6438 public object EncodeAsAttribute ()
6440 if (!is_one_dimensional){
6441 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6445 if (array_data == null){
6446 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6450 object [] ret = new object [array_data.Count];
6452 foreach (Expression e in array_data){
6455 if (e is NullLiteral)
6458 if (!Attribute.GetAttributeArgumentExpression (e, Location, out v))
6466 public Expression TurnIntoConstant ()
6469 // Should use something like the above attribute thing.
6470 // It should return a subclass of Constant that just returns
6471 // the computed value of the array
6473 throw new Exception ("Does not support yet Turning array into a Constant");
6478 /// Represents the `this' construct
6480 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6483 VariableInfo variable_info;
6485 public This (Block block, Location loc)
6491 public This (Location loc)
6496 public VariableInfo VariableInfo {
6497 get { return variable_info; }
6500 public bool VerifyFixed (bool is_expression)
6502 if ((variable_info == null) || (variable_info.LocalInfo == null))
6505 return variable_info.LocalInfo.IsFixed;
6508 public bool ResolveBase (EmitContext ec)
6510 eclass = ExprClass.Variable;
6511 type = ec.ContainerType;
6514 Error (26, "Keyword this not valid in static code");
6518 if ((block != null) && (block.ThisVariable != null))
6519 variable_info = block.ThisVariable.VariableInfo;
6524 public override Expression DoResolve (EmitContext ec)
6526 if (!ResolveBase (ec))
6529 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
6530 Error (188, "The this object cannot be used before all " +
6531 "of its fields are assigned to");
6532 variable_info.SetAssigned (ec);
6536 if (ec.IsFieldInitializer) {
6537 Error (27, "Keyword `this' can't be used outside a constructor, " +
6538 "a method or a property.");
6545 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6547 if (!ResolveBase (ec))
6550 if (variable_info != null)
6551 variable_info.SetAssigned (ec);
6553 if (ec.TypeContainer is Class){
6554 Error (1604, "Cannot assign to `this'");
6561 public override void Emit (EmitContext ec)
6563 ILGenerator ig = ec.ig;
6566 if (ec.TypeContainer is Struct)
6567 ig.Emit (OpCodes.Ldobj, type);
6570 public void EmitAssign (EmitContext ec, Expression source)
6572 ILGenerator ig = ec.ig;
6574 if (ec.TypeContainer is Struct){
6577 ig.Emit (OpCodes.Stobj, type);
6580 ig.Emit (OpCodes.Starg, 0);
6584 public void AddressOf (EmitContext ec, AddressOp mode)
6589 // FIGURE OUT WHY LDARG_S does not work
6591 // consider: struct X { int val; int P { set { val = value; }}}
6593 // Yes, this looks very bad. Look at `NOTAS' for
6595 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
6600 /// Represents the `__arglist' construct
6602 public class ArglistAccess : Expression
6604 public ArglistAccess (Location loc)
6609 public bool ResolveBase (EmitContext ec)
6611 eclass = ExprClass.Variable;
6612 type = TypeManager.runtime_argument_handle_type;
6616 public override Expression DoResolve (EmitContext ec)
6618 if (!ResolveBase (ec))
6621 if (ec.IsFieldInitializer || !ec.CurrentBlock.HasVarargs) {
6622 Error (190, "The __arglist construct is valid only within " +
6623 "a variable argument method.");
6630 public override void Emit (EmitContext ec)
6632 ec.ig.Emit (OpCodes.Arglist);
6637 /// Represents the `__arglist (....)' construct
6639 public class Arglist : Expression
6641 public readonly Argument[] Arguments;
6643 public Arglist (Argument[] args, Location l)
6649 public Type[] ArgumentTypes {
6651 Type[] retval = new Type [Arguments.Length];
6652 for (int i = 0; i < Arguments.Length; i++)
6653 retval [i] = Arguments [i].Type;
6658 public override Expression DoResolve (EmitContext ec)
6660 eclass = ExprClass.Variable;
6661 type = TypeManager.runtime_argument_handle_type;
6663 foreach (Argument arg in Arguments) {
6664 if (!arg.Resolve (ec, loc))
6671 public override void Emit (EmitContext ec)
6673 foreach (Argument arg in Arguments)
6679 // This produces the value that renders an instance, used by the iterators code
6681 public class ProxyInstance : Expression, IMemoryLocation {
6682 public override Expression DoResolve (EmitContext ec)
6684 eclass = ExprClass.Variable;
6685 type = ec.ContainerType;
6689 public override void Emit (EmitContext ec)
6691 ec.ig.Emit (OpCodes.Ldarg_0);
6695 public void AddressOf (EmitContext ec, AddressOp mode)
6697 ec.ig.Emit (OpCodes.Ldarg_0);
6702 /// Implements the typeof operator
6704 public class TypeOf : Expression {
6705 public readonly Expression QueriedType;
6706 protected Type typearg;
6708 public TypeOf (Expression queried_type, Location l)
6710 QueriedType = queried_type;
6714 public override Expression DoResolve (EmitContext ec)
6716 typearg = ec.DeclSpace.ResolveType (QueriedType, false, loc);
6718 if (typearg == null)
6721 if (typearg == TypeManager.void_type) {
6722 Error (673, "System.Void cannot be used from C# - " +
6723 "use typeof (void) to get the void type object");
6727 if (typearg.IsPointer && !ec.InUnsafe){
6731 CheckObsoleteAttribute (typearg);
6733 type = TypeManager.type_type;
6734 eclass = ExprClass.Type;
6738 public override void Emit (EmitContext ec)
6740 ec.ig.Emit (OpCodes.Ldtoken, typearg);
6741 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6744 public Type TypeArg {
6745 get { return typearg; }
6750 /// Implements the `typeof (void)' operator
6752 public class TypeOfVoid : TypeOf {
6753 public TypeOfVoid (Location l) : base (null, l)
6758 public override Expression DoResolve (EmitContext ec)
6760 type = TypeManager.type_type;
6761 typearg = TypeManager.void_type;
6762 eclass = ExprClass.Type;
6768 /// Implements the sizeof expression
6770 public class SizeOf : Expression {
6771 public readonly Expression QueriedType;
6774 public SizeOf (Expression queried_type, Location l)
6776 this.QueriedType = queried_type;
6780 public override Expression DoResolve (EmitContext ec)
6784 233, loc, "Sizeof may only be used in an unsafe context " +
6785 "(consider using System.Runtime.InteropServices.Marshal.Sizeof");
6789 type_queried = ec.DeclSpace.ResolveType (QueriedType, false, loc);
6790 if (type_queried == null)
6793 CheckObsoleteAttribute (type_queried);
6795 if (!TypeManager.IsUnmanagedType (type_queried)){
6796 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
6800 type = TypeManager.int32_type;
6801 eclass = ExprClass.Value;
6805 public override void Emit (EmitContext ec)
6807 int size = GetTypeSize (type_queried);
6810 ec.ig.Emit (OpCodes.Sizeof, type_queried);
6812 IntConstant.EmitInt (ec.ig, size);
6817 /// Implements the member access expression
6819 public class MemberAccess : Expression {
6820 public readonly string Identifier;
6823 public MemberAccess (Expression expr, string id, Location l)
6830 public Expression Expr {
6836 public static void error176 (Location loc, string name)
6838 Report.Error (176, loc, "Static member `" +
6839 name + "' cannot be accessed " +
6840 "with an instance reference, qualify with a " +
6841 "type name instead");
6844 public static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Expression left, Location loc)
6846 SimpleName sn = left_original as SimpleName;
6847 if (sn == null || left == null || left.Type.Name != sn.Name)
6850 return RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc) != null;
6853 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
6854 Expression left, Location loc,
6855 Expression left_original)
6857 bool left_is_type, left_is_explicit;
6859 // If `left' is null, then we're called from SimpleNameResolve and this is
6860 // a member in the currently defining class.
6862 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
6863 left_is_explicit = false;
6865 // Implicitly default to `this' unless we're static.
6866 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
6867 left = ec.GetThis (loc);
6869 left_is_type = left is TypeExpr;
6870 left_is_explicit = true;
6873 if (member_lookup is FieldExpr){
6874 FieldExpr fe = (FieldExpr) member_lookup;
6875 FieldInfo fi = fe.FieldInfo;
6876 Type decl_type = fi.DeclaringType;
6878 if (fi is FieldBuilder) {
6879 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
6883 if (!c.LookupConstantValue (out o))
6886 object real_value = ((Constant) c.Expr).GetValue ();
6888 return Constantify (real_value, fi.FieldType);
6893 Type t = fi.FieldType;
6897 if (fi is FieldBuilder)
6898 o = TypeManager.GetValue ((FieldBuilder) fi);
6900 o = fi.GetValue (fi);
6902 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
6903 if (left_is_explicit && !left_is_type &&
6904 !IdenticalNameAndTypeName (ec, left_original, member_lookup, loc)) {
6905 error176 (loc, fe.FieldInfo.Name);
6909 Expression enum_member = MemberLookup (
6910 ec, decl_type, "value__", MemberTypes.Field,
6911 AllBindingFlags, loc);
6913 Enum en = TypeManager.LookupEnum (decl_type);
6917 c = Constantify (o, en.UnderlyingType);
6919 c = Constantify (o, enum_member.Type);
6921 return new EnumConstant (c, decl_type);
6924 Expression exp = Constantify (o, t);
6926 if (left_is_explicit && !left_is_type) {
6927 error176 (loc, fe.FieldInfo.Name);
6934 if (fi.FieldType.IsPointer && !ec.InUnsafe){
6940 if (member_lookup is EventExpr) {
6941 EventExpr ee = (EventExpr) member_lookup;
6944 // If the event is local to this class, we transform ourselves into
6948 if (ee.EventInfo.DeclaringType == ec.ContainerType ||
6949 TypeManager.IsNestedChildOf(ec.ContainerType, ee.EventInfo.DeclaringType)) {
6950 MemberInfo mi = GetFieldFromEvent (ee);
6954 // If this happens, then we have an event with its own
6955 // accessors and private field etc so there's no need
6956 // to transform ourselves.
6958 ee.InstanceExpression = left;
6962 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
6965 Report.Error (-200, loc, "Internal error!!");
6969 if (!left_is_explicit)
6972 ee.InstanceExpression = left;
6974 return ResolveMemberAccess (ec, ml, left, loc, left_original);
6978 if (member_lookup is IMemberExpr) {
6979 IMemberExpr me = (IMemberExpr) member_lookup;
6980 MethodGroupExpr mg = me as MethodGroupExpr;
6983 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
6984 mg.IsExplicitImpl = left_is_explicit;
6987 if ((ec.IsFieldInitializer || ec.IsStatic) &&
6988 IdenticalNameAndTypeName (ec, left_original, member_lookup, loc))
6989 return member_lookup;
6991 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
6996 if (!me.IsInstance) {
6997 if (IdenticalNameAndTypeName (ec, left_original, left, loc))
6998 return member_lookup;
7000 if (left_is_explicit) {
7001 error176 (loc, me.Name);
7007 // Since we can not check for instance objects in SimpleName,
7008 // becaue of the rule that allows types and variables to share
7009 // the name (as long as they can be de-ambiguated later, see
7010 // IdenticalNameAndTypeName), we have to check whether left
7011 // is an instance variable in a static context
7013 // However, if the left-hand value is explicitly given, then
7014 // it is already our instance expression, so we aren't in
7018 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
7019 IMemberExpr mexp = (IMemberExpr) left;
7021 if (!mexp.IsStatic){
7022 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
7027 if ((mg != null) && IdenticalNameAndTypeName (ec, left_original, left, loc))
7028 mg.IdenticalTypeName = true;
7030 me.InstanceExpression = left;
7033 return member_lookup;
7036 Console.WriteLine ("Left is: " + left);
7037 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
7038 Environment.Exit (1);
7042 public Expression DoResolve (EmitContext ec, Expression right_side, ResolveFlags flags)
7045 throw new Exception ();
7048 // Resolve the expression with flow analysis turned off, we'll do the definite
7049 // assignment checks later. This is because we don't know yet what the expression
7050 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7051 // definite assignment check on the actual field and not on the whole struct.
7054 Expression original = expr;
7055 expr = expr.Resolve (ec, flags | ResolveFlags.Intermediate | ResolveFlags.DisableFlowAnalysis);
7059 if (expr is SimpleName){
7060 SimpleName child_expr = (SimpleName) expr;
7062 Expression new_expr = new SimpleName (child_expr.Name, Identifier, loc);
7064 return new_expr.Resolve (ec, flags);
7068 // TODO: I mailed Ravi about this, and apparently we can get rid
7069 // of this and put it in the right place.
7071 // Handle enums here when they are in transit.
7072 // Note that we cannot afford to hit MemberLookup in this case because
7073 // it will fail to find any members at all
7076 Type expr_type = expr.Type;
7077 if (expr is TypeExpr){
7078 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
7079 Report.Error_T (122, loc, expr_type);
7083 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
7084 Enum en = TypeManager.LookupEnum (expr_type);
7087 object value = en.LookupEnumValue (ec, Identifier, loc);
7090 ObsoleteAttribute oa = en.GetObsoleteAttribute (ec, Identifier);
7092 AttributeTester.Report_ObsoleteMessage (oa, en.GetSignatureForError (), Location);
7095 Constant c = Constantify (value, en.UnderlyingType);
7096 return new EnumConstant (c, expr_type);
7099 CheckObsoleteAttribute (expr_type);
7101 FieldInfo fi = expr_type.GetField (Identifier);
7103 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
7105 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), Location);
7111 if (expr_type.IsPointer){
7112 Error (23, "The `.' operator can not be applied to pointer operands (" +
7113 TypeManager.CSharpName (expr_type) + ")");
7117 Expression member_lookup;
7118 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
7119 if (member_lookup == null)
7122 if (member_lookup is TypeExpr) {
7123 if (!(expr is TypeExpr) && !(expr is SimpleName)) {
7124 Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
7125 member_lookup.Type + "' instead");
7129 return member_lookup;
7132 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
7133 if (member_lookup == null)
7136 // The following DoResolve/DoResolveLValue will do the definite assignment
7139 if (right_side != null)
7140 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
7142 member_lookup = member_lookup.DoResolve (ec);
7144 return member_lookup;
7147 public override Expression DoResolve (EmitContext ec)
7149 return DoResolve (ec, null, ResolveFlags.VariableOrValue |
7150 ResolveFlags.SimpleName | ResolveFlags.Type);
7153 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7155 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
7156 ResolveFlags.SimpleName | ResolveFlags.Type);
7159 public override Expression ResolveAsTypeStep (EmitContext ec)
7161 string fname = null;
7162 MemberAccess full_expr = this;
7163 while (full_expr != null) {
7165 fname = String.Concat (full_expr.Identifier, ".", fname);
7167 fname = full_expr.Identifier;
7169 if (full_expr.Expr is SimpleName) {
7170 string full_name = String.Concat (((SimpleName) full_expr.Expr).Name, ".", fname);
7171 Type fully_qualified = ec.DeclSpace.FindType (loc, full_name);
7172 if (fully_qualified != null)
7173 return new TypeExpression (fully_qualified, loc);
7176 full_expr = full_expr.Expr as MemberAccess;
7179 Expression new_expr = expr.ResolveAsTypeStep (ec);
7181 if (new_expr == null)
7184 if (new_expr is SimpleName){
7185 SimpleName child_expr = (SimpleName) new_expr;
7187 new_expr = new SimpleName (child_expr.Name, Identifier, loc);
7189 return new_expr.ResolveAsTypeStep (ec);
7192 Type expr_type = new_expr.Type;
7194 if (expr_type.IsPointer){
7195 Error (23, "The `.' operator can not be applied to pointer operands (" +
7196 TypeManager.CSharpName (expr_type) + ")");
7200 Expression member_lookup;
7201 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
7202 if (member_lookup == null)
7205 if (member_lookup is TypeExpr){
7206 member_lookup.Resolve (ec, ResolveFlags.Type);
7207 return member_lookup;
7213 public override void Emit (EmitContext ec)
7215 throw new Exception ("Should not happen");
7218 public override string ToString ()
7220 return expr + "." + Identifier;
7225 /// Implements checked expressions
7227 public class CheckedExpr : Expression {
7229 public Expression Expr;
7231 public CheckedExpr (Expression e, Location l)
7237 public override Expression DoResolve (EmitContext ec)
7239 bool last_check = ec.CheckState;
7240 bool last_const_check = ec.ConstantCheckState;
7242 ec.CheckState = true;
7243 ec.ConstantCheckState = true;
7244 Expr = Expr.Resolve (ec);
7245 ec.CheckState = last_check;
7246 ec.ConstantCheckState = last_const_check;
7251 if (Expr is Constant)
7254 eclass = Expr.eclass;
7259 public override void Emit (EmitContext ec)
7261 bool last_check = ec.CheckState;
7262 bool last_const_check = ec.ConstantCheckState;
7264 ec.CheckState = true;
7265 ec.ConstantCheckState = true;
7267 ec.CheckState = last_check;
7268 ec.ConstantCheckState = last_const_check;
7274 /// Implements the unchecked expression
7276 public class UnCheckedExpr : Expression {
7278 public Expression Expr;
7280 public UnCheckedExpr (Expression e, Location l)
7286 public override Expression DoResolve (EmitContext ec)
7288 bool last_check = ec.CheckState;
7289 bool last_const_check = ec.ConstantCheckState;
7291 ec.CheckState = false;
7292 ec.ConstantCheckState = false;
7293 Expr = Expr.Resolve (ec);
7294 ec.CheckState = last_check;
7295 ec.ConstantCheckState = last_const_check;
7300 if (Expr is Constant)
7303 eclass = Expr.eclass;
7308 public override void Emit (EmitContext ec)
7310 bool last_check = ec.CheckState;
7311 bool last_const_check = ec.ConstantCheckState;
7313 ec.CheckState = false;
7314 ec.ConstantCheckState = false;
7316 ec.CheckState = last_check;
7317 ec.ConstantCheckState = last_const_check;
7323 /// An Element Access expression.
7325 /// During semantic analysis these are transformed into
7326 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7328 public class ElementAccess : Expression {
7329 public ArrayList Arguments;
7330 public Expression Expr;
7332 public ElementAccess (Expression e, ArrayList e_list, Location l)
7341 Arguments = new ArrayList ();
7342 foreach (Expression tmp in e_list)
7343 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7347 bool CommonResolve (EmitContext ec)
7349 Expr = Expr.Resolve (ec);
7354 if (Arguments == null)
7357 foreach (Argument a in Arguments){
7358 if (!a.Resolve (ec, loc))
7365 Expression MakePointerAccess (EmitContext ec)
7369 if (t == TypeManager.void_ptr_type){
7370 Error (242, "The array index operation is not valid for void pointers");
7373 if (Arguments.Count != 1){
7374 Error (196, "A pointer must be indexed by a single value");
7379 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc).Resolve (ec);
7382 return new Indirection (p, loc).Resolve (ec);
7385 public override Expression DoResolve (EmitContext ec)
7387 if (!CommonResolve (ec))
7391 // We perform some simple tests, and then to "split" the emit and store
7392 // code we create an instance of a different class, and return that.
7394 // I am experimenting with this pattern.
7398 if (t == TypeManager.array_type){
7399 Report.Error (21, loc, "Cannot use indexer on System.Array");
7404 return (new ArrayAccess (this, loc)).Resolve (ec);
7405 else if (t.IsPointer)
7406 return MakePointerAccess (ec);
7408 return (new IndexerAccess (this, loc)).Resolve (ec);
7411 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7413 if (!CommonResolve (ec))
7418 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
7419 else if (t.IsPointer)
7420 return MakePointerAccess (ec);
7422 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
7425 public override void Emit (EmitContext ec)
7427 throw new Exception ("Should never be reached");
7432 /// Implements array access
7434 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7436 // Points to our "data" repository
7440 LocalTemporary [] cached_locations;
7442 public ArrayAccess (ElementAccess ea_data, Location l)
7445 eclass = ExprClass.Variable;
7449 public override Expression DoResolve (EmitContext ec)
7452 ExprClass eclass = ea.Expr.eclass;
7454 // As long as the type is valid
7455 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7456 eclass == ExprClass.Value)) {
7457 ea.Expr.Error_UnexpectedKind ("variable or value");
7462 Type t = ea.Expr.Type;
7463 if (t.GetArrayRank () != ea.Arguments.Count){
7465 "Incorrect number of indexes for array " +
7466 " expected: " + t.GetArrayRank () + " got: " +
7467 ea.Arguments.Count);
7471 type = TypeManager.GetElementType (t);
7472 if (type.IsPointer && !ec.InUnsafe){
7473 UnsafeError (ea.Location);
7477 foreach (Argument a in ea.Arguments){
7478 Type argtype = a.Type;
7480 if (argtype == TypeManager.int32_type ||
7481 argtype == TypeManager.uint32_type ||
7482 argtype == TypeManager.int64_type ||
7483 argtype == TypeManager.uint64_type)
7487 // Mhm. This is strage, because the Argument.Type is not the same as
7488 // Argument.Expr.Type: the value changes depending on the ref/out setting.
7490 // Wonder if I will run into trouble for this.
7492 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
7497 eclass = ExprClass.Variable;
7503 /// Emits the right opcode to load an object of Type `t'
7504 /// from an array of T
7506 static public void EmitLoadOpcode (ILGenerator ig, Type type)
7508 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7509 ig.Emit (OpCodes.Ldelem_U1);
7510 else if (type == TypeManager.sbyte_type)
7511 ig.Emit (OpCodes.Ldelem_I1);
7512 else if (type == TypeManager.short_type)
7513 ig.Emit (OpCodes.Ldelem_I2);
7514 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7515 ig.Emit (OpCodes.Ldelem_U2);
7516 else if (type == TypeManager.int32_type)
7517 ig.Emit (OpCodes.Ldelem_I4);
7518 else if (type == TypeManager.uint32_type)
7519 ig.Emit (OpCodes.Ldelem_U4);
7520 else if (type == TypeManager.uint64_type)
7521 ig.Emit (OpCodes.Ldelem_I8);
7522 else if (type == TypeManager.int64_type)
7523 ig.Emit (OpCodes.Ldelem_I8);
7524 else if (type == TypeManager.float_type)
7525 ig.Emit (OpCodes.Ldelem_R4);
7526 else if (type == TypeManager.double_type)
7527 ig.Emit (OpCodes.Ldelem_R8);
7528 else if (type == TypeManager.intptr_type)
7529 ig.Emit (OpCodes.Ldelem_I);
7530 else if (TypeManager.IsEnumType (type)){
7531 EmitLoadOpcode (ig, TypeManager.EnumToUnderlying (type));
7532 } else if (type.IsValueType){
7533 ig.Emit (OpCodes.Ldelema, type);
7534 ig.Emit (OpCodes.Ldobj, type);
7536 ig.Emit (OpCodes.Ldelem_Ref);
7540 /// Emits the right opcode to store an object of Type `t'
7541 /// from an array of T.
7543 static public void EmitStoreOpcode (ILGenerator ig, Type t)
7546 OpCode op = GetStoreOpcode (t, out is_stobj);
7548 ig.Emit (OpCodes.Stobj, t);
7554 /// Returns the right opcode to store an object of Type `t'
7555 /// from an array of T.
7557 static public OpCode GetStoreOpcode (Type t, out bool is_stobj)
7559 //Console.WriteLine (new System.Diagnostics.StackTrace ());
7561 t = TypeManager.TypeToCoreType (t);
7562 if (TypeManager.IsEnumType (t))
7563 t = TypeManager.EnumToUnderlying (t);
7564 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
7565 t == TypeManager.bool_type)
7566 return OpCodes.Stelem_I1;
7567 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
7568 t == TypeManager.char_type)
7569 return OpCodes.Stelem_I2;
7570 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
7571 return OpCodes.Stelem_I4;
7572 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
7573 return OpCodes.Stelem_I8;
7574 else if (t == TypeManager.float_type)
7575 return OpCodes.Stelem_R4;
7576 else if (t == TypeManager.double_type)
7577 return OpCodes.Stelem_R8;
7578 else if (t == TypeManager.intptr_type) {
7580 return OpCodes.Stobj;
7581 } else if (t.IsValueType) {
7583 return OpCodes.Stobj;
7585 return OpCodes.Stelem_Ref;
7588 MethodInfo FetchGetMethod ()
7590 ModuleBuilder mb = CodeGen.Module.Builder;
7591 int arg_count = ea.Arguments.Count;
7592 Type [] args = new Type [arg_count];
7595 for (int i = 0; i < arg_count; i++){
7596 //args [i++] = a.Type;
7597 args [i] = TypeManager.int32_type;
7600 get = mb.GetArrayMethod (
7601 ea.Expr.Type, "Get",
7602 CallingConventions.HasThis |
7603 CallingConventions.Standard,
7609 MethodInfo FetchAddressMethod ()
7611 ModuleBuilder mb = CodeGen.Module.Builder;
7612 int arg_count = ea.Arguments.Count;
7613 Type [] args = new Type [arg_count];
7617 ret_type = TypeManager.GetReferenceType (type);
7619 for (int i = 0; i < arg_count; i++){
7620 //args [i++] = a.Type;
7621 args [i] = TypeManager.int32_type;
7624 address = mb.GetArrayMethod (
7625 ea.Expr.Type, "Address",
7626 CallingConventions.HasThis |
7627 CallingConventions.Standard,
7634 // Load the array arguments into the stack.
7636 // If we have been requested to cache the values (cached_locations array
7637 // initialized), then load the arguments the first time and store them
7638 // in locals. otherwise load from local variables.
7640 void LoadArrayAndArguments (EmitContext ec)
7642 ILGenerator ig = ec.ig;
7644 if (cached_locations == null){
7646 foreach (Argument a in ea.Arguments){
7647 Type argtype = a.Expr.Type;
7651 if (argtype == TypeManager.int64_type)
7652 ig.Emit (OpCodes.Conv_Ovf_I);
7653 else if (argtype == TypeManager.uint64_type)
7654 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7659 if (cached_locations [0] == null){
7660 cached_locations [0] = new LocalTemporary (ec, ea.Expr.Type);
7662 ig.Emit (OpCodes.Dup);
7663 cached_locations [0].Store (ec);
7667 foreach (Argument a in ea.Arguments){
7668 Type argtype = a.Expr.Type;
7670 cached_locations [j] = new LocalTemporary (ec, TypeManager.intptr_type /* a.Expr.Type */);
7672 if (argtype == TypeManager.int64_type)
7673 ig.Emit (OpCodes.Conv_Ovf_I);
7674 else if (argtype == TypeManager.uint64_type)
7675 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7677 ig.Emit (OpCodes.Dup);
7678 cached_locations [j].Store (ec);
7684 foreach (LocalTemporary lt in cached_locations)
7688 public new void CacheTemporaries (EmitContext ec)
7690 cached_locations = new LocalTemporary [ea.Arguments.Count + 1];
7693 public override void Emit (EmitContext ec)
7695 int rank = ea.Expr.Type.GetArrayRank ();
7696 ILGenerator ig = ec.ig;
7698 LoadArrayAndArguments (ec);
7701 EmitLoadOpcode (ig, type);
7705 method = FetchGetMethod ();
7706 ig.Emit (OpCodes.Call, method);
7710 public void EmitAssign (EmitContext ec, Expression source)
7712 int rank = ea.Expr.Type.GetArrayRank ();
7713 ILGenerator ig = ec.ig;
7714 Type t = source.Type;
7716 LoadArrayAndArguments (ec);
7719 // The stobj opcode used by value types will need
7720 // an address on the stack, not really an array/array
7724 if (t == TypeManager.enum_type || t == TypeManager.decimal_type ||
7725 (t.IsSubclassOf (TypeManager.value_type) && !TypeManager.IsEnumType (t) && !TypeManager.IsBuiltinType (t)))
7726 ig.Emit (OpCodes.Ldelema, t);
7732 EmitStoreOpcode (ig, t);
7734 ModuleBuilder mb = CodeGen.Module.Builder;
7735 int arg_count = ea.Arguments.Count;
7736 Type [] args = new Type [arg_count + 1];
7739 for (int i = 0; i < arg_count; i++){
7740 //args [i++] = a.Type;
7741 args [i] = TypeManager.int32_type;
7744 args [arg_count] = type;
7746 set = mb.GetArrayMethod (
7747 ea.Expr.Type, "Set",
7748 CallingConventions.HasThis |
7749 CallingConventions.Standard,
7750 TypeManager.void_type, args);
7752 ig.Emit (OpCodes.Call, set);
7756 public void AddressOf (EmitContext ec, AddressOp mode)
7758 int rank = ea.Expr.Type.GetArrayRank ();
7759 ILGenerator ig = ec.ig;
7761 LoadArrayAndArguments (ec);
7764 ig.Emit (OpCodes.Ldelema, type);
7766 MethodInfo address = FetchAddressMethod ();
7767 ig.Emit (OpCodes.Call, address);
7774 public ArrayList Properties;
7775 static Hashtable map;
7777 public struct Indexer {
7778 public readonly Type Type;
7779 public readonly MethodInfo Getter, Setter;
7781 public Indexer (Type type, MethodInfo get, MethodInfo set)
7791 map = new Hashtable ();
7796 Properties = new ArrayList ();
7799 void Append (MemberInfo [] mi)
7801 foreach (PropertyInfo property in mi){
7802 MethodInfo get, set;
7804 get = property.GetGetMethod (true);
7805 set = property.GetSetMethod (true);
7806 Properties.Add (new Indexer (property.PropertyType, get, set));
7810 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
7812 string p_name = TypeManager.IndexerPropertyName (lookup_type);
7814 MemberInfo [] mi = TypeManager.MemberLookup (
7815 caller_type, caller_type, lookup_type, MemberTypes.Property,
7816 BindingFlags.Public | BindingFlags.Instance |
7817 BindingFlags.DeclaredOnly, p_name, null);
7819 if (mi == null || mi.Length == 0)
7825 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
7827 Indexers ix = (Indexers) map [lookup_type];
7832 Type copy = lookup_type;
7833 while (copy != TypeManager.object_type && copy != null){
7834 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
7838 ix = new Indexers ();
7843 copy = copy.BaseType;
7846 if (!lookup_type.IsInterface)
7849 TypeExpr [] ifaces = TypeManager.GetInterfaces (lookup_type);
7850 if (ifaces != null) {
7851 foreach (TypeExpr iface in ifaces) {
7852 Type itype = iface.Type;
7853 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
7856 ix = new Indexers ();
7868 /// Expressions that represent an indexer call.
7870 public class IndexerAccess : Expression, IAssignMethod {
7872 // Points to our "data" repository
7874 MethodInfo get, set;
7875 ArrayList set_arguments;
7876 bool is_base_indexer;
7878 protected Type indexer_type;
7879 protected Type current_type;
7880 protected Expression instance_expr;
7881 protected ArrayList arguments;
7883 public IndexerAccess (ElementAccess ea, Location loc)
7884 : this (ea.Expr, false, loc)
7886 this.arguments = ea.Arguments;
7889 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
7892 this.instance_expr = instance_expr;
7893 this.is_base_indexer = is_base_indexer;
7894 this.eclass = ExprClass.Value;
7898 protected virtual bool CommonResolve (EmitContext ec)
7900 indexer_type = instance_expr.Type;
7901 current_type = ec.ContainerType;
7906 public override Expression DoResolve (EmitContext ec)
7908 ArrayList AllGetters = new ArrayList();
7909 if (!CommonResolve (ec))
7913 // Step 1: Query for all `Item' *properties*. Notice
7914 // that the actual methods are pointed from here.
7916 // This is a group of properties, piles of them.
7918 bool found_any = false, found_any_getters = false;
7919 Type lookup_type = indexer_type;
7922 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
7923 if (ilist != null) {
7925 if (ilist.Properties != null) {
7926 foreach (Indexers.Indexer ix in ilist.Properties) {
7927 if (ix.Getter != null)
7928 AllGetters.Add(ix.Getter);
7933 if (AllGetters.Count > 0) {
7934 found_any_getters = true;
7935 get = (MethodInfo) Invocation.OverloadResolve (
7936 ec, new MethodGroupExpr (AllGetters, loc), arguments, loc);
7940 Report.Error (21, loc,
7941 "Type `" + TypeManager.CSharpName (indexer_type) +
7942 "' does not have any indexers defined");
7946 if (!found_any_getters) {
7947 Error (154, "indexer can not be used in this context, because " +
7948 "it lacks a `get' accessor");
7953 Error (1501, "No Overload for method `this' takes `" +
7954 arguments.Count + "' arguments");
7959 // Only base will allow this invocation to happen.
7961 if (get.IsAbstract && this is BaseIndexerAccess){
7962 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
7966 type = get.ReturnType;
7967 if (type.IsPointer && !ec.InUnsafe){
7972 eclass = ExprClass.IndexerAccess;
7976 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7978 ArrayList AllSetters = new ArrayList();
7979 if (!CommonResolve (ec))
7982 bool found_any = false, found_any_setters = false;
7984 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
7985 if (ilist != null) {
7987 if (ilist.Properties != null) {
7988 foreach (Indexers.Indexer ix in ilist.Properties) {
7989 if (ix.Setter != null)
7990 AllSetters.Add(ix.Setter);
7994 if (AllSetters.Count > 0) {
7995 found_any_setters = true;
7996 set_arguments = (ArrayList) arguments.Clone ();
7997 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
7998 set = (MethodInfo) Invocation.OverloadResolve (
7999 ec, new MethodGroupExpr (AllSetters, loc),
8000 set_arguments, loc);
8004 Report.Error (21, loc,
8005 "Type `" + TypeManager.CSharpName (indexer_type) +
8006 "' does not have any indexers defined");
8010 if (!found_any_setters) {
8011 Error (154, "indexer can not be used in this context, because " +
8012 "it lacks a `set' accessor");
8017 Error (1501, "No Overload for method `this' takes `" +
8018 arguments.Count + "' arguments");
8023 // Only base will allow this invocation to happen.
8025 if (set.IsAbstract && this is BaseIndexerAccess){
8026 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
8031 // Now look for the actual match in the list of indexers to set our "return" type
8033 type = TypeManager.void_type; // default value
8034 foreach (Indexers.Indexer ix in ilist.Properties){
8035 if (ix.Setter == set){
8041 eclass = ExprClass.IndexerAccess;
8045 public override void Emit (EmitContext ec)
8047 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc);
8051 // source is ignored, because we already have a copy of it from the
8052 // LValue resolution and we have already constructed a pre-cached
8053 // version of the arguments (ea.set_arguments);
8055 public void EmitAssign (EmitContext ec, Expression source)
8057 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc);
8062 /// The base operator for method names
8064 public class BaseAccess : Expression {
8067 public BaseAccess (string member, Location l)
8069 this.member = member;
8073 public override Expression DoResolve (EmitContext ec)
8075 Expression c = CommonResolve (ec);
8081 // MethodGroups use this opportunity to flag an error on lacking ()
8083 if (!(c is MethodGroupExpr))
8084 return c.Resolve (ec);
8088 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8090 Expression c = CommonResolve (ec);
8096 // MethodGroups use this opportunity to flag an error on lacking ()
8098 if (! (c is MethodGroupExpr))
8099 return c.DoResolveLValue (ec, right_side);
8104 Expression CommonResolve (EmitContext ec)
8106 Expression member_lookup;
8107 Type current_type = ec.ContainerType;
8108 Type base_type = current_type.BaseType;
8112 Error (1511, "Keyword base is not allowed in static method");
8116 if (ec.IsFieldInitializer){
8117 Error (1512, "Keyword base is not available in the current context");
8121 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type, member,
8122 AllMemberTypes, AllBindingFlags, loc);
8123 if (member_lookup == null) {
8124 MemberLookupFailed (ec, base_type, base_type, member, null, loc);
8131 left = new TypeExpression (base_type, loc);
8133 left = ec.GetThis (loc);
8135 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
8137 if (e is PropertyExpr){
8138 PropertyExpr pe = (PropertyExpr) e;
8143 if (e is MethodGroupExpr)
8144 ((MethodGroupExpr) e).IsBase = true;
8149 public override void Emit (EmitContext ec)
8151 throw new Exception ("Should never be called");
8156 /// The base indexer operator
8158 public class BaseIndexerAccess : IndexerAccess {
8159 public BaseIndexerAccess (ArrayList args, Location loc)
8160 : base (null, true, loc)
8162 arguments = new ArrayList ();
8163 foreach (Expression tmp in args)
8164 arguments.Add (new Argument (tmp, Argument.AType.Expression));
8167 protected override bool CommonResolve (EmitContext ec)
8169 instance_expr = ec.GetThis (loc);
8171 current_type = ec.ContainerType.BaseType;
8172 indexer_type = current_type;
8174 foreach (Argument a in arguments){
8175 if (!a.Resolve (ec, loc))
8184 /// This class exists solely to pass the Type around and to be a dummy
8185 /// that can be passed to the conversion functions (this is used by
8186 /// foreach implementation to typecast the object return value from
8187 /// get_Current into the proper type. All code has been generated and
8188 /// we only care about the side effect conversions to be performed
8190 /// This is also now used as a placeholder where a no-action expression
8191 /// is needed (the `New' class).
8193 public class EmptyExpression : Expression {
8194 public EmptyExpression ()
8196 type = TypeManager.object_type;
8197 eclass = ExprClass.Value;
8198 loc = Location.Null;
8201 public EmptyExpression (Type t)
8204 eclass = ExprClass.Value;
8205 loc = Location.Null;
8208 public override Expression DoResolve (EmitContext ec)
8213 public override void Emit (EmitContext ec)
8215 // nothing, as we only exist to not do anything.
8219 // This is just because we might want to reuse this bad boy
8220 // instead of creating gazillions of EmptyExpressions.
8221 // (CanImplicitConversion uses it)
8223 public void SetType (Type t)
8229 public class UserCast : Expression {
8233 public UserCast (MethodInfo method, Expression source, Location l)
8235 this.method = method;
8236 this.source = source;
8237 type = method.ReturnType;
8238 eclass = ExprClass.Value;
8242 public override Expression DoResolve (EmitContext ec)
8245 // We are born fully resolved
8250 public override void Emit (EmitContext ec)
8252 ILGenerator ig = ec.ig;
8256 if (method is MethodInfo)
8257 ig.Emit (OpCodes.Call, (MethodInfo) method);
8259 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
8265 // This class is used to "construct" the type during a typecast
8266 // operation. Since the Type.GetType class in .NET can parse
8267 // the type specification, we just use this to construct the type
8268 // one bit at a time.
8270 public class ComposedCast : TypeExpr {
8274 public ComposedCast (Expression left, string dim, Location l)
8281 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
8283 Type ltype = ec.DeclSpace.ResolveType (left, false, loc);
8287 if ((ltype == TypeManager.void_type) && (dim != "*")) {
8288 Report.Error (1547, Location,
8289 "Keyword 'void' cannot be used in this context");
8294 // ltype.Fullname is already fully qualified, so we can skip
8295 // a lot of probes, and go directly to TypeManager.LookupType
8297 string cname = ltype.FullName + dim;
8298 type = TypeManager.LookupTypeDirect (cname);
8301 // For arrays of enumerations we are having a problem
8302 // with the direct lookup. Need to investigate.
8304 // For now, fall back to the full lookup in that case.
8306 type = RootContext.LookupType (
8307 ec.DeclSpace, cname, false, loc);
8313 if (!ec.ResolvingTypeTree){
8315 // If the above flag is set, this is being invoked from the ResolveType function.
8316 // Upper layers take care of the type validity in this context.
8318 if (!ec.InUnsafe && type.IsPointer){
8324 eclass = ExprClass.Type;
8328 public override string Name {
8336 // This class is used to represent the address of an array, used
8337 // only by the Fixed statement, this is like the C "&a [0]" construct.
8339 public class ArrayPtr : Expression {
8342 public ArrayPtr (Expression array, Location l)
8344 Type array_type = TypeManager.GetElementType (array.Type);
8348 type = TypeManager.GetPointerType (array_type);
8349 eclass = ExprClass.Value;
8353 public override void Emit (EmitContext ec)
8355 ILGenerator ig = ec.ig;
8358 IntLiteral.EmitInt (ig, 0);
8359 ig.Emit (OpCodes.Ldelema, TypeManager.GetElementType (array.Type));
8362 public override Expression DoResolve (EmitContext ec)
8365 // We are born fully resolved
8372 // Used by the fixed statement
8374 public class StringPtr : Expression {
8377 public StringPtr (LocalBuilder b, Location l)
8380 eclass = ExprClass.Value;
8381 type = TypeManager.char_ptr_type;
8385 public override Expression DoResolve (EmitContext ec)
8387 // This should never be invoked, we are born in fully
8388 // initialized state.
8393 public override void Emit (EmitContext ec)
8395 ILGenerator ig = ec.ig;
8397 ig.Emit (OpCodes.Ldloc, b);
8398 ig.Emit (OpCodes.Conv_I);
8399 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
8400 ig.Emit (OpCodes.Add);
8405 // Implements the `stackalloc' keyword
8407 public class StackAlloc : Expression {
8412 public StackAlloc (Expression type, Expression count, Location l)
8419 public override Expression DoResolve (EmitContext ec)
8421 count = count.Resolve (ec);
8425 if (count.Type != TypeManager.int32_type){
8426 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8431 Constant c = count as Constant;
8432 // TODO: because we don't have property IsNegative
8433 if (c != null && c.ConvertToUInt () == null) {
8434 // "Cannot use a negative size with stackalloc"
8435 Report.Error_T (247, loc);
8439 if (ec.CurrentBranching.InCatch () ||
8440 ec.CurrentBranching.InFinally (true)) {
8442 "stackalloc can not be used in a catch or finally block");
8446 otype = ec.DeclSpace.ResolveType (t, false, loc);
8451 if (!TypeManager.VerifyUnManaged (otype, loc))
8454 type = TypeManager.GetPointerType (otype);
8455 eclass = ExprClass.Value;
8460 public override void Emit (EmitContext ec)
8462 int size = GetTypeSize (otype);
8463 ILGenerator ig = ec.ig;
8466 ig.Emit (OpCodes.Sizeof, otype);
8468 IntConstant.EmitInt (ig, size);
8470 ig.Emit (OpCodes.Mul);
8471 ig.Emit (OpCodes.Localloc);