2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
8 // (C) 2003, 2004 Novell, Inc.
12 namespace Mono.CSharp {
14 using System.Collections;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// This is just a helper class, it is generated by Unary, UnaryMutator
21 /// when an overloaded method has been found. It just emits the code for a
24 public class StaticCallExpr : ExpressionStatement {
28 public StaticCallExpr (MethodInfo m, ArrayList a, Location l)
34 eclass = ExprClass.Value;
38 public override Expression DoResolve (EmitContext ec)
41 // We are born fully resolved
46 public override void Emit (EmitContext ec)
49 Invocation.EmitArguments (ec, mi, args, false, null);
51 ec.ig.Emit (OpCodes.Call, mi);
55 static public StaticCallExpr MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
56 Expression e, Location loc)
61 args = new ArrayList (1);
62 Argument a = new Argument (e, Argument.AType.Expression);
64 // We need to resolve the arguments before sending them in !
65 if (!a.Resolve (ec, loc))
69 method = Invocation.OverloadResolve (
70 ec, (MethodGroupExpr) mg, args, false, loc);
75 return new StaticCallExpr ((MethodInfo) method, args, loc);
78 public override void EmitStatement (EmitContext ec)
81 if (TypeManager.TypeToCoreType (type) != TypeManager.void_type)
82 ec.ig.Emit (OpCodes.Pop);
85 public MethodInfo Method {
90 public class ParenthesizedExpression : Expression
92 public Expression Expr;
94 public ParenthesizedExpression (Expression expr, Location loc)
100 public override Expression DoResolve (EmitContext ec)
102 Expr = Expr.Resolve (ec);
106 public override void Emit (EmitContext ec)
108 throw new Exception ("Should not happen");
113 /// Unary expressions.
117 /// Unary implements unary expressions. It derives from
118 /// ExpressionStatement becuase the pre/post increment/decrement
119 /// operators can be used in a statement context.
121 public class Unary : Expression {
122 public enum Operator : byte {
123 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
124 Indirection, AddressOf, TOP
127 public Operator Oper;
128 public Expression Expr;
130 public Unary (Operator op, Expression expr, Location loc)
138 /// Returns a stringified representation of the Operator
140 static public string OperName (Operator oper)
143 case Operator.UnaryPlus:
145 case Operator.UnaryNegation:
147 case Operator.LogicalNot:
149 case Operator.OnesComplement:
151 case Operator.AddressOf:
153 case Operator.Indirection:
157 return oper.ToString ();
160 public static readonly string [] oper_names;
164 oper_names = new string [(int)Operator.TOP];
166 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
167 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
168 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
169 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
170 oper_names [(int) Operator.Indirection] = "op_Indirection";
171 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
174 void Error23 (Type t)
177 23, "Operator " + OperName (Oper) +
178 " cannot be applied to operand of type `" +
179 TypeManager.CSharpName (t) + "'");
183 /// The result has been already resolved:
185 /// FIXME: a minus constant -128 sbyte cant be turned into a
188 static Expression TryReduceNegative (Constant expr)
192 if (expr is IntConstant)
193 e = new IntConstant (-((IntConstant) expr).Value);
194 else if (expr is UIntConstant){
195 uint value = ((UIntConstant) expr).Value;
197 if (value < 2147483649)
198 return new IntConstant (-(int)value);
200 e = new LongConstant (-value);
202 else if (expr is LongConstant)
203 e = new LongConstant (-((LongConstant) expr).Value);
204 else if (expr is ULongConstant){
205 ulong value = ((ULongConstant) expr).Value;
207 if (value < 9223372036854775809)
208 return new LongConstant(-(long)value);
210 else if (expr is FloatConstant)
211 e = new FloatConstant (-((FloatConstant) expr).Value);
212 else if (expr is DoubleConstant)
213 e = new DoubleConstant (-((DoubleConstant) expr).Value);
214 else if (expr is DecimalConstant)
215 e = new DecimalConstant (-((DecimalConstant) expr).Value);
216 else if (expr is ShortConstant)
217 e = new IntConstant (-((ShortConstant) expr).Value);
218 else if (expr is UShortConstant)
219 e = new IntConstant (-((UShortConstant) expr).Value);
224 // This routine will attempt to simplify the unary expression when the
225 // argument is a constant. The result is returned in `result' and the
226 // function returns true or false depending on whether a reduction
227 // was performed or not
229 bool Reduce (EmitContext ec, Constant e, out Expression result)
231 Type expr_type = e.Type;
234 case Operator.UnaryPlus:
238 case Operator.UnaryNegation:
239 result = TryReduceNegative (e);
242 case Operator.LogicalNot:
243 if (expr_type != TypeManager.bool_type) {
249 BoolConstant b = (BoolConstant) e;
250 result = new BoolConstant (!(b.Value));
253 case Operator.OnesComplement:
254 if (!((expr_type == TypeManager.int32_type) ||
255 (expr_type == TypeManager.uint32_type) ||
256 (expr_type == TypeManager.int64_type) ||
257 (expr_type == TypeManager.uint64_type) ||
258 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
261 if (Convert.ImplicitConversionExists (ec, e, TypeManager.int32_type)){
262 result = new Cast (new TypeExpression (TypeManager.int32_type, loc), e, loc);
263 result = result.Resolve (ec);
264 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint32_type)){
265 result = new Cast (new TypeExpression (TypeManager.uint32_type, loc), e, loc);
266 result = result.Resolve (ec);
267 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.int64_type)){
268 result = new Cast (new TypeExpression (TypeManager.int64_type, loc), e, loc);
269 result = result.Resolve (ec);
270 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint64_type)){
271 result = new Cast (new TypeExpression (TypeManager.uint64_type, loc), e, loc);
272 result = result.Resolve (ec);
275 if (result == null || !(result is Constant)){
281 expr_type = result.Type;
282 e = (Constant) result;
285 if (e is EnumConstant){
286 EnumConstant enum_constant = (EnumConstant) e;
289 if (Reduce (ec, enum_constant.Child, out reduced)){
290 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
298 if (expr_type == TypeManager.int32_type){
299 result = new IntConstant (~ ((IntConstant) e).Value);
300 } else if (expr_type == TypeManager.uint32_type){
301 result = new UIntConstant (~ ((UIntConstant) e).Value);
302 } else if (expr_type == TypeManager.int64_type){
303 result = new LongConstant (~ ((LongConstant) e).Value);
304 } else if (expr_type == TypeManager.uint64_type){
305 result = new ULongConstant (~ ((ULongConstant) e).Value);
313 case Operator.AddressOf:
317 case Operator.Indirection:
321 throw new Exception ("Can not constant fold: " + Oper.ToString());
324 Expression ResolveOperator (EmitContext ec)
326 Type expr_type = Expr.Type;
329 // Step 1: Perform Operator Overload location
334 op_name = oper_names [(int) Oper];
336 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
339 Expression e = StaticCallExpr.MakeSimpleCall (
340 ec, (MethodGroupExpr) mg, Expr, loc);
350 // Only perform numeric promotions on:
353 if (expr_type == null)
357 // Step 2: Default operations on CLI native types.
360 // Attempt to use a constant folding operation.
361 if (Expr is Constant){
364 if (Reduce (ec, (Constant) Expr, out result))
369 case Operator.LogicalNot:
370 if (expr_type != TypeManager.bool_type) {
371 Expr = ResolveBoolean (ec, Expr, loc);
378 type = TypeManager.bool_type;
381 case Operator.OnesComplement:
382 if (!((expr_type == TypeManager.int32_type) ||
383 (expr_type == TypeManager.uint32_type) ||
384 (expr_type == TypeManager.int64_type) ||
385 (expr_type == TypeManager.uint64_type) ||
386 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
389 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
391 type = TypeManager.int32_type;
394 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint32_type, loc);
396 type = TypeManager.uint32_type;
399 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
401 type = TypeManager.int64_type;
404 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint64_type, loc);
406 type = TypeManager.uint64_type;
415 case Operator.AddressOf:
416 if (Expr.eclass != ExprClass.Variable){
417 Error (211, "Cannot take the address of non-variables");
426 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
430 IVariable variable = Expr as IVariable;
431 if (!ec.InFixedInitializer && ((variable == null) || !variable.VerifyFixed (false))) {
432 Error (212, "You can only take the address of an unfixed expression inside " +
433 "of a fixed statement initializer");
437 if (ec.InFixedInitializer && ((variable != null) && variable.VerifyFixed (false))) {
438 Error (213, "You can not fix an already fixed expression");
442 // According to the specs, a variable is considered definitely assigned if you take
444 if ((variable != null) && (variable.VariableInfo != null))
445 variable.VariableInfo.SetAssigned (ec);
447 type = TypeManager.GetPointerType (Expr.Type);
450 case Operator.Indirection:
456 if (!expr_type.IsPointer){
457 Error (193, "The * or -> operator can only be applied to pointers");
462 // We create an Indirection expression, because
463 // it can implement the IMemoryLocation.
465 return new Indirection (Expr, loc);
467 case Operator.UnaryPlus:
469 // A plus in front of something is just a no-op, so return the child.
473 case Operator.UnaryNegation:
475 // Deals with -literals
476 // int operator- (int x)
477 // long operator- (long x)
478 // float operator- (float f)
479 // double operator- (double d)
480 // decimal operator- (decimal d)
482 Expression expr = null;
485 // transform - - expr into expr
488 Unary unary = (Unary) Expr;
490 if (unary.Oper == Operator.UnaryNegation)
495 // perform numeric promotions to int,
499 // The following is inneficient, because we call
500 // ImplicitConversion too many times.
502 // It is also not clear if we should convert to Float
503 // or Double initially.
505 if (expr_type == TypeManager.uint32_type){
507 // FIXME: handle exception to this rule that
508 // permits the int value -2147483648 (-2^31) to
509 // bt wrote as a decimal interger literal
511 type = TypeManager.int64_type;
512 Expr = Convert.ImplicitConversion (ec, Expr, type, loc);
516 if (expr_type == TypeManager.uint64_type){
518 // FIXME: Handle exception of `long value'
519 // -92233720368547758087 (-2^63) to be wrote as
520 // decimal integer literal.
526 if (expr_type == TypeManager.float_type){
531 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
538 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
545 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.double_type, loc);
556 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
557 TypeManager.CSharpName (expr_type) + "'");
561 public override Expression DoResolve (EmitContext ec)
563 if (Oper == Operator.AddressOf)
564 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
566 Expr = Expr.Resolve (ec);
571 eclass = ExprClass.Value;
572 return ResolveOperator (ec);
575 public override Expression DoResolveLValue (EmitContext ec, Expression right)
577 if (Oper == Operator.Indirection)
578 return base.DoResolveLValue (ec, right);
580 Error (131, "The left-hand side of an assignment must be a " +
581 "variable, property or indexer");
585 public override void Emit (EmitContext ec)
587 ILGenerator ig = ec.ig;
590 case Operator.UnaryPlus:
591 throw new Exception ("This should be caught by Resolve");
593 case Operator.UnaryNegation:
595 ig.Emit (OpCodes.Ldc_I4_0);
596 if (type == TypeManager.int64_type)
597 ig.Emit (OpCodes.Conv_U8);
599 ig.Emit (OpCodes.Sub_Ovf);
602 ig.Emit (OpCodes.Neg);
607 case Operator.LogicalNot:
609 ig.Emit (OpCodes.Ldc_I4_0);
610 ig.Emit (OpCodes.Ceq);
613 case Operator.OnesComplement:
615 ig.Emit (OpCodes.Not);
618 case Operator.AddressOf:
619 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
623 throw new Exception ("This should not happen: Operator = "
628 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
630 if (Oper == Operator.LogicalNot)
631 Expr.EmitBranchable (ec, target, !onTrue);
633 base.EmitBranchable (ec, target, onTrue);
636 public override string ToString ()
638 return "Unary (" + Oper + ", " + Expr + ")";
644 // Unary operators are turned into Indirection expressions
645 // after semantic analysis (this is so we can take the address
646 // of an indirection).
648 public class Indirection : Expression, IMemoryLocation, IAssignMethod {
650 LocalTemporary temporary;
653 public Indirection (Expression expr, Location l)
656 this.type = TypeManager.GetElementType (expr.Type);
657 eclass = ExprClass.Variable;
661 void LoadExprValue (EmitContext ec)
665 public override void Emit (EmitContext ec)
670 LoadFromPtr (ec.ig, Type);
673 public void Emit (EmitContext ec, bool leave_copy)
677 ec.ig.Emit (OpCodes.Dup);
678 temporary = new LocalTemporary (ec, expr.Type);
679 temporary.Store (ec);
683 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
685 prepared = prepare_for_load;
689 if (prepare_for_load)
690 ec.ig.Emit (OpCodes.Dup);
694 ec.ig.Emit (OpCodes.Dup);
695 temporary = new LocalTemporary (ec, expr.Type);
696 temporary.Store (ec);
699 StoreFromPtr (ec.ig, type);
701 if (temporary != null)
705 public void AddressOf (EmitContext ec, AddressOp Mode)
710 public override Expression DoResolve (EmitContext ec)
713 // Born fully resolved
718 public override string ToString ()
720 return "*(" + expr + ")";
725 /// Unary Mutator expressions (pre and post ++ and --)
729 /// UnaryMutator implements ++ and -- expressions. It derives from
730 /// ExpressionStatement becuase the pre/post increment/decrement
731 /// operators can be used in a statement context.
733 /// FIXME: Idea, we could split this up in two classes, one simpler
734 /// for the common case, and one with the extra fields for more complex
735 /// classes (indexers require temporary access; overloaded require method)
738 public class UnaryMutator : ExpressionStatement {
740 public enum Mode : byte {
747 PreDecrement = IsDecrement,
748 PostIncrement = IsPost,
749 PostDecrement = IsPost | IsDecrement
753 bool is_expr = false;
754 bool recurse = false;
759 // This is expensive for the simplest case.
761 StaticCallExpr method;
763 public UnaryMutator (Mode m, Expression e, Location l)
770 static string OperName (Mode mode)
772 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
776 void Error23 (Type t)
779 23, "Operator " + OperName (mode) +
780 " cannot be applied to operand of type `" +
781 TypeManager.CSharpName (t) + "'");
785 /// Returns whether an object of type `t' can be incremented
786 /// or decremented with add/sub (ie, basically whether we can
787 /// use pre-post incr-decr operations on it, but it is not a
788 /// System.Decimal, which we require operator overloading to catch)
790 static bool IsIncrementableNumber (Type t)
792 return (t == TypeManager.sbyte_type) ||
793 (t == TypeManager.byte_type) ||
794 (t == TypeManager.short_type) ||
795 (t == TypeManager.ushort_type) ||
796 (t == TypeManager.int32_type) ||
797 (t == TypeManager.uint32_type) ||
798 (t == TypeManager.int64_type) ||
799 (t == TypeManager.uint64_type) ||
800 (t == TypeManager.char_type) ||
801 (t.IsSubclassOf (TypeManager.enum_type)) ||
802 (t == TypeManager.float_type) ||
803 (t == TypeManager.double_type) ||
804 (t.IsPointer && t != TypeManager.void_ptr_type);
807 Expression ResolveOperator (EmitContext ec)
809 Type expr_type = expr.Type;
812 // Step 1: Perform Operator Overload location
817 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
818 op_name = "op_Increment";
820 op_name = "op_Decrement";
822 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
824 if (mg == null && expr_type.BaseType != null)
825 mg = MemberLookup (ec, expr_type.BaseType, op_name,
826 MemberTypes.Method, AllBindingFlags, loc);
829 method = StaticCallExpr.MakeSimpleCall (
830 ec, (MethodGroupExpr) mg, expr, loc);
837 // The operand of the prefix/postfix increment decrement operators
838 // should be an expression that is classified as a variable,
839 // a property access or an indexer access
842 if (expr.eclass == ExprClass.Variable){
843 LocalVariableReference var = expr as LocalVariableReference;
844 if ((var != null) && var.IsReadOnly)
845 Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
846 if (IsIncrementableNumber (expr_type) ||
847 expr_type == TypeManager.decimal_type){
850 } else if (expr.eclass == ExprClass.IndexerAccess){
851 IndexerAccess ia = (IndexerAccess) expr;
853 expr = ia.ResolveLValue (ec, this);
858 } else if (expr.eclass == ExprClass.PropertyAccess){
859 PropertyExpr pe = (PropertyExpr) expr;
861 if (pe.VerifyAssignable ())
866 expr.Error_UnexpectedKind ("variable, indexer or property access");
870 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
871 TypeManager.CSharpName (expr_type) + "'");
875 public override Expression DoResolve (EmitContext ec)
877 expr = expr.Resolve (ec);
882 eclass = ExprClass.Value;
883 return ResolveOperator (ec);
886 static int PtrTypeSize (Type t)
888 return GetTypeSize (TypeManager.GetElementType (t));
892 // Loads the proper "1" into the stack based on the type, then it emits the
893 // opcode for the operation requested
895 void LoadOneAndEmitOp (EmitContext ec, Type t)
898 // Measure if getting the typecode and using that is more/less efficient
899 // that comparing types. t.GetTypeCode() is an internal call.
901 ILGenerator ig = ec.ig;
903 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
904 LongConstant.EmitLong (ig, 1);
905 else if (t == TypeManager.double_type)
906 ig.Emit (OpCodes.Ldc_R8, 1.0);
907 else if (t == TypeManager.float_type)
908 ig.Emit (OpCodes.Ldc_R4, 1.0F);
909 else if (t.IsPointer){
910 int n = PtrTypeSize (t);
913 ig.Emit (OpCodes.Sizeof, t);
915 IntConstant.EmitInt (ig, n);
917 ig.Emit (OpCodes.Ldc_I4_1);
920 // Now emit the operation
923 if (t == TypeManager.int32_type ||
924 t == TypeManager.int64_type){
925 if ((mode & Mode.IsDecrement) != 0)
926 ig.Emit (OpCodes.Sub_Ovf);
928 ig.Emit (OpCodes.Add_Ovf);
929 } else if (t == TypeManager.uint32_type ||
930 t == TypeManager.uint64_type){
931 if ((mode & Mode.IsDecrement) != 0)
932 ig.Emit (OpCodes.Sub_Ovf_Un);
934 ig.Emit (OpCodes.Add_Ovf_Un);
936 if ((mode & Mode.IsDecrement) != 0)
937 ig.Emit (OpCodes.Sub_Ovf);
939 ig.Emit (OpCodes.Add_Ovf);
942 if ((mode & Mode.IsDecrement) != 0)
943 ig.Emit (OpCodes.Sub);
945 ig.Emit (OpCodes.Add);
948 if (t == TypeManager.sbyte_type){
950 ig.Emit (OpCodes.Conv_Ovf_I1);
952 ig.Emit (OpCodes.Conv_I1);
953 } else if (t == TypeManager.byte_type){
955 ig.Emit (OpCodes.Conv_Ovf_U1);
957 ig.Emit (OpCodes.Conv_U1);
958 } else if (t == TypeManager.short_type){
960 ig.Emit (OpCodes.Conv_Ovf_I2);
962 ig.Emit (OpCodes.Conv_I2);
963 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
965 ig.Emit (OpCodes.Conv_Ovf_U2);
967 ig.Emit (OpCodes.Conv_U2);
972 void EmitCode (EmitContext ec, bool is_expr)
975 this.is_expr = is_expr;
976 ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
980 public override void Emit (EmitContext ec)
983 // We use recurse to allow ourselfs to be the source
984 // of an assignment. This little hack prevents us from
985 // having to allocate another expression
988 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
990 LoadOneAndEmitOp (ec, expr.Type);
992 ec.ig.Emit (OpCodes.Call, method.Method);
1000 public override void EmitStatement (EmitContext ec)
1002 EmitCode (ec, false);
1007 /// Base class for the `Is' and `As' classes.
1011 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1014 public abstract class Probe : Expression {
1015 public readonly Expression ProbeType;
1016 protected Expression expr;
1017 protected Type probe_type;
1019 public Probe (Expression expr, Expression probe_type, Location l)
1021 ProbeType = probe_type;
1026 public Expression Expr {
1032 public override Expression DoResolve (EmitContext ec)
1034 probe_type = ec.DeclSpace.ResolveType (ProbeType, false, loc);
1036 if (probe_type == null)
1039 CheckObsoleteAttribute (probe_type);
1041 expr = expr.Resolve (ec);
1050 /// Implementation of the `is' operator.
1052 public class Is : Probe {
1053 public Is (Expression expr, Expression probe_type, Location l)
1054 : base (expr, probe_type, l)
1059 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1064 public override void Emit (EmitContext ec)
1066 ILGenerator ig = ec.ig;
1071 case Action.AlwaysFalse:
1072 ig.Emit (OpCodes.Pop);
1073 IntConstant.EmitInt (ig, 0);
1075 case Action.AlwaysTrue:
1076 ig.Emit (OpCodes.Pop);
1077 IntConstant.EmitInt (ig, 1);
1079 case Action.LeaveOnStack:
1080 // the `e != null' rule.
1081 ig.Emit (OpCodes.Ldnull);
1082 ig.Emit (OpCodes.Ceq);
1083 ig.Emit (OpCodes.Ldc_I4_0);
1084 ig.Emit (OpCodes.Ceq);
1087 ig.Emit (OpCodes.Isinst, probe_type);
1088 ig.Emit (OpCodes.Ldnull);
1089 ig.Emit (OpCodes.Cgt_Un);
1092 throw new Exception ("never reached");
1095 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
1097 ILGenerator ig = ec.ig;
1100 case Action.AlwaysFalse:
1102 ig.Emit (OpCodes.Br, target);
1105 case Action.AlwaysTrue:
1107 ig.Emit (OpCodes.Br, target);
1110 case Action.LeaveOnStack:
1111 // the `e != null' rule.
1113 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1117 ig.Emit (OpCodes.Isinst, probe_type);
1118 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1121 throw new Exception ("never reached");
1124 public override Expression DoResolve (EmitContext ec)
1126 Expression e = base.DoResolve (ec);
1128 if ((e == null) || (expr == null))
1131 Type etype = expr.Type;
1132 bool warning_always_matches = false;
1133 bool warning_never_matches = false;
1135 type = TypeManager.bool_type;
1136 eclass = ExprClass.Value;
1139 // First case, if at compile time, there is an implicit conversion
1140 // then e != null (objects) or true (value types)
1142 e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1145 if (etype.IsValueType)
1146 action = Action.AlwaysTrue;
1148 action = Action.LeaveOnStack;
1150 warning_always_matches = true;
1151 } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1153 // Second case: explicit reference convresion
1155 if (expr is NullLiteral)
1156 action = Action.AlwaysFalse;
1158 action = Action.Probe;
1160 action = Action.AlwaysFalse;
1161 warning_never_matches = true;
1164 if (RootContext.WarningLevel >= 1){
1165 if (warning_always_matches)
1166 Warning (183, "The expression is always of type `" +
1167 TypeManager.CSharpName (probe_type) + "'");
1168 else if (warning_never_matches){
1169 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1171 "The expression is never of type `" +
1172 TypeManager.CSharpName (probe_type) + "'");
1181 /// Implementation of the `as' operator.
1183 public class As : Probe {
1184 public As (Expression expr, Expression probe_type, Location l)
1185 : base (expr, probe_type, l)
1189 bool do_isinst = false;
1191 public override void Emit (EmitContext ec)
1193 ILGenerator ig = ec.ig;
1198 ig.Emit (OpCodes.Isinst, probe_type);
1201 static void Error_CannotConvertType (Type source, Type target, Location loc)
1204 39, loc, "as operator can not convert from `" +
1205 TypeManager.CSharpName (source) + "' to `" +
1206 TypeManager.CSharpName (target) + "'");
1209 public override Expression DoResolve (EmitContext ec)
1211 Expression e = base.DoResolve (ec);
1217 eclass = ExprClass.Value;
1218 Type etype = expr.Type;
1220 if (TypeManager.IsValueType (probe_type)){
1221 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1222 TypeManager.CSharpName (probe_type) + " is a value type)");
1227 e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1234 if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1239 Error_CannotConvertType (etype, probe_type, loc);
1245 /// This represents a typecast in the source language.
1247 /// FIXME: Cast expressions have an unusual set of parsing
1248 /// rules, we need to figure those out.
1250 public class Cast : Expression {
1251 Expression target_type;
1254 public Cast (Expression cast_type, Expression expr, Location loc)
1256 this.target_type = cast_type;
1261 public Expression TargetType {
1267 public Expression Expr {
1276 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1278 if (!ec.ConstantCheckState)
1281 if ((value < min) || (value > max)) {
1282 Error (221, "Constant value `" + value + "' cannot be converted " +
1283 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1284 "syntax to override)");
1291 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1293 if (!ec.ConstantCheckState)
1297 Error (221, "Constant value `" + value + "' cannot be converted " +
1298 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1299 "syntax to override)");
1306 bool CheckUnsigned (EmitContext ec, long value, Type type)
1308 if (!ec.ConstantCheckState)
1312 Error (221, "Constant value `" + value + "' cannot be converted " +
1313 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1314 "syntax to override)");
1322 /// Attempts to do a compile-time folding of a constant cast.
1324 Expression TryReduce (EmitContext ec, Type target_type)
1326 Expression real_expr = expr;
1327 if (real_expr is EnumConstant)
1328 real_expr = ((EnumConstant) real_expr).Child;
1330 if (real_expr is ByteConstant){
1331 byte v = ((ByteConstant) real_expr).Value;
1333 if (target_type == TypeManager.sbyte_type) {
1334 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1336 return new SByteConstant ((sbyte) v);
1338 if (target_type == TypeManager.short_type)
1339 return new ShortConstant ((short) v);
1340 if (target_type == TypeManager.ushort_type)
1341 return new UShortConstant ((ushort) v);
1342 if (target_type == TypeManager.int32_type)
1343 return new IntConstant ((int) v);
1344 if (target_type == TypeManager.uint32_type)
1345 return new UIntConstant ((uint) v);
1346 if (target_type == TypeManager.int64_type)
1347 return new LongConstant ((long) v);
1348 if (target_type == TypeManager.uint64_type)
1349 return new ULongConstant ((ulong) v);
1350 if (target_type == TypeManager.float_type)
1351 return new FloatConstant ((float) v);
1352 if (target_type == TypeManager.double_type)
1353 return new DoubleConstant ((double) v);
1354 if (target_type == TypeManager.char_type)
1355 return new CharConstant ((char) v);
1356 if (target_type == TypeManager.decimal_type)
1357 return new DecimalConstant ((decimal) v);
1359 if (real_expr is SByteConstant){
1360 sbyte v = ((SByteConstant) real_expr).Value;
1362 if (target_type == TypeManager.byte_type) {
1363 if (!CheckUnsigned (ec, v, target_type))
1365 return new ByteConstant ((byte) v);
1367 if (target_type == TypeManager.short_type)
1368 return new ShortConstant ((short) v);
1369 if (target_type == TypeManager.ushort_type) {
1370 if (!CheckUnsigned (ec, v, target_type))
1372 return new UShortConstant ((ushort) v);
1373 } if (target_type == TypeManager.int32_type)
1374 return new IntConstant ((int) v);
1375 if (target_type == TypeManager.uint32_type) {
1376 if (!CheckUnsigned (ec, v, target_type))
1378 return new UIntConstant ((uint) v);
1379 } if (target_type == TypeManager.int64_type)
1380 return new LongConstant ((long) v);
1381 if (target_type == TypeManager.uint64_type) {
1382 if (!CheckUnsigned (ec, v, target_type))
1384 return new ULongConstant ((ulong) v);
1386 if (target_type == TypeManager.float_type)
1387 return new FloatConstant ((float) v);
1388 if (target_type == TypeManager.double_type)
1389 return new DoubleConstant ((double) v);
1390 if (target_type == TypeManager.char_type) {
1391 if (!CheckUnsigned (ec, v, target_type))
1393 return new CharConstant ((char) v);
1395 if (target_type == TypeManager.decimal_type)
1396 return new DecimalConstant ((decimal) v);
1398 if (real_expr is ShortConstant){
1399 short v = ((ShortConstant) real_expr).Value;
1401 if (target_type == TypeManager.byte_type) {
1402 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1404 return new ByteConstant ((byte) v);
1406 if (target_type == TypeManager.sbyte_type) {
1407 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1409 return new SByteConstant ((sbyte) v);
1411 if (target_type == TypeManager.ushort_type) {
1412 if (!CheckUnsigned (ec, v, target_type))
1414 return new UShortConstant ((ushort) v);
1416 if (target_type == TypeManager.int32_type)
1417 return new IntConstant ((int) v);
1418 if (target_type == TypeManager.uint32_type) {
1419 if (!CheckUnsigned (ec, v, target_type))
1421 return new UIntConstant ((uint) v);
1423 if (target_type == TypeManager.int64_type)
1424 return new LongConstant ((long) v);
1425 if (target_type == TypeManager.uint64_type) {
1426 if (!CheckUnsigned (ec, v, target_type))
1428 return new ULongConstant ((ulong) v);
1430 if (target_type == TypeManager.float_type)
1431 return new FloatConstant ((float) v);
1432 if (target_type == TypeManager.double_type)
1433 return new DoubleConstant ((double) v);
1434 if (target_type == TypeManager.char_type) {
1435 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1437 return new CharConstant ((char) v);
1439 if (target_type == TypeManager.decimal_type)
1440 return new DecimalConstant ((decimal) v);
1442 if (real_expr is UShortConstant){
1443 ushort v = ((UShortConstant) real_expr).Value;
1445 if (target_type == TypeManager.byte_type) {
1446 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1448 return new ByteConstant ((byte) v);
1450 if (target_type == TypeManager.sbyte_type) {
1451 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1453 return new SByteConstant ((sbyte) v);
1455 if (target_type == TypeManager.short_type) {
1456 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1458 return new ShortConstant ((short) v);
1460 if (target_type == TypeManager.int32_type)
1461 return new IntConstant ((int) v);
1462 if (target_type == TypeManager.uint32_type)
1463 return new UIntConstant ((uint) v);
1464 if (target_type == TypeManager.int64_type)
1465 return new LongConstant ((long) v);
1466 if (target_type == TypeManager.uint64_type)
1467 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 (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1475 return new CharConstant ((char) v);
1477 if (target_type == TypeManager.decimal_type)
1478 return new DecimalConstant ((decimal) v);
1480 if (real_expr is IntConstant){
1481 int v = ((IntConstant) 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.short_type) {
1494 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1496 return new ShortConstant ((short) v);
1498 if (target_type == TypeManager.ushort_type) {
1499 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1501 return new UShortConstant ((ushort) v);
1503 if (target_type == TypeManager.uint32_type) {
1504 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1506 return new UIntConstant ((uint) v);
1508 if (target_type == TypeManager.int64_type)
1509 return new LongConstant ((long) v);
1510 if (target_type == TypeManager.uint64_type) {
1511 if (!CheckUnsigned (ec, v, target_type))
1513 return new ULongConstant ((ulong) v);
1515 if (target_type == TypeManager.float_type)
1516 return new FloatConstant ((float) v);
1517 if (target_type == TypeManager.double_type)
1518 return new DoubleConstant ((double) v);
1519 if (target_type == TypeManager.char_type) {
1520 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1522 return new CharConstant ((char) v);
1524 if (target_type == TypeManager.decimal_type)
1525 return new DecimalConstant ((decimal) v);
1527 if (real_expr is UIntConstant){
1528 uint v = ((UIntConstant) real_expr).Value;
1530 if (target_type == TypeManager.byte_type) {
1531 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1533 return new ByteConstant ((byte) v);
1535 if (target_type == TypeManager.sbyte_type) {
1536 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1538 return new SByteConstant ((sbyte) v);
1540 if (target_type == TypeManager.short_type) {
1541 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1543 return new ShortConstant ((short) v);
1545 if (target_type == TypeManager.ushort_type) {
1546 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1548 return new UShortConstant ((ushort) v);
1550 if (target_type == TypeManager.int32_type) {
1551 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1553 return new IntConstant ((int) v);
1555 if (target_type == TypeManager.int64_type)
1556 return new LongConstant ((long) v);
1557 if (target_type == TypeManager.uint64_type)
1558 return new ULongConstant ((ulong) v);
1559 if (target_type == TypeManager.float_type)
1560 return new FloatConstant ((float) v);
1561 if (target_type == TypeManager.double_type)
1562 return new DoubleConstant ((double) v);
1563 if (target_type == TypeManager.char_type) {
1564 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1566 return new CharConstant ((char) v);
1568 if (target_type == TypeManager.decimal_type)
1569 return new DecimalConstant ((decimal) v);
1571 if (real_expr is LongConstant){
1572 long v = ((LongConstant) real_expr).Value;
1574 if (target_type == TypeManager.byte_type) {
1575 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1577 return new ByteConstant ((byte) v);
1579 if (target_type == TypeManager.sbyte_type) {
1580 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1582 return new SByteConstant ((sbyte) v);
1584 if (target_type == TypeManager.short_type) {
1585 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1587 return new ShortConstant ((short) v);
1589 if (target_type == TypeManager.ushort_type) {
1590 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1592 return new UShortConstant ((ushort) v);
1594 if (target_type == TypeManager.int32_type) {
1595 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1597 return new IntConstant ((int) v);
1599 if (target_type == TypeManager.uint32_type) {
1600 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1602 return new UIntConstant ((uint) v);
1604 if (target_type == TypeManager.uint64_type) {
1605 if (!CheckUnsigned (ec, v, target_type))
1607 return new ULongConstant ((ulong) v);
1609 if (target_type == TypeManager.float_type)
1610 return new FloatConstant ((float) v);
1611 if (target_type == TypeManager.double_type)
1612 return new DoubleConstant ((double) v);
1613 if (target_type == TypeManager.char_type) {
1614 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1616 return new CharConstant ((char) v);
1618 if (target_type == TypeManager.decimal_type)
1619 return new DecimalConstant ((decimal) v);
1621 if (real_expr is ULongConstant){
1622 ulong v = ((ULongConstant) real_expr).Value;
1624 if (target_type == TypeManager.byte_type) {
1625 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1627 return new ByteConstant ((byte) v);
1629 if (target_type == TypeManager.sbyte_type) {
1630 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1632 return new SByteConstant ((sbyte) v);
1634 if (target_type == TypeManager.short_type) {
1635 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1637 return new ShortConstant ((short) v);
1639 if (target_type == TypeManager.ushort_type) {
1640 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1642 return new UShortConstant ((ushort) v);
1644 if (target_type == TypeManager.int32_type) {
1645 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1647 return new IntConstant ((int) v);
1649 if (target_type == TypeManager.uint32_type) {
1650 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1652 return new UIntConstant ((uint) v);
1654 if (target_type == TypeManager.int64_type) {
1655 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1657 return new LongConstant ((long) v);
1659 if (target_type == TypeManager.float_type)
1660 return new FloatConstant ((float) v);
1661 if (target_type == TypeManager.double_type)
1662 return new DoubleConstant ((double) v);
1663 if (target_type == TypeManager.char_type) {
1664 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1666 return new CharConstant ((char) v);
1668 if (target_type == TypeManager.decimal_type)
1669 return new DecimalConstant ((decimal) v);
1671 if (real_expr is FloatConstant){
1672 float v = ((FloatConstant) real_expr).Value;
1674 if (target_type == TypeManager.byte_type)
1675 return new ByteConstant ((byte) v);
1676 if (target_type == TypeManager.sbyte_type)
1677 return new SByteConstant ((sbyte) v);
1678 if (target_type == TypeManager.short_type)
1679 return new ShortConstant ((short) v);
1680 if (target_type == TypeManager.ushort_type)
1681 return new UShortConstant ((ushort) v);
1682 if (target_type == TypeManager.int32_type)
1683 return new IntConstant ((int) v);
1684 if (target_type == TypeManager.uint32_type)
1685 return new UIntConstant ((uint) v);
1686 if (target_type == TypeManager.int64_type)
1687 return new LongConstant ((long) v);
1688 if (target_type == TypeManager.uint64_type)
1689 return new ULongConstant ((ulong) v);
1690 if (target_type == TypeManager.double_type)
1691 return new DoubleConstant ((double) v);
1692 if (target_type == TypeManager.char_type)
1693 return new CharConstant ((char) v);
1694 if (target_type == TypeManager.decimal_type)
1695 return new DecimalConstant ((decimal) v);
1697 if (real_expr is DoubleConstant){
1698 double v = ((DoubleConstant) real_expr).Value;
1700 if (target_type == TypeManager.byte_type){
1701 return new ByteConstant ((byte) v);
1702 } if (target_type == TypeManager.sbyte_type)
1703 return new SByteConstant ((sbyte) v);
1704 if (target_type == TypeManager.short_type)
1705 return new ShortConstant ((short) v);
1706 if (target_type == TypeManager.ushort_type)
1707 return new UShortConstant ((ushort) v);
1708 if (target_type == TypeManager.int32_type)
1709 return new IntConstant ((int) v);
1710 if (target_type == TypeManager.uint32_type)
1711 return new UIntConstant ((uint) v);
1712 if (target_type == TypeManager.int64_type)
1713 return new LongConstant ((long) v);
1714 if (target_type == TypeManager.uint64_type)
1715 return new ULongConstant ((ulong) v);
1716 if (target_type == TypeManager.float_type)
1717 return new FloatConstant ((float) v);
1718 if (target_type == TypeManager.char_type)
1719 return new CharConstant ((char) v);
1720 if (target_type == TypeManager.decimal_type)
1721 return new DecimalConstant ((decimal) v);
1724 if (real_expr is CharConstant){
1725 char v = ((CharConstant) real_expr).Value;
1727 if (target_type == TypeManager.byte_type) {
1728 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1730 return new ByteConstant ((byte) v);
1732 if (target_type == TypeManager.sbyte_type) {
1733 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1735 return new SByteConstant ((sbyte) v);
1737 if (target_type == TypeManager.short_type) {
1738 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1740 return new ShortConstant ((short) v);
1742 if (target_type == TypeManager.int32_type)
1743 return new IntConstant ((int) v);
1744 if (target_type == TypeManager.uint32_type)
1745 return new UIntConstant ((uint) v);
1746 if (target_type == TypeManager.int64_type)
1747 return new LongConstant ((long) v);
1748 if (target_type == TypeManager.uint64_type)
1749 return new ULongConstant ((ulong) v);
1750 if (target_type == TypeManager.float_type)
1751 return new FloatConstant ((float) v);
1752 if (target_type == TypeManager.double_type)
1753 return new DoubleConstant ((double) v);
1754 if (target_type == TypeManager.char_type) {
1755 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1757 return new CharConstant ((char) v);
1759 if (target_type == TypeManager.decimal_type)
1760 return new DecimalConstant ((decimal) v);
1766 public override Expression DoResolve (EmitContext ec)
1768 expr = expr.Resolve (ec);
1772 type = ec.DeclSpace.ResolveType (target_type, false, Location);
1777 CheckObsoleteAttribute (type);
1779 eclass = ExprClass.Value;
1781 if (expr is Constant){
1782 Expression e = TryReduce (ec, type);
1788 if (type.IsPointer && !ec.InUnsafe) {
1792 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1796 public override void Emit (EmitContext ec)
1799 // This one will never happen
1801 throw new Exception ("Should not happen");
1806 /// Binary operators
1808 public class Binary : Expression {
1809 public enum Operator : byte {
1810 Multiply, Division, Modulus,
1811 Addition, Subtraction,
1812 LeftShift, RightShift,
1813 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1814 Equality, Inequality,
1824 Expression left, right;
1826 // This must be kept in sync with Operator!!!
1827 public static readonly string [] oper_names;
1831 oper_names = new string [(int) Operator.TOP];
1833 oper_names [(int) Operator.Multiply] = "op_Multiply";
1834 oper_names [(int) Operator.Division] = "op_Division";
1835 oper_names [(int) Operator.Modulus] = "op_Modulus";
1836 oper_names [(int) Operator.Addition] = "op_Addition";
1837 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1838 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1839 oper_names [(int) Operator.RightShift] = "op_RightShift";
1840 oper_names [(int) Operator.LessThan] = "op_LessThan";
1841 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1842 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1843 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1844 oper_names [(int) Operator.Equality] = "op_Equality";
1845 oper_names [(int) Operator.Inequality] = "op_Inequality";
1846 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1847 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1848 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1849 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1850 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1853 public Binary (Operator oper, Expression left, Expression right, Location loc)
1861 public Operator Oper {
1870 public Expression Left {
1879 public Expression Right {
1890 /// Returns a stringified representation of the Operator
1892 static string OperName (Operator oper)
1895 case Operator.Multiply:
1897 case Operator.Division:
1899 case Operator.Modulus:
1901 case Operator.Addition:
1903 case Operator.Subtraction:
1905 case Operator.LeftShift:
1907 case Operator.RightShift:
1909 case Operator.LessThan:
1911 case Operator.GreaterThan:
1913 case Operator.LessThanOrEqual:
1915 case Operator.GreaterThanOrEqual:
1917 case Operator.Equality:
1919 case Operator.Inequality:
1921 case Operator.BitwiseAnd:
1923 case Operator.BitwiseOr:
1925 case Operator.ExclusiveOr:
1927 case Operator.LogicalOr:
1929 case Operator.LogicalAnd:
1933 return oper.ToString ();
1936 public override string ToString ()
1938 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1939 right.ToString () + ")";
1942 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1944 if (expr.Type == target_type)
1947 return Convert.ImplicitConversion (ec, expr, target_type, loc);
1950 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1953 34, loc, "Operator `" + OperName (oper)
1954 + "' is ambiguous on operands of type `"
1955 + TypeManager.CSharpName (l) + "' "
1956 + "and `" + TypeManager.CSharpName (r)
1960 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
1962 if ((l == t) || (r == t))
1965 if (!check_user_conversions)
1968 if (Convert.ImplicitUserConversionExists (ec, l, t))
1970 else if (Convert.ImplicitUserConversionExists (ec, r, t))
1977 // Note that handling the case l == Decimal || r == Decimal
1978 // is taken care of by the Step 1 Operator Overload resolution.
1980 // If `check_user_conv' is true, we also check whether a user-defined conversion
1981 // exists. Note that we only need to do this if both arguments are of a user-defined
1982 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
1983 // so we don't explicitly check for performance reasons.
1985 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
1987 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
1989 // If either operand is of type double, the other operand is
1990 // conveted to type double.
1992 if (r != TypeManager.double_type)
1993 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
1994 if (l != TypeManager.double_type)
1995 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
1997 type = TypeManager.double_type;
1998 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
2000 // if either operand is of type float, the other operand is
2001 // converted to type float.
2003 if (r != TypeManager.double_type)
2004 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
2005 if (l != TypeManager.double_type)
2006 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
2007 type = TypeManager.float_type;
2008 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2012 // If either operand is of type ulong, the other operand is
2013 // converted to type ulong. or an error ocurrs if the other
2014 // operand is of type sbyte, short, int or long
2016 if (l == TypeManager.uint64_type){
2017 if (r != TypeManager.uint64_type){
2018 if (right is IntConstant){
2019 IntConstant ic = (IntConstant) right;
2021 e = Convert.TryImplicitIntConversion (l, ic);
2024 } else if (right is LongConstant){
2025 long ll = ((LongConstant) right).Value;
2028 right = new ULongConstant ((ulong) ll);
2030 e = Convert.ImplicitNumericConversion (ec, right, l, loc);
2037 if (left is IntConstant){
2038 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
2041 } else if (left is LongConstant){
2042 long ll = ((LongConstant) left).Value;
2045 left = new ULongConstant ((ulong) ll);
2047 e = Convert.ImplicitNumericConversion (ec, left, r, loc);
2054 if ((other == TypeManager.sbyte_type) ||
2055 (other == TypeManager.short_type) ||
2056 (other == TypeManager.int32_type) ||
2057 (other == TypeManager.int64_type))
2058 Error_OperatorAmbiguous (loc, oper, l, r);
2060 left = ForceConversion (ec, left, TypeManager.uint64_type);
2061 right = ForceConversion (ec, right, TypeManager.uint64_type);
2063 type = TypeManager.uint64_type;
2064 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2066 // If either operand is of type long, the other operand is converted
2069 if (l != TypeManager.int64_type)
2070 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
2071 if (r != TypeManager.int64_type)
2072 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
2074 type = TypeManager.int64_type;
2075 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2077 // If either operand is of type uint, and the other
2078 // operand is of type sbyte, short or int, othe operands are
2079 // converted to type long (unless we have an int constant).
2083 if (l == TypeManager.uint32_type){
2084 if (right is IntConstant){
2085 IntConstant ic = (IntConstant) right;
2089 right = new UIntConstant ((uint) val);
2096 } else if (r == TypeManager.uint32_type){
2097 if (left is IntConstant){
2098 IntConstant ic = (IntConstant) left;
2102 left = new UIntConstant ((uint) val);
2111 if ((other == TypeManager.sbyte_type) ||
2112 (other == TypeManager.short_type) ||
2113 (other == TypeManager.int32_type)){
2114 left = ForceConversion (ec, left, TypeManager.int64_type);
2115 right = ForceConversion (ec, right, TypeManager.int64_type);
2116 type = TypeManager.int64_type;
2119 // if either operand is of type uint, the other
2120 // operand is converd to type uint
2122 left = ForceConversion (ec, left, TypeManager.uint32_type);
2123 right = ForceConversion (ec, right, TypeManager.uint32_type);
2124 type = TypeManager.uint32_type;
2126 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2127 if (l != TypeManager.decimal_type)
2128 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
2130 if (r != TypeManager.decimal_type)
2131 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
2132 type = TypeManager.decimal_type;
2134 left = ForceConversion (ec, left, TypeManager.int32_type);
2135 right = ForceConversion (ec, right, TypeManager.int32_type);
2137 type = TypeManager.int32_type;
2140 return (left != null) && (right != null);
2143 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2145 Report.Error (19, loc,
2146 "Operator " + name + " cannot be applied to operands of type `" +
2147 TypeManager.CSharpName (l) + "' and `" +
2148 TypeManager.CSharpName (r) + "'");
2151 void Error_OperatorCannotBeApplied ()
2153 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2156 static bool is_unsigned (Type t)
2158 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2159 t == TypeManager.short_type || t == TypeManager.byte_type);
2162 static bool is_user_defined (Type t)
2164 if (t.IsSubclassOf (TypeManager.value_type) &&
2165 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2171 Expression Make32or64 (EmitContext ec, Expression e)
2175 if (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2176 t == TypeManager.int64_type || t == TypeManager.uint64_type)
2178 Expression ee = Convert.ImplicitConversion (ec, e, TypeManager.int32_type, loc);
2181 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint32_type, loc);
2184 ee = Convert.ImplicitConversion (ec, e, TypeManager.int64_type, loc);
2187 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint64_type, loc);
2193 Expression CheckShiftArguments (EmitContext ec)
2197 e = ForceConversion (ec, right, TypeManager.int32_type);
2199 Error_OperatorCannotBeApplied ();
2204 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
2205 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
2206 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
2207 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
2211 if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
2212 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (31), loc);
2213 right = right.DoResolve (ec);
2215 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (63), loc);
2216 right = right.DoResolve (ec);
2221 Error_OperatorCannotBeApplied ();
2225 Expression ResolveOperator (EmitContext ec)
2228 Type r = right.Type;
2230 bool overload_failed = false;
2233 // Special cases: string or type parameter comapred to null
2235 if (oper == Operator.Equality || oper == Operator.Inequality){
2236 if ((l == TypeManager.string_type && (right is NullLiteral)) ||
2237 (r == TypeManager.string_type && (left is NullLiteral))){
2238 Type = TypeManager.bool_type;
2243 if (l.IsGenericParameter && (right is NullLiteral)) {
2244 if (l.BaseType == TypeManager.value_type) {
2245 Error_OperatorCannotBeApplied ();
2249 left = new BoxedCast (left);
2250 Type = TypeManager.bool_type;
2254 if (r.IsGenericParameter && (left is NullLiteral)) {
2255 if (r.BaseType == TypeManager.value_type) {
2256 Error_OperatorCannotBeApplied ();
2260 right = new BoxedCast (right);
2261 Type = TypeManager.bool_type;
2266 if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
2267 Type = TypeManager.bool_type;
2274 // Do not perform operator overload resolution when both sides are
2277 if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
2279 // Step 1: Perform Operator Overload location
2281 Expression left_expr, right_expr;
2283 string op = oper_names [(int) oper];
2285 MethodGroupExpr union;
2286 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2288 right_expr = MemberLookup (
2289 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2290 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2292 union = (MethodGroupExpr) left_expr;
2294 if (union != null) {
2295 ArrayList args = new ArrayList (2);
2296 args.Add (new Argument (left, Argument.AType.Expression));
2297 args.Add (new Argument (right, Argument.AType.Expression));
2299 MethodBase method = Invocation.OverloadResolve (
2300 ec, union, args, true, Location.Null);
2302 if (method != null) {
2303 MethodInfo mi = (MethodInfo) method;
2305 return new BinaryMethod (mi.ReturnType, method, args);
2307 overload_failed = true;
2313 // Step 0: String concatenation (because overloading will get this wrong)
2315 if (oper == Operator.Addition){
2317 // If any of the arguments is a string, cast to string
2320 // Simple constant folding
2321 if (left is StringConstant && right is StringConstant)
2322 return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value);
2324 if (l == TypeManager.string_type || r == TypeManager.string_type) {
2326 if (r == TypeManager.void_type || l == TypeManager.void_type) {
2327 Error_OperatorCannotBeApplied ();
2331 // try to fold it in on the left
2332 if (left is StringConcat) {
2335 // We have to test here for not-null, since we can be doubly-resolved
2336 // take care of not appending twice
2339 type = TypeManager.string_type;
2340 ((StringConcat) left).Append (ec, right);
2341 return left.Resolve (ec);
2347 // Otherwise, start a new concat expression
2348 return new StringConcat (ec, loc, left, right).Resolve (ec);
2352 // Transform a + ( - b) into a - b
2354 if (right is Unary){
2355 Unary right_unary = (Unary) right;
2357 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2358 oper = Operator.Subtraction;
2359 right = right_unary.Expr;
2365 if (oper == Operator.Equality || oper == Operator.Inequality){
2366 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2367 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2368 Error_OperatorCannotBeApplied ();
2372 type = TypeManager.bool_type;
2377 // operator != (object a, object b)
2378 // operator == (object a, object b)
2380 // For this to be used, both arguments have to be reference-types.
2381 // Read the rationale on the spec (14.9.6)
2383 // Also, if at compile time we know that the classes do not inherit
2384 // one from the other, then we catch the error there.
2386 if (!(l.IsValueType || r.IsValueType)){
2387 type = TypeManager.bool_type;
2392 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2396 // Also, a standard conversion must exist from either one
2398 if (!(Convert.ImplicitStandardConversionExists (left, r) ||
2399 Convert.ImplicitStandardConversionExists (right, l))){
2400 Error_OperatorCannotBeApplied ();
2404 // We are going to have to convert to an object to compare
2406 if (l != TypeManager.object_type)
2407 left = new EmptyCast (left, TypeManager.object_type);
2408 if (r != TypeManager.object_type)
2409 right = new EmptyCast (right, TypeManager.object_type);
2412 // FIXME: CSC here catches errors cs254 and cs252
2418 // One of them is a valuetype, but the other one is not.
2420 if (!l.IsValueType || !r.IsValueType) {
2421 Error_OperatorCannotBeApplied ();
2426 // Only perform numeric promotions on:
2427 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2429 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2430 if (TypeManager.IsDelegateType (l)){
2431 if (right.eclass == ExprClass.MethodGroup && RootContext.V2){
2432 Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2439 if (TypeManager.IsDelegateType (r)){
2441 ArrayList args = new ArrayList (2);
2443 args = new ArrayList (2);
2444 args.Add (new Argument (left, Argument.AType.Expression));
2445 args.Add (new Argument (right, Argument.AType.Expression));
2447 if (oper == Operator.Addition)
2448 method = TypeManager.delegate_combine_delegate_delegate;
2450 method = TypeManager.delegate_remove_delegate_delegate;
2453 Error_OperatorCannotBeApplied ();
2457 return new BinaryDelegate (l, method, args);
2462 // Pointer arithmetic:
2464 // T* operator + (T* x, int y);
2465 // T* operator + (T* x, uint y);
2466 // T* operator + (T* x, long y);
2467 // T* operator + (T* x, ulong y);
2469 // T* operator + (int y, T* x);
2470 // T* operator + (uint y, T *x);
2471 // T* operator + (long y, T *x);
2472 // T* operator + (ulong y, T *x);
2474 // T* operator - (T* x, int y);
2475 // T* operator - (T* x, uint y);
2476 // T* operator - (T* x, long y);
2477 // T* operator - (T* x, ulong y);
2479 // long operator - (T* x, T *y)
2482 if (r.IsPointer && oper == Operator.Subtraction){
2484 return new PointerArithmetic (
2485 false, left, right, TypeManager.int64_type,
2488 Expression t = Make32or64 (ec, right);
2490 return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc);
2492 } else if (r.IsPointer && oper == Operator.Addition){
2493 Expression t = Make32or64 (ec, left);
2495 return new PointerArithmetic (true, right, t, r, loc);
2500 // Enumeration operators
2502 bool lie = TypeManager.IsEnumType (l);
2503 bool rie = TypeManager.IsEnumType (r);
2507 // U operator - (E e, E f)
2509 if (oper == Operator.Subtraction){
2511 type = TypeManager.EnumToUnderlying (l);
2514 Error_OperatorCannotBeApplied ();
2520 // operator + (E e, U x)
2521 // operator - (E e, U x)
2523 if (oper == Operator.Addition || oper == Operator.Subtraction){
2524 Type enum_type = lie ? l : r;
2525 Type other_type = lie ? r : l;
2526 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2528 if (underlying_type != other_type){
2529 temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
2539 Error_OperatorCannotBeApplied ();
2548 temp = Convert.ImplicitConversion (ec, right, l, loc);
2552 Error_OperatorCannotBeApplied ();
2556 temp = Convert.ImplicitConversion (ec, left, r, loc);
2561 Error_OperatorCannotBeApplied ();
2566 if (oper == Operator.Equality || oper == Operator.Inequality ||
2567 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2568 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2569 if (left.Type != right.Type){
2570 Error_OperatorCannotBeApplied ();
2573 type = TypeManager.bool_type;
2577 if (oper == Operator.BitwiseAnd ||
2578 oper == Operator.BitwiseOr ||
2579 oper == Operator.ExclusiveOr){
2583 Error_OperatorCannotBeApplied ();
2587 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2588 return CheckShiftArguments (ec);
2590 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2591 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2592 type = TypeManager.bool_type;
2597 Error_OperatorCannotBeApplied ();
2601 Expression e = new ConditionalLogicalOperator (
2602 oper == Operator.LogicalAnd, left, right, l, loc);
2603 return e.Resolve (ec);
2607 // operator & (bool x, bool y)
2608 // operator | (bool x, bool y)
2609 // operator ^ (bool x, bool y)
2611 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2612 if (oper == Operator.BitwiseAnd ||
2613 oper == Operator.BitwiseOr ||
2614 oper == Operator.ExclusiveOr){
2621 // Pointer comparison
2623 if (l.IsPointer && r.IsPointer){
2624 if (oper == Operator.Equality || oper == Operator.Inequality ||
2625 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2626 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2627 type = TypeManager.bool_type;
2633 // We are dealing with numbers
2635 if (overload_failed){
2636 Error_OperatorCannotBeApplied ();
2641 // This will leave left or right set to null if there is an error
2643 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2644 DoNumericPromotions (ec, l, r, check_user_conv);
2645 if (left == null || right == null){
2646 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2651 // reload our cached types if required
2656 if (oper == Operator.BitwiseAnd ||
2657 oper == Operator.BitwiseOr ||
2658 oper == Operator.ExclusiveOr){
2660 if (((l == TypeManager.int32_type) ||
2661 (l == TypeManager.uint32_type) ||
2662 (l == TypeManager.short_type) ||
2663 (l == TypeManager.ushort_type) ||
2664 (l == TypeManager.int64_type) ||
2665 (l == TypeManager.uint64_type))){
2668 Error_OperatorCannotBeApplied ();
2672 Error_OperatorCannotBeApplied ();
2677 if (oper == Operator.Equality ||
2678 oper == Operator.Inequality ||
2679 oper == Operator.LessThanOrEqual ||
2680 oper == Operator.LessThan ||
2681 oper == Operator.GreaterThanOrEqual ||
2682 oper == Operator.GreaterThan){
2683 type = TypeManager.bool_type;
2689 public override Expression DoResolve (EmitContext ec)
2691 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2692 left = ((ParenthesizedExpression) left).Expr;
2693 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2697 if (left.eclass == ExprClass.Type) {
2698 Error (75, "Casting a negative value needs to have the value in parentheses.");
2702 left = left.Resolve (ec);
2703 right = right.Resolve (ec);
2705 if (left == null || right == null)
2708 eclass = ExprClass.Value;
2710 Constant rc = right as Constant;
2711 Constant lc = left as Constant;
2713 if (rc != null & lc != null){
2714 Expression e = ConstantFold.BinaryFold (
2715 ec, oper, lc, rc, loc);
2720 return ResolveOperator (ec);
2724 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2725 /// context of a conditional bool expression. This function will return
2726 /// false if it is was possible to use EmitBranchable, or true if it was.
2728 /// The expression's code is generated, and we will generate a branch to `target'
2729 /// if the resulting expression value is equal to isTrue
2731 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2733 ILGenerator ig = ec.ig;
2736 // This is more complicated than it looks, but its just to avoid
2737 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2738 // but on top of that we want for == and != to use a special path
2739 // if we are comparing against null
2741 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
2742 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2745 // put the constant on the rhs, for simplicity
2747 if (left is Constant) {
2748 Expression swap = right;
2753 if (((Constant) right).IsZeroInteger) {
2756 ig.Emit (OpCodes.Brtrue, target);
2758 ig.Emit (OpCodes.Brfalse, target);
2761 } else if (right is BoolConstant){
2763 if (my_on_true != ((BoolConstant) right).Value)
2764 ig.Emit (OpCodes.Brtrue, target);
2766 ig.Emit (OpCodes.Brfalse, target);
2771 } else if (oper == Operator.LogicalAnd) {
2774 Label tests_end = ig.DefineLabel ();
2776 left.EmitBranchable (ec, tests_end, false);
2777 right.EmitBranchable (ec, target, true);
2778 ig.MarkLabel (tests_end);
2780 left.EmitBranchable (ec, target, false);
2781 right.EmitBranchable (ec, target, false);
2786 } else if (oper == Operator.LogicalOr){
2788 left.EmitBranchable (ec, target, true);
2789 right.EmitBranchable (ec, target, true);
2792 Label tests_end = ig.DefineLabel ();
2793 left.EmitBranchable (ec, tests_end, true);
2794 right.EmitBranchable (ec, target, false);
2795 ig.MarkLabel (tests_end);
2800 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2801 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2802 oper == Operator.Equality || oper == Operator.Inequality)) {
2803 base.EmitBranchable (ec, target, onTrue);
2811 bool isUnsigned = is_unsigned (t) || t == TypeManager.double_type || t == TypeManager.float_type;
2814 case Operator.Equality:
2816 ig.Emit (OpCodes.Beq, target);
2818 ig.Emit (OpCodes.Bne_Un, target);
2821 case Operator.Inequality:
2823 ig.Emit (OpCodes.Bne_Un, target);
2825 ig.Emit (OpCodes.Beq, target);
2828 case Operator.LessThan:
2831 ig.Emit (OpCodes.Blt_Un, target);
2833 ig.Emit (OpCodes.Blt, target);
2836 ig.Emit (OpCodes.Bge_Un, target);
2838 ig.Emit (OpCodes.Bge, target);
2841 case Operator.GreaterThan:
2844 ig.Emit (OpCodes.Bgt_Un, target);
2846 ig.Emit (OpCodes.Bgt, target);
2849 ig.Emit (OpCodes.Ble_Un, target);
2851 ig.Emit (OpCodes.Ble, target);
2854 case Operator.LessThanOrEqual:
2857 ig.Emit (OpCodes.Ble_Un, target);
2859 ig.Emit (OpCodes.Ble, target);
2862 ig.Emit (OpCodes.Bgt_Un, target);
2864 ig.Emit (OpCodes.Bgt, target);
2868 case Operator.GreaterThanOrEqual:
2871 ig.Emit (OpCodes.Bge_Un, target);
2873 ig.Emit (OpCodes.Bge, target);
2876 ig.Emit (OpCodes.Blt_Un, target);
2878 ig.Emit (OpCodes.Blt, target);
2881 Console.WriteLine (oper);
2882 throw new Exception ("what is THAT");
2886 public override void Emit (EmitContext ec)
2888 ILGenerator ig = ec.ig;
2893 // Handle short-circuit operators differently
2896 if (oper == Operator.LogicalAnd) {
2897 Label load_zero = ig.DefineLabel ();
2898 Label end = ig.DefineLabel ();
2900 left.EmitBranchable (ec, load_zero, false);
2902 ig.Emit (OpCodes.Br, end);
2904 ig.MarkLabel (load_zero);
2905 ig.Emit (OpCodes.Ldc_I4_0);
2908 } else if (oper == Operator.LogicalOr) {
2909 Label load_one = ig.DefineLabel ();
2910 Label end = ig.DefineLabel ();
2912 left.EmitBranchable (ec, load_one, true);
2914 ig.Emit (OpCodes.Br, end);
2916 ig.MarkLabel (load_one);
2917 ig.Emit (OpCodes.Ldc_I4_1);
2925 bool isUnsigned = is_unsigned (left.Type);
2928 case Operator.Multiply:
2930 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2931 opcode = OpCodes.Mul_Ovf;
2932 else if (isUnsigned)
2933 opcode = OpCodes.Mul_Ovf_Un;
2935 opcode = OpCodes.Mul;
2937 opcode = OpCodes.Mul;
2941 case Operator.Division:
2943 opcode = OpCodes.Div_Un;
2945 opcode = OpCodes.Div;
2948 case Operator.Modulus:
2950 opcode = OpCodes.Rem_Un;
2952 opcode = OpCodes.Rem;
2955 case Operator.Addition:
2957 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2958 opcode = OpCodes.Add_Ovf;
2959 else if (isUnsigned)
2960 opcode = OpCodes.Add_Ovf_Un;
2962 opcode = OpCodes.Add;
2964 opcode = OpCodes.Add;
2967 case Operator.Subtraction:
2969 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2970 opcode = OpCodes.Sub_Ovf;
2971 else if (isUnsigned)
2972 opcode = OpCodes.Sub_Ovf_Un;
2974 opcode = OpCodes.Sub;
2976 opcode = OpCodes.Sub;
2979 case Operator.RightShift:
2981 opcode = OpCodes.Shr_Un;
2983 opcode = OpCodes.Shr;
2986 case Operator.LeftShift:
2987 opcode = OpCodes.Shl;
2990 case Operator.Equality:
2991 opcode = OpCodes.Ceq;
2994 case Operator.Inequality:
2995 ig.Emit (OpCodes.Ceq);
2996 ig.Emit (OpCodes.Ldc_I4_0);
2998 opcode = OpCodes.Ceq;
3001 case Operator.LessThan:
3003 opcode = OpCodes.Clt_Un;
3005 opcode = OpCodes.Clt;
3008 case Operator.GreaterThan:
3010 opcode = OpCodes.Cgt_Un;
3012 opcode = OpCodes.Cgt;
3015 case Operator.LessThanOrEqual:
3016 Type lt = left.Type;
3018 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
3019 ig.Emit (OpCodes.Cgt_Un);
3021 ig.Emit (OpCodes.Cgt);
3022 ig.Emit (OpCodes.Ldc_I4_0);
3024 opcode = OpCodes.Ceq;
3027 case Operator.GreaterThanOrEqual:
3028 Type le = left.Type;
3030 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3031 ig.Emit (OpCodes.Clt_Un);
3033 ig.Emit (OpCodes.Clt);
3035 ig.Emit (OpCodes.Ldc_I4_0);
3037 opcode = OpCodes.Ceq;
3040 case Operator.BitwiseOr:
3041 opcode = OpCodes.Or;
3044 case Operator.BitwiseAnd:
3045 opcode = OpCodes.And;
3048 case Operator.ExclusiveOr:
3049 opcode = OpCodes.Xor;
3053 throw new Exception ("This should not happen: Operator = "
3054 + oper.ToString ());
3062 // Object created by Binary when the binary operator uses an method instead of being
3063 // a binary operation that maps to a CIL binary operation.
3065 public class BinaryMethod : Expression {
3066 public MethodBase method;
3067 public ArrayList Arguments;
3069 public BinaryMethod (Type t, MethodBase m, ArrayList args)
3074 eclass = ExprClass.Value;
3077 public override Expression DoResolve (EmitContext ec)
3082 public override void Emit (EmitContext ec)
3084 ILGenerator ig = ec.ig;
3086 if (Arguments != null)
3087 Invocation.EmitArguments (ec, method, Arguments, false, null);
3089 if (method is MethodInfo)
3090 ig.Emit (OpCodes.Call, (MethodInfo) method);
3092 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3097 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3098 // b, c, d... may be strings or objects.
3100 public class StringConcat : Expression {
3102 bool invalid = false;
3105 public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
3108 type = TypeManager.string_type;
3109 eclass = ExprClass.Value;
3111 operands = new ArrayList (2);
3116 public override Expression DoResolve (EmitContext ec)
3124 public void Append (EmitContext ec, Expression operand)
3129 if (operand is StringConstant && operands.Count != 0) {
3130 StringConstant last_operand = operands [operands.Count - 1] as StringConstant;
3131 if (last_operand != null) {
3132 operands [operands.Count - 1] = new StringConstant (last_operand.Value + ((StringConstant) operand).Value);
3138 // Conversion to object
3140 if (operand.Type != TypeManager.string_type) {
3141 Expression no = Convert.ImplicitConversion (ec, operand, TypeManager.object_type, loc);
3144 Binary.Error_OperatorCannotBeApplied (loc, "+", TypeManager.string_type, operand.Type);
3150 operands.Add (operand);
3153 public override void Emit (EmitContext ec)
3155 MethodInfo concat_method = null;
3158 // Are we also concating objects?
3160 bool is_strings_only = true;
3163 // Do conversion to arguments; check for strings only
3165 for (int i = 0; i < operands.Count; i ++) {
3166 Expression e = (Expression) operands [i];
3167 is_strings_only &= e.Type == TypeManager.string_type;
3170 for (int i = 0; i < operands.Count; i ++) {
3171 Expression e = (Expression) operands [i];
3173 if (! is_strings_only && e.Type == TypeManager.string_type) {
3174 // need to make sure this is an object, because the EmitParams
3175 // method might look at the type of this expression, see it is a
3176 // string and emit a string [] when we want an object [];
3178 e = Convert.ImplicitConversion (ec, e, TypeManager.object_type, loc);
3180 operands [i] = new Argument (e, Argument.AType.Expression);
3184 // Find the right method
3186 switch (operands.Count) {
3189 // This should not be possible, because simple constant folding
3190 // is taken care of in the Binary code.
3192 throw new Exception ("how did you get here?");
3195 concat_method = is_strings_only ?
3196 TypeManager.string_concat_string_string :
3197 TypeManager.string_concat_object_object ;
3200 concat_method = is_strings_only ?
3201 TypeManager.string_concat_string_string_string :
3202 TypeManager.string_concat_object_object_object ;
3206 // There is not a 4 param overlaod for object (the one that there is
3207 // is actually a varargs methods, and is only in corlib because it was
3208 // introduced there before.).
3210 if (!is_strings_only)
3213 concat_method = TypeManager.string_concat_string_string_string_string;
3216 concat_method = is_strings_only ?
3217 TypeManager.string_concat_string_dot_dot_dot :
3218 TypeManager.string_concat_object_dot_dot_dot ;
3222 Invocation.EmitArguments (ec, concat_method, operands, false, null);
3223 ec.ig.Emit (OpCodes.Call, concat_method);
3228 // Object created with +/= on delegates
3230 public class BinaryDelegate : Expression {
3234 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3239 eclass = ExprClass.Value;
3242 public override Expression DoResolve (EmitContext ec)
3247 public override void Emit (EmitContext ec)
3249 ILGenerator ig = ec.ig;
3251 Invocation.EmitArguments (ec, method, args, false, null);
3253 ig.Emit (OpCodes.Call, (MethodInfo) method);
3254 ig.Emit (OpCodes.Castclass, type);
3257 public Expression Right {
3259 Argument arg = (Argument) args [1];
3264 public bool IsAddition {
3266 return method == TypeManager.delegate_combine_delegate_delegate;
3272 // User-defined conditional logical operator
3273 public class ConditionalLogicalOperator : Expression {
3274 Expression left, right;
3277 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3280 eclass = ExprClass.Value;
3284 this.is_and = is_and;
3287 protected void Error19 ()
3289 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3292 protected void Error218 ()
3294 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3295 "declarations of operator true and operator false");
3298 Expression op_true, op_false, op;
3299 LocalTemporary left_temp;
3301 public override Expression DoResolve (EmitContext ec)
3304 Expression operator_group;
3306 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3307 if (operator_group == null) {
3312 left_temp = new LocalTemporary (ec, type);
3314 ArrayList arguments = new ArrayList ();
3315 arguments.Add (new Argument (left_temp, Argument.AType.Expression));
3316 arguments.Add (new Argument (right, Argument.AType.Expression));
3317 method = Invocation.OverloadResolve (
3318 ec, (MethodGroupExpr) operator_group, arguments, false, loc)
3320 if ((method == null) || (method.ReturnType != type)) {
3325 op = new StaticCallExpr (method, arguments, loc);
3327 op_true = GetOperatorTrue (ec, left_temp, loc);
3328 op_false = GetOperatorFalse (ec, left_temp, loc);
3329 if ((op_true == null) || (op_false == null)) {
3337 public override void Emit (EmitContext ec)
3339 ILGenerator ig = ec.ig;
3340 Label false_target = ig.DefineLabel ();
3341 Label end_target = ig.DefineLabel ();
3343 ig.Emit (OpCodes.Nop);
3346 left_temp.Store (ec);
3348 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
3349 left_temp.Emit (ec);
3350 ig.Emit (OpCodes.Br, end_target);
3351 ig.MarkLabel (false_target);
3353 ig.MarkLabel (end_target);
3355 ig.Emit (OpCodes.Nop);
3359 public class PointerArithmetic : Expression {
3360 Expression left, right;
3364 // We assume that `l' is always a pointer
3366 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3369 eclass = ExprClass.Variable;
3373 is_add = is_addition;
3376 public override Expression DoResolve (EmitContext ec)
3379 // We are born fully resolved
3384 public override void Emit (EmitContext ec)
3386 Type op_type = left.Type;
3387 ILGenerator ig = ec.ig;
3388 int size = GetTypeSize (TypeManager.GetElementType (op_type));
3389 Type rtype = right.Type;
3391 if (rtype.IsPointer){
3393 // handle (pointer - pointer)
3397 ig.Emit (OpCodes.Sub);
3401 ig.Emit (OpCodes.Sizeof, op_type);
3403 IntLiteral.EmitInt (ig, size);
3404 ig.Emit (OpCodes.Div);
3406 ig.Emit (OpCodes.Conv_I8);
3409 // handle + and - on (pointer op int)
3412 ig.Emit (OpCodes.Conv_I);
3416 ig.Emit (OpCodes.Sizeof, op_type);
3418 IntLiteral.EmitInt (ig, size);
3419 if (rtype == TypeManager.int64_type)
3420 ig.Emit (OpCodes.Conv_I8);
3421 else if (rtype == TypeManager.uint64_type)
3422 ig.Emit (OpCodes.Conv_U8);
3423 ig.Emit (OpCodes.Mul);
3424 ig.Emit (OpCodes.Conv_I);
3427 ig.Emit (OpCodes.Add);
3429 ig.Emit (OpCodes.Sub);
3435 /// Implements the ternary conditional operator (?:)
3437 public class Conditional : Expression {
3438 Expression expr, trueExpr, falseExpr;
3440 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3443 this.trueExpr = trueExpr;
3444 this.falseExpr = falseExpr;
3448 public Expression Expr {
3454 public Expression TrueExpr {
3460 public Expression FalseExpr {
3466 public override Expression DoResolve (EmitContext ec)
3468 expr = expr.Resolve (ec);
3473 if (expr.Type != TypeManager.bool_type){
3474 expr = Expression.ResolveBoolean (
3481 trueExpr = trueExpr.Resolve (ec);
3482 falseExpr = falseExpr.Resolve (ec);
3484 if (trueExpr == null || falseExpr == null)
3487 eclass = ExprClass.Value;
3488 if (trueExpr.Type == falseExpr.Type)
3489 type = trueExpr.Type;
3492 Type true_type = trueExpr.Type;
3493 Type false_type = falseExpr.Type;
3495 if (trueExpr is NullLiteral){
3498 } else if (falseExpr is NullLiteral){
3504 // First, if an implicit conversion exists from trueExpr
3505 // to falseExpr, then the result type is of type falseExpr.Type
3507 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3510 // Check if both can convert implicitl to each other's type
3512 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3514 "Can not compute type of conditional expression " +
3515 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3516 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3517 "' convert implicitly to each other");
3522 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3526 Error (173, "The type of the conditional expression can " +
3527 "not be computed because there is no implicit conversion" +
3528 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3529 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3534 if (expr is BoolConstant){
3535 BoolConstant bc = (BoolConstant) expr;
3546 public override void Emit (EmitContext ec)
3548 ILGenerator ig = ec.ig;
3549 Label false_target = ig.DefineLabel ();
3550 Label end_target = ig.DefineLabel ();
3552 expr.EmitBranchable (ec, false_target, false);
3554 ig.Emit (OpCodes.Br, end_target);
3555 ig.MarkLabel (false_target);
3556 falseExpr.Emit (ec);
3557 ig.MarkLabel (end_target);
3565 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3566 public readonly string Name;
3567 public readonly Block Block;
3568 LocalInfo local_info;
3571 public LocalVariableReference (Block block, string name, Location l)
3576 eclass = ExprClass.Variable;
3579 // Setting `is_readonly' to false will allow you to create a writable
3580 // reference to a read-only variable. This is used by foreach and using.
3581 public LocalVariableReference (Block block, string name, Location l,
3582 LocalInfo local_info, bool is_readonly)
3583 : this (block, name, l)
3585 this.local_info = local_info;
3586 this.is_readonly = is_readonly;
3589 public VariableInfo VariableInfo {
3590 get { return local_info.VariableInfo; }
3593 public bool IsReadOnly {
3599 protected void DoResolveBase (EmitContext ec)
3601 if (local_info == null) {
3602 local_info = Block.GetLocalInfo (Name);
3603 is_readonly = local_info.ReadOnly;
3606 type = local_info.VariableType;
3608 if (ec.InAnonymousMethod)
3609 Block.LiftVariable (local_info);
3613 protected Expression DoResolve (EmitContext ec, bool is_lvalue)
3615 Expression e = Block.GetConstantExpression (Name);
3617 local_info.Used = true;
3618 eclass = ExprClass.Value;
3619 return e.Resolve (ec);
3622 VariableInfo variable_info = local_info.VariableInfo;
3623 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3627 local_info.Used = true;
3629 if (local_info.LocalBuilder == null)
3630 return ec.RemapLocal (local_info);
3635 public override Expression DoResolve (EmitContext ec)
3639 return DoResolve (ec, false);
3642 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3646 VariableInfo variable_info = local_info.VariableInfo;
3647 if (variable_info != null)
3648 variable_info.SetAssigned (ec);
3650 Expression e = DoResolve (ec, true);
3656 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3660 CheckObsoleteAttribute (e.Type);
3662 if (local_info.LocalBuilder == null)
3663 return ec.RemapLocalLValue (local_info, right_side);
3668 public bool VerifyFixed (bool is_expression)
3670 return !is_expression || local_info.IsFixed;
3673 public override void Emit (EmitContext ec)
3675 ILGenerator ig = ec.ig;
3677 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3680 public void Emit (EmitContext ec, bool leave_copy)
3684 ec.ig.Emit (OpCodes.Dup);
3687 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3691 ec.ig.Emit (OpCodes.Dup);
3692 ec.ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3695 public void AddressOf (EmitContext ec, AddressOp mode)
3697 ILGenerator ig = ec.ig;
3699 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3702 public override string ToString ()
3704 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3709 /// This represents a reference to a parameter in the intermediate
3712 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3718 public Parameter.Modifier mod;
3719 public bool is_ref, is_out, prepared;
3720 LocalTemporary temp;
3722 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3729 eclass = ExprClass.Variable;
3732 public VariableInfo VariableInfo {
3736 public bool VerifyFixed (bool is_expression)
3738 return !is_expression || TypeManager.IsValueType (type);
3741 public bool IsAssigned (EmitContext ec, Location loc)
3743 if (!ec.DoFlowAnalysis || !is_out ||
3744 ec.CurrentBranching.IsAssigned (vi))
3747 Report.Error (165, loc,
3748 "Use of unassigned parameter `" + name + "'");
3752 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3754 if (!ec.DoFlowAnalysis || !is_out ||
3755 ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3758 Report.Error (170, loc,
3759 "Use of possibly unassigned field `" + field_name + "'");
3763 public void SetAssigned (EmitContext ec)
3765 if (is_out && ec.DoFlowAnalysis)
3766 ec.CurrentBranching.SetAssigned (vi);
3769 public void SetFieldAssigned (EmitContext ec, string field_name)
3771 if (is_out && ec.DoFlowAnalysis)
3772 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3775 protected void DoResolveBase (EmitContext ec)
3777 type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
3778 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3779 is_out = (mod & Parameter.Modifier.OUT) != 0;
3780 eclass = ExprClass.Variable;
3783 vi = block.ParameterMap [idx];
3787 // Notice that for ref/out parameters, the type exposed is not the
3788 // same type exposed externally.
3791 // externally we expose "int&"
3792 // here we expose "int".
3794 // We record this in "is_ref". This means that the type system can treat
3795 // the type as it is expected, but when we generate the code, we generate
3796 // the alternate kind of code.
3798 public override Expression DoResolve (EmitContext ec)
3802 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3805 if (ec.RemapToProxy)
3806 return ec.RemapParameter (idx);
3811 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3817 if (ec.RemapToProxy)
3818 return ec.RemapParameterLValue (idx, right_side);
3823 static public void EmitLdArg (ILGenerator ig, int x)
3827 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3828 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3829 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3830 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3831 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3834 ig.Emit (OpCodes.Ldarg, x);
3838 // This method is used by parameters that are references, that are
3839 // being passed as references: we only want to pass the pointer (that
3840 // is already stored in the parameter, not the address of the pointer,
3841 // and not the value of the variable).
3843 public void EmitLoad (EmitContext ec)
3845 ILGenerator ig = ec.ig;
3851 EmitLdArg (ig, arg_idx);
3854 public override void Emit (EmitContext ec)
3859 public void Emit (EmitContext ec, bool leave_copy)
3861 ILGenerator ig = ec.ig;
3868 EmitLdArg (ig, arg_idx);
3872 ec.ig.Emit (OpCodes.Dup);
3875 // If we are a reference, we loaded on the stack a pointer
3876 // Now lets load the real value
3878 LoadFromPtr (ig, type);
3882 ec.ig.Emit (OpCodes.Dup);
3885 temp = new LocalTemporary (ec, type);
3891 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3893 ILGenerator ig = ec.ig;
3896 prepared = prepare_for_load;
3901 if (is_ref && !prepared)
3902 EmitLdArg (ig, arg_idx);
3907 ec.ig.Emit (OpCodes.Dup);
3911 temp = new LocalTemporary (ec, type);
3915 StoreFromPtr (ig, type);
3921 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
3923 ig.Emit (OpCodes.Starg, arg_idx);
3927 public void AddressOf (EmitContext ec, AddressOp mode)
3936 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
3938 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
3941 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
3943 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
3950 /// Used for arguments to New(), Invocation()
3952 public class Argument {
3953 public enum AType : byte {
3960 public readonly AType ArgType;
3961 public Expression Expr;
3963 public Argument (Expression expr, AType type)
3966 this.ArgType = type;
3969 public Argument (Expression expr)
3972 this.ArgType = AType.Expression;
3977 if (ArgType == AType.Ref || ArgType == AType.Out)
3978 return TypeManager.GetReferenceType (Expr.Type);
3984 public Parameter.Modifier GetParameterModifier ()
3988 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
3991 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
3994 return Parameter.Modifier.NONE;
3998 public static string FullDesc (Argument a)
4000 if (a.ArgType == AType.ArgList)
4003 return (a.ArgType == AType.Ref ? "ref " :
4004 (a.ArgType == AType.Out ? "out " : "")) +
4005 TypeManager.CSharpName (a.Expr.Type);
4008 public bool ResolveMethodGroup (EmitContext ec, Location loc)
4010 ConstructedType ctype = Expr as ConstructedType;
4012 Expr = ctype.GetSimpleName (ec);
4014 // FIXME: csc doesn't report any error if you try to use `ref' or
4015 // `out' in a delegate creation expression.
4016 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4023 public bool Resolve (EmitContext ec, Location loc)
4025 if (ArgType == AType.Ref) {
4026 Expr = Expr.Resolve (ec);
4030 Expr = Expr.ResolveLValue (ec, Expr);
4031 } else if (ArgType == AType.Out)
4032 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
4034 Expr = Expr.Resolve (ec);
4039 if (ArgType == AType.Expression)
4043 // Catch errors where fields of a MarshalByRefObject are passed as ref or out
4044 // This is only allowed for `this'
4046 FieldExpr fe = Expr as FieldExpr;
4047 if (fe != null && !fe.IsStatic){
4048 Expression instance = fe.InstanceExpression;
4050 if (instance.GetType () != typeof (This)){
4051 if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
4052 Report.Error (197, loc,
4053 "Can not pass a type that derives from MarshalByRefObject with out or ref");
4060 if (Expr.eclass != ExprClass.Variable){
4062 // We just probe to match the CSC output
4064 if (Expr.eclass == ExprClass.PropertyAccess ||
4065 Expr.eclass == ExprClass.IndexerAccess){
4068 "A property or indexer can not be passed as an out or ref " +
4073 "An lvalue is required as an argument to out or ref");
4081 public void Emit (EmitContext ec)
4084 // Ref and Out parameters need to have their addresses taken.
4086 // ParameterReferences might already be references, so we want
4087 // to pass just the value
4089 if (ArgType == AType.Ref || ArgType == AType.Out){
4090 AddressOp mode = AddressOp.Store;
4092 if (ArgType == AType.Ref)
4093 mode |= AddressOp.Load;
4095 if (Expr is ParameterReference){
4096 ParameterReference pr = (ParameterReference) Expr;
4102 pr.AddressOf (ec, mode);
4105 ((IMemoryLocation)Expr).AddressOf (ec, mode);
4113 /// Invocation of methods or delegates.
4115 public class Invocation : ExpressionStatement {
4116 public readonly ArrayList Arguments;
4119 MethodBase method = null;
4122 static Hashtable method_parameter_cache;
4124 static Invocation ()
4126 method_parameter_cache = new PtrHashtable ();
4130 // arguments is an ArrayList, but we do not want to typecast,
4131 // as it might be null.
4133 // FIXME: only allow expr to be a method invocation or a
4134 // delegate invocation (7.5.5)
4136 public Invocation (Expression expr, ArrayList arguments, Location l)
4139 Arguments = arguments;
4143 public Expression Expr {
4150 /// Returns the Parameters (a ParameterData interface) for the
4153 public static ParameterData GetParameterData (MethodBase mb)
4155 object pd = method_parameter_cache [mb];
4159 return (ParameterData) pd;
4161 ip = TypeManager.LookupParametersByBuilder (mb);
4163 method_parameter_cache [mb] = ip;
4165 return (ParameterData) ip;
4167 ReflectionParameters rp = new ReflectionParameters (mb);
4168 method_parameter_cache [mb] = rp;
4170 return (ParameterData) rp;
4175 /// Determines "better conversion" as specified in 7.4.2.3
4177 /// Returns : 1 if a->p is better
4178 /// 0 if a->q or neither is better
4180 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
4182 Type argument_type = TypeManager.TypeToCoreType (a.Type);
4183 Expression argument_expr = a.Expr;
4185 // p = TypeManager.TypeToCoreType (p);
4186 // q = TypeManager.TypeToCoreType (q);
4188 if (argument_type == null)
4189 throw new Exception ("Expression of type " + a.Expr +
4190 " does not resolve its type");
4193 // This is a special case since csc behaves this way.
4195 if (argument_expr is NullLiteral &&
4196 p == TypeManager.string_type &&
4197 q == TypeManager.object_type)
4199 else if (argument_expr is NullLiteral &&
4200 p == TypeManager.object_type &&
4201 q == TypeManager.string_type)
4205 // csc behaves this way so we emulate it. Basically, if the argument
4206 // is null and one of the types to compare is 'object' and the other
4207 // is a reference type, we prefer the other.
4209 // I can't find this anywhere in the spec but we can interpret this
4210 // to mean that null can be of any type you wish in such a context
4212 if (p != null && q != null) {
4213 if (argument_expr is NullLiteral &&
4215 q == TypeManager.object_type)
4217 else if (argument_expr is NullLiteral &&
4219 p == TypeManager.object_type)
4226 if (argument_type == p)
4229 if (argument_type == q)
4233 Expression tmp = Convert.ImplicitConversion (ec, argument_expr, p, loc);
4241 Expression p_tmp = new EmptyExpression (p);
4242 Expression q_tmp = new EmptyExpression (q);
4244 if (Convert.ImplicitConversionExists (ec, p_tmp, q) == true &&
4245 Convert.ImplicitConversionExists (ec, q_tmp, p) == false)
4248 if (p == TypeManager.sbyte_type)
4249 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4250 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4253 if (p == TypeManager.short_type)
4254 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4255 q == TypeManager.uint64_type)
4258 if (p == TypeManager.int32_type)
4259 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4262 if (p == TypeManager.int64_type)
4263 if (q == TypeManager.uint64_type)
4270 /// Determines "Better function" between candidate
4271 /// and the current best match
4274 /// Returns an integer indicating :
4275 /// 0 if candidate ain't better
4276 /// 1 if candidate is better than the current best match
4278 static int BetterFunction (EmitContext ec, MethodGroupExpr me, ArrayList args,
4279 MethodBase candidate, bool candidate_params,
4280 MethodBase best, bool best_params,
4283 ParameterData candidate_pd = GetParameterData (candidate);
4284 ParameterData best_pd;
4290 argument_count = args.Count;
4292 int cand_count = candidate_pd.Count;
4295 // If there is no best method, than this one
4296 // is better, however, if we already found a
4297 // best method, we cant tell. This happens
4308 // interface IFooBar : IFoo, IBar {}
4310 // We cant tell if IFoo.DoIt is better than IBar.DoIt
4312 // However, we have to consider that
4313 // Trim (); is better than Trim (params char[] chars);
4315 if (cand_count == 0 && argument_count == 0)
4316 return best == null || best_params ? 1 : 0;
4318 if ((candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS) &&
4319 (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.ARGLIST))
4320 if (cand_count != argument_count)
4326 if (argument_count == 0 && cand_count == 1 &&
4327 candidate_pd.ParameterModifier (cand_count - 1) == Parameter.Modifier.PARAMS)
4330 for (int j = 0; j < argument_count; ++j) {
4332 Argument a = (Argument) args [j];
4333 Type t = TypeManager.TypeToCoreType (
4334 candidate_pd.ParameterType (j));
4336 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4337 if (candidate_params)
4338 t = TypeManager.GetElementType (t);
4340 x = BetterConversion (ec, a, t, null, loc);
4352 best_pd = GetParameterData (best);
4354 int rating1 = 0, rating2 = 0;
4356 for (int j = 0; j < argument_count; ++j) {
4359 Argument a = (Argument) args [j];
4361 Type ct = TypeManager.TypeToCoreType (
4362 candidate_pd.ParameterType (j));
4363 Type bt = TypeManager.TypeToCoreType (
4364 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);
4478 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4479 ArrayList arguments, bool do_varargs,
4480 ref MethodBase candidate)
4482 if (!me.HasTypeArguments &&
4483 !InferParamsTypeArguments (ec, arguments, ref candidate))
4486 return IsParamsMethodApplicable (ec, arguments, candidate, do_varargs);
4490 /// Determines if the candidate method, if a params method, is applicable
4491 /// in its expanded form to the given set of arguments
4493 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
4494 MethodBase candidate, bool do_varargs)
4498 if (arguments == null)
4501 arg_count = arguments.Count;
4503 ParameterData pd = GetParameterData (candidate);
4505 int pd_count = pd.Count;
4510 int count = pd_count - 1;
4512 if (pd.ParameterModifier (count) != Parameter.Modifier.ARGLIST)
4514 if (pd_count != arg_count)
4517 if (pd.ParameterModifier (count) != Parameter.Modifier.PARAMS)
4521 if (count > arg_count)
4524 if (pd_count == 1 && arg_count == 0)
4528 // If we have come this far, the case which
4529 // remains is when the number of parameters is
4530 // less than or equal to the argument count.
4532 for (int i = 0; i < count; ++i) {
4534 Argument a = (Argument) arguments [i];
4536 Parameter.Modifier a_mod = a.GetParameterModifier () &
4537 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4538 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4539 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4541 if (a_mod == p_mod) {
4543 if (a_mod == Parameter.Modifier.NONE)
4544 if (!Convert.ImplicitConversionExists (ec,
4546 pd.ParameterType (i)))
4549 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4550 Type pt = pd.ParameterType (i);
4553 pt = TypeManager.GetReferenceType (pt);
4564 Argument a = (Argument) arguments [count];
4565 if (!(a.Expr is Arglist))
4571 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4573 for (int i = pd_count - 1; i < arg_count; i++) {
4574 Argument a = (Argument) arguments [i];
4576 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4583 static bool IsApplicable (EmitContext ec, MethodGroupExpr me,
4584 ArrayList arguments, ref MethodBase candidate)
4586 if (!me.HasTypeArguments &&
4587 !InferTypeArguments (ec, arguments, ref candidate))
4590 return IsApplicable (ec, arguments, candidate);
4594 /// Determines if the candidate method is applicable (section 14.4.2.1)
4595 /// to the given set of arguments
4597 static bool IsApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
4601 if (arguments == null)
4604 arg_count = arguments.Count;
4607 ParameterData pd = GetParameterData (candidate);
4609 if (arg_count != pd.Count)
4612 for (int i = arg_count; i > 0; ) {
4615 Argument a = (Argument) arguments [i];
4617 Parameter.Modifier a_mod = a.GetParameterModifier () &
4618 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4619 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4620 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4623 if (a_mod == p_mod ||
4624 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4625 if (a_mod == Parameter.Modifier.NONE) {
4626 if (!Convert.ImplicitConversionExists (ec,
4628 pd.ParameterType (i)))
4632 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4633 Type pt = pd.ParameterType (i);
4636 pt = TypeManager.GetReferenceType (pt);
4649 /// Find the Applicable Function Members (7.4.2.1)
4651 /// me: Method Group expression with the members to select.
4652 /// it might contain constructors or methods (or anything
4653 /// that maps to a method).
4655 /// Arguments: ArrayList containing resolved Argument objects.
4657 /// loc: The location if we want an error to be reported, or a Null
4658 /// location for "probing" purposes.
4660 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4661 /// that is the best match of me on Arguments.
4664 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4665 ArrayList Arguments, bool may_fail,
4668 MethodBase method = null;
4669 Type applicable_type = null;
4671 ArrayList candidates = new ArrayList ();
4674 // Used to keep a map between the candidate
4675 // and whether it is being considered in its
4676 // normal or expanded form
4678 // false is normal form, true is expanded form
4680 Hashtable candidate_to_form = new PtrHashtable ();
4684 // First we construct the set of applicable methods
4686 // We start at the top of the type hierarchy and
4687 // go down to find applicable methods
4689 applicable_type = me.DeclaringType;
4691 if (me.Name == "Invoke" && TypeManager.IsDelegateType (applicable_type)) {
4692 Error_InvokeOnDelegate (loc);
4696 bool found_applicable = false;
4698 MethodBase[] methods = me.Methods;
4700 for (int i = 0; i < methods.Length; i++) {
4701 Type decl_type = methods [i].DeclaringType;
4704 // If we have already found an applicable method
4705 // we eliminate all base types (Section 14.5.5.1)
4707 if (decl_type != applicable_type &&
4708 (applicable_type.IsSubclassOf (decl_type) ||
4709 TypeManager.ImplementsInterface (applicable_type, decl_type)) &&
4713 // Check if candidate is applicable (section 14.4.2.1)
4714 if (IsApplicable (ec, me, Arguments, ref methods [i])) {
4715 // Candidate is applicable in normal form
4716 MethodBase candidate = methods [i];
4717 candidates.Add (candidate);
4718 applicable_type = candidate.DeclaringType;
4719 found_applicable = true;
4720 candidate_to_form [candidate] = false;
4721 } else if (IsParamsMethodApplicable (
4722 ec, me, Arguments,false, ref methods [i])) {
4723 // Candidate is applicable in expanded form
4724 MethodBase candidate = methods [i];
4725 candidates.Add (candidate);
4726 applicable_type = candidate.DeclaringType;
4727 found_applicable = true;
4728 candidate_to_form [candidate] = true;
4729 } else if (IsParamsMethodApplicable (
4730 ec, me, Arguments,true, ref methods [i])) {
4731 // Candidate is applicable in expanded form
4732 MethodBase candidate = methods [i];
4733 candidates.Add (candidate);
4734 applicable_type = candidate.DeclaringType;
4735 found_applicable = true;
4736 candidate_to_form [candidate] = true;
4740 if (Arguments == null)
4743 argument_count = Arguments.Count;
4746 // Now we actually find the best method
4748 int candidate_top = candidates.Count;
4749 for (int ix = 0; ix < candidate_top; ix++){
4750 MethodBase candidate = (MethodBase) candidates [ix];
4752 bool cand_params = (bool) candidate_to_form [candidate];
4753 bool method_params = false;
4756 method_params = (bool) candidate_to_form [method];
4758 int x = BetterFunction (ec, me, Arguments,
4759 candidate, cand_params,
4760 method, method_params,
4768 if (method == null) {
4769 int errors = Report.Errors;
4772 // Okay so we have failed to find anything so we
4773 // return by providing info about the closest match
4775 for (int i = 0; i < methods.Length; ++i) {
4777 MethodBase c = methods [i];
4781 ParameterData pd = GetParameterData (c);
4782 if (pd.Count != argument_count)
4785 if (!InferTypeArguments (ec, Arguments, ref c))
4788 VerifyArgumentsCompat (ec, Arguments, argument_count,
4789 c, false, null, loc);
4793 if (Report.Errors > errors)
4796 string report_name = me.Name;
4797 if (report_name == ".ctor")
4798 report_name = me.DeclaringType.ToString ();
4800 for (int i = 0; i < methods.Length; ++i) {
4802 MethodBase c = methods [i];
4806 ParameterData pd = GetParameterData (c);
4807 if (pd.Count != argument_count)
4810 if (InferTypeArguments (ec, Arguments, ref c))
4813 Report.Error (411, loc, "The type arguments for " +
4814 "method `{0}' cannot be infered from " +
4815 "the usage. Try specifying the type " +
4816 "arguments explicitly.", report_name);
4820 if (!may_fail && (errors == Report.Errors))
4821 Error_WrongNumArguments (loc, report_name,
4828 // Now check that there are no ambiguities i.e the selected method
4829 // should be better than all the others
4831 bool best_params = (bool) candidate_to_form [method];
4833 for (int ix = 0; ix < candidate_top; ix++){
4834 MethodBase candidate = (MethodBase) candidates [ix];
4836 if (candidate == method)
4840 // If a normal method is applicable in
4841 // the sense that it has the same
4842 // number of arguments, then the
4843 // expanded params method is never
4844 // applicable so we debar the params
4847 // if ((IsParamsMethodApplicable (ec, Arguments, candidate) &&
4848 // IsApplicable (ec, Arguments, method)))
4851 bool cand_params = (bool) candidate_to_form [candidate];
4852 int x = BetterFunction (ec, me, Arguments,
4853 method, best_params,
4854 candidate, cand_params,
4860 "Ambiguous call when selecting function due to implicit casts");
4866 // And now check if the arguments are all
4867 // compatible, perform conversions if
4868 // necessary etc. and return if everything is
4871 if (!VerifyArgumentsCompat (ec, Arguments, argument_count, method,
4872 best_params, null, loc))
4878 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
4880 Report.Error (1501, loc,
4881 "No overload for method `" + name + "' takes `" +
4882 arg_count + "' arguments");
4885 static void Error_InvokeOnDelegate (Location loc)
4887 Report.Error (1533, loc,
4888 "Invoke cannot be called directly on a delegate");
4891 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
4892 Type delegate_type, string arg_sig, string par_desc)
4894 if (delegate_type == null)
4895 Report.Error (1502, loc,
4896 "The best overloaded match for method '" +
4897 FullMethodDesc (method) +
4898 "' has some invalid arguments");
4900 Report.Error (1594, loc,
4901 "Delegate '" + delegate_type.ToString () +
4902 "' has some invalid arguments.");
4903 Report.Error (1503, loc,
4904 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
4905 idx, arg_sig, par_desc));
4908 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
4911 bool chose_params_expanded,
4915 ParameterData pd = GetParameterData (method);
4916 int pd_count = pd.Count;
4918 for (int j = 0; j < argument_count; j++) {
4919 Argument a = (Argument) Arguments [j];
4920 Expression a_expr = a.Expr;
4921 Type parameter_type = pd.ParameterType (j);
4922 Parameter.Modifier pm = pd.ParameterModifier (j);
4924 if (pm == Parameter.Modifier.PARAMS){
4925 if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
4926 if (!Location.IsNull (loc))
4927 Error_InvalidArguments (
4928 loc, j, method, delegate_type,
4929 Argument.FullDesc (a), pd.ParameterDesc (j));
4933 if (chose_params_expanded)
4934 parameter_type = TypeManager.GetElementType (parameter_type);
4935 } else if (pm == Parameter.Modifier.ARGLIST){
4941 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
4942 if (!Location.IsNull (loc))
4943 Error_InvalidArguments (
4944 loc, j, method, delegate_type,
4945 Argument.FullDesc (a), pd.ParameterDesc (j));
4953 if (a.Type != parameter_type){
4956 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
4959 if (!Location.IsNull (loc))
4960 Error_InvalidArguments (
4961 loc, j, method, delegate_type,
4962 Argument.FullDesc (a), pd.ParameterDesc (j));
4967 // Update the argument with the implicit conversion
4973 Parameter.Modifier a_mod = a.GetParameterModifier () &
4974 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4975 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
4976 ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4978 if (a_mod != p_mod &&
4979 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
4980 if (!Location.IsNull (loc)) {
4981 Report.Error (1502, loc,
4982 "The best overloaded match for method '" + FullMethodDesc (method)+
4983 "' has some invalid arguments");
4984 Report.Error (1503, loc,
4985 "Argument " + (j+1) +
4986 ": Cannot convert from '" + Argument.FullDesc (a)
4987 + "' to '" + pd.ParameterDesc (j) + "'");
4997 static bool InferType (Type pt, Type at, ref Type[] infered)
4999 if (pt.IsGenericParameter) {
5000 int pos = pt.GenericParameterPosition;
5002 if (infered [pos] == null) {
5004 while (check.IsArray)
5005 check = check.GetElementType ();
5007 if (pt.Equals (check))
5014 if (infered [pos] != at)
5020 if (!pt.ContainsGenericParameters)
5025 (at.GetArrayRank () != pt.GetArrayRank ()))
5028 return InferType (pt.GetElementType (), at.GetElementType (),
5034 (pt.GetArrayRank () != at.GetArrayRank ()))
5037 return InferType (pt.GetElementType (), at.GetElementType (),
5041 if (!at.IsGenericInstance)
5044 Type[] at_args = at.GetGenericArguments ();
5045 Type[] pt_args = pt.GetGenericArguments ();
5047 if (at_args.Length != pt_args.Length)
5050 Type[] infered_types = new Type [at_args.Length];
5052 for (int i = 0; i < at_args.Length; i++)
5053 if (!InferType (pt_args [i], at_args [i], ref infered_types))
5056 for (int i = 0; i < infered_types.Length; i++)
5057 if (infered_types [i] == null)
5060 for (int i = 0; i < infered_types.Length; i++) {
5061 if (infered [i] == null) {
5062 infered [i] = infered_types [i];
5066 if (infered [i] != infered_types [i])
5073 static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
5074 ref MethodBase method)
5076 if ((arguments == null) || !TypeManager.IsGenericMethod (method))
5081 if (arguments == null)
5084 arg_count = arguments.Count;
5086 ParameterData pd = GetParameterData (method);
5088 int pd_count = pd.Count;
5093 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
5096 if (pd_count - 1 > arg_count)
5099 if (pd_count == 1 && arg_count == 0)
5102 Type[] method_args = method.GetGenericArguments ();
5103 Type[] infered_types = new Type [method_args.Length];
5106 // If we have come this far, the case which
5107 // remains is when the number of parameters is
5108 // less than or equal to the argument count.
5110 for (int i = 0; i < pd_count - 1; ++i) {
5111 Argument a = (Argument) arguments [i];
5113 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
5116 Type pt = pd.ParameterType (i);
5119 if (!InferType (pt, at, ref infered_types))
5123 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
5125 for (int i = pd_count - 1; i < arg_count; i++) {
5126 Argument a = (Argument) arguments [i];
5128 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
5131 if (!InferType (element_type, a.Type, ref infered_types))
5135 for (int i = 0; i < infered_types.Length; i++)
5136 if (infered_types [i] == null)
5139 method = method.BindGenericParameters (infered_types);
5143 public static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
5144 ref Type[] infered_types)
5146 for (int i = 0; i < arg_types.Length; i++) {
5147 if (arg_types [i] == null)
5150 if (!InferType (param_types [i], arg_types [i],
5155 for (int i = 0; i < infered_types.Length; i++)
5156 if (infered_types [i] == null)
5162 static bool InferTypeArguments (EmitContext ec, ArrayList arguments,
5163 ref MethodBase method)
5165 if (!TypeManager.IsGenericMethod (method))
5169 if (arguments != null)
5170 arg_count = arguments.Count;
5174 ParameterData pd = GetParameterData (method);
5175 if (arg_count != pd.Count)
5178 Type[] method_args = method.GetGenericArguments ();
5179 Type[] infered_types = new Type [method_args.Length];
5181 Type[] param_types = new Type [pd.Count];
5182 Type[] arg_types = new Type [pd.Count];
5184 for (int i = 0; i < arg_count; i++) {
5185 param_types [i] = pd.ParameterType (i);
5187 Argument a = (Argument) arguments [i];
5188 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
5191 arg_types [i] = a.Type;
5194 if (!InferTypeArguments (param_types, arg_types, ref infered_types))
5197 method = method.BindGenericParameters (infered_types);
5201 public static bool InferTypeArguments (EmitContext ec, ParameterData apd,
5202 ref MethodBase method)
5204 if (!TypeManager.IsGenericMethod (method))
5207 ParameterData pd = GetParameterData (method);
5208 if (apd.Count != pd.Count)
5211 Type[] method_args = method.GetGenericArguments ();
5212 Type[] infered_types = new Type [method_args.Length];
5214 Type[] param_types = new Type [pd.Count];
5215 Type[] arg_types = new Type [pd.Count];
5217 for (int i = 0; i < apd.Count; i++) {
5218 param_types [i] = pd.ParameterType (i);
5219 arg_types [i] = apd.ParameterType (i);
5222 if (!InferTypeArguments (param_types, arg_types, ref infered_types))
5225 method = method.BindGenericParameters (infered_types);
5229 public override Expression DoResolve (EmitContext ec)
5232 // First, resolve the expression that is used to
5233 // trigger the invocation
5235 if (expr is BaseAccess)
5238 if (expr is ConstructedType)
5239 expr = ((ConstructedType) expr).GetSimpleName (ec);
5241 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
5245 if (!(expr is MethodGroupExpr)) {
5246 Type expr_type = expr.Type;
5248 if (expr_type != null){
5249 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
5251 return (new DelegateInvocation (
5252 this.expr, Arguments, loc)).Resolve (ec);
5256 if (!(expr is MethodGroupExpr)){
5257 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup);
5262 // Next, evaluate all the expressions in the argument list
5264 if (Arguments != null){
5265 foreach (Argument a in Arguments){
5266 if (!a.Resolve (ec, loc))
5271 MethodGroupExpr mg = (MethodGroupExpr) expr;
5272 method = OverloadResolve (ec, mg, Arguments, false, loc);
5277 MethodInfo mi = method as MethodInfo;
5279 type = TypeManager.TypeToCoreType (mi.ReturnType);
5280 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null)) {
5281 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
5285 Expression iexpr = mg.InstanceExpression;
5286 if (mi.IsStatic && (iexpr != null) && !(iexpr is This)) {
5287 if (mg.IdenticalTypeName)
5288 mg.InstanceExpression = null;
5290 MemberAccess.error176 (loc, mi.Name);
5296 if (type.IsPointer){
5304 // Only base will allow this invocation to happen.
5306 if (is_base && method.IsAbstract){
5307 Report.Error (205, loc, "Cannot call an abstract base member: " +
5308 FullMethodDesc (method));
5312 if ((method.Attributes & MethodAttributes.SpecialName) != 0){
5313 if (TypeManager.IsSpecialMethod (method))
5314 Report.Error (571, loc, method.Name + ": can not call operator or accessor");
5317 eclass = ExprClass.Value;
5322 // Emits the list of arguments as an array
5324 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
5326 ILGenerator ig = ec.ig;
5327 int count = arguments.Count - idx;
5328 Argument a = (Argument) arguments [idx];
5329 Type t = a.Expr.Type;
5331 IntConstant.EmitInt (ig, count);
5332 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
5334 int top = arguments.Count;
5335 for (int j = idx; j < top; j++){
5336 a = (Argument) arguments [j];
5338 ig.Emit (OpCodes.Dup);
5339 IntConstant.EmitInt (ig, j - idx);
5341 bool is_stobj, has_type_arg;
5342 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj, out has_type_arg);
5344 ig.Emit (OpCodes.Ldelema, t);
5356 /// Emits a list of resolved Arguments that are in the arguments
5359 /// The MethodBase argument might be null if the
5360 /// emission of the arguments is known not to contain
5361 /// a `params' field (for example in constructors or other routines
5362 /// that keep their arguments in this structure)
5364 /// if `dup_args' is true, a copy of the arguments will be left
5365 /// on the stack. If `dup_args' is true, you can specify `this_arg'
5366 /// which will be duplicated before any other args. Only EmitCall
5367 /// should be using this interface.
5369 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments, bool dup_args, LocalTemporary this_arg)
5373 pd = GetParameterData (mb);
5377 LocalTemporary [] temps = null;
5380 temps = new LocalTemporary [arguments.Count];
5383 // If we are calling a params method with no arguments, special case it
5385 if (arguments == null){
5386 if (pd != null && pd.Count > 0 &&
5387 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
5388 ILGenerator ig = ec.ig;
5390 IntConstant.EmitInt (ig, 0);
5391 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
5397 int top = arguments.Count;
5399 for (int i = 0; i < top; i++){
5400 Argument a = (Argument) arguments [i];
5403 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
5405 // Special case if we are passing the same data as the
5406 // params argument, do not put it in an array.
5408 if (pd.ParameterType (i) == a.Type)
5411 EmitParams (ec, i, arguments);
5418 ec.ig.Emit (OpCodes.Dup);
5419 (temps [i] = new LocalTemporary (ec, a.Type)).Store (ec);
5424 if (this_arg != null)
5427 for (int i = 0; i < top; i ++)
5428 temps [i].Emit (ec);
5431 if (pd != null && pd.Count > top &&
5432 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
5433 ILGenerator ig = ec.ig;
5435 IntConstant.EmitInt (ig, 0);
5436 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
5440 static Type[] GetVarargsTypes (EmitContext ec, MethodBase mb,
5441 ArrayList arguments)
5443 ParameterData pd = GetParameterData (mb);
5445 if (arguments == null)
5446 return new Type [0];
5448 Argument a = (Argument) arguments [pd.Count - 1];
5449 Arglist list = (Arglist) a.Expr;
5451 return list.ArgumentTypes;
5455 /// This checks the ConditionalAttribute on the method
5457 static bool IsMethodExcluded (MethodBase method, EmitContext ec)
5459 if (method.IsConstructor)
5462 IMethodData md = TypeManager.GetMethod (method);
5464 return md.IsExcluded (ec);
5466 // For some methods (generated by delegate class) GetMethod returns null
5467 // because they are not included in builder_to_method table
5468 if (method.DeclaringType is TypeBuilder)
5471 return AttributeTester.IsConditionalMethodExcluded (method);
5475 /// is_base tells whether we want to force the use of the `call'
5476 /// opcode instead of using callvirt. Call is required to call
5477 /// a specific method, while callvirt will always use the most
5478 /// recent method in the vtable.
5480 /// is_static tells whether this is an invocation on a static method
5482 /// instance_expr is an expression that represents the instance
5483 /// it must be non-null if is_static is false.
5485 /// method is the method to invoke.
5487 /// Arguments is the list of arguments to pass to the method or constructor.
5489 public static void EmitCall (EmitContext ec, bool is_base,
5490 bool is_static, Expression instance_expr,
5491 MethodBase method, ArrayList Arguments, Location loc)
5493 EmitCall (ec, is_base, is_static, instance_expr, method, Arguments, loc, false, false);
5496 // `dup_args' leaves an extra copy of the arguments on the stack
5497 // `omit_args' does not leave any arguments at all.
5498 // So, basically, you could make one call with `dup_args' set to true,
5499 // and then another with `omit_args' set to true, and the two calls
5500 // would have the same set of arguments. However, each argument would
5501 // only have been evaluated once.
5502 public static void EmitCall (EmitContext ec, bool is_base,
5503 bool is_static, Expression instance_expr,
5504 MethodBase method, ArrayList Arguments, Location loc,
5505 bool dup_args, bool omit_args)
5507 ILGenerator ig = ec.ig;
5508 bool struct_call = false;
5509 bool this_call = false;
5510 LocalTemporary this_arg = null;
5512 Type decl_type = method.DeclaringType;
5514 if (!RootContext.StdLib) {
5515 // Replace any calls to the system's System.Array type with calls to
5516 // the newly created one.
5517 if (method == TypeManager.system_int_array_get_length)
5518 method = TypeManager.int_array_get_length;
5519 else if (method == TypeManager.system_int_array_get_rank)
5520 method = TypeManager.int_array_get_rank;
5521 else if (method == TypeManager.system_object_array_clone)
5522 method = TypeManager.object_array_clone;
5523 else if (method == TypeManager.system_int_array_get_length_int)
5524 method = TypeManager.int_array_get_length_int;
5525 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5526 method = TypeManager.int_array_get_lower_bound_int;
5527 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5528 method = TypeManager.int_array_get_upper_bound_int;
5529 else if (method == TypeManager.system_void_array_copyto_array_int)
5530 method = TypeManager.void_array_copyto_array_int;
5534 // This checks ObsoleteAttribute on the method and on the declaring type
5536 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
5538 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
5540 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
5542 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
5546 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
5548 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
5551 if (IsMethodExcluded (method, ec))
5555 this_call = instance_expr == null;
5556 if (decl_type.IsValueType || (!this_call && instance_expr.Type.IsValueType))
5560 // If this is ourselves, push "this"
5565 ig.Emit (OpCodes.Ldarg_0);
5569 // Push the instance expression
5571 if (instance_expr.Type.IsValueType) {
5573 // Special case: calls to a function declared in a
5574 // reference-type with a value-type argument need
5575 // to have their value boxed.
5576 if (decl_type.IsValueType) {
5578 // If the expression implements IMemoryLocation, then
5579 // we can optimize and use AddressOf on the
5582 // If not we have to use some temporary storage for
5584 if (instance_expr is IMemoryLocation) {
5585 ((IMemoryLocation)instance_expr).
5586 AddressOf (ec, AddressOp.LoadStore);
5588 LocalTemporary temp = new LocalTemporary (ec, instance_expr.Type);
5589 instance_expr.Emit (ec);
5591 temp.AddressOf (ec, AddressOp.Load);
5594 // avoid the overhead of doing this all the time.
5596 t = TypeManager.GetReferenceType (instance_expr.Type);
5598 instance_expr.Emit (ec);
5599 ig.Emit (OpCodes.Box, instance_expr.Type);
5600 t = TypeManager.object_type;
5603 instance_expr.Emit (ec);
5604 t = instance_expr.Type;
5609 this_arg = new LocalTemporary (ec, t);
5610 ig.Emit (OpCodes.Dup);
5611 this_arg.Store (ec);
5617 EmitArguments (ec, method, Arguments, dup_args, this_arg);
5620 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
5621 call_op = OpCodes.Call;
5623 call_op = OpCodes.Callvirt;
5625 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
5626 Type[] varargs_types = GetVarargsTypes (ec, method, Arguments);
5627 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
5634 // and DoFoo is not virtual, you can omit the callvirt,
5635 // because you don't need the null checking behavior.
5637 if (method is MethodInfo)
5638 ig.Emit (call_op, (MethodInfo) method);
5640 ig.Emit (call_op, (ConstructorInfo) method);
5643 public override void Emit (EmitContext ec)
5645 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5647 EmitCall (ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5650 public override void EmitStatement (EmitContext ec)
5655 // Pop the return value if there is one
5657 if (method is MethodInfo){
5658 Type ret = ((MethodInfo)method).ReturnType;
5659 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5660 ec.ig.Emit (OpCodes.Pop);
5665 public class InvocationOrCast : ExpressionStatement
5668 Expression argument;
5670 public InvocationOrCast (Expression expr, Expression argument, Location loc)
5673 this.argument = argument;
5677 public override Expression DoResolve (EmitContext ec)
5680 // First try to resolve it as a cast.
5682 type = ec.DeclSpace.ResolveType (expr, true, loc);
5684 Cast cast = new Cast (new TypeExpression (type, loc), argument, loc);
5685 return cast.Resolve (ec);
5689 // This can either be a type or a delegate invocation.
5690 // Let's just resolve it and see what we'll get.
5692 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5697 // Ok, so it's a Cast.
5699 if (expr.eclass == ExprClass.Type) {
5700 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
5701 return cast.Resolve (ec);
5705 // It's a delegate invocation.
5707 if (!TypeManager.IsDelegateType (expr.Type)) {
5708 Error (149, "Method name expected");
5712 ArrayList args = new ArrayList ();
5713 args.Add (new Argument (argument, Argument.AType.Expression));
5714 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5715 return invocation.Resolve (ec);
5720 Error (201, "Only assignment, call, increment, decrement and new object " +
5721 "expressions can be used as a statement");
5724 public override ExpressionStatement ResolveStatement (EmitContext ec)
5727 // First try to resolve it as a cast.
5729 type = ec.DeclSpace.ResolveType (expr, true, loc);
5736 // This can either be a type or a delegate invocation.
5737 // Let's just resolve it and see what we'll get.
5739 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5740 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5746 // It's a delegate invocation.
5748 if (!TypeManager.IsDelegateType (expr.Type)) {
5749 Error (149, "Method name expected");
5753 ArrayList args = new ArrayList ();
5754 args.Add (new Argument (argument, Argument.AType.Expression));
5755 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5756 return invocation.ResolveStatement (ec);
5759 public override void Emit (EmitContext ec)
5761 throw new Exception ("Cannot happen");
5764 public override void EmitStatement (EmitContext ec)
5766 throw new Exception ("Cannot happen");
5771 // This class is used to "disable" the code generation for the
5772 // temporary variable when initializing value types.
5774 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5775 public void AddressOf (EmitContext ec, AddressOp Mode)
5782 /// Implements the new expression
5784 public class New : ExpressionStatement, IMemoryLocation {
5785 public readonly ArrayList Arguments;
5788 // During bootstrap, it contains the RequestedType,
5789 // but if `type' is not null, it *might* contain a NewDelegate
5790 // (because of field multi-initialization)
5792 public Expression RequestedType;
5794 MethodBase method = null;
5797 // If set, the new expression is for a value_target, and
5798 // we will not leave anything on the stack.
5800 Expression value_target;
5801 bool value_target_set = false;
5802 bool is_type_parameter = false;
5804 public New (Expression requested_type, ArrayList arguments, Location l)
5806 RequestedType = requested_type;
5807 Arguments = arguments;
5811 public bool SetValueTypeVariable (Expression value)
5813 value_target = value;
5814 value_target_set = true;
5815 if (!(value_target is IMemoryLocation)){
5816 Error_UnexpectedKind ("variable");
5823 // This function is used to disable the following code sequence for
5824 // value type initialization:
5826 // AddressOf (temporary)
5830 // Instead the provide will have provided us with the address on the
5831 // stack to store the results.
5833 static Expression MyEmptyExpression;
5835 public void DisableTemporaryValueType ()
5837 if (MyEmptyExpression == null)
5838 MyEmptyExpression = new EmptyAddressOf ();
5841 // To enable this, look into:
5842 // test-34 and test-89 and self bootstrapping.
5844 // For instance, we can avoid a copy by using `newobj'
5845 // instead of Call + Push-temp on value types.
5846 // value_target = MyEmptyExpression;
5849 public override Expression DoResolve (EmitContext ec)
5852 // The New DoResolve might be called twice when initializing field
5853 // expressions (see EmitFieldInitializers, the call to
5854 // GetInitializerExpression will perform a resolve on the expression,
5855 // and later the assign will trigger another resolution
5857 // This leads to bugs (#37014)
5860 if (RequestedType is NewDelegate)
5861 return RequestedType;
5865 type = ec.DeclSpace.ResolveType (RequestedType, false, loc);
5870 CheckObsoleteAttribute (type);
5872 bool IsDelegate = TypeManager.IsDelegateType (type);
5875 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5876 if (RequestedType != null)
5877 if (!(RequestedType is NewDelegate))
5878 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
5879 return RequestedType;
5882 if (type.IsGenericParameter) {
5883 if (!TypeManager.HasConstructorConstraint (type)) {
5884 Error (304, String.Format (
5885 "Cannot create an instance of the " +
5886 "variable type '{0}' because it " +
5887 "doesn't have the new() constraint",
5892 if ((Arguments != null) && (Arguments.Count != 0)) {
5893 Error (417, String.Format (
5894 "`{0}': cannot provide arguments " +
5895 "when creating an instance of a " +
5896 "variable type.", type));
5900 is_type_parameter = true;
5901 eclass = ExprClass.Value;
5903 } else if (type.IsInterface || type.IsAbstract){
5904 Error (144, "It is not possible to create instances of interfaces or abstract classes");
5908 bool is_struct = type.IsValueType;
5909 eclass = ExprClass.Value;
5912 // SRE returns a match for .ctor () on structs (the object constructor),
5913 // so we have to manually ignore it.
5915 if (is_struct && Arguments == null)
5919 ml = MemberLookupFinal (ec, type, type, ".ctor",
5920 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
5921 MemberTypes.Constructor,
5922 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5927 if (! (ml is MethodGroupExpr)){
5929 ml.Error_UnexpectedKind ("method group");
5935 if (Arguments != null){
5936 foreach (Argument a in Arguments){
5937 if (!a.Resolve (ec, loc))
5942 method = Invocation.OverloadResolve (
5943 ec, (MethodGroupExpr) ml, Arguments, false, loc);
5947 if (method == null) {
5948 if (!is_struct || Arguments.Count > 0) {
5949 Error (1501, String.Format (
5950 "New invocation: Can not find a constructor in `{0}' for this argument list",
5951 TypeManager.CSharpName (type)));
5959 bool DoEmitTypeParameter (EmitContext ec)
5961 ILGenerator ig = ec.ig;
5963 ig.Emit (OpCodes.Ldtoken, type);
5964 ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
5965 ig.Emit (OpCodes.Call, TypeManager.activator_create_instance);
5966 ig.Emit (OpCodes.Unbox_Any, type);
5972 // This DoEmit can be invoked in two contexts:
5973 // * As a mechanism that will leave a value on the stack (new object)
5974 // * As one that wont (init struct)
5976 // You can control whether a value is required on the stack by passing
5977 // need_value_on_stack. The code *might* leave a value on the stack
5978 // so it must be popped manually
5980 // If we are dealing with a ValueType, we have a few
5981 // situations to deal with:
5983 // * The target is a ValueType, and we have been provided
5984 // the instance (this is easy, we are being assigned).
5986 // * The target of New is being passed as an argument,
5987 // to a boxing operation or a function that takes a
5990 // In this case, we need to create a temporary variable
5991 // that is the argument of New.
5993 // Returns whether a value is left on the stack
5995 bool DoEmit (EmitContext ec, bool need_value_on_stack)
5997 bool is_value_type = type.IsValueType;
5998 ILGenerator ig = ec.ig;
6003 // Allow DoEmit() to be called multiple times.
6004 // We need to create a new LocalTemporary each time since
6005 // you can't share LocalBuilders among ILGeneators.
6006 if (!value_target_set)
6007 value_target = new LocalTemporary (ec, type);
6009 ml = (IMemoryLocation) value_target;
6010 ml.AddressOf (ec, AddressOp.Store);
6014 Invocation.EmitArguments (ec, method, Arguments, false, null);
6018 ig.Emit (OpCodes.Initobj, type);
6020 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6021 if (need_value_on_stack){
6022 value_target.Emit (ec);
6027 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
6032 public override void Emit (EmitContext ec)
6034 if (is_type_parameter)
6035 DoEmitTypeParameter (ec);
6040 public override void EmitStatement (EmitContext ec)
6042 if (is_type_parameter)
6043 throw new InvalidOperationException ();
6045 if (DoEmit (ec, false))
6046 ec.ig.Emit (OpCodes.Pop);
6049 public void AddressOf (EmitContext ec, AddressOp Mode)
6051 if (is_type_parameter)
6052 throw new InvalidOperationException ();
6054 if (!type.IsValueType){
6056 // We throw an exception. So far, I believe we only need to support
6058 // foreach (int j in new StructType ())
6061 throw new Exception ("AddressOf should not be used for classes");
6064 if (!value_target_set)
6065 value_target = new LocalTemporary (ec, type);
6067 IMemoryLocation ml = (IMemoryLocation) value_target;
6068 ml.AddressOf (ec, AddressOp.Store);
6070 Invocation.EmitArguments (ec, method, Arguments, false, null);
6073 ec.ig.Emit (OpCodes.Initobj, type);
6075 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6077 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
6082 /// 14.5.10.2: Represents an array creation expression.
6086 /// There are two possible scenarios here: one is an array creation
6087 /// expression that specifies the dimensions and optionally the
6088 /// initialization data and the other which does not need dimensions
6089 /// specified but where initialization data is mandatory.
6091 public class ArrayCreation : Expression {
6092 Expression requested_base_type;
6093 ArrayList initializers;
6096 // The list of Argument types.
6097 // This is used to construct the `newarray' or constructor signature
6099 ArrayList arguments;
6102 // Method used to create the array object.
6104 MethodBase new_method = null;
6106 Type array_element_type;
6107 Type underlying_type;
6108 bool is_one_dimensional = false;
6109 bool is_builtin_type = false;
6110 bool expect_initializers = false;
6111 int num_arguments = 0;
6115 ArrayList array_data;
6120 // The number of array initializers that we can handle
6121 // via the InitializeArray method - through EmitStaticInitializers
6123 int num_automatic_initializers;
6125 const int max_automatic_initializers = 6;
6127 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
6129 this.requested_base_type = requested_base_type;
6130 this.initializers = initializers;
6134 arguments = new ArrayList ();
6136 foreach (Expression e in exprs) {
6137 arguments.Add (new Argument (e, Argument.AType.Expression));
6142 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
6144 this.requested_base_type = requested_base_type;
6145 this.initializers = initializers;
6149 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
6151 //string tmp = rank.Substring (rank.LastIndexOf ('['));
6153 //dimensions = tmp.Length - 1;
6154 expect_initializers = true;
6157 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
6159 StringBuilder sb = new StringBuilder (rank);
6162 for (int i = 1; i < idx_count; i++)
6167 return new ComposedCast (base_type, sb.ToString (), loc);
6170 void Error_IncorrectArrayInitializer ()
6172 Error (178, "Incorrectly structured array initializer");
6175 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
6177 if (specified_dims) {
6178 Argument a = (Argument) arguments [idx];
6180 if (!a.Resolve (ec, loc))
6183 if (!(a.Expr is Constant)) {
6184 Error (150, "A constant value is expected");
6188 int value = (int) ((Constant) a.Expr).GetValue ();
6190 if (value != probe.Count) {
6191 Error_IncorrectArrayInitializer ();
6195 bounds [idx] = value;
6198 int child_bounds = -1;
6199 foreach (object o in probe) {
6200 if (o is ArrayList) {
6201 int current_bounds = ((ArrayList) o).Count;
6203 if (child_bounds == -1)
6204 child_bounds = current_bounds;
6206 else if (child_bounds != current_bounds){
6207 Error_IncorrectArrayInitializer ();
6210 if (specified_dims && (idx + 1 >= arguments.Count)){
6211 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
6215 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
6219 if (child_bounds != -1){
6220 Error_IncorrectArrayInitializer ();
6224 Expression tmp = (Expression) o;
6225 tmp = tmp.Resolve (ec);
6229 // Console.WriteLine ("I got: " + tmp);
6230 // Handle initialization from vars, fields etc.
6232 Expression conv = Convert.ImplicitConversionRequired (
6233 ec, tmp, underlying_type, loc);
6238 if (conv is StringConstant || conv is DecimalConstant || conv is NullCast) {
6239 // These are subclasses of Constant that can appear as elements of an
6240 // array that cannot be statically initialized (with num_automatic_initializers
6241 // > max_automatic_initializers), so num_automatic_initializers should be left as zero.
6242 array_data.Add (conv);
6243 } else if (conv is Constant) {
6244 // These are the types of Constant that can appear in arrays that can be
6245 // statically allocated.
6246 array_data.Add (conv);
6247 num_automatic_initializers++;
6249 array_data.Add (conv);
6256 public void UpdateIndices (EmitContext ec)
6259 for (ArrayList probe = initializers; probe != null;) {
6260 if (probe.Count > 0 && probe [0] is ArrayList) {
6261 Expression e = new IntConstant (probe.Count);
6262 arguments.Add (new Argument (e, Argument.AType.Expression));
6264 bounds [i++] = probe.Count;
6266 probe = (ArrayList) probe [0];
6269 Expression e = new IntConstant (probe.Count);
6270 arguments.Add (new Argument (e, Argument.AType.Expression));
6272 bounds [i++] = probe.Count;
6279 public bool ValidateInitializers (EmitContext ec, Type array_type)
6281 if (initializers == null) {
6282 if (expect_initializers)
6288 if (underlying_type == null)
6292 // We use this to store all the date values in the order in which we
6293 // will need to store them in the byte blob later
6295 array_data = new ArrayList ();
6296 bounds = new Hashtable ();
6300 if (arguments != null) {
6301 ret = CheckIndices (ec, initializers, 0, true);
6304 arguments = new ArrayList ();
6306 ret = CheckIndices (ec, initializers, 0, false);
6313 if (arguments.Count != dimensions) {
6314 Error_IncorrectArrayInitializer ();
6322 void Error_NegativeArrayIndex ()
6324 Error (284, "Can not create array with a negative size");
6328 // Converts `source' to an int, uint, long or ulong.
6330 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
6334 bool old_checked = ec.CheckState;
6335 ec.CheckState = true;
6337 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
6338 if (target == null){
6339 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
6340 if (target == null){
6341 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
6342 if (target == null){
6343 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
6345 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
6349 ec.CheckState = old_checked;
6352 // Only positive constants are allowed at compile time
6354 if (target is Constant){
6355 if (target is IntConstant){
6356 if (((IntConstant) target).Value < 0){
6357 Error_NegativeArrayIndex ();
6362 if (target is LongConstant){
6363 if (((LongConstant) target).Value < 0){
6364 Error_NegativeArrayIndex ();
6375 // Creates the type of the array
6377 bool LookupType (EmitContext ec)
6379 StringBuilder array_qualifier = new StringBuilder (rank);
6382 // `In the first form allocates an array instace of the type that results
6383 // from deleting each of the individual expression from the expression list'
6385 if (num_arguments > 0) {
6386 array_qualifier.Append ("[");
6387 for (int i = num_arguments-1; i > 0; i--)
6388 array_qualifier.Append (",");
6389 array_qualifier.Append ("]");
6395 Expression array_type_expr;
6396 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
6397 type = ec.DeclSpace.ResolveType (array_type_expr, false, loc);
6402 underlying_type = type;
6403 if (underlying_type.IsArray)
6404 underlying_type = TypeManager.GetElementType (underlying_type);
6405 dimensions = type.GetArrayRank ();
6410 public override Expression DoResolve (EmitContext ec)
6414 if (!LookupType (ec))
6418 // First step is to validate the initializers and fill
6419 // in any missing bits
6421 if (!ValidateInitializers (ec, type))
6424 if (arguments == null)
6427 arg_count = arguments.Count;
6428 foreach (Argument a in arguments){
6429 if (!a.Resolve (ec, loc))
6432 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
6433 if (real_arg == null)
6440 array_element_type = TypeManager.GetElementType (type);
6442 if (arg_count == 1) {
6443 is_one_dimensional = true;
6444 eclass = ExprClass.Value;
6448 is_builtin_type = TypeManager.IsBuiltinType (type);
6450 if (is_builtin_type) {
6453 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
6454 AllBindingFlags, loc);
6456 if (!(ml is MethodGroupExpr)) {
6457 ml.Error_UnexpectedKind ("method group");
6462 Error (-6, "New invocation: Can not find a constructor for " +
6463 "this argument list");
6467 new_method = Invocation.OverloadResolve (
6468 ec, (MethodGroupExpr) ml, arguments, false, loc);
6470 if (new_method == null) {
6471 Error (-6, "New invocation: Can not find a constructor for " +
6472 "this argument list");
6476 eclass = ExprClass.Value;
6479 ModuleBuilder mb = CodeGen.Module.Builder;
6480 ArrayList args = new ArrayList ();
6482 if (arguments != null) {
6483 for (int i = 0; i < arg_count; i++)
6484 args.Add (TypeManager.int32_type);
6487 Type [] arg_types = null;
6490 arg_types = new Type [args.Count];
6492 args.CopyTo (arg_types, 0);
6494 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
6497 if (new_method == null) {
6498 Error (-6, "New invocation: Can not find a constructor for " +
6499 "this argument list");
6503 eclass = ExprClass.Value;
6508 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
6513 int count = array_data.Count;
6515 if (underlying_type.IsEnum)
6516 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
6518 factor = GetTypeSize (underlying_type);
6520 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
6522 data = new byte [(count * factor + 4) & ~3];
6525 for (int i = 0; i < count; ++i) {
6526 object v = array_data [i];
6528 if (v is EnumConstant)
6529 v = ((EnumConstant) v).Child;
6531 if (v is Constant && !(v is StringConstant))
6532 v = ((Constant) v).GetValue ();
6538 if (underlying_type == TypeManager.int64_type){
6539 if (!(v is Expression)){
6540 long val = (long) v;
6542 for (int j = 0; j < factor; ++j) {
6543 data [idx + j] = (byte) (val & 0xFF);
6547 } else if (underlying_type == TypeManager.uint64_type){
6548 if (!(v is Expression)){
6549 ulong val = (ulong) v;
6551 for (int j = 0; j < factor; ++j) {
6552 data [idx + j] = (byte) (val & 0xFF);
6556 } else if (underlying_type == TypeManager.float_type) {
6557 if (!(v is Expression)){
6558 element = BitConverter.GetBytes ((float) v);
6560 for (int j = 0; j < factor; ++j)
6561 data [idx + j] = element [j];
6563 } else if (underlying_type == TypeManager.double_type) {
6564 if (!(v is Expression)){
6565 element = BitConverter.GetBytes ((double) v);
6567 for (int j = 0; j < factor; ++j)
6568 data [idx + j] = element [j];
6570 } else if (underlying_type == TypeManager.char_type){
6571 if (!(v is Expression)){
6572 int val = (int) ((char) v);
6574 data [idx] = (byte) (val & 0xff);
6575 data [idx+1] = (byte) (val >> 8);
6577 } else if (underlying_type == TypeManager.short_type){
6578 if (!(v is Expression)){
6579 int val = (int) ((short) v);
6581 data [idx] = (byte) (val & 0xff);
6582 data [idx+1] = (byte) (val >> 8);
6584 } else if (underlying_type == TypeManager.ushort_type){
6585 if (!(v is Expression)){
6586 int val = (int) ((ushort) v);
6588 data [idx] = (byte) (val & 0xff);
6589 data [idx+1] = (byte) (val >> 8);
6591 } else if (underlying_type == TypeManager.int32_type) {
6592 if (!(v is Expression)){
6595 data [idx] = (byte) (val & 0xff);
6596 data [idx+1] = (byte) ((val >> 8) & 0xff);
6597 data [idx+2] = (byte) ((val >> 16) & 0xff);
6598 data [idx+3] = (byte) (val >> 24);
6600 } else if (underlying_type == TypeManager.uint32_type) {
6601 if (!(v is Expression)){
6602 uint val = (uint) v;
6604 data [idx] = (byte) (val & 0xff);
6605 data [idx+1] = (byte) ((val >> 8) & 0xff);
6606 data [idx+2] = (byte) ((val >> 16) & 0xff);
6607 data [idx+3] = (byte) (val >> 24);
6609 } else if (underlying_type == TypeManager.sbyte_type) {
6610 if (!(v is Expression)){
6611 sbyte val = (sbyte) v;
6612 data [idx] = (byte) val;
6614 } else if (underlying_type == TypeManager.byte_type) {
6615 if (!(v is Expression)){
6616 byte val = (byte) v;
6617 data [idx] = (byte) val;
6619 } else if (underlying_type == TypeManager.bool_type) {
6620 if (!(v is Expression)){
6621 bool val = (bool) v;
6622 data [idx] = (byte) (val ? 1 : 0);
6624 } else if (underlying_type == TypeManager.decimal_type){
6625 if (!(v is Expression)){
6626 int [] bits = Decimal.GetBits ((decimal) v);
6629 // FIXME: For some reason, this doesn't work on the MS runtime.
6630 int [] nbits = new int [4];
6631 nbits [0] = bits [3];
6632 nbits [1] = bits [2];
6633 nbits [2] = bits [0];
6634 nbits [3] = bits [1];
6636 for (int j = 0; j < 4; j++){
6637 data [p++] = (byte) (nbits [j] & 0xff);
6638 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6639 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6640 data [p++] = (byte) (nbits [j] >> 24);
6644 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6653 // Emits the initializers for the array
6655 void EmitStaticInitializers (EmitContext ec)
6658 // First, the static data
6661 ILGenerator ig = ec.ig;
6663 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6665 fb = RootContext.MakeStaticData (data);
6667 ig.Emit (OpCodes.Dup);
6668 ig.Emit (OpCodes.Ldtoken, fb);
6669 ig.Emit (OpCodes.Call,
6670 TypeManager.void_initializearray_array_fieldhandle);
6674 // Emits pieces of the array that can not be computed at compile
6675 // time (variables and string locations).
6677 // This always expect the top value on the stack to be the array
6679 void EmitDynamicInitializers (EmitContext ec)
6681 ILGenerator ig = ec.ig;
6682 int dims = bounds.Count;
6683 int [] current_pos = new int [dims];
6684 int top = array_data.Count;
6686 MethodInfo set = null;
6690 ModuleBuilder mb = null;
6691 mb = CodeGen.Module.Builder;
6692 args = new Type [dims + 1];
6695 for (j = 0; j < dims; j++)
6696 args [j] = TypeManager.int32_type;
6698 args [j] = array_element_type;
6700 set = mb.GetArrayMethod (
6702 CallingConventions.HasThis | CallingConventions.Standard,
6703 TypeManager.void_type, args);
6706 for (int i = 0; i < top; i++){
6708 Expression e = null;
6710 if (array_data [i] is Expression)
6711 e = (Expression) array_data [i];
6715 // Basically we do this for string literals and
6716 // other non-literal expressions
6718 if (e is EnumConstant){
6719 e = ((EnumConstant) e).Child;
6722 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6723 num_automatic_initializers <= max_automatic_initializers) {
6724 Type etype = e.Type;
6726 ig.Emit (OpCodes.Dup);
6728 for (int idx = 0; idx < dims; idx++)
6729 IntConstant.EmitInt (ig, current_pos [idx]);
6732 // If we are dealing with a struct, get the
6733 // address of it, so we can store it.
6736 etype.IsSubclassOf (TypeManager.value_type) &&
6737 (!TypeManager.IsBuiltinOrEnum (etype) ||
6738 etype == TypeManager.decimal_type)) {
6743 // Let new know that we are providing
6744 // the address where to store the results
6746 n.DisableTemporaryValueType ();
6749 ig.Emit (OpCodes.Ldelema, etype);
6755 bool is_stobj, has_typearg;
6756 OpCode op = ArrayAccess.GetStoreOpcode (
6757 etype, out is_stobj,
6760 ig.Emit (OpCodes.Stobj, etype);
6764 ig.Emit (OpCodes.Call, set);
6771 for (int j = dims - 1; j >= 0; j--){
6773 if (current_pos [j] < (int) bounds [j])
6775 current_pos [j] = 0;
6780 void EmitArrayArguments (EmitContext ec)
6782 ILGenerator ig = ec.ig;
6784 foreach (Argument a in arguments) {
6785 Type atype = a.Type;
6788 if (atype == TypeManager.uint64_type)
6789 ig.Emit (OpCodes.Conv_Ovf_U4);
6790 else if (atype == TypeManager.int64_type)
6791 ig.Emit (OpCodes.Conv_Ovf_I4);
6795 public override void Emit (EmitContext ec)
6797 ILGenerator ig = ec.ig;
6799 EmitArrayArguments (ec);
6800 if (is_one_dimensional)
6801 ig.Emit (OpCodes.Newarr, array_element_type);
6803 if (is_builtin_type)
6804 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6806 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6809 if (initializers != null){
6811 // FIXME: Set this variable correctly.
6813 bool dynamic_initializers = true;
6815 // This will never be true for array types that cannot be statically
6816 // initialized. num_automatic_initializers will always be zero. See
6818 if (num_automatic_initializers > max_automatic_initializers)
6819 EmitStaticInitializers (ec);
6821 if (dynamic_initializers)
6822 EmitDynamicInitializers (ec);
6826 public object EncodeAsAttribute ()
6828 if (!is_one_dimensional){
6829 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6833 if (array_data == null){
6834 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6838 object [] ret = new object [array_data.Count];
6840 foreach (Expression e in array_data){
6843 if (e is NullLiteral)
6846 if (!Attribute.GetAttributeArgumentExpression (e, Location, out v))
6854 public Expression TurnIntoConstant ()
6857 // Should use something like the above attribute thing.
6858 // It should return a subclass of Constant that just returns
6859 // the computed value of the array
6861 throw new Exception ("Does not support yet Turning array into a Constant");
6866 /// Represents the `this' construct
6868 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6871 VariableInfo variable_info;
6873 public This (Block block, Location loc)
6879 public This (Location loc)
6884 public VariableInfo VariableInfo {
6885 get { return variable_info; }
6888 public bool VerifyFixed (bool is_expression)
6890 if ((variable_info == null) || (variable_info.LocalInfo == null))
6893 return variable_info.LocalInfo.IsFixed;
6896 public bool ResolveBase (EmitContext ec)
6898 eclass = ExprClass.Variable;
6900 if (ec.TypeContainer.CurrentType != null)
6901 type = ec.TypeContainer.CurrentType.ResolveType (ec);
6903 type = ec.ContainerType;
6906 Error (26, "Keyword this not valid in static code");
6910 if ((block != null) && (block.ThisVariable != null))
6911 variable_info = block.ThisVariable.VariableInfo;
6916 public override Expression DoResolve (EmitContext ec)
6918 if (!ResolveBase (ec))
6921 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
6922 Error (188, "The this object cannot be used before all " +
6923 "of its fields are assigned to");
6924 variable_info.SetAssigned (ec);
6928 if (ec.IsFieldInitializer) {
6929 Error (27, "Keyword `this' can't be used outside a constructor, " +
6930 "a method or a property.");
6937 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6939 if (!ResolveBase (ec))
6942 if (variable_info != null)
6943 variable_info.SetAssigned (ec);
6945 if (ec.TypeContainer is Class){
6946 Error (1604, "Cannot assign to `this'");
6953 public void Emit (EmitContext ec, bool leave_copy)
6957 ec.ig.Emit (OpCodes.Dup);
6960 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
6962 ILGenerator ig = ec.ig;
6964 if (ec.TypeContainer is Struct){
6968 ec.ig.Emit (OpCodes.Dup);
6969 ig.Emit (OpCodes.Stobj, type);
6971 throw new Exception ("how did you get here");
6975 public override void Emit (EmitContext ec)
6977 ILGenerator ig = ec.ig;
6980 if (ec.TypeContainer is Struct)
6981 ig.Emit (OpCodes.Ldobj, type);
6984 public void AddressOf (EmitContext ec, AddressOp mode)
6989 // FIGURE OUT WHY LDARG_S does not work
6991 // consider: struct X { int val; int P { set { val = value; }}}
6993 // Yes, this looks very bad. Look at `NOTAS' for
6995 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
7000 /// Represents the `__arglist' construct
7002 public class ArglistAccess : Expression
7004 public ArglistAccess (Location loc)
7009 public bool ResolveBase (EmitContext ec)
7011 eclass = ExprClass.Variable;
7012 type = TypeManager.runtime_argument_handle_type;
7016 public override Expression DoResolve (EmitContext ec)
7018 if (!ResolveBase (ec))
7021 if (ec.IsFieldInitializer || !ec.CurrentBlock.HasVarargs) {
7022 Error (190, "The __arglist construct is valid only within " +
7023 "a variable argument method.");
7030 public override void Emit (EmitContext ec)
7032 ec.ig.Emit (OpCodes.Arglist);
7037 /// Represents the `__arglist (....)' construct
7039 public class Arglist : Expression
7041 public readonly Argument[] Arguments;
7043 public Arglist (Argument[] args, Location l)
7049 public Type[] ArgumentTypes {
7051 Type[] retval = new Type [Arguments.Length];
7052 for (int i = 0; i < Arguments.Length; i++)
7053 retval [i] = Arguments [i].Type;
7058 public override Expression DoResolve (EmitContext ec)
7060 eclass = ExprClass.Variable;
7061 type = TypeManager.runtime_argument_handle_type;
7063 foreach (Argument arg in Arguments) {
7064 if (!arg.Resolve (ec, loc))
7071 public override void Emit (EmitContext ec)
7073 foreach (Argument arg in Arguments)
7079 // This produces the value that renders an instance, used by the iterators code
7081 public class ProxyInstance : Expression, IMemoryLocation {
7082 public override Expression DoResolve (EmitContext ec)
7084 eclass = ExprClass.Variable;
7085 type = ec.ContainerType;
7089 public override void Emit (EmitContext ec)
7091 ec.ig.Emit (OpCodes.Ldarg_0);
7095 public void AddressOf (EmitContext ec, AddressOp mode)
7097 ec.ig.Emit (OpCodes.Ldarg_0);
7102 /// Implements the typeof operator
7104 public class TypeOf : Expression {
7105 public readonly Expression QueriedType;
7106 protected Type typearg;
7108 public TypeOf (Expression queried_type, Location l)
7110 QueriedType = queried_type;
7114 public override Expression DoResolve (EmitContext ec)
7116 typearg = ec.DeclSpace.ResolveType (QueriedType, false, loc);
7118 if (typearg == null)
7121 if (typearg == TypeManager.void_type) {
7122 Error (673, "System.Void cannot be used from C# - " +
7123 "use typeof (void) to get the void type object");
7127 CheckObsoleteAttribute (typearg);
7129 type = TypeManager.type_type;
7130 eclass = ExprClass.Type;
7134 public override void Emit (EmitContext ec)
7136 ec.ig.Emit (OpCodes.Ldtoken, typearg);
7137 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
7140 public Type TypeArg {
7141 get { return typearg; }
7146 /// Implements the `typeof (void)' operator
7148 public class TypeOfVoid : TypeOf {
7149 public TypeOfVoid (Location l) : base (null, l)
7154 public override Expression DoResolve (EmitContext ec)
7156 type = TypeManager.type_type;
7157 typearg = TypeManager.void_type;
7158 eclass = ExprClass.Type;
7164 /// Implements the sizeof expression
7166 public class SizeOf : Expression {
7167 public Expression QueriedType;
7170 public SizeOf (Expression queried_type, Location l)
7172 this.QueriedType = queried_type;
7176 public override Expression DoResolve (EmitContext ec)
7180 233, loc, "Sizeof may only be used in an unsafe context " +
7181 "(consider using System.Runtime.InteropServices.Marshal.Sizeof");
7185 QueriedType = ec.DeclSpace.ResolveTypeExpr (QueriedType, false, loc);
7186 if (QueriedType == null || QueriedType.Type == null)
7189 if (QueriedType is TypeParameterExpr){
7190 ((TypeParameterExpr)QueriedType).Error_CannotUseAsUnmanagedType (loc);
7194 type_queried = QueriedType.Type;
7195 if (type_queried == null)
7198 CheckObsoleteAttribute (type_queried);
7200 if (!TypeManager.IsUnmanagedType (type_queried)){
7201 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
7205 type = TypeManager.int32_type;
7206 eclass = ExprClass.Value;
7210 public override void Emit (EmitContext ec)
7212 int size = GetTypeSize (type_queried);
7215 ec.ig.Emit (OpCodes.Sizeof, type_queried);
7217 IntConstant.EmitInt (ec.ig, size);
7222 /// Implements the member access expression
7224 public class MemberAccess : Expression {
7225 public string Identifier;
7226 protected Expression expr;
7227 protected TypeArguments args;
7229 public MemberAccess (Expression expr, string id, Location l)
7236 public MemberAccess (Expression expr, string id, TypeArguments args,
7238 : this (expr, id, l)
7243 public Expression Expr {
7249 public static void error176 (Location loc, string name)
7251 Report.Error (176, loc, "Static member `" +
7252 name + "' cannot be accessed " +
7253 "with an instance reference, qualify with a " +
7254 "type name instead");
7257 public static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Expression left, Location loc)
7259 SimpleName sn = left_original as SimpleName;
7260 if (sn == null || left == null || left.Type.Name != sn.Name)
7263 return RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc) != null;
7266 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
7267 Expression left, Location loc,
7268 Expression left_original)
7270 bool left_is_type, left_is_explicit;
7272 // If `left' is null, then we're called from SimpleNameResolve and this is
7273 // a member in the currently defining class.
7275 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
7276 left_is_explicit = false;
7278 // Implicitly default to `this' unless we're static.
7279 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
7280 left = ec.GetThis (loc);
7282 left_is_type = left is TypeExpr;
7283 left_is_explicit = true;
7286 if (member_lookup is FieldExpr){
7287 FieldExpr fe = (FieldExpr) member_lookup;
7288 FieldInfo fi = fe.FieldInfo.Mono_GetGenericFieldDefinition ();
7289 Type decl_type = fi.DeclaringType;
7291 if (fi is FieldBuilder) {
7292 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
7296 if (!c.LookupConstantValue (out o))
7299 object real_value = ((Constant) c.Expr).GetValue ();
7301 return Constantify (real_value, fi.FieldType);
7306 Type t = fi.FieldType;
7310 if (fi is FieldBuilder)
7311 o = TypeManager.GetValue ((FieldBuilder) fi);
7313 o = fi.GetValue (fi);
7315 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
7316 if (left_is_explicit && !left_is_type &&
7317 !IdenticalNameAndTypeName (ec, left_original, member_lookup, loc)) {
7318 error176 (loc, fe.FieldInfo.Name);
7322 Expression enum_member = MemberLookup (
7323 ec, decl_type, "value__", MemberTypes.Field,
7324 AllBindingFlags, loc);
7326 Enum en = TypeManager.LookupEnum (decl_type);
7330 c = Constantify (o, en.UnderlyingType);
7332 c = Constantify (o, enum_member.Type);
7334 return new EnumConstant (c, decl_type);
7337 Expression exp = Constantify (o, t);
7339 if (left_is_explicit && !left_is_type) {
7340 error176 (loc, fe.FieldInfo.Name);
7347 if (fi.FieldType.IsPointer && !ec.InUnsafe){
7353 if (member_lookup is EventExpr) {
7354 EventExpr ee = (EventExpr) member_lookup;
7357 // If the event is local to this class, we transform ourselves into
7361 if (ee.EventInfo.DeclaringType == ec.ContainerType ||
7362 TypeManager.IsNestedChildOf(ec.ContainerType, ee.EventInfo.DeclaringType)) {
7363 MemberInfo mi = GetFieldFromEvent (ee);
7367 // If this happens, then we have an event with its own
7368 // accessors and private field etc so there's no need
7369 // to transform ourselves.
7371 ee.InstanceExpression = left;
7375 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
7378 Report.Error (-200, loc, "Internal error!!");
7382 if (!left_is_explicit)
7385 ee.InstanceExpression = left;
7387 return ResolveMemberAccess (ec, ml, left, loc, left_original);
7391 if (member_lookup is IMemberExpr) {
7392 IMemberExpr me = (IMemberExpr) member_lookup;
7393 MethodGroupExpr mg = me as MethodGroupExpr;
7396 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
7397 mg.IsExplicitImpl = left_is_explicit;
7400 if ((ec.IsFieldInitializer || ec.IsStatic) &&
7401 IdenticalNameAndTypeName (ec, left_original, member_lookup, loc))
7402 return member_lookup;
7404 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
7409 if (!me.IsInstance){
7410 if (IdenticalNameAndTypeName (ec, left_original, left, loc))
7411 return member_lookup;
7413 if (left_is_explicit) {
7414 error176 (loc, me.Name);
7420 // Since we can not check for instance objects in SimpleName,
7421 // becaue of the rule that allows types and variables to share
7422 // the name (as long as they can be de-ambiguated later, see
7423 // IdenticalNameAndTypeName), we have to check whether left
7424 // is an instance variable in a static context
7426 // However, if the left-hand value is explicitly given, then
7427 // it is already our instance expression, so we aren't in
7431 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
7432 IMemberExpr mexp = (IMemberExpr) left;
7434 if (!mexp.IsStatic){
7435 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
7440 if ((mg != null) && IdenticalNameAndTypeName (ec, left_original, left, loc))
7441 mg.IdenticalTypeName = true;
7443 me.InstanceExpression = left;
7446 return member_lookup;
7449 Console.WriteLine ("Left is: " + left);
7450 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
7451 Environment.Exit (1);
7455 public virtual Expression DoResolve (EmitContext ec, Expression right_side,
7459 throw new Exception ();
7462 // Resolve the expression with flow analysis turned off, we'll do the definite
7463 // assignment checks later. This is because we don't know yet what the expression
7464 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7465 // definite assignment check on the actual field and not on the whole struct.
7468 Expression original = expr;
7469 expr = expr.Resolve (ec, flags | ResolveFlags.Intermediate | ResolveFlags.DisableFlowAnalysis);
7473 if (expr is SimpleName){
7474 SimpleName child_expr = (SimpleName) expr;
7476 Expression new_expr = new SimpleName (child_expr.Name, Identifier, loc);
7478 return new_expr.Resolve (ec, flags);
7482 // TODO: I mailed Ravi about this, and apparently we can get rid
7483 // of this and put it in the right place.
7485 // Handle enums here when they are in transit.
7486 // Note that we cannot afford to hit MemberLookup in this case because
7487 // it will fail to find any members at all
7491 if (expr is TypeExpr){
7492 expr_type = ((TypeExpr) expr).ResolveType (ec);
7494 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
7495 Report.Error_T (122, loc, expr_type);
7499 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
7500 Enum en = TypeManager.LookupEnum (expr_type);
7503 object value = en.LookupEnumValue (ec, Identifier, loc);
7506 ObsoleteAttribute oa = en.GetObsoleteAttribute (ec, Identifier);
7508 AttributeTester.Report_ObsoleteMessage (oa, en.GetSignatureForError (), Location);
7511 Constant c = Constantify (value, en.UnderlyingType);
7512 return new EnumConstant (c, expr_type);
7515 CheckObsoleteAttribute (expr_type);
7517 FieldInfo fi = expr_type.GetField (Identifier);
7519 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
7521 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), Location);
7526 expr_type = expr.Type;
7528 if (expr_type.IsPointer){
7529 Error (23, "The `.' operator can not be applied to pointer operands (" +
7530 TypeManager.CSharpName (expr_type) + ")");
7534 int errors = Report.Errors;
7536 Expression member_lookup;
7537 member_lookup = MemberLookup (
7538 ec, expr_type, expr_type, Identifier, loc);
7539 if ((member_lookup == null) && (args != null)) {
7540 string lookup_id = MemberName.MakeName (Identifier, args);
7541 member_lookup = MemberLookup (
7542 ec, expr_type, expr_type, lookup_id, loc);
7544 if (member_lookup == null) {
7545 MemberLookupFailed (
7546 ec, expr_type, expr_type, Identifier, null, loc);
7550 if (member_lookup is TypeExpr) {
7551 if (!(expr is TypeExpr) && !(expr is SimpleName)) {
7552 Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
7553 member_lookup.Type + "' instead");
7557 return member_lookup;
7561 string full_name = expr_type + "." + Identifier;
7563 if (member_lookup is FieldExpr) {
7564 Report.Error (307, loc, "The field `{0}' cannot " +
7565 "be used with type arguments", full_name);
7567 } else if (member_lookup is EventExpr) {
7568 Report.Error (307, loc, "The event `{0}' cannot " +
7569 "be used with type arguments", full_name);
7571 } else if (member_lookup is PropertyExpr) {
7572 Report.Error (307, loc, "The property `{0}' cannot " +
7573 "be used with type arguments", full_name);
7578 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
7579 if (member_lookup == null)
7583 MethodGroupExpr mg = member_lookup as MethodGroupExpr;
7585 throw new InternalErrorException ();
7587 return mg.ResolveGeneric (ec, args);
7590 // The following DoResolve/DoResolveLValue will do the definite assignment
7593 if (right_side != null)
7594 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
7596 member_lookup = member_lookup.DoResolve (ec);
7598 return member_lookup;
7601 public override Expression DoResolve (EmitContext ec)
7603 return DoResolve (ec, null, ResolveFlags.VariableOrValue |
7604 ResolveFlags.SimpleName | ResolveFlags.Type);
7607 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7609 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
7610 ResolveFlags.SimpleName | ResolveFlags.Type);
7613 public override Expression ResolveAsTypeStep (EmitContext ec)
7615 string fname = null;
7616 MemberAccess full_expr = this;
7617 while (full_expr != null) {
7619 fname = String.Concat (full_expr.Identifier, ".", fname);
7621 fname = full_expr.Identifier;
7623 fname = MemberName.MakeName (fname, args);
7625 if (full_expr.Expr is SimpleName) {
7626 string full_name = String.Concat (((SimpleName) full_expr.Expr).Name, ".", fname);
7627 Type fully_qualified = ec.DeclSpace.FindType (loc, full_name);
7628 if (fully_qualified != null)
7629 return new TypeExpression (fully_qualified, loc);
7632 full_expr = full_expr.Expr as MemberAccess;
7635 Expression new_expr = expr.ResolveAsTypeStep (ec);
7637 if (new_expr == null)
7640 if (new_expr is SimpleName){
7641 SimpleName child_expr = (SimpleName) new_expr;
7643 new_expr = new SimpleName (child_expr.Name, Identifier, loc);
7645 return new_expr.ResolveAsTypeStep (ec);
7648 Type expr_type = ((TypeExpr) new_expr).ResolveType (ec);
7650 if (expr_type.IsPointer){
7651 Error (23, "The `.' operator can not be applied to pointer operands (" +
7652 TypeManager.CSharpName (expr_type) + ")");
7656 Expression member_lookup;
7658 lookup_id = MemberName.MakeName (Identifier, args);
7659 member_lookup = MemberLookupFinal (
7660 ec, expr_type, expr_type, lookup_id, loc);
7661 if (member_lookup == null)
7664 TypeExpr texpr = member_lookup as TypeExpr;
7668 Type t = texpr.ResolveType (ec);
7672 if (TypeManager.HasGenericArguments (expr_type)) {
7673 Type[] decl_args = TypeManager.GetTypeArguments (expr_type);
7675 TypeArguments new_args = new TypeArguments (loc);
7676 foreach (Type decl in decl_args)
7677 new_args.Add (new TypeExpression (decl, loc));
7680 new_args.Add (args);
7686 ConstructedType ctype = new ConstructedType (t, args, loc);
7687 return ctype.ResolveAsTypeStep (ec);
7693 public override void Emit (EmitContext ec)
7695 throw new Exception ("Should not happen");
7698 public override string ToString ()
7700 return expr + "." + MemberName.MakeName (Identifier, args);
7705 /// Implements checked expressions
7707 public class CheckedExpr : Expression {
7709 public Expression Expr;
7711 public CheckedExpr (Expression e, Location l)
7717 public override Expression DoResolve (EmitContext ec)
7719 bool last_check = ec.CheckState;
7720 bool last_const_check = ec.ConstantCheckState;
7722 ec.CheckState = true;
7723 ec.ConstantCheckState = true;
7724 Expr = Expr.Resolve (ec);
7725 ec.CheckState = last_check;
7726 ec.ConstantCheckState = last_const_check;
7731 if (Expr is Constant)
7734 eclass = Expr.eclass;
7739 public override void Emit (EmitContext ec)
7741 bool last_check = ec.CheckState;
7742 bool last_const_check = ec.ConstantCheckState;
7744 ec.CheckState = true;
7745 ec.ConstantCheckState = true;
7747 ec.CheckState = last_check;
7748 ec.ConstantCheckState = last_const_check;
7754 /// Implements the unchecked expression
7756 public class UnCheckedExpr : Expression {
7758 public Expression Expr;
7760 public UnCheckedExpr (Expression e, Location l)
7766 public override Expression DoResolve (EmitContext ec)
7768 bool last_check = ec.CheckState;
7769 bool last_const_check = ec.ConstantCheckState;
7771 ec.CheckState = false;
7772 ec.ConstantCheckState = false;
7773 Expr = Expr.Resolve (ec);
7774 ec.CheckState = last_check;
7775 ec.ConstantCheckState = last_const_check;
7780 if (Expr is Constant)
7783 eclass = Expr.eclass;
7788 public override void Emit (EmitContext ec)
7790 bool last_check = ec.CheckState;
7791 bool last_const_check = ec.ConstantCheckState;
7793 ec.CheckState = false;
7794 ec.ConstantCheckState = false;
7796 ec.CheckState = last_check;
7797 ec.ConstantCheckState = last_const_check;
7803 /// An Element Access expression.
7805 /// During semantic analysis these are transformed into
7806 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7808 public class ElementAccess : Expression {
7809 public ArrayList Arguments;
7810 public Expression Expr;
7812 public ElementAccess (Expression e, ArrayList e_list, Location l)
7821 Arguments = new ArrayList ();
7822 foreach (Expression tmp in e_list)
7823 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7827 bool CommonResolve (EmitContext ec)
7829 Expr = Expr.Resolve (ec);
7834 if (Arguments == null)
7837 foreach (Argument a in Arguments){
7838 if (!a.Resolve (ec, loc))
7845 Expression MakePointerAccess ()
7849 if (t == TypeManager.void_ptr_type){
7850 Error (242, "The array index operation is not valid for void pointers");
7853 if (Arguments.Count != 1){
7854 Error (196, "A pointer must be indexed by a single value");
7859 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc);
7860 return new Indirection (p, loc);
7863 public override Expression DoResolve (EmitContext ec)
7865 if (!CommonResolve (ec))
7869 // We perform some simple tests, and then to "split" the emit and store
7870 // code we create an instance of a different class, and return that.
7872 // I am experimenting with this pattern.
7876 if (t == TypeManager.array_type){
7877 Report.Error (21, loc, "Cannot use indexer on System.Array");
7882 return (new ArrayAccess (this, loc)).Resolve (ec);
7883 else if (t.IsPointer)
7884 return MakePointerAccess ();
7886 return (new IndexerAccess (this, loc)).Resolve (ec);
7889 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7891 if (!CommonResolve (ec))
7896 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
7897 else if (t.IsPointer)
7898 return MakePointerAccess ();
7900 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
7903 public override void Emit (EmitContext ec)
7905 throw new Exception ("Should never be reached");
7910 /// Implements array access
7912 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7914 // Points to our "data" repository
7918 LocalTemporary temp;
7921 public ArrayAccess (ElementAccess ea_data, Location l)
7924 eclass = ExprClass.Variable;
7928 public override Expression DoResolve (EmitContext ec)
7931 ExprClass eclass = ea.Expr.eclass;
7933 // As long as the type is valid
7934 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7935 eclass == ExprClass.Value)) {
7936 ea.Expr.Error_UnexpectedKind ("variable or value");
7941 Type t = ea.Expr.Type;
7942 if (t.GetArrayRank () != ea.Arguments.Count){
7944 "Incorrect number of indexes for array " +
7945 " expected: " + t.GetArrayRank () + " got: " +
7946 ea.Arguments.Count);
7950 type = TypeManager.GetElementType (t);
7951 if (type.IsPointer && !ec.InUnsafe){
7952 UnsafeError (ea.Location);
7956 foreach (Argument a in ea.Arguments){
7957 Type argtype = a.Type;
7959 if (argtype == TypeManager.int32_type ||
7960 argtype == TypeManager.uint32_type ||
7961 argtype == TypeManager.int64_type ||
7962 argtype == TypeManager.uint64_type)
7966 // Mhm. This is strage, because the Argument.Type is not the same as
7967 // Argument.Expr.Type: the value changes depending on the ref/out setting.
7969 // Wonder if I will run into trouble for this.
7971 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
7976 eclass = ExprClass.Variable;
7982 /// Emits the right opcode to load an object of Type `t'
7983 /// from an array of T
7985 static public void EmitLoadOpcode (ILGenerator ig, Type type)
7987 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7988 ig.Emit (OpCodes.Ldelem_U1);
7989 else if (type == TypeManager.sbyte_type)
7990 ig.Emit (OpCodes.Ldelem_I1);
7991 else if (type == TypeManager.short_type)
7992 ig.Emit (OpCodes.Ldelem_I2);
7993 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7994 ig.Emit (OpCodes.Ldelem_U2);
7995 else if (type == TypeManager.int32_type)
7996 ig.Emit (OpCodes.Ldelem_I4);
7997 else if (type == TypeManager.uint32_type)
7998 ig.Emit (OpCodes.Ldelem_U4);
7999 else if (type == TypeManager.uint64_type)
8000 ig.Emit (OpCodes.Ldelem_I8);
8001 else if (type == TypeManager.int64_type)
8002 ig.Emit (OpCodes.Ldelem_I8);
8003 else if (type == TypeManager.float_type)
8004 ig.Emit (OpCodes.Ldelem_R4);
8005 else if (type == TypeManager.double_type)
8006 ig.Emit (OpCodes.Ldelem_R8);
8007 else if (type == TypeManager.intptr_type)
8008 ig.Emit (OpCodes.Ldelem_I);
8009 else if (TypeManager.IsEnumType (type)){
8010 EmitLoadOpcode (ig, TypeManager.EnumToUnderlying (type));
8011 } else if (type.IsValueType){
8012 ig.Emit (OpCodes.Ldelema, type);
8013 ig.Emit (OpCodes.Ldobj, type);
8014 } else if (type.IsGenericParameter)
8015 ig.Emit (OpCodes.Ldelem_Any, type);
8017 ig.Emit (OpCodes.Ldelem_Ref);
8021 /// Returns the right opcode to store an object of Type `t'
8022 /// from an array of T.
8024 static public OpCode GetStoreOpcode (Type t, out bool is_stobj, out bool has_type_arg)
8026 //Console.WriteLine (new System.Diagnostics.StackTrace ());
8027 has_type_arg = false; is_stobj = false;
8028 t = TypeManager.TypeToCoreType (t);
8029 if (TypeManager.IsEnumType (t))
8030 t = TypeManager.EnumToUnderlying (t);
8031 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
8032 t == TypeManager.bool_type)
8033 return OpCodes.Stelem_I1;
8034 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
8035 t == TypeManager.char_type)
8036 return OpCodes.Stelem_I2;
8037 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
8038 return OpCodes.Stelem_I4;
8039 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
8040 return OpCodes.Stelem_I8;
8041 else if (t == TypeManager.float_type)
8042 return OpCodes.Stelem_R4;
8043 else if (t == TypeManager.double_type)
8044 return OpCodes.Stelem_R8;
8045 else if (t == TypeManager.intptr_type) {
8046 has_type_arg = true;
8048 return OpCodes.Stobj;
8049 } else if (t.IsValueType) {
8050 has_type_arg = true;
8052 return OpCodes.Stobj;
8053 } else if (t.IsGenericParameter) {
8054 has_type_arg = true;
8055 return OpCodes.Stelem_Any;
8057 return OpCodes.Stelem_Ref;
8060 MethodInfo FetchGetMethod ()
8062 ModuleBuilder mb = CodeGen.Module.Builder;
8063 int arg_count = ea.Arguments.Count;
8064 Type [] args = new Type [arg_count];
8067 for (int i = 0; i < arg_count; i++){
8068 //args [i++] = a.Type;
8069 args [i] = TypeManager.int32_type;
8072 get = mb.GetArrayMethod (
8073 ea.Expr.Type, "Get",
8074 CallingConventions.HasThis |
8075 CallingConventions.Standard,
8081 MethodInfo FetchAddressMethod ()
8083 ModuleBuilder mb = CodeGen.Module.Builder;
8084 int arg_count = ea.Arguments.Count;
8085 Type [] args = new Type [arg_count];
8089 ret_type = TypeManager.GetReferenceType (type);
8091 for (int i = 0; i < arg_count; i++){
8092 //args [i++] = a.Type;
8093 args [i] = TypeManager.int32_type;
8096 address = mb.GetArrayMethod (
8097 ea.Expr.Type, "Address",
8098 CallingConventions.HasThis |
8099 CallingConventions.Standard,
8106 // Load the array arguments into the stack.
8108 // If we have been requested to cache the values (cached_locations array
8109 // initialized), then load the arguments the first time and store them
8110 // in locals. otherwise load from local variables.
8112 void LoadArrayAndArguments (EmitContext ec)
8114 ILGenerator ig = ec.ig;
8117 foreach (Argument a in ea.Arguments){
8118 Type argtype = a.Expr.Type;
8122 if (argtype == TypeManager.int64_type)
8123 ig.Emit (OpCodes.Conv_Ovf_I);
8124 else if (argtype == TypeManager.uint64_type)
8125 ig.Emit (OpCodes.Conv_Ovf_I_Un);
8129 public void Emit (EmitContext ec, bool leave_copy)
8131 int rank = ea.Expr.Type.GetArrayRank ();
8132 ILGenerator ig = ec.ig;
8135 LoadArrayAndArguments (ec);
8138 EmitLoadOpcode (ig, type);
8142 method = FetchGetMethod ();
8143 ig.Emit (OpCodes.Call, method);
8146 LoadFromPtr (ec.ig, this.type);
8149 ec.ig.Emit (OpCodes.Dup);
8150 temp = new LocalTemporary (ec, this.type);
8155 public override void Emit (EmitContext ec)
8160 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8162 int rank = ea.Expr.Type.GetArrayRank ();
8163 ILGenerator ig = ec.ig;
8164 Type t = source.Type;
8165 prepared = prepare_for_load;
8167 if (prepare_for_load) {
8168 AddressOf (ec, AddressOp.LoadStore);
8169 ec.ig.Emit (OpCodes.Dup);
8172 ec.ig.Emit (OpCodes.Dup);
8173 temp = new LocalTemporary (ec, this.type);
8176 StoreFromPtr (ec.ig, t);
8184 LoadArrayAndArguments (ec);
8187 bool is_stobj, has_type_arg;
8188 OpCode op = GetStoreOpcode (t, out is_stobj, out has_type_arg);
8190 // The stobj opcode used by value types will need
8191 // an address on the stack, not really an array/array
8195 ig.Emit (OpCodes.Ldelema, t);
8199 ec.ig.Emit (OpCodes.Dup);
8200 temp = new LocalTemporary (ec, this.type);
8205 ig.Emit (OpCodes.Stobj, t);
8209 ModuleBuilder mb = CodeGen.Module.Builder;
8210 int arg_count = ea.Arguments.Count;
8211 Type [] args = new Type [arg_count + 1];
8216 ec.ig.Emit (OpCodes.Dup);
8217 temp = new LocalTemporary (ec, this.type);
8221 for (int i = 0; i < arg_count; i++){
8222 //args [i++] = a.Type;
8223 args [i] = TypeManager.int32_type;
8226 args [arg_count] = type;
8228 set = mb.GetArrayMethod (
8229 ea.Expr.Type, "Set",
8230 CallingConventions.HasThis |
8231 CallingConventions.Standard,
8232 TypeManager.void_type, args);
8234 ig.Emit (OpCodes.Call, set);
8241 public void AddressOf (EmitContext ec, AddressOp mode)
8243 int rank = ea.Expr.Type.GetArrayRank ();
8244 ILGenerator ig = ec.ig;
8246 LoadArrayAndArguments (ec);
8249 ig.Emit (OpCodes.Ldelema, type);
8251 MethodInfo address = FetchAddressMethod ();
8252 ig.Emit (OpCodes.Call, address);
8259 public ArrayList Properties;
8260 static Hashtable map;
8262 public struct Indexer {
8263 public readonly Type Type;
8264 public readonly MethodInfo Getter, Setter;
8266 public Indexer (Type type, MethodInfo get, MethodInfo set)
8276 map = new Hashtable ();
8281 Properties = new ArrayList ();
8284 void Append (MemberInfo [] mi)
8286 foreach (PropertyInfo property in mi){
8287 MethodInfo get, set;
8289 get = property.GetGetMethod (true);
8290 set = property.GetSetMethod (true);
8291 Properties.Add (new Indexer (property.PropertyType, get, set));
8295 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
8297 string p_name = TypeManager.IndexerPropertyName (lookup_type);
8299 MemberInfo [] mi = TypeManager.MemberLookup (
8300 caller_type, caller_type, lookup_type, MemberTypes.Property,
8301 BindingFlags.Public | BindingFlags.Instance |
8302 BindingFlags.DeclaredOnly, p_name, null);
8304 if (mi == null || mi.Length == 0)
8310 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
8312 Indexers ix = (Indexers) map [lookup_type];
8317 Type copy = lookup_type;
8318 while (copy != TypeManager.object_type && copy != null){
8319 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
8323 ix = new Indexers ();
8328 copy = copy.BaseType;
8331 if (!lookup_type.IsInterface)
8334 TypeExpr [] ifaces = TypeManager.GetInterfaces (lookup_type);
8335 if (ifaces != null) {
8336 foreach (TypeExpr iface in ifaces) {
8337 Type itype = iface.Type;
8338 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
8341 ix = new Indexers ();
8353 /// Expressions that represent an indexer call.
8355 public class IndexerAccess : Expression, IAssignMethod {
8357 // Points to our "data" repository
8359 MethodInfo get, set;
8360 ArrayList set_arguments;
8361 bool is_base_indexer;
8363 protected Type indexer_type;
8364 protected Type current_type;
8365 protected Expression instance_expr;
8366 protected ArrayList arguments;
8368 public IndexerAccess (ElementAccess ea, Location loc)
8369 : this (ea.Expr, false, loc)
8371 this.arguments = ea.Arguments;
8374 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
8377 this.instance_expr = instance_expr;
8378 this.is_base_indexer = is_base_indexer;
8379 this.eclass = ExprClass.Value;
8383 protected virtual bool CommonResolve (EmitContext ec)
8385 indexer_type = instance_expr.Type;
8386 current_type = ec.ContainerType;
8391 public override Expression DoResolve (EmitContext ec)
8393 ArrayList AllGetters = new ArrayList();
8394 if (!CommonResolve (ec))
8398 // Step 1: Query for all `Item' *properties*. Notice
8399 // that the actual methods are pointed from here.
8401 // This is a group of properties, piles of them.
8403 bool found_any = false, found_any_getters = false;
8404 Type lookup_type = indexer_type;
8407 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
8408 if (ilist != null) {
8410 if (ilist.Properties != null) {
8411 foreach (Indexers.Indexer ix in ilist.Properties) {
8412 if (ix.Getter != null)
8413 AllGetters.Add(ix.Getter);
8418 if (AllGetters.Count > 0) {
8419 found_any_getters = true;
8420 get = (MethodInfo) Invocation.OverloadResolve (
8421 ec, new MethodGroupExpr (AllGetters, loc),
8422 arguments, false, loc);
8426 Report.Error (21, loc,
8427 "Type `" + TypeManager.CSharpName (indexer_type) +
8428 "' does not have any indexers defined");
8432 if (!found_any_getters) {
8433 Error (154, "indexer can not be used in this context, because " +
8434 "it lacks a `get' accessor");
8439 Error (1501, "No Overload for method `this' takes `" +
8440 arguments.Count + "' arguments");
8445 // Only base will allow this invocation to happen.
8447 if (get.IsAbstract && this is BaseIndexerAccess){
8448 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
8452 type = get.ReturnType;
8453 if (type.IsPointer && !ec.InUnsafe){
8458 eclass = ExprClass.IndexerAccess;
8462 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8464 ArrayList AllSetters = new ArrayList();
8465 if (!CommonResolve (ec))
8468 bool found_any = false, found_any_setters = false;
8470 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
8471 if (ilist != null) {
8473 if (ilist.Properties != null) {
8474 foreach (Indexers.Indexer ix in ilist.Properties) {
8475 if (ix.Setter != null)
8476 AllSetters.Add(ix.Setter);
8480 if (AllSetters.Count > 0) {
8481 found_any_setters = true;
8482 set_arguments = (ArrayList) arguments.Clone ();
8483 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
8484 set = (MethodInfo) Invocation.OverloadResolve (
8485 ec, new MethodGroupExpr (AllSetters, loc),
8486 set_arguments, false, loc);
8490 Report.Error (21, loc,
8491 "Type `" + TypeManager.CSharpName (indexer_type) +
8492 "' does not have any indexers defined");
8496 if (!found_any_setters) {
8497 Error (154, "indexer can not be used in this context, because " +
8498 "it lacks a `set' accessor");
8503 Error (1501, "No Overload for method `this' takes `" +
8504 arguments.Count + "' arguments");
8509 // Only base will allow this invocation to happen.
8511 if (set.IsAbstract && this is BaseIndexerAccess){
8512 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
8517 // Now look for the actual match in the list of indexers to set our "return" type
8519 type = TypeManager.void_type; // default value
8520 foreach (Indexers.Indexer ix in ilist.Properties){
8521 if (ix.Setter == set){
8527 eclass = ExprClass.IndexerAccess;
8531 bool prepared = false;
8532 LocalTemporary temp;
8534 public void Emit (EmitContext ec, bool leave_copy)
8536 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc, prepared, false);
8538 ec.ig.Emit (OpCodes.Dup);
8539 temp = new LocalTemporary (ec, Type);
8545 // source is ignored, because we already have a copy of it from the
8546 // LValue resolution and we have already constructed a pre-cached
8547 // version of the arguments (ea.set_arguments);
8549 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8551 prepared = prepare_for_load;
8552 Argument a = (Argument) set_arguments [set_arguments.Count - 1];
8557 ec.ig.Emit (OpCodes.Dup);
8558 temp = new LocalTemporary (ec, Type);
8561 } else if (leave_copy) {
8562 temp = new LocalTemporary (ec, Type);
8568 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc, false, prepared);
8575 public override void Emit (EmitContext ec)
8582 /// The base operator for method names
8584 public class BaseAccess : Expression {
8587 public BaseAccess (string member, Location l)
8589 this.member = member;
8593 public override Expression DoResolve (EmitContext ec)
8595 Expression c = CommonResolve (ec);
8601 // MethodGroups use this opportunity to flag an error on lacking ()
8603 if (!(c is MethodGroupExpr))
8604 return c.Resolve (ec);
8608 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8610 Expression c = CommonResolve (ec);
8616 // MethodGroups use this opportunity to flag an error on lacking ()
8618 if (! (c is MethodGroupExpr))
8619 return c.DoResolveLValue (ec, right_side);
8624 Expression CommonResolve (EmitContext ec)
8626 Expression member_lookup;
8627 Type current_type = ec.ContainerType;
8628 Type base_type = current_type.BaseType;
8632 Error (1511, "Keyword base is not allowed in static method");
8636 if (ec.IsFieldInitializer){
8637 Error (1512, "Keyword base is not available in the current context");
8641 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type,
8642 member, AllMemberTypes, AllBindingFlags,
8644 if (member_lookup == null) {
8645 MemberLookupFailed (
8646 ec, base_type, base_type, member, null, loc);
8653 left = new TypeExpression (base_type, loc);
8655 left = ec.GetThis (loc);
8657 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
8659 if (e is PropertyExpr){
8660 PropertyExpr pe = (PropertyExpr) e;
8668 public override void Emit (EmitContext ec)
8670 throw new Exception ("Should never be called");
8675 /// The base indexer operator
8677 public class BaseIndexerAccess : IndexerAccess {
8678 public BaseIndexerAccess (ArrayList args, Location loc)
8679 : base (null, true, loc)
8681 arguments = new ArrayList ();
8682 foreach (Expression tmp in args)
8683 arguments.Add (new Argument (tmp, Argument.AType.Expression));
8686 protected override bool CommonResolve (EmitContext ec)
8688 instance_expr = ec.GetThis (loc);
8690 current_type = ec.ContainerType.BaseType;
8691 indexer_type = current_type;
8693 foreach (Argument a in arguments){
8694 if (!a.Resolve (ec, loc))
8703 /// This class exists solely to pass the Type around and to be a dummy
8704 /// that can be passed to the conversion functions (this is used by
8705 /// foreach implementation to typecast the object return value from
8706 /// get_Current into the proper type. All code has been generated and
8707 /// we only care about the side effect conversions to be performed
8709 /// This is also now used as a placeholder where a no-action expression
8710 /// is needed (the `New' class).
8712 public class EmptyExpression : Expression {
8713 public EmptyExpression ()
8715 type = TypeManager.object_type;
8716 eclass = ExprClass.Value;
8717 loc = Location.Null;
8720 public EmptyExpression (Type t)
8723 eclass = ExprClass.Value;
8724 loc = Location.Null;
8727 public override Expression DoResolve (EmitContext ec)
8732 public override void Emit (EmitContext ec)
8734 // nothing, as we only exist to not do anything.
8738 // This is just because we might want to reuse this bad boy
8739 // instead of creating gazillions of EmptyExpressions.
8740 // (CanImplicitConversion uses it)
8742 public void SetType (Type t)
8748 public class UserCast : Expression {
8752 public UserCast (MethodInfo method, Expression source, Location l)
8754 this.method = method;
8755 this.source = source;
8756 type = method.ReturnType;
8757 eclass = ExprClass.Value;
8761 public override Expression DoResolve (EmitContext ec)
8764 // We are born fully resolved
8769 public override void Emit (EmitContext ec)
8771 ILGenerator ig = ec.ig;
8775 if (method is MethodInfo)
8776 ig.Emit (OpCodes.Call, (MethodInfo) method);
8778 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
8784 // This class is used to "construct" the type during a typecast
8785 // operation. Since the Type.GetType class in .NET can parse
8786 // the type specification, we just use this to construct the type
8787 // one bit at a time.
8789 public class ComposedCast : TypeExpr {
8793 public ComposedCast (Expression left, string dim, Location l)
8800 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
8802 Type ltype = ec.DeclSpace.ResolveType (left, false, loc);
8806 if ((ltype == TypeManager.void_type) && (dim != "*")) {
8807 Report.Error (1547, Location,
8808 "Keyword 'void' cannot be used in this context");
8813 while ((pos < dim.Length) && (dim [pos] == '[')) {
8816 if (dim [pos] == ']') {
8817 ltype = ltype.MakeArrayType ();
8820 if (pos < dim.Length)
8824 eclass = ExprClass.Type;
8829 while (dim [pos] == ',') {
8833 if ((dim [pos] != ']') || (pos != dim.Length-1))
8836 type = ltype.MakeArrayType (rank + 1);
8837 eclass = ExprClass.Type;
8842 // ltype.Fullname is already fully qualified, so we can skip
8843 // a lot of probes, and go directly to TypeManager.LookupType
8845 string fname = ltype.FullName != null ? ltype.FullName : ltype.Name;
8846 string cname = fname + dim;
8847 type = TypeManager.LookupTypeDirect (cname);
8850 // For arrays of enumerations we are having a problem
8851 // with the direct lookup. Need to investigate.
8853 // For now, fall back to the full lookup in that case.
8855 TypeExpr texpr = RootContext.LookupType (
8856 ec.DeclSpace, cname, false, loc);
8861 type = texpr.ResolveType (ec);
8866 if (!ec.ResolvingTypeTree){
8868 // If the above flag is set, this is being invoked from the ResolveType function.
8869 // Upper layers take care of the type validity in this context.
8871 if (!ec.InUnsafe && type.IsPointer){
8877 eclass = ExprClass.Type;
8881 public override string Name {
8889 // This class is used to represent the address of an array, used
8890 // only by the Fixed statement, this is like the C "&a [0]" construct.
8892 public class ArrayPtr : Expression {
8895 public ArrayPtr (Expression array, Location l)
8897 Type array_type = TypeManager.GetElementType (array.Type);
8901 type = TypeManager.GetPointerType (array_type);
8902 eclass = ExprClass.Value;
8906 public override void Emit (EmitContext ec)
8908 ILGenerator ig = ec.ig;
8911 IntLiteral.EmitInt (ig, 0);
8912 ig.Emit (OpCodes.Ldelema, TypeManager.GetElementType (array.Type));
8915 public override Expression DoResolve (EmitContext ec)
8918 // We are born fully resolved
8925 // Used by the fixed statement
8927 public class StringPtr : Expression {
8930 public StringPtr (LocalBuilder b, Location l)
8933 eclass = ExprClass.Value;
8934 type = TypeManager.char_ptr_type;
8938 public override Expression DoResolve (EmitContext ec)
8940 // This should never be invoked, we are born in fully
8941 // initialized state.
8946 public override void Emit (EmitContext ec)
8948 ILGenerator ig = ec.ig;
8950 ig.Emit (OpCodes.Ldloc, b);
8951 ig.Emit (OpCodes.Conv_I);
8952 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
8953 ig.Emit (OpCodes.Add);
8958 // Implements the `stackalloc' keyword
8960 public class StackAlloc : Expression {
8965 public StackAlloc (Expression type, Expression count, Location l)
8972 public override Expression DoResolve (EmitContext ec)
8974 count = count.Resolve (ec);
8978 if (count.Type != TypeManager.int32_type){
8979 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8984 Constant c = count as Constant;
8985 // TODO: because we don't have property IsNegative
8986 if (c != null && c.ConvertToUInt () == null) {
8987 // "Cannot use a negative size with stackalloc"
8988 Report.Error_T (247, loc);
8992 if (ec.CurrentBranching.InCatch () ||
8993 ec.CurrentBranching.InFinally (true)) {
8995 "stackalloc can not be used in a catch or finally block");
8999 otype = ec.DeclSpace.ResolveType (t, false, loc);
9004 if (!TypeManager.VerifyUnManaged (otype, loc))
9007 type = TypeManager.GetPointerType (otype);
9008 eclass = ExprClass.Value;
9013 public override void Emit (EmitContext ec)
9015 int size = GetTypeSize (otype);
9016 ILGenerator ig = ec.ig;
9019 ig.Emit (OpCodes.Sizeof, otype);
9021 IntConstant.EmitInt (ig, size);
9023 ig.Emit (OpCodes.Mul);
9024 ig.Emit (OpCodes.Localloc);