2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
8 // (C) 2003, 2004 Novell, Inc.
12 namespace Mono.CSharp {
14 using System.Collections;
15 using System.Reflection;
16 using System.Reflection.Emit;
20 /// This is just a helper class, it is generated by Unary, UnaryMutator
21 /// when an overloaded method has been found. It just emits the code for a
24 public class StaticCallExpr : ExpressionStatement {
28 public StaticCallExpr (MethodInfo m, ArrayList a, Location l)
34 eclass = ExprClass.Value;
38 public override Expression DoResolve (EmitContext ec)
41 // We are born fully resolved
46 public override void Emit (EmitContext ec)
49 Invocation.EmitArguments (ec, mi, args, false, null);
51 ec.ig.Emit (OpCodes.Call, mi);
55 static public StaticCallExpr MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
56 Expression e, Location loc)
61 args = new ArrayList (1);
62 Argument a = new Argument (e, Argument.AType.Expression);
64 // We need to resolve the arguments before sending them in !
65 if (!a.Resolve (ec, loc))
69 method = Invocation.OverloadResolve (
70 ec, (MethodGroupExpr) mg, args, false, loc);
75 return new StaticCallExpr ((MethodInfo) method, args, loc);
78 public override void EmitStatement (EmitContext ec)
81 if (TypeManager.TypeToCoreType (type) != TypeManager.void_type)
82 ec.ig.Emit (OpCodes.Pop);
85 public MethodInfo Method {
90 public class ParenthesizedExpression : Expression
92 public Expression Expr;
94 public ParenthesizedExpression (Expression expr, Location loc)
100 public override Expression DoResolve (EmitContext ec)
102 Expr = Expr.Resolve (ec);
106 public override void Emit (EmitContext ec)
108 throw new Exception ("Should not happen");
113 /// Unary expressions.
117 /// Unary implements unary expressions. It derives from
118 /// ExpressionStatement becuase the pre/post increment/decrement
119 /// operators can be used in a statement context.
121 public class Unary : Expression {
122 public enum Operator : byte {
123 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
124 Indirection, AddressOf, TOP
127 public Operator Oper;
128 public Expression Expr;
130 public Unary (Operator op, Expression expr, Location loc)
138 /// Returns a stringified representation of the Operator
140 static public string OperName (Operator oper)
143 case Operator.UnaryPlus:
145 case Operator.UnaryNegation:
147 case Operator.LogicalNot:
149 case Operator.OnesComplement:
151 case Operator.AddressOf:
153 case Operator.Indirection:
157 return oper.ToString ();
160 public static readonly string [] oper_names;
164 oper_names = new string [(int)Operator.TOP];
166 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
167 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
168 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
169 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
170 oper_names [(int) Operator.Indirection] = "op_Indirection";
171 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
174 void Error23 (Type t)
177 23, "Operator " + OperName (Oper) +
178 " cannot be applied to operand of type `" +
179 TypeManager.CSharpName (t) + "'");
183 /// The result has been already resolved:
185 /// FIXME: a minus constant -128 sbyte cant be turned into a
188 static Expression TryReduceNegative (Constant expr)
192 if (expr is IntConstant)
193 e = new IntConstant (-((IntConstant) expr).Value);
194 else if (expr is UIntConstant){
195 uint value = ((UIntConstant) expr).Value;
197 if (value < 2147483649)
198 return new IntConstant (-(int)value);
200 e = new LongConstant (-value);
202 else if (expr is LongConstant)
203 e = new LongConstant (-((LongConstant) expr).Value);
204 else if (expr is ULongConstant){
205 ulong value = ((ULongConstant) expr).Value;
207 if (value < 9223372036854775809)
208 return new LongConstant(-(long)value);
210 else if (expr is FloatConstant)
211 e = new FloatConstant (-((FloatConstant) expr).Value);
212 else if (expr is DoubleConstant)
213 e = new DoubleConstant (-((DoubleConstant) expr).Value);
214 else if (expr is DecimalConstant)
215 e = new DecimalConstant (-((DecimalConstant) expr).Value);
216 else if (expr is ShortConstant)
217 e = new IntConstant (-((ShortConstant) expr).Value);
218 else if (expr is UShortConstant)
219 e = new IntConstant (-((UShortConstant) expr).Value);
220 else if (expr is SByteConstant)
221 e = new IntConstant (-((SByteConstant) expr).Value);
222 else if (expr is ByteConstant)
223 e = new IntConstant (-((ByteConstant) expr).Value);
228 // This routine will attempt to simplify the unary expression when the
229 // argument is a constant. The result is returned in `result' and the
230 // function returns true or false depending on whether a reduction
231 // was performed or not
233 bool Reduce (EmitContext ec, Constant e, out Expression result)
235 Type expr_type = e.Type;
238 case Operator.UnaryPlus:
242 case Operator.UnaryNegation:
243 result = TryReduceNegative (e);
244 return result != null;
246 case Operator.LogicalNot:
247 if (expr_type != TypeManager.bool_type) {
253 BoolConstant b = (BoolConstant) e;
254 result = new BoolConstant (!(b.Value));
257 case Operator.OnesComplement:
258 if (!((expr_type == TypeManager.int32_type) ||
259 (expr_type == TypeManager.uint32_type) ||
260 (expr_type == TypeManager.int64_type) ||
261 (expr_type == TypeManager.uint64_type) ||
262 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
265 if (Convert.ImplicitConversionExists (ec, e, TypeManager.int32_type)){
266 result = new Cast (new TypeExpression (TypeManager.int32_type, loc), e, loc);
267 result = result.Resolve (ec);
268 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint32_type)){
269 result = new Cast (new TypeExpression (TypeManager.uint32_type, loc), e, loc);
270 result = result.Resolve (ec);
271 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.int64_type)){
272 result = new Cast (new TypeExpression (TypeManager.int64_type, loc), e, loc);
273 result = result.Resolve (ec);
274 } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint64_type)){
275 result = new Cast (new TypeExpression (TypeManager.uint64_type, loc), e, loc);
276 result = result.Resolve (ec);
279 if (result == null || !(result is Constant)){
285 expr_type = result.Type;
286 e = (Constant) result;
289 if (e is EnumConstant){
290 EnumConstant enum_constant = (EnumConstant) e;
293 if (Reduce (ec, enum_constant.Child, out reduced)){
294 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
302 if (expr_type == TypeManager.int32_type){
303 result = new IntConstant (~ ((IntConstant) e).Value);
304 } else if (expr_type == TypeManager.uint32_type){
305 result = new UIntConstant (~ ((UIntConstant) e).Value);
306 } else if (expr_type == TypeManager.int64_type){
307 result = new LongConstant (~ ((LongConstant) e).Value);
308 } else if (expr_type == TypeManager.uint64_type){
309 result = new ULongConstant (~ ((ULongConstant) e).Value);
317 case Operator.AddressOf:
321 case Operator.Indirection:
325 throw new Exception ("Can not constant fold: " + Oper.ToString());
328 Expression ResolveOperator (EmitContext ec)
331 // Step 1: Default operations on CLI native types.
334 // Attempt to use a constant folding operation.
335 if (Expr is Constant){
338 if (Reduce (ec, (Constant) Expr, out result))
343 // Step 2: Perform Operator Overload location
345 Type expr_type = Expr.Type;
349 op_name = oper_names [(int) Oper];
351 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
354 Expression e = StaticCallExpr.MakeSimpleCall (
355 ec, (MethodGroupExpr) mg, Expr, loc);
365 // Only perform numeric promotions on:
368 if (expr_type == null)
372 case Operator.LogicalNot:
373 if (expr_type != TypeManager.bool_type) {
374 Expr = ResolveBoolean (ec, Expr, loc);
381 type = TypeManager.bool_type;
384 case Operator.OnesComplement:
385 if (!((expr_type == TypeManager.int32_type) ||
386 (expr_type == TypeManager.uint32_type) ||
387 (expr_type == TypeManager.int64_type) ||
388 (expr_type == TypeManager.uint64_type) ||
389 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
392 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
394 type = TypeManager.int32_type;
397 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint32_type, loc);
399 type = TypeManager.uint32_type;
402 e = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
404 type = TypeManager.int64_type;
407 e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint64_type, loc);
409 type = TypeManager.uint64_type;
418 case Operator.AddressOf:
424 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
428 IVariable variable = Expr as IVariable;
429 bool is_fixed = variable != null && variable.VerifyFixed (false);
431 if (!ec.InFixedInitializer && !is_fixed) {
432 Error (212, "You can only take the address of an unfixed expression inside " +
433 "of a fixed statement initializer");
437 if (ec.InFixedInitializer && is_fixed) {
438 Error (213, "You can not fix an already fixed expression");
442 LocalVariableReference lr = Expr as LocalVariableReference;
444 if (lr.local_info.IsCaptured){
445 AnonymousMethod.Error_AddressOfCapturedVar (lr.Name, loc);
448 lr.local_info.AddressTaken = true;
449 lr.local_info.Used = true;
452 // According to the specs, a variable is considered definitely assigned if you take
454 if ((variable != null) && (variable.VariableInfo != null)){
455 variable.VariableInfo.SetAssigned (ec);
458 type = TypeManager.GetPointerType (Expr.Type);
461 case Operator.Indirection:
467 if (!expr_type.IsPointer){
468 Error (193, "The * or -> operator can only be applied to pointers");
473 // We create an Indirection expression, because
474 // it can implement the IMemoryLocation.
476 return new Indirection (Expr, loc);
478 case Operator.UnaryPlus:
480 // A plus in front of something is just a no-op, so return the child.
484 case Operator.UnaryNegation:
486 // Deals with -literals
487 // int operator- (int x)
488 // long operator- (long x)
489 // float operator- (float f)
490 // double operator- (double d)
491 // decimal operator- (decimal d)
493 Expression expr = null;
496 // transform - - expr into expr
499 Unary unary = (Unary) Expr;
501 if (unary.Oper == Operator.UnaryNegation)
506 // perform numeric promotions to int,
510 // The following is inneficient, because we call
511 // ImplicitConversion too many times.
513 // It is also not clear if we should convert to Float
514 // or Double initially.
516 if (expr_type == TypeManager.uint32_type){
518 // FIXME: handle exception to this rule that
519 // permits the int value -2147483648 (-2^31) to
520 // bt wrote as a decimal interger literal
522 type = TypeManager.int64_type;
523 Expr = Convert.ImplicitConversion (ec, Expr, type, loc);
527 if (expr_type == TypeManager.uint64_type){
529 // FIXME: Handle exception of `long value'
530 // -92233720368547758087 (-2^63) to be wrote as
531 // decimal integer literal.
537 if (expr_type == TypeManager.float_type){
542 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
549 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
556 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.double_type, loc);
567 Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
568 TypeManager.CSharpName (expr_type) + "'");
572 public override Expression DoResolve (EmitContext ec)
574 if (Oper == Operator.AddressOf) {
575 Expr = Expr.DoResolveLValue (ec, new EmptyExpression ());
577 if (Expr == null || Expr.eclass != ExprClass.Variable){
578 Error (211, "Cannot take the address of non-variables");
583 Expr = Expr.Resolve (ec);
588 eclass = ExprClass.Value;
589 return ResolveOperator (ec);
592 public override Expression DoResolveLValue (EmitContext ec, Expression right)
594 if (Oper == Operator.Indirection)
595 return DoResolve (ec);
600 public override void Emit (EmitContext ec)
602 ILGenerator ig = ec.ig;
605 case Operator.UnaryPlus:
606 throw new Exception ("This should be caught by Resolve");
608 case Operator.UnaryNegation:
610 ig.Emit (OpCodes.Ldc_I4_0);
611 if (type == TypeManager.int64_type)
612 ig.Emit (OpCodes.Conv_U8);
614 ig.Emit (OpCodes.Sub_Ovf);
617 ig.Emit (OpCodes.Neg);
622 case Operator.LogicalNot:
624 ig.Emit (OpCodes.Ldc_I4_0);
625 ig.Emit (OpCodes.Ceq);
628 case Operator.OnesComplement:
630 ig.Emit (OpCodes.Not);
633 case Operator.AddressOf:
634 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
638 throw new Exception ("This should not happen: Operator = "
643 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
645 if (Oper == Operator.LogicalNot)
646 Expr.EmitBranchable (ec, target, !onTrue);
648 base.EmitBranchable (ec, target, onTrue);
651 public override string ToString ()
653 return "Unary (" + Oper + ", " + Expr + ")";
659 // Unary operators are turned into Indirection expressions
660 // after semantic analysis (this is so we can take the address
661 // of an indirection).
663 public class Indirection : Expression, IMemoryLocation, IAssignMethod, IVariable {
665 LocalTemporary temporary;
668 public Indirection (Expression expr, Location l)
671 type = TypeManager.HasElementType (expr.Type) ? TypeManager.GetElementType (expr.Type) : expr.Type;
672 eclass = ExprClass.Variable;
676 void LoadExprValue (EmitContext ec)
680 public override void Emit (EmitContext ec)
685 LoadFromPtr (ec.ig, Type);
688 public void Emit (EmitContext ec, bool leave_copy)
692 ec.ig.Emit (OpCodes.Dup);
693 temporary = new LocalTemporary (ec, expr.Type);
694 temporary.Store (ec);
698 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
700 prepared = prepare_for_load;
704 if (prepare_for_load)
705 ec.ig.Emit (OpCodes.Dup);
709 ec.ig.Emit (OpCodes.Dup);
710 temporary = new LocalTemporary (ec, expr.Type);
711 temporary.Store (ec);
714 StoreFromPtr (ec.ig, type);
716 if (temporary != null)
720 public void AddressOf (EmitContext ec, AddressOp Mode)
725 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
727 return DoResolve (ec);
730 public override Expression DoResolve (EmitContext ec)
733 // Born fully resolved
738 public override string ToString ()
740 return "*(" + expr + ")";
743 #region IVariable Members
745 public VariableInfo VariableInfo {
751 public bool VerifyFixed (bool is_expression)
760 /// Unary Mutator expressions (pre and post ++ and --)
764 /// UnaryMutator implements ++ and -- expressions. It derives from
765 /// ExpressionStatement becuase the pre/post increment/decrement
766 /// operators can be used in a statement context.
768 /// FIXME: Idea, we could split this up in two classes, one simpler
769 /// for the common case, and one with the extra fields for more complex
770 /// classes (indexers require temporary access; overloaded require method)
773 public class UnaryMutator : ExpressionStatement {
775 public enum Mode : byte {
782 PreDecrement = IsDecrement,
783 PostIncrement = IsPost,
784 PostDecrement = IsPost | IsDecrement
788 bool is_expr = false;
789 bool recurse = false;
794 // This is expensive for the simplest case.
796 StaticCallExpr method;
798 public UnaryMutator (Mode m, Expression e, Location l)
805 static string OperName (Mode mode)
807 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
811 void Error23 (Type t)
814 23, "Operator " + OperName (mode) +
815 " cannot be applied to operand of type `" +
816 TypeManager.CSharpName (t) + "'");
820 /// Returns whether an object of type `t' can be incremented
821 /// or decremented with add/sub (ie, basically whether we can
822 /// use pre-post incr-decr operations on it, but it is not a
823 /// System.Decimal, which we require operator overloading to catch)
825 static bool IsIncrementableNumber (Type t)
827 return (t == TypeManager.sbyte_type) ||
828 (t == TypeManager.byte_type) ||
829 (t == TypeManager.short_type) ||
830 (t == TypeManager.ushort_type) ||
831 (t == TypeManager.int32_type) ||
832 (t == TypeManager.uint32_type) ||
833 (t == TypeManager.int64_type) ||
834 (t == TypeManager.uint64_type) ||
835 (t == TypeManager.char_type) ||
836 (t.IsSubclassOf (TypeManager.enum_type)) ||
837 (t == TypeManager.float_type) ||
838 (t == TypeManager.double_type) ||
839 (t.IsPointer && t != TypeManager.void_ptr_type);
842 Expression ResolveOperator (EmitContext ec)
844 Type expr_type = expr.Type;
847 // Step 1: Perform Operator Overload location
852 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
853 op_name = "op_Increment";
855 op_name = "op_Decrement";
857 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
860 method = StaticCallExpr.MakeSimpleCall (
861 ec, (MethodGroupExpr) mg, expr, loc);
864 } else if (!IsIncrementableNumber (expr_type)) {
865 Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
866 TypeManager.CSharpName (expr_type) + "'");
871 // The operand of the prefix/postfix increment decrement operators
872 // should be an expression that is classified as a variable,
873 // a property access or an indexer access
876 if (expr.eclass == ExprClass.Variable){
877 LocalVariableReference var = expr as LocalVariableReference;
878 if ((var != null) && var.IsReadOnly) {
879 Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
882 } else if (expr.eclass == ExprClass.IndexerAccess || expr.eclass == ExprClass.PropertyAccess){
883 expr = expr.ResolveLValue (ec, this);
887 expr.Error_UnexpectedKind ("variable, indexer or property access", loc);
894 public override Expression DoResolve (EmitContext ec)
896 expr = expr.Resolve (ec);
901 eclass = ExprClass.Value;
902 return ResolveOperator (ec);
905 static int PtrTypeSize (Type t)
907 return GetTypeSize (TypeManager.GetElementType (t));
911 // Loads the proper "1" into the stack based on the type, then it emits the
912 // opcode for the operation requested
914 void LoadOneAndEmitOp (EmitContext ec, Type t)
917 // Measure if getting the typecode and using that is more/less efficient
918 // that comparing types. t.GetTypeCode() is an internal call.
920 ILGenerator ig = ec.ig;
922 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
923 LongConstant.EmitLong (ig, 1);
924 else if (t == TypeManager.double_type)
925 ig.Emit (OpCodes.Ldc_R8, 1.0);
926 else if (t == TypeManager.float_type)
927 ig.Emit (OpCodes.Ldc_R4, 1.0F);
928 else if (t.IsPointer){
929 int n = PtrTypeSize (t);
932 ig.Emit (OpCodes.Sizeof, t);
934 IntConstant.EmitInt (ig, n);
936 ig.Emit (OpCodes.Ldc_I4_1);
939 // Now emit the operation
942 if (t == TypeManager.int32_type ||
943 t == TypeManager.int64_type){
944 if ((mode & Mode.IsDecrement) != 0)
945 ig.Emit (OpCodes.Sub_Ovf);
947 ig.Emit (OpCodes.Add_Ovf);
948 } else if (t == TypeManager.uint32_type ||
949 t == TypeManager.uint64_type){
950 if ((mode & Mode.IsDecrement) != 0)
951 ig.Emit (OpCodes.Sub_Ovf_Un);
953 ig.Emit (OpCodes.Add_Ovf_Un);
955 if ((mode & Mode.IsDecrement) != 0)
956 ig.Emit (OpCodes.Sub_Ovf);
958 ig.Emit (OpCodes.Add_Ovf);
961 if ((mode & Mode.IsDecrement) != 0)
962 ig.Emit (OpCodes.Sub);
964 ig.Emit (OpCodes.Add);
967 if (t == TypeManager.sbyte_type){
969 ig.Emit (OpCodes.Conv_Ovf_I1);
971 ig.Emit (OpCodes.Conv_I1);
972 } else if (t == TypeManager.byte_type){
974 ig.Emit (OpCodes.Conv_Ovf_U1);
976 ig.Emit (OpCodes.Conv_U1);
977 } else if (t == TypeManager.short_type){
979 ig.Emit (OpCodes.Conv_Ovf_I2);
981 ig.Emit (OpCodes.Conv_I2);
982 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
984 ig.Emit (OpCodes.Conv_Ovf_U2);
986 ig.Emit (OpCodes.Conv_U2);
991 void EmitCode (EmitContext ec, bool is_expr)
994 this.is_expr = is_expr;
995 ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
999 public override void Emit (EmitContext ec)
1002 // We use recurse to allow ourselfs to be the source
1003 // of an assignment. This little hack prevents us from
1004 // having to allocate another expression
1007 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
1009 LoadOneAndEmitOp (ec, expr.Type);
1011 ec.ig.Emit (OpCodes.Call, method.Method);
1016 EmitCode (ec, true);
1019 public override void EmitStatement (EmitContext ec)
1021 EmitCode (ec, false);
1026 /// Base class for the `Is' and `As' classes.
1030 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1033 public abstract class Probe : Expression {
1034 public Expression ProbeType;
1035 protected Expression expr;
1036 protected Type probe_type;
1038 public Probe (Expression expr, Expression probe_type, Location l)
1040 ProbeType = probe_type;
1045 public Expression Expr {
1051 public override Expression DoResolve (EmitContext ec)
1053 TypeExpr texpr = ProbeType.ResolveAsTypeTerminal (ec, false);
1056 probe_type = texpr.ResolveType (ec);
1058 CheckObsoleteAttribute (probe_type);
1060 expr = expr.Resolve (ec);
1064 if (expr.Type.IsPointer) {
1065 Report.Error (244, loc, "\"is\" or \"as\" are not valid on pointer types");
1073 /// Implementation of the `is' operator.
1075 public class Is : Probe {
1076 public Is (Expression expr, Expression probe_type, Location l)
1077 : base (expr, probe_type, l)
1082 AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1087 public override void Emit (EmitContext ec)
1089 ILGenerator ig = ec.ig;
1094 case Action.AlwaysFalse:
1095 ig.Emit (OpCodes.Pop);
1096 IntConstant.EmitInt (ig, 0);
1098 case Action.AlwaysTrue:
1099 ig.Emit (OpCodes.Pop);
1100 IntConstant.EmitInt (ig, 1);
1102 case Action.LeaveOnStack:
1103 // the `e != null' rule.
1104 ig.Emit (OpCodes.Ldnull);
1105 ig.Emit (OpCodes.Ceq);
1106 ig.Emit (OpCodes.Ldc_I4_0);
1107 ig.Emit (OpCodes.Ceq);
1110 ig.Emit (OpCodes.Isinst, probe_type);
1111 ig.Emit (OpCodes.Ldnull);
1112 ig.Emit (OpCodes.Cgt_Un);
1115 throw new Exception ("never reached");
1118 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
1120 ILGenerator ig = ec.ig;
1123 case Action.AlwaysFalse:
1125 ig.Emit (OpCodes.Br, target);
1128 case Action.AlwaysTrue:
1130 ig.Emit (OpCodes.Br, target);
1133 case Action.LeaveOnStack:
1134 // the `e != null' rule.
1136 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1140 ig.Emit (OpCodes.Isinst, probe_type);
1141 ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1144 throw new Exception ("never reached");
1147 public override Expression DoResolve (EmitContext ec)
1149 Expression e = base.DoResolve (ec);
1151 if ((e == null) || (expr == null))
1154 Type etype = expr.Type;
1155 bool warning_always_matches = false;
1156 bool warning_never_matches = false;
1158 type = TypeManager.bool_type;
1159 eclass = ExprClass.Value;
1162 // First case, if at compile time, there is an implicit conversion
1163 // then e != null (objects) or true (value types)
1165 e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1168 if (etype.IsValueType)
1169 action = Action.AlwaysTrue;
1171 action = Action.LeaveOnStack;
1173 warning_always_matches = true;
1174 } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1176 // Second case: explicit reference convresion
1178 if (expr is NullLiteral)
1179 action = Action.AlwaysFalse;
1181 action = Action.Probe;
1183 action = Action.AlwaysFalse;
1184 warning_never_matches = true;
1187 if (warning_always_matches)
1188 Warning (183, "The given expression is always of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1189 else if (warning_never_matches){
1190 if (!(probe_type.IsInterface || expr.Type.IsInterface))
1191 Warning (184, "The given expression is never of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
1199 /// Implementation of the `as' operator.
1201 public class As : Probe {
1202 public As (Expression expr, Expression probe_type, Location l)
1203 : base (expr, probe_type, l)
1207 bool do_isinst = false;
1209 public override void Emit (EmitContext ec)
1211 ILGenerator ig = ec.ig;
1216 ig.Emit (OpCodes.Isinst, probe_type);
1219 static void Error_CannotConvertType (Type source, Type target, Location loc)
1222 39, loc, "as operator can not convert from `" +
1223 TypeManager.CSharpName (source) + "' to `" +
1224 TypeManager.CSharpName (target) + "'");
1227 public override Expression DoResolve (EmitContext ec)
1229 Expression e = base.DoResolve (ec);
1235 eclass = ExprClass.Value;
1236 Type etype = expr.Type;
1238 if (TypeManager.IsValueType (probe_type)){
1239 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1240 TypeManager.CSharpName (probe_type) + " is a value type)");
1245 e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1252 if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1257 Error_CannotConvertType (etype, probe_type, loc);
1263 /// This represents a typecast in the source language.
1265 /// FIXME: Cast expressions have an unusual set of parsing
1266 /// rules, we need to figure those out.
1268 public class Cast : Expression {
1269 Expression target_type;
1272 public Cast (Expression cast_type, Expression expr, Location loc)
1274 this.target_type = cast_type;
1279 public Expression TargetType {
1285 public Expression Expr {
1294 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1296 if (!ec.ConstantCheckState)
1299 if ((value < min) || (value > max)) {
1300 Error (221, "Constant value `" + value + "' cannot be converted " +
1301 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1302 "syntax to override)");
1309 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1311 if (!ec.ConstantCheckState)
1315 Error (221, "Constant value `" + value + "' cannot be converted " +
1316 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1317 "syntax to override)");
1324 bool CheckUnsigned (EmitContext ec, long value, Type type)
1326 if (!ec.ConstantCheckState)
1330 Error (221, "Constant value `" + value + "' cannot be converted " +
1331 "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1332 "syntax to override)");
1340 /// Attempts to do a compile-time folding of a constant cast.
1342 Expression TryReduce (EmitContext ec, Type target_type)
1344 Expression real_expr = expr;
1345 if (real_expr is EnumConstant)
1346 real_expr = ((EnumConstant) real_expr).Child;
1348 if (real_expr is ByteConstant){
1349 byte v = ((ByteConstant) real_expr).Value;
1351 if (target_type == TypeManager.sbyte_type) {
1352 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1354 return new SByteConstant ((sbyte) v);
1356 if (target_type == TypeManager.short_type)
1357 return new ShortConstant ((short) v);
1358 if (target_type == TypeManager.ushort_type)
1359 return new UShortConstant ((ushort) v);
1360 if (target_type == TypeManager.int32_type)
1361 return new IntConstant ((int) v);
1362 if (target_type == TypeManager.uint32_type)
1363 return new UIntConstant ((uint) v);
1364 if (target_type == TypeManager.int64_type)
1365 return new LongConstant ((long) v);
1366 if (target_type == TypeManager.uint64_type)
1367 return new ULongConstant ((ulong) v);
1368 if (target_type == TypeManager.float_type)
1369 return new FloatConstant ((float) v);
1370 if (target_type == TypeManager.double_type)
1371 return new DoubleConstant ((double) v);
1372 if (target_type == TypeManager.char_type)
1373 return new CharConstant ((char) v);
1374 if (target_type == TypeManager.decimal_type)
1375 return new DecimalConstant ((decimal) v);
1377 if (real_expr is SByteConstant){
1378 sbyte v = ((SByteConstant) real_expr).Value;
1380 if (target_type == TypeManager.byte_type) {
1381 if (!CheckUnsigned (ec, v, target_type))
1383 return new ByteConstant ((byte) v);
1385 if (target_type == TypeManager.short_type)
1386 return new ShortConstant ((short) v);
1387 if (target_type == TypeManager.ushort_type) {
1388 if (!CheckUnsigned (ec, v, target_type))
1390 return new UShortConstant ((ushort) v);
1391 } if (target_type == TypeManager.int32_type)
1392 return new IntConstant ((int) v);
1393 if (target_type == TypeManager.uint32_type) {
1394 if (!CheckUnsigned (ec, v, target_type))
1396 return new UIntConstant ((uint) v);
1397 } if (target_type == TypeManager.int64_type)
1398 return new LongConstant ((long) v);
1399 if (target_type == TypeManager.uint64_type) {
1400 if (!CheckUnsigned (ec, v, target_type))
1402 return new ULongConstant ((ulong) v);
1404 if (target_type == TypeManager.float_type)
1405 return new FloatConstant ((float) v);
1406 if (target_type == TypeManager.double_type)
1407 return new DoubleConstant ((double) v);
1408 if (target_type == TypeManager.char_type) {
1409 if (!CheckUnsigned (ec, v, target_type))
1411 return new CharConstant ((char) v);
1413 if (target_type == TypeManager.decimal_type)
1414 return new DecimalConstant ((decimal) v);
1416 if (real_expr is ShortConstant){
1417 short v = ((ShortConstant) real_expr).Value;
1419 if (target_type == TypeManager.byte_type) {
1420 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1422 return new ByteConstant ((byte) v);
1424 if (target_type == TypeManager.sbyte_type) {
1425 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1427 return new SByteConstant ((sbyte) v);
1429 if (target_type == TypeManager.ushort_type) {
1430 if (!CheckUnsigned (ec, v, target_type))
1432 return new UShortConstant ((ushort) v);
1434 if (target_type == TypeManager.int32_type)
1435 return new IntConstant ((int) v);
1436 if (target_type == TypeManager.uint32_type) {
1437 if (!CheckUnsigned (ec, v, target_type))
1439 return new UIntConstant ((uint) v);
1441 if (target_type == TypeManager.int64_type)
1442 return new LongConstant ((long) v);
1443 if (target_type == TypeManager.uint64_type) {
1444 if (!CheckUnsigned (ec, v, target_type))
1446 return new ULongConstant ((ulong) v);
1448 if (target_type == TypeManager.float_type)
1449 return new FloatConstant ((float) v);
1450 if (target_type == TypeManager.double_type)
1451 return new DoubleConstant ((double) v);
1452 if (target_type == TypeManager.char_type) {
1453 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1455 return new CharConstant ((char) v);
1457 if (target_type == TypeManager.decimal_type)
1458 return new DecimalConstant ((decimal) v);
1460 if (real_expr is UShortConstant){
1461 ushort v = ((UShortConstant) real_expr).Value;
1463 if (target_type == TypeManager.byte_type) {
1464 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1466 return new ByteConstant ((byte) v);
1468 if (target_type == TypeManager.sbyte_type) {
1469 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1471 return new SByteConstant ((sbyte) v);
1473 if (target_type == TypeManager.short_type) {
1474 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1476 return new ShortConstant ((short) v);
1478 if (target_type == TypeManager.int32_type)
1479 return new IntConstant ((int) v);
1480 if (target_type == TypeManager.uint32_type)
1481 return new UIntConstant ((uint) v);
1482 if (target_type == TypeManager.int64_type)
1483 return new LongConstant ((long) v);
1484 if (target_type == TypeManager.uint64_type)
1485 return new ULongConstant ((ulong) v);
1486 if (target_type == TypeManager.float_type)
1487 return new FloatConstant ((float) v);
1488 if (target_type == TypeManager.double_type)
1489 return new DoubleConstant ((double) v);
1490 if (target_type == TypeManager.char_type) {
1491 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1493 return new CharConstant ((char) v);
1495 if (target_type == TypeManager.decimal_type)
1496 return new DecimalConstant ((decimal) v);
1498 if (real_expr is IntConstant){
1499 int v = ((IntConstant) real_expr).Value;
1501 if (target_type == TypeManager.byte_type) {
1502 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1504 return new ByteConstant ((byte) v);
1506 if (target_type == TypeManager.sbyte_type) {
1507 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1509 return new SByteConstant ((sbyte) v);
1511 if (target_type == TypeManager.short_type) {
1512 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1514 return new ShortConstant ((short) v);
1516 if (target_type == TypeManager.ushort_type) {
1517 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1519 return new UShortConstant ((ushort) v);
1521 if (target_type == TypeManager.uint32_type) {
1522 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1524 return new UIntConstant ((uint) v);
1526 if (target_type == TypeManager.int64_type)
1527 return new LongConstant ((long) v);
1528 if (target_type == TypeManager.uint64_type) {
1529 if (!CheckUnsigned (ec, v, target_type))
1531 return new ULongConstant ((ulong) v);
1533 if (target_type == TypeManager.float_type)
1534 return new FloatConstant ((float) v);
1535 if (target_type == TypeManager.double_type)
1536 return new DoubleConstant ((double) v);
1537 if (target_type == TypeManager.char_type) {
1538 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1540 return new CharConstant ((char) v);
1542 if (target_type == TypeManager.decimal_type)
1543 return new DecimalConstant ((decimal) v);
1545 if (real_expr is UIntConstant){
1546 uint v = ((UIntConstant) real_expr).Value;
1548 if (target_type == TypeManager.byte_type) {
1549 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1551 return new ByteConstant ((byte) v);
1553 if (target_type == TypeManager.sbyte_type) {
1554 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1556 return new SByteConstant ((sbyte) v);
1558 if (target_type == TypeManager.short_type) {
1559 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1561 return new ShortConstant ((short) v);
1563 if (target_type == TypeManager.ushort_type) {
1564 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1566 return new UShortConstant ((ushort) v);
1568 if (target_type == TypeManager.int32_type) {
1569 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1571 return new IntConstant ((int) v);
1573 if (target_type == TypeManager.int64_type)
1574 return new LongConstant ((long) v);
1575 if (target_type == TypeManager.uint64_type)
1576 return new ULongConstant ((ulong) v);
1577 if (target_type == TypeManager.float_type)
1578 return new FloatConstant ((float) v);
1579 if (target_type == TypeManager.double_type)
1580 return new DoubleConstant ((double) v);
1581 if (target_type == TypeManager.char_type) {
1582 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1584 return new CharConstant ((char) v);
1586 if (target_type == TypeManager.decimal_type)
1587 return new DecimalConstant ((decimal) v);
1589 if (real_expr is LongConstant){
1590 long v = ((LongConstant) real_expr).Value;
1592 if (target_type == TypeManager.byte_type) {
1593 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1595 return new ByteConstant ((byte) v);
1597 if (target_type == TypeManager.sbyte_type) {
1598 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1600 return new SByteConstant ((sbyte) v);
1602 if (target_type == TypeManager.short_type) {
1603 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1605 return new ShortConstant ((short) v);
1607 if (target_type == TypeManager.ushort_type) {
1608 if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1610 return new UShortConstant ((ushort) v);
1612 if (target_type == TypeManager.int32_type) {
1613 if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1615 return new IntConstant ((int) v);
1617 if (target_type == TypeManager.uint32_type) {
1618 if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1620 return new UIntConstant ((uint) v);
1622 if (target_type == TypeManager.uint64_type) {
1623 if (!CheckUnsigned (ec, v, target_type))
1625 return new ULongConstant ((ulong) v);
1627 if (target_type == TypeManager.float_type)
1628 return new FloatConstant ((float) v);
1629 if (target_type == TypeManager.double_type)
1630 return new DoubleConstant ((double) v);
1631 if (target_type == TypeManager.char_type) {
1632 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1634 return new CharConstant ((char) v);
1636 if (target_type == TypeManager.decimal_type)
1637 return new DecimalConstant ((decimal) v);
1639 if (real_expr is ULongConstant){
1640 ulong v = ((ULongConstant) real_expr).Value;
1642 if (target_type == TypeManager.byte_type) {
1643 if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1645 return new ByteConstant ((byte) v);
1647 if (target_type == TypeManager.sbyte_type) {
1648 if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1650 return new SByteConstant ((sbyte) v);
1652 if (target_type == TypeManager.short_type) {
1653 if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1655 return new ShortConstant ((short) v);
1657 if (target_type == TypeManager.ushort_type) {
1658 if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1660 return new UShortConstant ((ushort) v);
1662 if (target_type == TypeManager.int32_type) {
1663 if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1665 return new IntConstant ((int) v);
1667 if (target_type == TypeManager.uint32_type) {
1668 if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1670 return new UIntConstant ((uint) v);
1672 if (target_type == TypeManager.int64_type) {
1673 if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1675 return new LongConstant ((long) v);
1677 if (target_type == TypeManager.float_type)
1678 return new FloatConstant ((float) v);
1679 if (target_type == TypeManager.double_type)
1680 return new DoubleConstant ((double) v);
1681 if (target_type == TypeManager.char_type) {
1682 if (!CheckRange (ec, v, target_type, Char.MaxValue))
1684 return new CharConstant ((char) v);
1686 if (target_type == TypeManager.decimal_type)
1687 return new DecimalConstant ((decimal) v);
1689 if (real_expr is FloatConstant){
1690 float v = ((FloatConstant) real_expr).Value;
1692 if (target_type == TypeManager.byte_type)
1693 return new ByteConstant ((byte) v);
1694 if (target_type == TypeManager.sbyte_type)
1695 return new SByteConstant ((sbyte) v);
1696 if (target_type == TypeManager.short_type)
1697 return new ShortConstant ((short) v);
1698 if (target_type == TypeManager.ushort_type)
1699 return new UShortConstant ((ushort) v);
1700 if (target_type == TypeManager.int32_type)
1701 return new IntConstant ((int) v);
1702 if (target_type == TypeManager.uint32_type)
1703 return new UIntConstant ((uint) v);
1704 if (target_type == TypeManager.int64_type)
1705 return new LongConstant ((long) v);
1706 if (target_type == TypeManager.uint64_type)
1707 return new ULongConstant ((ulong) v);
1708 if (target_type == TypeManager.double_type)
1709 return new DoubleConstant ((double) v);
1710 if (target_type == TypeManager.char_type)
1711 return new CharConstant ((char) v);
1712 if (target_type == TypeManager.decimal_type)
1713 return new DecimalConstant ((decimal) v);
1715 if (real_expr is DoubleConstant){
1716 double v = ((DoubleConstant) real_expr).Value;
1718 if (target_type == TypeManager.byte_type){
1719 return new ByteConstant ((byte) v);
1720 } if (target_type == TypeManager.sbyte_type)
1721 return new SByteConstant ((sbyte) v);
1722 if (target_type == TypeManager.short_type)
1723 return new ShortConstant ((short) v);
1724 if (target_type == TypeManager.ushort_type)
1725 return new UShortConstant ((ushort) v);
1726 if (target_type == TypeManager.int32_type)
1727 return new IntConstant ((int) v);
1728 if (target_type == TypeManager.uint32_type)
1729 return new UIntConstant ((uint) v);
1730 if (target_type == TypeManager.int64_type)
1731 return new LongConstant ((long) v);
1732 if (target_type == TypeManager.uint64_type)
1733 return new ULongConstant ((ulong) v);
1734 if (target_type == TypeManager.float_type)
1735 return new FloatConstant ((float) v);
1736 if (target_type == TypeManager.char_type)
1737 return new CharConstant ((char) v);
1738 if (target_type == TypeManager.decimal_type)
1739 return new DecimalConstant ((decimal) v);
1742 if (real_expr is CharConstant){
1743 char v = ((CharConstant) real_expr).Value;
1745 if (target_type == TypeManager.byte_type) {
1746 if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1748 return new ByteConstant ((byte) v);
1750 if (target_type == TypeManager.sbyte_type) {
1751 if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1753 return new SByteConstant ((sbyte) v);
1755 if (target_type == TypeManager.short_type) {
1756 if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1758 return new ShortConstant ((short) v);
1760 if (target_type == TypeManager.int32_type)
1761 return new IntConstant ((int) v);
1762 if (target_type == TypeManager.uint32_type)
1763 return new UIntConstant ((uint) v);
1764 if (target_type == TypeManager.int64_type)
1765 return new LongConstant ((long) v);
1766 if (target_type == TypeManager.uint64_type)
1767 return new ULongConstant ((ulong) v);
1768 if (target_type == TypeManager.float_type)
1769 return new FloatConstant ((float) v);
1770 if (target_type == TypeManager.double_type)
1771 return new DoubleConstant ((double) v);
1772 if (target_type == TypeManager.char_type) {
1773 if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1775 return new CharConstant ((char) v);
1777 if (target_type == TypeManager.decimal_type)
1778 return new DecimalConstant ((decimal) v);
1784 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1786 expr = expr.DoResolveLValue (ec, right_side);
1790 return ResolveRest (ec);
1793 public override Expression DoResolve (EmitContext ec)
1795 expr = expr.Resolve (ec);
1799 return ResolveRest (ec);
1802 Expression ResolveRest (EmitContext ec)
1804 TypeExpr target = target_type.ResolveAsTypeTerminal (ec, false);
1808 type = target.ResolveType (ec);
1810 CheckObsoleteAttribute (type);
1812 if (type.IsAbstract && type.IsSealed) {
1813 Report.Error (716, loc, "Cannot convert to static type '{0}'", TypeManager.CSharpName (type));
1817 eclass = ExprClass.Value;
1819 if (expr is Constant){
1820 Expression e = TryReduce (ec, type);
1826 if (type.IsPointer && !ec.InUnsafe) {
1830 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1834 public override void Emit (EmitContext ec)
1837 // This one will never happen
1839 throw new Exception ("Should not happen");
1844 /// Binary operators
1846 public class Binary : Expression {
1847 public enum Operator : byte {
1848 Multiply, Division, Modulus,
1849 Addition, Subtraction,
1850 LeftShift, RightShift,
1851 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1852 Equality, Inequality,
1862 Expression left, right;
1864 // This must be kept in sync with Operator!!!
1865 public static readonly string [] oper_names;
1869 oper_names = new string [(int) Operator.TOP];
1871 oper_names [(int) Operator.Multiply] = "op_Multiply";
1872 oper_names [(int) Operator.Division] = "op_Division";
1873 oper_names [(int) Operator.Modulus] = "op_Modulus";
1874 oper_names [(int) Operator.Addition] = "op_Addition";
1875 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1876 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1877 oper_names [(int) Operator.RightShift] = "op_RightShift";
1878 oper_names [(int) Operator.LessThan] = "op_LessThan";
1879 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1880 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1881 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1882 oper_names [(int) Operator.Equality] = "op_Equality";
1883 oper_names [(int) Operator.Inequality] = "op_Inequality";
1884 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1885 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1886 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1887 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1888 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1891 public Binary (Operator oper, Expression left, Expression right, Location loc)
1899 public Operator Oper {
1908 public Expression Left {
1917 public Expression Right {
1928 /// Returns a stringified representation of the Operator
1930 static string OperName (Operator oper)
1933 case Operator.Multiply:
1935 case Operator.Division:
1937 case Operator.Modulus:
1939 case Operator.Addition:
1941 case Operator.Subtraction:
1943 case Operator.LeftShift:
1945 case Operator.RightShift:
1947 case Operator.LessThan:
1949 case Operator.GreaterThan:
1951 case Operator.LessThanOrEqual:
1953 case Operator.GreaterThanOrEqual:
1955 case Operator.Equality:
1957 case Operator.Inequality:
1959 case Operator.BitwiseAnd:
1961 case Operator.BitwiseOr:
1963 case Operator.ExclusiveOr:
1965 case Operator.LogicalOr:
1967 case Operator.LogicalAnd:
1971 return oper.ToString ();
1974 public override string ToString ()
1976 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1977 right.ToString () + ")";
1980 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1982 if (expr.Type == target_type)
1985 return Convert.ImplicitConversion (ec, expr, target_type, loc);
1988 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1991 34, loc, "Operator `" + OperName (oper)
1992 + "' is ambiguous on operands of type `"
1993 + TypeManager.CSharpName (l) + "' "
1994 + "and `" + TypeManager.CSharpName (r)
1998 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
2000 if ((l == t) || (r == t))
2003 if (!check_user_conversions)
2006 if (Convert.ImplicitUserConversionExists (ec, l, t))
2008 else if (Convert.ImplicitUserConversionExists (ec, r, t))
2015 // Note that handling the case l == Decimal || r == Decimal
2016 // is taken care of by the Step 1 Operator Overload resolution.
2018 // If `check_user_conv' is true, we also check whether a user-defined conversion
2019 // exists. Note that we only need to do this if both arguments are of a user-defined
2020 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
2021 // so we don't explicitly check for performance reasons.
2023 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
2025 if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
2027 // If either operand is of type double, the other operand is
2028 // conveted to type double.
2030 if (r != TypeManager.double_type)
2031 right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
2032 if (l != TypeManager.double_type)
2033 left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
2035 type = TypeManager.double_type;
2036 } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
2038 // if either operand is of type float, the other operand is
2039 // converted to type float.
2041 if (r != TypeManager.double_type)
2042 right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
2043 if (l != TypeManager.double_type)
2044 left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
2045 type = TypeManager.float_type;
2046 } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2050 // If either operand is of type ulong, the other operand is
2051 // converted to type ulong. or an error ocurrs if the other
2052 // operand is of type sbyte, short, int or long
2054 if (l == TypeManager.uint64_type){
2055 if (r != TypeManager.uint64_type){
2056 if (right is IntConstant){
2057 IntConstant ic = (IntConstant) right;
2059 e = Convert.TryImplicitIntConversion (l, ic);
2062 } else if (right is LongConstant){
2063 long ll = ((LongConstant) right).Value;
2066 right = new ULongConstant ((ulong) ll);
2068 e = Convert.ImplicitNumericConversion (ec, right, l, loc);
2075 if (left is IntConstant){
2076 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
2079 } else if (left is LongConstant){
2080 long ll = ((LongConstant) left).Value;
2083 left = new ULongConstant ((ulong) ll);
2085 e = Convert.ImplicitNumericConversion (ec, left, r, loc);
2092 if ((other == TypeManager.sbyte_type) ||
2093 (other == TypeManager.short_type) ||
2094 (other == TypeManager.int32_type) ||
2095 (other == TypeManager.int64_type))
2096 Error_OperatorAmbiguous (loc, oper, l, r);
2098 left = ForceConversion (ec, left, TypeManager.uint64_type);
2099 right = ForceConversion (ec, right, TypeManager.uint64_type);
2101 type = TypeManager.uint64_type;
2102 } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2104 // If either operand is of type long, the other operand is converted
2107 if (l != TypeManager.int64_type)
2108 left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
2109 if (r != TypeManager.int64_type)
2110 right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
2112 type = TypeManager.int64_type;
2113 } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2115 // If either operand is of type uint, and the other
2116 // operand is of type sbyte, short or int, othe operands are
2117 // converted to type long (unless we have an int constant).
2121 if (l == TypeManager.uint32_type){
2122 if (right is IntConstant){
2123 IntConstant ic = (IntConstant) right;
2127 right = new UIntConstant ((uint) val);
2134 } else if (r == TypeManager.uint32_type){
2135 if (left is IntConstant){
2136 IntConstant ic = (IntConstant) left;
2140 left = new UIntConstant ((uint) val);
2149 if ((other == TypeManager.sbyte_type) ||
2150 (other == TypeManager.short_type) ||
2151 (other == TypeManager.int32_type)){
2152 left = ForceConversion (ec, left, TypeManager.int64_type);
2153 right = ForceConversion (ec, right, TypeManager.int64_type);
2154 type = TypeManager.int64_type;
2157 // if either operand is of type uint, the other
2158 // operand is converd to type uint
2160 left = ForceConversion (ec, left, TypeManager.uint32_type);
2161 right = ForceConversion (ec, right, TypeManager.uint32_type);
2162 type = TypeManager.uint32_type;
2164 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2165 if (l != TypeManager.decimal_type)
2166 left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
2168 if (r != TypeManager.decimal_type)
2169 right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
2170 type = TypeManager.decimal_type;
2172 left = ForceConversion (ec, left, TypeManager.int32_type);
2173 right = ForceConversion (ec, right, TypeManager.int32_type);
2175 type = TypeManager.int32_type;
2178 return (left != null) && (right != null);
2181 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2183 Report.Error (19, loc,
2184 "Operator " + name + " cannot be applied to operands of type `" +
2185 TypeManager.CSharpName (l) + "' and `" +
2186 TypeManager.CSharpName (r) + "'");
2189 void Error_OperatorCannotBeApplied ()
2191 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2194 static bool is_unsigned (Type t)
2196 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2197 t == TypeManager.short_type || t == TypeManager.byte_type);
2200 static bool is_user_defined (Type t)
2202 if (t.IsSubclassOf (TypeManager.value_type) &&
2203 (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2209 Expression Make32or64 (EmitContext ec, Expression e)
2213 if (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2214 t == TypeManager.int64_type || t == TypeManager.uint64_type)
2216 Expression ee = Convert.ImplicitConversion (ec, e, TypeManager.int32_type, loc);
2219 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint32_type, loc);
2222 ee = Convert.ImplicitConversion (ec, e, TypeManager.int64_type, loc);
2225 ee = Convert.ImplicitConversion (ec, e, TypeManager.uint64_type, loc);
2231 Expression CheckShiftArguments (EmitContext ec)
2235 e = ForceConversion (ec, right, TypeManager.int32_type);
2237 Error_OperatorCannotBeApplied ();
2242 if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
2243 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
2244 ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
2245 ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
2249 if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
2250 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (31), loc);
2251 right = right.DoResolve (ec);
2253 right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (63), loc);
2254 right = right.DoResolve (ec);
2259 Error_OperatorCannotBeApplied ();
2263 Expression ResolveOperator (EmitContext ec)
2266 Type r = right.Type;
2269 // Special cases: string comapred to null
2271 if (oper == Operator.Equality || oper == Operator.Inequality){
2272 if ((!TypeManager.IsValueType (l) && r == TypeManager.null_type) ||
2273 (!TypeManager.IsValueType (r) && l == TypeManager.null_type)) {
2274 Type = TypeManager.bool_type;
2280 if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
2281 Type = TypeManager.bool_type;
2288 // Do not perform operator overload resolution when both sides are
2291 if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
2293 // Step 1: Perform Operator Overload location
2295 Expression left_expr, right_expr;
2297 string op = oper_names [(int) oper];
2299 MethodGroupExpr union;
2300 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2302 right_expr = MemberLookup (
2303 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2304 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2306 union = (MethodGroupExpr) left_expr;
2308 if (union != null) {
2309 ArrayList args = new ArrayList (2);
2310 args.Add (new Argument (left, Argument.AType.Expression));
2311 args.Add (new Argument (right, Argument.AType.Expression));
2313 MethodBase method = Invocation.OverloadResolve (
2314 ec, union, args, true, Location.Null);
2316 if (method != null) {
2317 MethodInfo mi = (MethodInfo) method;
2319 return new BinaryMethod (mi.ReturnType, method, args);
2325 // Step 0: String concatenation (because overloading will get this wrong)
2327 if (oper == Operator.Addition){
2329 // If any of the arguments is a string, cast to string
2332 // Simple constant folding
2333 if (left is StringConstant && right is StringConstant)
2334 return new StringConstant (((StringConstant) left).Value + ((StringConstant) right).Value);
2336 if (l == TypeManager.string_type || r == TypeManager.string_type) {
2338 if (r == TypeManager.void_type || l == TypeManager.void_type) {
2339 Error_OperatorCannotBeApplied ();
2343 // try to fold it in on the left
2344 if (left is StringConcat) {
2347 // We have to test here for not-null, since we can be doubly-resolved
2348 // take care of not appending twice
2351 type = TypeManager.string_type;
2352 ((StringConcat) left).Append (ec, right);
2353 return left.Resolve (ec);
2359 // Otherwise, start a new concat expression
2360 return new StringConcat (ec, loc, left, right).Resolve (ec);
2364 // Transform a + ( - b) into a - b
2366 if (right is Unary){
2367 Unary right_unary = (Unary) right;
2369 if (right_unary.Oper == Unary.Operator.UnaryNegation){
2370 oper = Operator.Subtraction;
2371 right = right_unary.Expr;
2377 if (oper == Operator.Equality || oper == Operator.Inequality){
2378 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2379 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2380 Error_OperatorCannotBeApplied ();
2384 type = TypeManager.bool_type;
2389 // operator != (object a, object b)
2390 // operator == (object a, object b)
2392 // For this to be used, both arguments have to be reference-types.
2393 // Read the rationale on the spec (14.9.6)
2395 // Also, if at compile time we know that the classes do not inherit
2396 // one from the other, then we catch the error there.
2398 if (!(l.IsValueType || r.IsValueType)){
2399 type = TypeManager.bool_type;
2404 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2408 // Also, a standard conversion must exist from either one
2410 if (!(Convert.ImplicitStandardConversionExists (ec, left, r) ||
2411 Convert.ImplicitStandardConversionExists (ec, right, l))){
2412 Error_OperatorCannotBeApplied ();
2416 // We are going to have to convert to an object to compare
2418 if (l != TypeManager.object_type)
2419 left = new EmptyCast (left, TypeManager.object_type);
2420 if (r != TypeManager.object_type)
2421 right = new EmptyCast (right, TypeManager.object_type);
2424 // FIXME: CSC here catches errors cs254 and cs252
2430 // One of them is a valuetype, but the other one is not.
2432 if (!l.IsValueType || !r.IsValueType) {
2433 Error_OperatorCannotBeApplied ();
2438 // Only perform numeric promotions on:
2439 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2441 if (oper == Operator.Addition || oper == Operator.Subtraction) {
2442 if (l.IsSubclassOf (TypeManager.delegate_type)){
2443 if (((right.eclass == ExprClass.MethodGroup) ||
2444 (r == TypeManager.anonymous_method_type))){
2445 if ((RootContext.Version != LanguageVersion.ISO_1)){
2446 Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2454 if (r.IsSubclassOf (TypeManager.delegate_type)){
2456 ArrayList args = new ArrayList (2);
2458 args = new ArrayList (2);
2459 args.Add (new Argument (left, Argument.AType.Expression));
2460 args.Add (new Argument (right, Argument.AType.Expression));
2462 if (oper == Operator.Addition)
2463 method = TypeManager.delegate_combine_delegate_delegate;
2465 method = TypeManager.delegate_remove_delegate_delegate;
2468 Error_OperatorCannotBeApplied ();
2472 return new BinaryDelegate (l, method, args);
2477 // Pointer arithmetic:
2479 // T* operator + (T* x, int y);
2480 // T* operator + (T* x, uint y);
2481 // T* operator + (T* x, long y);
2482 // T* operator + (T* x, ulong y);
2484 // T* operator + (int y, T* x);
2485 // T* operator + (uint y, T *x);
2486 // T* operator + (long y, T *x);
2487 // T* operator + (ulong y, T *x);
2489 // T* operator - (T* x, int y);
2490 // T* operator - (T* x, uint y);
2491 // T* operator - (T* x, long y);
2492 // T* operator - (T* x, ulong y);
2494 // long operator - (T* x, T *y)
2497 if (r.IsPointer && oper == Operator.Subtraction){
2499 return new PointerArithmetic (
2500 false, left, right, TypeManager.int64_type,
2503 Expression t = Make32or64 (ec, right);
2505 return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc).Resolve (ec);
2507 } else if (r.IsPointer && oper == Operator.Addition){
2508 Expression t = Make32or64 (ec, left);
2510 return new PointerArithmetic (true, right, t, r, loc).Resolve (ec);
2515 // Enumeration operators
2517 bool lie = TypeManager.IsEnumType (l);
2518 bool rie = TypeManager.IsEnumType (r);
2522 // U operator - (E e, E f)
2524 if (oper == Operator.Subtraction){
2526 type = TypeManager.EnumToUnderlying (l);
2529 Error_OperatorCannotBeApplied ();
2535 // operator + (E e, U x)
2536 // operator - (E e, U x)
2538 if (oper == Operator.Addition || oper == Operator.Subtraction){
2539 Type enum_type = lie ? l : r;
2540 Type other_type = lie ? r : l;
2541 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2543 if (underlying_type != other_type){
2544 temp = Convert.ImplicitConversion (ec, lie ? right : left, underlying_type, loc);
2554 Error_OperatorCannotBeApplied ();
2563 temp = Convert.ImplicitConversion (ec, right, l, loc);
2567 Error_OperatorCannotBeApplied ();
2571 temp = Convert.ImplicitConversion (ec, left, r, loc);
2576 Error_OperatorCannotBeApplied ();
2581 if (oper == Operator.Equality || oper == Operator.Inequality ||
2582 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2583 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2584 if (left.Type != right.Type){
2585 Error_OperatorCannotBeApplied ();
2588 type = TypeManager.bool_type;
2592 if (oper == Operator.BitwiseAnd ||
2593 oper == Operator.BitwiseOr ||
2594 oper == Operator.ExclusiveOr){
2598 Error_OperatorCannotBeApplied ();
2602 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2603 return CheckShiftArguments (ec);
2605 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2606 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2607 type = TypeManager.bool_type;
2612 Error_OperatorCannotBeApplied ();
2616 Expression e = new ConditionalLogicalOperator (
2617 oper == Operator.LogicalAnd, left, right, l, loc);
2618 return e.Resolve (ec);
2622 // operator & (bool x, bool y)
2623 // operator | (bool x, bool y)
2624 // operator ^ (bool x, bool y)
2626 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2627 if (oper == Operator.BitwiseAnd ||
2628 oper == Operator.BitwiseOr ||
2629 oper == Operator.ExclusiveOr){
2636 // Pointer comparison
2638 if (l.IsPointer && r.IsPointer){
2639 if (oper == Operator.Equality || oper == Operator.Inequality ||
2640 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2641 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2642 type = TypeManager.bool_type;
2648 // This will leave left or right set to null if there is an error
2650 bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2651 DoNumericPromotions (ec, l, r, check_user_conv);
2652 if (left == null || right == null){
2653 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2658 // reload our cached types if required
2663 if (oper == Operator.BitwiseAnd ||
2664 oper == Operator.BitwiseOr ||
2665 oper == Operator.ExclusiveOr){
2667 if (((l == TypeManager.int32_type) ||
2668 (l == TypeManager.uint32_type) ||
2669 (l == TypeManager.short_type) ||
2670 (l == TypeManager.ushort_type) ||
2671 (l == TypeManager.int64_type) ||
2672 (l == TypeManager.uint64_type))){
2675 Error_OperatorCannotBeApplied ();
2679 Error_OperatorCannotBeApplied ();
2684 if (oper == Operator.Equality ||
2685 oper == Operator.Inequality ||
2686 oper == Operator.LessThanOrEqual ||
2687 oper == Operator.LessThan ||
2688 oper == Operator.GreaterThanOrEqual ||
2689 oper == Operator.GreaterThan){
2690 type = TypeManager.bool_type;
2696 public override Expression DoResolve (EmitContext ec)
2698 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2699 left = ((ParenthesizedExpression) left).Expr;
2700 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2704 if (left.eclass == ExprClass.Type) {
2705 Error (75, "Casting a negative value needs to have the value in parentheses.");
2709 left = left.Resolve (ec);
2714 Constant lc = left as Constant;
2715 if (lc != null && lc.Type == TypeManager.bool_type &&
2716 ((oper == Operator.LogicalAnd && (bool)lc.GetValue () == false) ||
2717 (oper == Operator.LogicalOr && (bool)lc.GetValue () == true))) {
2719 // TODO: make a sense to resolve unreachable expression as we do for statement
2720 Report.Warning (429, 4, loc, "Unreachable expression code detected");
2724 right = right.Resolve (ec);
2728 eclass = ExprClass.Value;
2730 Constant rc = right as Constant;
2731 if (rc != null & lc != null){
2732 Expression e = ConstantFold.BinaryFold (
2733 ec, oper, lc, rc, loc);
2738 return ResolveOperator (ec);
2742 /// EmitBranchable is called from Statement.EmitBoolExpression in the
2743 /// context of a conditional bool expression. This function will return
2744 /// false if it is was possible to use EmitBranchable, or true if it was.
2746 /// The expression's code is generated, and we will generate a branch to `target'
2747 /// if the resulting expression value is equal to isTrue
2749 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
2751 ILGenerator ig = ec.ig;
2754 // This is more complicated than it looks, but its just to avoid
2755 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2756 // but on top of that we want for == and != to use a special path
2757 // if we are comparing against null
2759 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
2760 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2763 // put the constant on the rhs, for simplicity
2765 if (left is Constant) {
2766 Expression swap = right;
2771 if (((Constant) right).IsZeroInteger) {
2774 ig.Emit (OpCodes.Brtrue, target);
2776 ig.Emit (OpCodes.Brfalse, target);
2779 } else if (right is BoolConstant) {
2781 if (my_on_true != ((BoolConstant) right).Value)
2782 ig.Emit (OpCodes.Brtrue, target);
2784 ig.Emit (OpCodes.Brfalse, target);
2789 } else if (oper == Operator.LogicalAnd) {
2792 Label tests_end = ig.DefineLabel ();
2794 left.EmitBranchable (ec, tests_end, false);
2795 right.EmitBranchable (ec, target, true);
2796 ig.MarkLabel (tests_end);
2798 left.EmitBranchable (ec, target, false);
2799 right.EmitBranchable (ec, target, false);
2804 } else if (oper == Operator.LogicalOr){
2806 left.EmitBranchable (ec, target, true);
2807 right.EmitBranchable (ec, target, true);
2810 Label tests_end = ig.DefineLabel ();
2811 left.EmitBranchable (ec, tests_end, true);
2812 right.EmitBranchable (ec, target, false);
2813 ig.MarkLabel (tests_end);
2818 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
2819 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
2820 oper == Operator.Equality || oper == Operator.Inequality)) {
2821 base.EmitBranchable (ec, target, onTrue);
2829 bool isUnsigned = is_unsigned (t) || t == TypeManager.double_type || t == TypeManager.float_type;
2832 case Operator.Equality:
2834 ig.Emit (OpCodes.Beq, target);
2836 ig.Emit (OpCodes.Bne_Un, target);
2839 case Operator.Inequality:
2841 ig.Emit (OpCodes.Bne_Un, target);
2843 ig.Emit (OpCodes.Beq, target);
2846 case Operator.LessThan:
2849 ig.Emit (OpCodes.Blt_Un, target);
2851 ig.Emit (OpCodes.Blt, target);
2854 ig.Emit (OpCodes.Bge_Un, target);
2856 ig.Emit (OpCodes.Bge, target);
2859 case Operator.GreaterThan:
2862 ig.Emit (OpCodes.Bgt_Un, target);
2864 ig.Emit (OpCodes.Bgt, target);
2867 ig.Emit (OpCodes.Ble_Un, target);
2869 ig.Emit (OpCodes.Ble, target);
2872 case Operator.LessThanOrEqual:
2875 ig.Emit (OpCodes.Ble_Un, target);
2877 ig.Emit (OpCodes.Ble, target);
2880 ig.Emit (OpCodes.Bgt_Un, target);
2882 ig.Emit (OpCodes.Bgt, target);
2886 case Operator.GreaterThanOrEqual:
2889 ig.Emit (OpCodes.Bge_Un, target);
2891 ig.Emit (OpCodes.Bge, target);
2894 ig.Emit (OpCodes.Blt_Un, target);
2896 ig.Emit (OpCodes.Blt, target);
2899 Console.WriteLine (oper);
2900 throw new Exception ("what is THAT");
2904 public override void Emit (EmitContext ec)
2906 ILGenerator ig = ec.ig;
2911 // Handle short-circuit operators differently
2914 if (oper == Operator.LogicalAnd) {
2915 Label load_zero = ig.DefineLabel ();
2916 Label end = ig.DefineLabel ();
2918 left.EmitBranchable (ec, load_zero, false);
2920 ig.Emit (OpCodes.Br, end);
2922 ig.MarkLabel (load_zero);
2923 ig.Emit (OpCodes.Ldc_I4_0);
2926 } else if (oper == Operator.LogicalOr) {
2927 Label load_one = ig.DefineLabel ();
2928 Label end = ig.DefineLabel ();
2930 left.EmitBranchable (ec, load_one, true);
2932 ig.Emit (OpCodes.Br, end);
2934 ig.MarkLabel (load_one);
2935 ig.Emit (OpCodes.Ldc_I4_1);
2943 bool isUnsigned = is_unsigned (left.Type);
2946 case Operator.Multiply:
2948 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2949 opcode = OpCodes.Mul_Ovf;
2950 else if (isUnsigned)
2951 opcode = OpCodes.Mul_Ovf_Un;
2953 opcode = OpCodes.Mul;
2955 opcode = OpCodes.Mul;
2959 case Operator.Division:
2961 opcode = OpCodes.Div_Un;
2963 opcode = OpCodes.Div;
2966 case Operator.Modulus:
2968 opcode = OpCodes.Rem_Un;
2970 opcode = OpCodes.Rem;
2973 case Operator.Addition:
2975 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2976 opcode = OpCodes.Add_Ovf;
2977 else if (isUnsigned)
2978 opcode = OpCodes.Add_Ovf_Un;
2980 opcode = OpCodes.Add;
2982 opcode = OpCodes.Add;
2985 case Operator.Subtraction:
2987 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2988 opcode = OpCodes.Sub_Ovf;
2989 else if (isUnsigned)
2990 opcode = OpCodes.Sub_Ovf_Un;
2992 opcode = OpCodes.Sub;
2994 opcode = OpCodes.Sub;
2997 case Operator.RightShift:
2999 opcode = OpCodes.Shr_Un;
3001 opcode = OpCodes.Shr;
3004 case Operator.LeftShift:
3005 opcode = OpCodes.Shl;
3008 case Operator.Equality:
3009 opcode = OpCodes.Ceq;
3012 case Operator.Inequality:
3013 ig.Emit (OpCodes.Ceq);
3014 ig.Emit (OpCodes.Ldc_I4_0);
3016 opcode = OpCodes.Ceq;
3019 case Operator.LessThan:
3021 opcode = OpCodes.Clt_Un;
3023 opcode = OpCodes.Clt;
3026 case Operator.GreaterThan:
3028 opcode = OpCodes.Cgt_Un;
3030 opcode = OpCodes.Cgt;
3033 case Operator.LessThanOrEqual:
3034 Type lt = left.Type;
3036 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
3037 ig.Emit (OpCodes.Cgt_Un);
3039 ig.Emit (OpCodes.Cgt);
3040 ig.Emit (OpCodes.Ldc_I4_0);
3042 opcode = OpCodes.Ceq;
3045 case Operator.GreaterThanOrEqual:
3046 Type le = left.Type;
3048 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3049 ig.Emit (OpCodes.Clt_Un);
3051 ig.Emit (OpCodes.Clt);
3053 ig.Emit (OpCodes.Ldc_I4_0);
3055 opcode = OpCodes.Ceq;
3058 case Operator.BitwiseOr:
3059 opcode = OpCodes.Or;
3062 case Operator.BitwiseAnd:
3063 opcode = OpCodes.And;
3066 case Operator.ExclusiveOr:
3067 opcode = OpCodes.Xor;
3071 throw new Exception ("This should not happen: Operator = "
3072 + oper.ToString ());
3080 // Object created by Binary when the binary operator uses an method instead of being
3081 // a binary operation that maps to a CIL binary operation.
3083 public class BinaryMethod : Expression {
3084 public MethodBase method;
3085 public ArrayList Arguments;
3087 public BinaryMethod (Type t, MethodBase m, ArrayList args)
3092 eclass = ExprClass.Value;
3095 public override Expression DoResolve (EmitContext ec)
3100 public override void Emit (EmitContext ec)
3102 ILGenerator ig = ec.ig;
3104 if (Arguments != null)
3105 Invocation.EmitArguments (ec, method, Arguments, false, null);
3107 if (method is MethodInfo)
3108 ig.Emit (OpCodes.Call, (MethodInfo) method);
3110 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3115 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3116 // b, c, d... may be strings or objects.
3118 public class StringConcat : Expression {
3120 bool invalid = false;
3121 bool emit_conv_done = false;
3123 // Are we also concating objects?
3125 bool is_strings_only = true;
3127 public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
3130 type = TypeManager.string_type;
3131 eclass = ExprClass.Value;
3133 operands = new ArrayList (2);
3138 public override Expression DoResolve (EmitContext ec)
3146 public void Append (EmitContext ec, Expression operand)
3151 if (operand is StringConstant && operands.Count != 0) {
3152 StringConstant last_operand = operands [operands.Count - 1] as StringConstant;
3153 if (last_operand != null) {
3154 operands [operands.Count - 1] = new StringConstant (last_operand.Value + ((StringConstant) operand).Value);
3160 // Conversion to object
3162 if (operand.Type != TypeManager.string_type) {
3163 Expression no = Convert.ImplicitConversion (ec, operand, TypeManager.object_type, loc);
3166 Binary.Error_OperatorCannotBeApplied (loc, "+", TypeManager.string_type, operand.Type);
3172 operands.Add (operand);
3175 public override void Emit (EmitContext ec)
3177 MethodInfo concat_method = null;
3180 // Do conversion to arguments; check for strings only
3183 // This can get called multiple times, so we have to deal with that.
3184 if (!emit_conv_done) {
3185 emit_conv_done = true;
3186 for (int i = 0; i < operands.Count; i ++) {
3187 Expression e = (Expression) operands [i];
3188 is_strings_only &= e.Type == TypeManager.string_type;
3191 for (int i = 0; i < operands.Count; i ++) {
3192 Expression e = (Expression) operands [i];
3194 if (! is_strings_only && e.Type == TypeManager.string_type) {
3195 // need to make sure this is an object, because the EmitParams
3196 // method might look at the type of this expression, see it is a
3197 // string and emit a string [] when we want an object [];
3199 e = new EmptyCast (e, TypeManager.object_type);
3201 operands [i] = new Argument (e, Argument.AType.Expression);
3206 // Find the right method
3208 switch (operands.Count) {
3211 // This should not be possible, because simple constant folding
3212 // is taken care of in the Binary code.
3214 throw new Exception ("how did you get here?");
3217 concat_method = is_strings_only ?
3218 TypeManager.string_concat_string_string :
3219 TypeManager.string_concat_object_object ;
3222 concat_method = is_strings_only ?
3223 TypeManager.string_concat_string_string_string :
3224 TypeManager.string_concat_object_object_object ;
3228 // There is not a 4 param overlaod for object (the one that there is
3229 // is actually a varargs methods, and is only in corlib because it was
3230 // introduced there before.).
3232 if (!is_strings_only)
3235 concat_method = TypeManager.string_concat_string_string_string_string;
3238 concat_method = is_strings_only ?
3239 TypeManager.string_concat_string_dot_dot_dot :
3240 TypeManager.string_concat_object_dot_dot_dot ;
3244 Invocation.EmitArguments (ec, concat_method, operands, false, null);
3245 ec.ig.Emit (OpCodes.Call, concat_method);
3250 // Object created with +/= on delegates
3252 public class BinaryDelegate : Expression {
3256 public BinaryDelegate (Type t, MethodInfo mi, ArrayList args)
3261 eclass = ExprClass.Value;
3264 public override Expression DoResolve (EmitContext ec)
3269 public override void Emit (EmitContext ec)
3271 ILGenerator ig = ec.ig;
3273 Invocation.EmitArguments (ec, method, args, false, null);
3275 ig.Emit (OpCodes.Call, (MethodInfo) method);
3276 ig.Emit (OpCodes.Castclass, type);
3279 public Expression Right {
3281 Argument arg = (Argument) args [1];
3286 public bool IsAddition {
3288 return method == TypeManager.delegate_combine_delegate_delegate;
3294 // User-defined conditional logical operator
3295 public class ConditionalLogicalOperator : Expression {
3296 Expression left, right;
3299 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3302 eclass = ExprClass.Value;
3306 this.is_and = is_and;
3309 protected void Error19 ()
3311 Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3314 protected void Error218 ()
3316 Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3317 "declarations of operator true and operator false");
3320 Expression op_true, op_false, op;
3321 LocalTemporary left_temp;
3323 public override Expression DoResolve (EmitContext ec)
3326 Expression operator_group;
3328 operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3329 if (operator_group == null) {
3334 left_temp = new LocalTemporary (ec, type);
3336 ArrayList arguments = new ArrayList ();
3337 arguments.Add (new Argument (left_temp, Argument.AType.Expression));
3338 arguments.Add (new Argument (right, Argument.AType.Expression));
3339 method = Invocation.OverloadResolve (
3340 ec, (MethodGroupExpr) operator_group, arguments, false, loc)
3342 if (method == null) {
3347 if (method.ReturnType != type) {
3348 Report.Error (217, loc, "In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') " +
3349 "must have the same return type as the type of its 2 parameters", TypeManager.CSharpSignature (method));
3353 op = new StaticCallExpr (method, arguments, loc);
3355 op_true = GetOperatorTrue (ec, left_temp, loc);
3356 op_false = GetOperatorFalse (ec, left_temp, loc);
3357 if ((op_true == null) || (op_false == null)) {
3365 public override void Emit (EmitContext ec)
3367 ILGenerator ig = ec.ig;
3368 Label false_target = ig.DefineLabel ();
3369 Label end_target = ig.DefineLabel ();
3372 left_temp.Store (ec);
3374 (is_and ? op_false : op_true).EmitBranchable (ec, false_target, false);
3375 left_temp.Emit (ec);
3376 ig.Emit (OpCodes.Br, end_target);
3377 ig.MarkLabel (false_target);
3379 ig.MarkLabel (end_target);
3383 public class PointerArithmetic : Expression {
3384 Expression left, right;
3388 // We assume that `l' is always a pointer
3390 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3396 is_add = is_addition;
3399 public override Expression DoResolve (EmitContext ec)
3401 eclass = ExprClass.Variable;
3403 if (left.Type == TypeManager.void_ptr_type) {
3404 Error (242, "The operation in question is undefined on void pointers");
3411 public override void Emit (EmitContext ec)
3413 Type op_type = left.Type;
3414 ILGenerator ig = ec.ig;
3416 // It must be either array or fixed buffer
3417 Type element = TypeManager.HasElementType (op_type) ?
3418 element = TypeManager.GetElementType (op_type) :
3419 element = AttributeTester.GetFixedBuffer (((FieldExpr)left).FieldInfo).ElementType;
3421 int size = GetTypeSize (element);
3422 Type rtype = right.Type;
3424 if (rtype.IsPointer){
3426 // handle (pointer - pointer)
3430 ig.Emit (OpCodes.Sub);
3434 ig.Emit (OpCodes.Sizeof, element);
3436 IntLiteral.EmitInt (ig, size);
3437 ig.Emit (OpCodes.Div);
3439 ig.Emit (OpCodes.Conv_I8);
3442 // handle + and - on (pointer op int)
3445 ig.Emit (OpCodes.Conv_I);
3447 Constant right_const = right as Constant;
3448 if (right_const != null && size != 0) {
3449 Expression ex = ConstantFold.BinaryFold (ec, Binary.Operator.Multiply, new IntConstant (size), right_const, loc);
3457 ig.Emit (OpCodes.Sizeof, element);
3459 IntLiteral.EmitInt (ig, size);
3460 if (rtype == TypeManager.int64_type)
3461 ig.Emit (OpCodes.Conv_I8);
3462 else if (rtype == TypeManager.uint64_type)
3463 ig.Emit (OpCodes.Conv_U8);
3464 ig.Emit (OpCodes.Mul);
3468 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
3469 ig.Emit (OpCodes.Conv_I);
3472 ig.Emit (OpCodes.Add);
3474 ig.Emit (OpCodes.Sub);
3480 /// Implements the ternary conditional operator (?:)
3482 public class Conditional : Expression {
3483 Expression expr, trueExpr, falseExpr;
3485 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3488 this.trueExpr = trueExpr;
3489 this.falseExpr = falseExpr;
3493 public Expression Expr {
3499 public Expression TrueExpr {
3505 public Expression FalseExpr {
3511 public override Expression DoResolve (EmitContext ec)
3513 expr = expr.Resolve (ec);
3518 if (expr.Type != TypeManager.bool_type){
3519 expr = Expression.ResolveBoolean (
3526 trueExpr = trueExpr.Resolve (ec);
3527 falseExpr = falseExpr.Resolve (ec);
3529 if (trueExpr == null || falseExpr == null)
3532 eclass = ExprClass.Value;
3533 if (trueExpr.Type == falseExpr.Type)
3534 type = trueExpr.Type;
3537 Type true_type = trueExpr.Type;
3538 Type false_type = falseExpr.Type;
3541 // First, if an implicit conversion exists from trueExpr
3542 // to falseExpr, then the result type is of type falseExpr.Type
3544 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3547 // Check if both can convert implicitl to each other's type
3549 if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3551 "Can not compute type of conditional expression " +
3552 "as `" + TypeManager.CSharpName (trueExpr.Type) +
3553 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3554 "' convert implicitly to each other");
3559 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3563 Error (173, "The type of the conditional expression can " +
3564 "not be computed because there is no implicit conversion" +
3565 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3566 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3571 // Dead code optimalization
3572 if (expr is BoolConstant){
3573 BoolConstant bc = (BoolConstant) expr;
3575 Report.Warning (429, 4, bc.Value ? falseExpr.Location : trueExpr.Location, "Unreachable expression code detected");
3576 return bc.Value ? trueExpr : falseExpr;
3582 public override void Emit (EmitContext ec)
3584 ILGenerator ig = ec.ig;
3585 Label false_target = ig.DefineLabel ();
3586 Label end_target = ig.DefineLabel ();
3588 expr.EmitBranchable (ec, false_target, false);
3590 ig.Emit (OpCodes.Br, end_target);
3591 ig.MarkLabel (false_target);
3592 falseExpr.Emit (ec);
3593 ig.MarkLabel (end_target);
3601 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3602 public readonly string Name;
3603 public readonly Block Block;
3604 public LocalInfo local_info;
3607 LocalTemporary temp;
3609 public LocalVariableReference (Block block, string name, Location l)
3614 eclass = ExprClass.Variable;
3618 // Setting `is_readonly' to false will allow you to create a writable
3619 // reference to a read-only variable. This is used by foreach and using.
3621 public LocalVariableReference (Block block, string name, Location l,
3622 LocalInfo local_info, bool is_readonly)
3623 : this (block, name, l)
3625 this.local_info = local_info;
3626 this.is_readonly = is_readonly;
3629 public VariableInfo VariableInfo {
3631 return local_info.VariableInfo;
3635 public bool IsReadOnly {
3641 protected Expression DoResolveBase (EmitContext ec, Expression lvalue_right_side)
3643 if (local_info == null) {
3644 local_info = Block.GetLocalInfo (Name);
3647 if (lvalue_right_side == EmptyExpression.Null)
3648 local_info.Used = true;
3650 is_readonly = local_info.ReadOnly;
3653 type = local_info.VariableType;
3655 VariableInfo variable_info = local_info.VariableInfo;
3656 if (lvalue_right_side != null){
3658 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3662 if (variable_info != null)
3663 variable_info.SetAssigned (ec);
3666 Expression e = Block.GetConstantExpression (Name);
3668 local_info.Used = true;
3669 eclass = ExprClass.Value;
3670 return e.Resolve (ec);
3673 if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3676 if (lvalue_right_side == null)
3677 local_info.Used = true;
3679 if (ec.CurrentAnonymousMethod != null){
3681 // If we are referencing a variable from the external block
3682 // flag it for capturing
3684 if (local_info.Block.Toplevel != ec.CurrentBlock.Toplevel){
3685 if (local_info.AddressTaken){
3686 AnonymousMethod.Error_AddressOfCapturedVar (local_info.Name, loc);
3689 ec.CaptureVariable (local_info);
3696 public override Expression DoResolve (EmitContext ec)
3698 return DoResolveBase (ec, null);
3701 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3703 Expression ret = DoResolveBase (ec, right_side);
3705 CheckObsoleteAttribute (ret.Type);
3710 public bool VerifyFixed (bool is_expression)
3712 return !is_expression || local_info.IsFixed;
3715 public override int GetHashCode()
3717 return Name.GetHashCode ();
3720 public override bool Equals (object obj)
3722 LocalVariableReference lvr = obj as LocalVariableReference;
3726 return Name == lvr.Name && Block == lvr.Block;
3729 public override void Emit (EmitContext ec)
3731 ILGenerator ig = ec.ig;
3733 if (local_info.FieldBuilder == null){
3735 // A local variable on the local CLR stack
3737 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3740 // A local variable captured by anonymous methods.
3743 ec.EmitCapturedVariableInstance (local_info);
3745 ig.Emit (OpCodes.Ldfld, local_info.FieldBuilder);
3749 public void Emit (EmitContext ec, bool leave_copy)
3753 ec.ig.Emit (OpCodes.Dup);
3754 if (local_info.FieldBuilder != null){
3755 temp = new LocalTemporary (ec, Type);
3761 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3763 ILGenerator ig = ec.ig;
3764 prepared = prepare_for_load;
3766 if (local_info.FieldBuilder == null){
3768 // A local variable on the local CLR stack
3770 if (local_info.LocalBuilder == null)
3771 throw new Exception ("This should not happen: both Field and Local are null");
3775 ec.ig.Emit (OpCodes.Dup);
3776 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3779 // A local variable captured by anonymous methods or itereators.
3781 ec.EmitCapturedVariableInstance (local_info);
3783 if (prepare_for_load)
3784 ig.Emit (OpCodes.Dup);
3787 ig.Emit (OpCodes.Dup);
3788 temp = new LocalTemporary (ec, Type);
3791 ig.Emit (OpCodes.Stfld, local_info.FieldBuilder);
3797 public void AddressOf (EmitContext ec, AddressOp mode)
3799 ILGenerator ig = ec.ig;
3801 if (local_info.FieldBuilder == null){
3803 // A local variable on the local CLR stack
3805 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3808 // A local variable captured by anonymous methods or iterators
3810 ec.EmitCapturedVariableInstance (local_info);
3811 ig.Emit (OpCodes.Ldflda, local_info.FieldBuilder);
3815 public override string ToString ()
3817 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3822 /// This represents a reference to a parameter in the intermediate
3825 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3831 public Parameter.Modifier mod;
3832 public bool is_ref, is_out, prepared;
3846 LocalTemporary temp;
3848 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3855 eclass = ExprClass.Variable;
3858 public VariableInfo VariableInfo {
3862 public bool VerifyFixed (bool is_expression)
3864 return !is_expression || TypeManager.IsValueType (type);
3867 public bool IsAssigned (EmitContext ec, Location loc)
3869 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsAssigned (vi))
3872 Report.Error (269, loc,
3873 "Use of unassigned out parameter '{0}'", name);
3877 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3879 if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3882 Report.Error (170, loc,
3883 "Use of possibly unassigned field `" + field_name + "'");
3887 public void SetAssigned (EmitContext ec)
3889 if (is_out && ec.DoFlowAnalysis)
3890 ec.CurrentBranching.SetAssigned (vi);
3893 public void SetFieldAssigned (EmitContext ec, string field_name)
3895 if (is_out && ec.DoFlowAnalysis)
3896 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3899 protected void DoResolveBase (EmitContext ec)
3901 type = pars.GetParameterInfo (ec, idx, out mod);
3902 is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3903 is_out = (mod & Parameter.Modifier.OUT) != 0;
3904 eclass = ExprClass.Variable;
3907 vi = block.ParameterMap [idx];
3909 if (ec.CurrentAnonymousMethod != null){
3911 Report.Error (1628, Location,
3912 "Can not reference a ref or out parameter in an anonymous method");
3917 // If we are referencing the parameter from the external block
3918 // flag it for capturing
3920 //Console.WriteLine ("Is parameter `{0}' local? {1}", name, block.IsLocalParameter (name));
3921 if (!block.IsLocalParameter (name)){
3922 ec.CaptureParameter (name, type, idx);
3927 public override int GetHashCode()
3929 return name.GetHashCode ();
3932 public override bool Equals (object obj)
3934 ParameterReference pr = obj as ParameterReference;
3938 return name == pr.name && block == pr.block;
3942 // Notice that for ref/out parameters, the type exposed is not the
3943 // same type exposed externally.
3946 // externally we expose "int&"
3947 // here we expose "int".
3949 // We record this in "is_ref". This means that the type system can treat
3950 // the type as it is expected, but when we generate the code, we generate
3951 // the alternate kind of code.
3953 public override Expression DoResolve (EmitContext ec)
3957 if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3960 if (ec.RemapToProxy)
3961 return ec.RemapParameter (idx);
3966 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3972 if (ec.RemapToProxy)
3973 return ec.RemapParameterLValue (idx, right_side);
3978 static public void EmitLdArg (ILGenerator ig, int x)
3982 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3983 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3984 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3985 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3986 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3989 ig.Emit (OpCodes.Ldarg, x);
3993 // This method is used by parameters that are references, that are
3994 // being passed as references: we only want to pass the pointer (that
3995 // is already stored in the parameter, not the address of the pointer,
3996 // and not the value of the variable).
3998 public void EmitLoad (EmitContext ec)
4000 ILGenerator ig = ec.ig;
4003 if (!ec.MethodIsStatic)
4007 EmitLdArg (ig, arg_idx);
4010 // FIXME: Review for anonymous methods
4014 public override void Emit (EmitContext ec)
4016 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4017 ec.EmitParameter (name);
4024 public void Emit (EmitContext ec, bool leave_copy)
4026 ILGenerator ig = ec.ig;
4029 if (!ec.MethodIsStatic)
4032 EmitLdArg (ig, arg_idx);
4036 ec.ig.Emit (OpCodes.Dup);
4039 // If we are a reference, we loaded on the stack a pointer
4040 // Now lets load the real value
4042 LoadFromPtr (ig, type);
4046 ec.ig.Emit (OpCodes.Dup);
4049 temp = new LocalTemporary (ec, type);
4055 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
4057 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4058 ec.EmitAssignParameter (name, source, leave_copy, prepare_for_load);
4062 ILGenerator ig = ec.ig;
4065 prepared = prepare_for_load;
4067 if (!ec.MethodIsStatic)
4070 if (is_ref && !prepared)
4071 EmitLdArg (ig, arg_idx);
4076 ec.ig.Emit (OpCodes.Dup);
4080 temp = new LocalTemporary (ec, type);
4084 StoreFromPtr (ig, type);
4090 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
4092 ig.Emit (OpCodes.Starg, arg_idx);
4096 public void AddressOf (EmitContext ec, AddressOp mode)
4098 if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
4099 ec.EmitAddressOfParameter (name);
4105 if (!ec.MethodIsStatic)
4110 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
4112 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
4115 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
4117 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
4124 /// Used for arguments to New(), Invocation()
4126 public class Argument {
4127 public enum AType : byte {
4134 public readonly AType ArgType;
4135 public Expression Expr;
4137 public Argument (Expression expr, AType type)
4140 this.ArgType = type;
4143 public Argument (Expression expr)
4146 this.ArgType = AType.Expression;
4151 if (ArgType == AType.Ref || ArgType == AType.Out)
4152 return TypeManager.GetReferenceType (Expr.Type);
4158 public Parameter.Modifier GetParameterModifier ()
4162 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
4165 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
4168 return Parameter.Modifier.NONE;
4172 public static string FullDesc (Argument a)
4174 if (a.ArgType == AType.ArgList)
4177 return (a.ArgType == AType.Ref ? "ref " :
4178 (a.ArgType == AType.Out ? "out " : "")) +
4179 TypeManager.CSharpName (a.Expr.Type);
4182 public bool ResolveMethodGroup (EmitContext ec, Location loc)
4184 // FIXME: csc doesn't report any error if you try to use `ref' or
4185 // `out' in a delegate creation expression.
4186 Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4193 void Error_LValueRequired (Location loc)
4195 Report.Error (1510, loc, "An lvalue is required as an argument to out or ref");
4198 public bool Resolve (EmitContext ec, Location loc)
4200 if (ArgType == AType.Ref) {
4201 Expr = Expr.Resolve (ec);
4205 if (!ec.IsConstructor) {
4206 FieldExpr fe = Expr as FieldExpr;
4207 if (fe != null && fe.FieldInfo.IsInitOnly) {
4208 if (fe.FieldInfo.IsStatic)
4209 Report.Error (199, loc, "A static readonly field cannot be passed ref or out (except in a static constructor)");
4211 Report.Error (192, loc, "A readonly field cannot be passed ref or out (except in a constructor)");
4215 Expr = Expr.DoResolveLValue (ec, Expr);
4217 Error_LValueRequired (loc);
4218 } else if (ArgType == AType.Out) {
4219 Expr = Expr.DoResolveLValue (ec, EmptyExpression.Null);
4221 Error_LValueRequired (loc);
4224 Expr = Expr.Resolve (ec);
4229 if (Expr is IMemberExpr) {
4230 IMemberExpr me = Expr as IMemberExpr;
4233 // This can happen with the following code:
4237 // public Y (X x) {}
4241 // public Z () : base (X) {}
4244 // SimpleNameResolve is conservative about flagging the X as
4245 // an error since it has identical name and type. However,
4246 // because there's no MemberAccess, that is not really justified.
4247 // It is still simpler to fix it here, rather than in SimpleNameResolve.
4249 if (me.IsInstance && me.InstanceExpression == null) {
4250 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
4255 if (ArgType == AType.Expression)
4259 // Catch errors where fields of a MarshalByRefObject are passed as ref or out
4260 // This is only allowed for `this'
4262 FieldExpr fe = Expr as FieldExpr;
4263 if (fe != null && !fe.IsStatic){
4264 Expression instance = fe.InstanceExpression;
4266 if (instance.GetType () != typeof (This)){
4267 if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
4268 Report.SymbolRelatedToPreviousError (fe.InstanceExpression.Type);
4269 Report.Error (197, loc, "Cannot pass '{0}' as ref or out or take its address because it is a member of a marshal-by-reference class",
4277 if (Expr.eclass != ExprClass.Variable){
4279 // We just probe to match the CSC output
4281 if (Expr.eclass == ExprClass.PropertyAccess ||
4282 Expr.eclass == ExprClass.IndexerAccess){
4285 "A property or indexer can not be passed as an out or ref " +
4288 Error_LValueRequired (loc);
4296 public void Emit (EmitContext ec)
4299 // Ref and Out parameters need to have their addresses taken.
4301 // ParameterReferences might already be references, so we want
4302 // to pass just the value
4304 if (ArgType == AType.Ref || ArgType == AType.Out){
4305 AddressOp mode = AddressOp.Store;
4307 if (ArgType == AType.Ref)
4308 mode |= AddressOp.Load;
4310 if (Expr is ParameterReference){
4311 ParameterReference pr = (ParameterReference) Expr;
4317 pr.AddressOf (ec, mode);
4320 if (Expr is IMemoryLocation)
4321 ((IMemoryLocation) Expr).AddressOf (ec, mode);
4324 1510, Expr.Location,
4325 "An lvalue is required as an argument to out or ref");
4335 /// Invocation of methods or delegates.
4337 public class Invocation : ExpressionStatement {
4338 public readonly ArrayList Arguments;
4341 MethodBase method = null;
4344 // arguments is an ArrayList, but we do not want to typecast,
4345 // as it might be null.
4347 // FIXME: only allow expr to be a method invocation or a
4348 // delegate invocation (7.5.5)
4350 public Invocation (Expression expr, ArrayList arguments, Location l)
4353 Arguments = arguments;
4357 public Expression Expr {
4364 /// Determines "better conversion" as specified in 7.4.2.3
4366 /// Returns : p if a->p is better,
4367 /// q if a->q is better,
4368 /// null if neither is better
4370 static Type BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
4372 Type argument_type = a.Type;
4373 Expression argument_expr = a.Expr;
4375 if (argument_type == null)
4376 throw new Exception ("Expression of type " + a.Expr +
4377 " does not resolve its type");
4379 if (p == null || q == null)
4380 throw new InternalErrorException ("BetterConversion Got a null conversion");
4385 if (argument_expr is NullLiteral) {
4387 // If the argument is null and one of the types to compare is 'object' and
4388 // the other is a reference type, we prefer the other.
4390 // This follows from the usual rules:
4391 // * There is an implicit conversion from 'null' to type 'object'
4392 // * There is an implicit conversion from 'null' to any reference type
4393 // * There is an implicit conversion from any reference type to type 'object'
4394 // * There is no implicit conversion from type 'object' to other reference types
4395 // => Conversion of 'null' to a reference type is better than conversion to 'object'
4397 // FIXME: This probably isn't necessary, since the type of a NullLiteral is the
4398 // null type. I think it used to be 'object' and thus needed a special
4399 // case to avoid the immediately following two checks.
4401 if (!p.IsValueType && q == TypeManager.object_type)
4403 if (!q.IsValueType && p == TypeManager.object_type)
4407 if (argument_type == p)
4410 if (argument_type == q)
4413 Expression p_tmp = new EmptyExpression (p);
4414 Expression q_tmp = new EmptyExpression (q);
4416 bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
4417 bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
4419 if (p_to_q && !q_to_p)
4422 if (q_to_p && !p_to_q)
4425 if (p == TypeManager.sbyte_type)
4426 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4427 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4429 if (q == TypeManager.sbyte_type)
4430 if (p == TypeManager.byte_type || p == TypeManager.ushort_type ||
4431 p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4434 if (p == TypeManager.short_type)
4435 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4436 q == TypeManager.uint64_type)
4438 if (q == TypeManager.short_type)
4439 if (p == TypeManager.ushort_type || p == TypeManager.uint32_type ||
4440 p == TypeManager.uint64_type)
4443 if (p == TypeManager.int32_type)
4444 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4446 if (q == TypeManager.int32_type)
4447 if (p == TypeManager.uint32_type || p == TypeManager.uint64_type)
4450 if (p == TypeManager.int64_type)
4451 if (q == TypeManager.uint64_type)
4453 if (q == TypeManager.int64_type)
4454 if (p == TypeManager.uint64_type)
4461 /// Determines "Better function" between candidate
4462 /// and the current best match
4465 /// Returns an integer indicating :
4466 /// false if candidate ain't better
4467 /// true if candidate is better than the current best match
4469 static bool BetterFunction (EmitContext ec, ArrayList args, int argument_count,
4470 MethodBase candidate, bool candidate_params,
4471 MethodBase best, bool best_params, Location loc)
4473 ParameterData candidate_pd = TypeManager.GetParameterData (candidate);
4474 ParameterData best_pd = TypeManager.GetParameterData (best);
4476 bool better_at_least_one = false;
4478 for (int j = 0; j < argument_count; ++j) {
4479 Argument a = (Argument) args [j];
4481 Type ct = TypeManager.TypeToCoreType (candidate_pd.ParameterType (j));
4482 Type bt = TypeManager.TypeToCoreType (best_pd.ParameterType (j));
4484 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4485 if (candidate_params)
4486 ct = TypeManager.GetElementType (ct);
4488 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4490 bt = TypeManager.GetElementType (bt);
4496 Type better = BetterConversion (ec, a, ct, bt, loc);
4498 // for each argument, the conversion to 'ct' should be no worse than
4499 // the conversion to 'bt'.
4503 // for at least one argument, the conversion to 'ct' should be better than
4504 // the conversion to 'bt'.
4506 better_at_least_one = true;
4509 if (better_at_least_one)
4513 // This handles the case
4515 // Add (float f1, float f2, float f3);
4516 // Add (params decimal [] foo);
4518 // The call Add (3, 4, 5) should be ambiguous. Without this check, the
4519 // first candidate would've chosen as better.
4525 // This handles the following cases:
4527 // Trim () is better than Trim (params char[] chars)
4528 // Concat (string s1, string s2, string s3) is better than
4529 // Concat (string s1, params string [] srest)
4531 return !candidate_params && best_params;
4534 static bool IsOverride (MethodBase cand_method, MethodBase base_method)
4536 if (!IsAncestralType (base_method.DeclaringType, cand_method.DeclaringType))
4539 ParameterData cand_pd = TypeManager.GetParameterData (cand_method);
4540 ParameterData base_pd = TypeManager.GetParameterData (base_method);
4542 if (cand_pd.Count != base_pd.Count)
4545 for (int j = 0; j < cand_pd.Count; ++j) {
4546 Parameter.Modifier cm = cand_pd.ParameterModifier (j);
4547 Parameter.Modifier bm = base_pd.ParameterModifier (j);
4548 Type ct = TypeManager.TypeToCoreType (cand_pd.ParameterType (j));
4549 Type bt = TypeManager.TypeToCoreType (base_pd.ParameterType (j));
4551 if (cm != bm || ct != bt)
4558 public static string FullMethodDesc (MethodBase mb)
4560 string ret_type = "";
4565 if (mb is MethodInfo)
4566 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
4568 StringBuilder sb = new StringBuilder (ret_type);
4570 sb.Append (mb.ReflectedType.ToString ());
4572 sb.Append (mb.Name);
4574 ParameterData pd = TypeManager.GetParameterData (mb);
4576 int count = pd.Count;
4579 for (int i = count; i > 0; ) {
4582 sb.Append (pd.ParameterDesc (count - i - 1));
4588 return sb.ToString ();
4591 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4593 MemberInfo [] miset;
4594 MethodGroupExpr union;
4599 return (MethodGroupExpr) mg2;
4602 return (MethodGroupExpr) mg1;
4605 MethodGroupExpr left_set = null, right_set = null;
4606 int length1 = 0, length2 = 0;
4608 left_set = (MethodGroupExpr) mg1;
4609 length1 = left_set.Methods.Length;
4611 right_set = (MethodGroupExpr) mg2;
4612 length2 = right_set.Methods.Length;
4614 ArrayList common = new ArrayList ();
4616 foreach (MethodBase r in right_set.Methods){
4617 if (TypeManager.ArrayContainsMethod (left_set.Methods, r))
4621 miset = new MemberInfo [length1 + length2 - common.Count];
4622 left_set.Methods.CopyTo (miset, 0);
4626 foreach (MethodBase r in right_set.Methods) {
4627 if (!common.Contains (r))
4631 union = new MethodGroupExpr (miset, loc);
4636 public static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4637 ArrayList arguments, int arg_count,
4638 ref MethodBase candidate)
4640 return IsParamsMethodApplicable (
4641 ec, me, arguments, arg_count, false, ref candidate) ||
4642 IsParamsMethodApplicable (
4643 ec, me, arguments, arg_count, true, ref candidate);
4648 static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
4649 ArrayList arguments, int arg_count,
4650 bool do_varargs, ref MethodBase candidate)
4652 return IsParamsMethodApplicable (
4653 ec, arguments, arg_count, candidate, do_varargs);
4657 /// Determines if the candidate method, if a params method, is applicable
4658 /// in its expanded form to the given set of arguments
4660 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
4661 int arg_count, MethodBase candidate,
4664 ParameterData pd = TypeManager.GetParameterData (candidate);
4666 int pd_count = pd.Count;
4670 int count = pd_count - 1;
4672 if (pd.ParameterModifier (count) != Parameter.Modifier.ARGLIST)
4674 if (pd_count != arg_count)
4677 if (pd.ParameterModifier (count) != Parameter.Modifier.PARAMS)
4681 if (count > arg_count)
4684 if (pd_count == 1 && arg_count == 0)
4688 // If we have come this far, the case which
4689 // remains is when the number of parameters is
4690 // less than or equal to the argument count.
4692 for (int i = 0; i < count; ++i) {
4694 Argument a = (Argument) arguments [i];
4696 Parameter.Modifier a_mod = a.GetParameterModifier () &
4697 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4698 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4699 (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
4701 if (a_mod == p_mod) {
4703 if (a_mod == Parameter.Modifier.NONE)
4704 if (!Convert.ImplicitConversionExists (ec,
4706 pd.ParameterType (i)))
4709 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4710 Type pt = pd.ParameterType (i);
4713 pt = TypeManager.GetReferenceType (pt);
4724 Argument a = (Argument) arguments [count];
4725 if (!(a.Expr is Arglist))
4731 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
4733 for (int i = pd_count - 1; i < arg_count; i++) {
4734 Argument a = (Argument) arguments [i];
4736 if (!Convert.ImplicitConversionExists (ec, a.Expr, element_type))
4743 public static bool IsApplicable (EmitContext ec, MethodGroupExpr me,
4744 ArrayList arguments, int arg_count,
4745 ref MethodBase candidate)
4747 return IsApplicable (ec, arguments, arg_count, candidate);
4751 /// Determines if the candidate method is applicable (section 14.4.2.1)
4752 /// to the given set of arguments
4754 static bool IsApplicable (EmitContext ec, ArrayList arguments, int arg_count,
4755 MethodBase candidate)
4757 ParameterData pd = TypeManager.GetParameterData (candidate);
4759 if (arg_count != pd.Count)
4762 for (int i = arg_count; i > 0; ) {
4765 Argument a = (Argument) arguments [i];
4767 Parameter.Modifier a_mod = a.GetParameterModifier () &
4768 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4769 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4770 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
4773 if (a_mod == p_mod ||
4774 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4775 if (a_mod == Parameter.Modifier.NONE) {
4776 if (!Convert.ImplicitConversionExists (ec,
4778 pd.ParameterType (i)))
4782 if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4783 Type pt = pd.ParameterType (i);
4786 pt = TypeManager.GetReferenceType (pt);
4798 static private bool IsAncestralType (Type first_type, Type second_type)
4800 return first_type != second_type &&
4801 (second_type.IsSubclassOf (first_type) ||
4802 TypeManager.ImplementsInterface (second_type, first_type));
4806 /// Find the Applicable Function Members (7.4.2.1)
4808 /// me: Method Group expression with the members to select.
4809 /// it might contain constructors or methods (or anything
4810 /// that maps to a method).
4812 /// Arguments: ArrayList containing resolved Argument objects.
4814 /// loc: The location if we want an error to be reported, or a Null
4815 /// location for "probing" purposes.
4817 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4818 /// that is the best match of me on Arguments.
4821 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4822 ArrayList Arguments, bool may_fail,
4825 MethodBase method = null;
4826 bool method_params = false;
4827 Type applicable_type = null;
4829 ArrayList candidates = new ArrayList (2);
4830 ArrayList candidate_overrides = null;
4833 // Used to keep a map between the candidate
4834 // and whether it is being considered in its
4835 // normal or expanded form
4837 // false is normal form, true is expanded form
4839 Hashtable candidate_to_form = null;
4841 if (Arguments != null)
4842 arg_count = Arguments.Count;
4844 if ((me.Name == "Invoke") &&
4845 TypeManager.IsDelegateType (me.DeclaringType)) {
4846 Error_InvokeOnDelegate (loc);
4850 MethodBase[] methods = me.Methods;
4853 // First we construct the set of applicable methods
4855 bool is_sorted = true;
4856 for (int i = 0; i < methods.Length; i++){
4857 Type decl_type = methods [i].DeclaringType;
4860 // If we have already found an applicable method
4861 // we eliminate all base types (Section 14.5.5.1)
4863 if ((applicable_type != null) &&
4864 IsAncestralType (decl_type, applicable_type))
4868 // Methods marked 'override' don't take part in 'applicable_type'
4869 // computation, nor in the actual overload resolution.
4870 // However, they still need to be emitted instead of a base virtual method.
4871 // We avoid doing the 'applicable' test here, since it'll anyway be applied
4872 // to the base virtual function, and IsOverride is much faster than IsApplicable.
4875 methods [i].IsVirtual &&
4876 (methods [i].Attributes & MethodAttributes.NewSlot) == 0) {
4877 if (candidate_overrides == null)
4878 candidate_overrides = new ArrayList ();
4879 candidate_overrides.Add (methods [i]);
4884 // Check if candidate is applicable (section 14.4.2.1)
4885 // Is candidate applicable in normal form?
4887 bool is_applicable = IsApplicable (
4888 ec, me, Arguments, arg_count, ref methods [i]);
4890 if (!is_applicable &&
4891 (IsParamsMethodApplicable (
4892 ec, me, Arguments, arg_count, ref methods [i]))) {
4893 MethodBase candidate = methods [i];
4894 if (candidate_to_form == null)
4895 candidate_to_form = new PtrHashtable ();
4896 candidate_to_form [candidate] = candidate;
4897 // Candidate is applicable in expanded form
4898 is_applicable = true;
4904 candidates.Add (methods [i]);
4906 if (applicable_type == null)
4907 applicable_type = decl_type;
4908 else if (applicable_type != decl_type) {
4910 if (IsAncestralType (applicable_type, decl_type))
4911 applicable_type = decl_type;
4915 int candidate_top = candidates.Count;
4917 if (applicable_type == null) {
4919 // Okay so we have failed to find anything so we
4920 // return by providing info about the closest match
4922 for (int i = 0; i < methods.Length; ++i) {
4923 MethodBase c = (MethodBase) methods [i];
4924 ParameterData pd = TypeManager.GetParameterData (c);
4926 if (pd.Count != arg_count)
4929 VerifyArgumentsCompat (ec, Arguments, arg_count,
4930 c, false, null, may_fail, loc);
4935 string report_name = me.Name;
4936 if (report_name == ".ctor")
4937 report_name = me.DeclaringType.ToString ();
4939 Error_WrongNumArguments (
4940 loc, report_name, arg_count);
4949 // At this point, applicable_type is _one_ of the most derived types
4950 // in the set of types containing the methods in this MethodGroup.
4951 // Filter the candidates so that they only contain methods from the
4952 // most derived types.
4955 int finalized = 0; // Number of finalized candidates
4958 // Invariant: applicable_type is a most derived type
4960 // We'll try to complete Section 14.5.5.1 for 'applicable_type' by
4961 // eliminating all it's base types. At the same time, we'll also move
4962 // every unrelated type to the end of the array, and pick the next
4963 // 'applicable_type'.
4965 Type next_applicable_type = null;
4966 int j = finalized; // where to put the next finalized candidate
4967 int k = finalized; // where to put the next undiscarded candidate
4968 for (int i = finalized; i < candidate_top; ++i) {
4969 MethodBase candidate = (MethodBase) candidates [i];
4970 Type decl_type = candidate.DeclaringType;
4972 if (decl_type == applicable_type) {
4973 candidates [k++] = candidates [j];
4974 candidates [j++] = candidates [i];
4978 if (IsAncestralType (decl_type, applicable_type))
4981 if (next_applicable_type != null &&
4982 IsAncestralType (decl_type, next_applicable_type))
4985 candidates [k++] = candidates [i];
4987 if (next_applicable_type == null ||
4988 IsAncestralType (next_applicable_type, decl_type))
4989 next_applicable_type = decl_type;
4992 applicable_type = next_applicable_type;
4995 } while (applicable_type != null);
4999 // Now we actually find the best method
5002 method = (MethodBase) candidates [0];
5003 method_params = candidate_to_form != null && candidate_to_form.Contains (method);
5004 for (int ix = 1; ix < candidate_top; ix++){
5005 MethodBase candidate = (MethodBase) candidates [ix];
5007 if (candidate == method)
5010 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
5012 if (BetterFunction (ec, Arguments, arg_count,
5013 candidate, cand_params,
5014 method, method_params, loc)) {
5016 method_params = cand_params;
5021 // Now check that there are no ambiguities i.e the selected method
5022 // should be better than all the others
5024 bool ambiguous = false;
5025 for (int ix = 0; ix < candidate_top; ix++){
5026 MethodBase candidate = (MethodBase) candidates [ix];
5028 if (candidate == method)
5031 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
5032 if (!BetterFunction (ec, Arguments, arg_count,
5033 method, method_params,
5034 candidate, cand_params,
5036 Report.SymbolRelatedToPreviousError (candidate);
5042 Report.SymbolRelatedToPreviousError (method);
5043 Report.Error (121, loc, "Ambiguous call when selecting function due to implicit casts");
5048 // If the method is a virtual function, pick an override closer to the LHS type.
5050 if (!me.IsBase && method.IsVirtual) {
5051 if ((method.Attributes & MethodAttributes.NewSlot) != MethodAttributes.NewSlot)
5052 throw new InternalErrorException (
5053 "Should not happen. An 'override' method took part in overload resolution: " + method);
5055 if (candidate_overrides != null)
5056 foreach (MethodBase candidate in candidate_overrides) {
5057 if (IsOverride (candidate, method))
5063 // And now check if the arguments are all
5064 // compatible, perform conversions if
5065 // necessary etc. and return if everything is
5068 if (!VerifyArgumentsCompat (ec, Arguments, arg_count, method,
5069 method_params, null, may_fail, loc))
5075 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
5077 if (name == "Finalize" && arg_count == 0) {
5078 Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
5081 Report.Error (1501, loc,
5082 "No overload for method `" + name + "' takes `" +
5083 arg_count + "' arguments");
5087 static void Error_InvokeOnDelegate (Location loc)
5089 Report.Error (1533, loc,
5090 "Invoke cannot be called directly on a delegate");
5093 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
5094 Type delegate_type, string arg_sig, string par_desc)
5096 if (delegate_type == null)
5097 Report.Error (1502, loc,
5098 "The best overloaded match for method '" +
5099 FullMethodDesc (method) +
5100 "' has some invalid arguments");
5102 Report.Error (1594, loc,
5103 "Delegate '" + delegate_type.ToString () +
5104 "' has some invalid arguments.");
5105 Report.Error (1503, loc,
5106 String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
5107 idx, arg_sig, par_desc));
5110 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
5111 int arg_count, MethodBase method,
5112 bool chose_params_expanded,
5113 Type delegate_type, bool may_fail,
5116 ParameterData pd = TypeManager.GetParameterData (method);
5117 int pd_count = pd.Count;
5119 for (int j = 0; j < arg_count; j++) {
5120 Argument a = (Argument) Arguments [j];
5121 Expression a_expr = a.Expr;
5122 Type parameter_type = pd.ParameterType (j);
5123 Parameter.Modifier pm = pd.ParameterModifier (j);
5125 if (pm == Parameter.Modifier.PARAMS){
5126 if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
5128 Error_InvalidArguments (
5129 loc, j, method, delegate_type,
5130 Argument.FullDesc (a), pd.ParameterDesc (j));
5134 if (chose_params_expanded)
5135 parameter_type = TypeManager.GetElementType (parameter_type);
5136 } else if (pm == Parameter.Modifier.ARGLIST){
5142 if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
5144 Error_InvalidArguments (
5145 loc, j, method, delegate_type,
5146 Argument.FullDesc (a), pd.ParameterDesc (j));
5154 if (!a.Type.Equals (parameter_type)){
5157 conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
5161 Error_InvalidArguments (
5162 loc, j, method, delegate_type,
5163 Argument.FullDesc (a), pd.ParameterDesc (j));
5168 // Update the argument with the implicit conversion
5174 if (parameter_type.IsPointer){
5181 Parameter.Modifier a_mod = a.GetParameterModifier () &
5182 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5183 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
5184 unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
5186 if (a_mod != p_mod &&
5187 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
5189 Report.Error (1502, loc,
5190 "The best overloaded match for method '" + FullMethodDesc (method)+
5191 "' has some invalid arguments");
5192 Report.Error (1503, loc,
5193 "Argument " + (j+1) +
5194 ": Cannot convert from '" + Argument.FullDesc (a)
5195 + "' to '" + pd.ParameterDesc (j) + "'");
5205 public override Expression DoResolve (EmitContext ec)
5208 // First, resolve the expression that is used to
5209 // trigger the invocation
5211 expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
5215 if (!(expr is MethodGroupExpr)) {
5216 Type expr_type = expr.Type;
5218 if (expr_type != null){
5219 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
5221 return (new DelegateInvocation (
5222 this.expr, Arguments, loc)).Resolve (ec);
5226 if (!(expr is MethodGroupExpr)){
5227 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup, loc);
5232 // Next, evaluate all the expressions in the argument list
5234 if (Arguments != null){
5235 foreach (Argument a in Arguments){
5236 if (!a.Resolve (ec, loc))
5241 MethodGroupExpr mg = (MethodGroupExpr) expr;
5242 method = OverloadResolve (ec, mg, Arguments, false, loc);
5247 MethodInfo mi = method as MethodInfo;
5249 type = TypeManager.TypeToCoreType (mi.ReturnType);
5250 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null)) {
5251 SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
5255 Expression iexpr = mg.InstanceExpression;
5256 if (mi.IsStatic && (iexpr != null) && !(iexpr is This)) {
5257 if (mg.IdenticalTypeName)
5258 mg.InstanceExpression = null;
5260 MemberAccess.error176 (loc, mi.Name);
5266 if (type.IsPointer){
5274 // Only base will allow this invocation to happen.
5276 if (mg.IsBase && method.IsAbstract){
5277 Report.Error (205, loc, "Cannot call an abstract base member: " +
5278 FullMethodDesc (method));
5282 if (method.Name == "Finalize" && Arguments == null) {
5283 Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
5287 if ((method.Attributes & MethodAttributes.SpecialName) != 0) {
5288 if (TypeManager.LookupDeclSpace (method.DeclaringType) != null || TypeManager.IsSpecialMethod (method)) {
5289 Report.Error (571, loc, TypeManager.CSharpSignature (method) + ": can not call operator or accessor");
5294 if (mg.InstanceExpression != null)
5295 mg.InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
5297 eclass = ExprClass.Value;
5302 // Emits the list of arguments as an array
5304 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
5306 ILGenerator ig = ec.ig;
5307 int count = arguments.Count - idx;
5308 Argument a = (Argument) arguments [idx];
5309 Type t = a.Expr.Type;
5311 IntConstant.EmitInt (ig, count);
5312 ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
5314 int top = arguments.Count;
5315 for (int j = idx; j < top; j++){
5316 a = (Argument) arguments [j];
5318 ig.Emit (OpCodes.Dup);
5319 IntConstant.EmitInt (ig, j - idx);
5322 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj);
5324 ig.Emit (OpCodes.Ldelema, t);
5329 ig.Emit (OpCodes.Stobj, t);
5336 /// Emits a list of resolved Arguments that are in the arguments
5339 /// The MethodBase argument might be null if the
5340 /// emission of the arguments is known not to contain
5341 /// a `params' field (for example in constructors or other routines
5342 /// that keep their arguments in this structure)
5344 /// if `dup_args' is true, a copy of the arguments will be left
5345 /// on the stack. If `dup_args' is true, you can specify `this_arg'
5346 /// which will be duplicated before any other args. Only EmitCall
5347 /// should be using this interface.
5349 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments, bool dup_args, LocalTemporary this_arg)
5353 pd = TypeManager.GetParameterData (mb);
5357 LocalTemporary [] temps = null;
5360 temps = new LocalTemporary [arguments.Count];
5363 // If we are calling a params method with no arguments, special case it
5365 if (arguments == null){
5366 if (pd != null && pd.Count > 0 &&
5367 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
5368 ILGenerator ig = ec.ig;
5370 IntConstant.EmitInt (ig, 0);
5371 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
5377 int top = arguments.Count;
5379 for (int i = 0; i < top; i++){
5380 Argument a = (Argument) arguments [i];
5383 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
5385 // Special case if we are passing the same data as the
5386 // params argument, do not put it in an array.
5388 if (pd.ParameterType (i) == a.Type)
5391 EmitParams (ec, i, arguments);
5398 ec.ig.Emit (OpCodes.Dup);
5399 (temps [i] = new LocalTemporary (ec, a.Type)).Store (ec);
5404 if (this_arg != null)
5407 for (int i = 0; i < top; i ++)
5408 temps [i].Emit (ec);
5411 if (pd != null && pd.Count > top &&
5412 pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
5413 ILGenerator ig = ec.ig;
5415 IntConstant.EmitInt (ig, 0);
5416 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
5420 static Type[] GetVarargsTypes (EmitContext ec, MethodBase mb,
5421 ArrayList arguments)
5423 ParameterData pd = TypeManager.GetParameterData (mb);
5425 if (arguments == null)
5426 return new Type [0];
5428 Argument a = (Argument) arguments [pd.Count - 1];
5429 Arglist list = (Arglist) a.Expr;
5431 return list.ArgumentTypes;
5435 /// This checks the ConditionalAttribute on the method
5437 static bool IsMethodExcluded (MethodBase method, EmitContext ec)
5439 if (method.IsConstructor)
5442 IMethodData md = TypeManager.GetMethod (method);
5444 return md.IsExcluded (ec);
5446 // For some methods (generated by delegate class) GetMethod returns null
5447 // because they are not included in builder_to_method table
5448 if (method.DeclaringType is TypeBuilder)
5451 return AttributeTester.IsConditionalMethodExcluded (method);
5455 /// is_base tells whether we want to force the use of the `call'
5456 /// opcode instead of using callvirt. Call is required to call
5457 /// a specific method, while callvirt will always use the most
5458 /// recent method in the vtable.
5460 /// is_static tells whether this is an invocation on a static method
5462 /// instance_expr is an expression that represents the instance
5463 /// it must be non-null if is_static is false.
5465 /// method is the method to invoke.
5467 /// Arguments is the list of arguments to pass to the method or constructor.
5469 public static void EmitCall (EmitContext ec, bool is_base,
5470 bool is_static, Expression instance_expr,
5471 MethodBase method, ArrayList Arguments, Location loc)
5473 EmitCall (ec, is_base, is_static, instance_expr, method, Arguments, loc, false, false);
5476 // `dup_args' leaves an extra copy of the arguments on the stack
5477 // `omit_args' does not leave any arguments at all.
5478 // So, basically, you could make one call with `dup_args' set to true,
5479 // and then another with `omit_args' set to true, and the two calls
5480 // would have the same set of arguments. However, each argument would
5481 // only have been evaluated once.
5482 public static void EmitCall (EmitContext ec, bool is_base,
5483 bool is_static, Expression instance_expr,
5484 MethodBase method, ArrayList Arguments, Location loc,
5485 bool dup_args, bool omit_args)
5487 ILGenerator ig = ec.ig;
5488 bool struct_call = false;
5489 bool this_call = false;
5490 LocalTemporary this_arg = null;
5492 Type decl_type = method.DeclaringType;
5494 if (!RootContext.StdLib) {
5495 // Replace any calls to the system's System.Array type with calls to
5496 // the newly created one.
5497 if (method == TypeManager.system_int_array_get_length)
5498 method = TypeManager.int_array_get_length;
5499 else if (method == TypeManager.system_int_array_get_rank)
5500 method = TypeManager.int_array_get_rank;
5501 else if (method == TypeManager.system_object_array_clone)
5502 method = TypeManager.object_array_clone;
5503 else if (method == TypeManager.system_int_array_get_length_int)
5504 method = TypeManager.int_array_get_length_int;
5505 else if (method == TypeManager.system_int_array_get_lower_bound_int)
5506 method = TypeManager.int_array_get_lower_bound_int;
5507 else if (method == TypeManager.system_int_array_get_upper_bound_int)
5508 method = TypeManager.int_array_get_upper_bound_int;
5509 else if (method == TypeManager.system_void_array_copyto_array_int)
5510 method = TypeManager.void_array_copyto_array_int;
5513 if (ec.TestObsoleteMethodUsage) {
5515 // This checks ObsoleteAttribute on the method and on the declaring type
5517 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
5519 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
5522 oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
5524 AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
5528 if (IsMethodExcluded (method, ec))
5532 this_call = instance_expr == null;
5533 if (decl_type.IsValueType || (!this_call && instance_expr.Type.IsValueType))
5537 // If this is ourselves, push "this"
5542 ig.Emit (OpCodes.Ldarg_0);
5546 // Push the instance expression
5548 if (instance_expr.Type.IsValueType) {
5550 // Special case: calls to a function declared in a
5551 // reference-type with a value-type argument need
5552 // to have their value boxed.
5553 if (decl_type.IsValueType) {
5555 // If the expression implements IMemoryLocation, then
5556 // we can optimize and use AddressOf on the
5559 // If not we have to use some temporary storage for
5561 if (instance_expr is IMemoryLocation) {
5562 ((IMemoryLocation)instance_expr).
5563 AddressOf (ec, AddressOp.LoadStore);
5565 LocalTemporary temp = new LocalTemporary (ec, instance_expr.Type);
5566 instance_expr.Emit (ec);
5568 temp.AddressOf (ec, AddressOp.Load);
5571 // avoid the overhead of doing this all the time.
5573 t = TypeManager.GetReferenceType (instance_expr.Type);
5575 instance_expr.Emit (ec);
5576 ig.Emit (OpCodes.Box, instance_expr.Type);
5577 t = TypeManager.object_type;
5580 instance_expr.Emit (ec);
5581 t = instance_expr.Type;
5586 this_arg = new LocalTemporary (ec, t);
5587 ig.Emit (OpCodes.Dup);
5588 this_arg.Store (ec);
5594 EmitArguments (ec, method, Arguments, dup_args, this_arg);
5597 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
5598 call_op = OpCodes.Call;
5600 call_op = OpCodes.Callvirt;
5602 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
5603 Type[] varargs_types = GetVarargsTypes (ec, method, Arguments);
5604 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
5611 // and DoFoo is not virtual, you can omit the callvirt,
5612 // because you don't need the null checking behavior.
5614 if (method is MethodInfo)
5615 ig.Emit (call_op, (MethodInfo) method);
5617 ig.Emit (call_op, (ConstructorInfo) method);
5620 public override void Emit (EmitContext ec)
5622 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5624 EmitCall (ec, mg.IsBase, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5627 public override void EmitStatement (EmitContext ec)
5632 // Pop the return value if there is one
5634 if (method is MethodInfo){
5635 Type ret = ((MethodInfo)method).ReturnType;
5636 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5637 ec.ig.Emit (OpCodes.Pop);
5642 public class InvocationOrCast : ExpressionStatement
5645 Expression argument;
5647 public InvocationOrCast (Expression expr, Expression argument, Location loc)
5650 this.argument = argument;
5654 public override Expression DoResolve (EmitContext ec)
5657 // First try to resolve it as a cast.
5659 TypeExpr te = expr.ResolveAsTypeTerminal (ec, true);
5661 Cast cast = new Cast (te, argument, loc);
5662 return cast.Resolve (ec);
5666 // This can either be a type or a delegate invocation.
5667 // Let's just resolve it and see what we'll get.
5669 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5674 // Ok, so it's a Cast.
5676 if (expr.eclass == ExprClass.Type) {
5677 Cast cast = new Cast (new TypeExpression (expr.Type, loc), argument, loc);
5678 return cast.Resolve (ec);
5682 // It's a delegate invocation.
5684 if (!TypeManager.IsDelegateType (expr.Type)) {
5685 Error (149, "Method name expected");
5689 ArrayList args = new ArrayList ();
5690 args.Add (new Argument (argument, Argument.AType.Expression));
5691 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5692 return invocation.Resolve (ec);
5697 Error (201, "Only assignment, call, increment, decrement and new object " +
5698 "expressions can be used as a statement");
5701 public override ExpressionStatement ResolveStatement (EmitContext ec)
5704 // First try to resolve it as a cast.
5706 TypeExpr te = expr.ResolveAsTypeTerminal (ec, true);
5713 // This can either be a type or a delegate invocation.
5714 // Let's just resolve it and see what we'll get.
5716 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5717 if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5723 // It's a delegate invocation.
5725 if (!TypeManager.IsDelegateType (expr.Type)) {
5726 Error (149, "Method name expected");
5730 ArrayList args = new ArrayList ();
5731 args.Add (new Argument (argument, Argument.AType.Expression));
5732 DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5733 return invocation.ResolveStatement (ec);
5736 public override void Emit (EmitContext ec)
5738 throw new Exception ("Cannot happen");
5741 public override void EmitStatement (EmitContext ec)
5743 throw new Exception ("Cannot happen");
5748 // This class is used to "disable" the code generation for the
5749 // temporary variable when initializing value types.
5751 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5752 public void AddressOf (EmitContext ec, AddressOp Mode)
5759 /// Implements the new expression
5761 public class New : ExpressionStatement, IMemoryLocation {
5762 public readonly ArrayList Arguments;
5765 // During bootstrap, it contains the RequestedType,
5766 // but if `type' is not null, it *might* contain a NewDelegate
5767 // (because of field multi-initialization)
5769 public Expression RequestedType;
5771 MethodBase method = null;
5774 // If set, the new expression is for a value_target, and
5775 // we will not leave anything on the stack.
5777 Expression value_target;
5778 bool value_target_set = false;
5780 public New (Expression requested_type, ArrayList arguments, Location l)
5782 RequestedType = requested_type;
5783 Arguments = arguments;
5787 public bool SetValueTypeVariable (Expression value)
5789 value_target = value;
5790 value_target_set = true;
5791 if (!(value_target is IMemoryLocation)){
5792 Error_UnexpectedKind ("variable", loc);
5799 // This function is used to disable the following code sequence for
5800 // value type initialization:
5802 // AddressOf (temporary)
5806 // Instead the provide will have provided us with the address on the
5807 // stack to store the results.
5809 static Expression MyEmptyExpression;
5811 public void DisableTemporaryValueType ()
5813 if (MyEmptyExpression == null)
5814 MyEmptyExpression = new EmptyAddressOf ();
5817 // To enable this, look into:
5818 // test-34 and test-89 and self bootstrapping.
5820 // For instance, we can avoid a copy by using `newobj'
5821 // instead of Call + Push-temp on value types.
5822 // value_target = MyEmptyExpression;
5827 /// Converts complex core type syntax like 'new int ()' to simple constant
5829 Expression Constantify (Type t)
5831 if (t == TypeManager.int32_type)
5832 return new IntConstant (0);
5833 if (t == TypeManager.uint32_type)
5834 return new UIntConstant (0);
5835 if (t == TypeManager.int64_type)
5836 return new LongConstant (0);
5837 if (t == TypeManager.uint64_type)
5838 return new ULongConstant (0);
5839 if (t == TypeManager.float_type)
5840 return new FloatConstant (0);
5841 if (t == TypeManager.double_type)
5842 return new DoubleConstant (0);
5843 if (t == TypeManager.short_type)
5844 return new ShortConstant (0);
5845 if (t == TypeManager.ushort_type)
5846 return new UShortConstant (0);
5847 if (t == TypeManager.sbyte_type)
5848 return new SByteConstant (0);
5849 if (t == TypeManager.byte_type)
5850 return new ByteConstant (0);
5851 if (t == TypeManager.char_type)
5852 return new CharConstant ('\0');
5853 if (t == TypeManager.bool_type)
5854 return new BoolConstant (false);
5855 if (t == TypeManager.decimal_type)
5856 return new DecimalConstant (0);
5861 public override Expression DoResolve (EmitContext ec)
5864 // The New DoResolve might be called twice when initializing field
5865 // expressions (see EmitFieldInitializers, the call to
5866 // GetInitializerExpression will perform a resolve on the expression,
5867 // and later the assign will trigger another resolution
5869 // This leads to bugs (#37014)
5872 if (RequestedType is NewDelegate)
5873 return RequestedType;
5877 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec, false);
5881 type = texpr.ResolveType (ec);
5883 if (Arguments == null) {
5884 Expression c = Constantify (type);
5889 CheckObsoleteAttribute (type);
5891 bool IsDelegate = TypeManager.IsDelegateType (type);
5894 RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5895 if (RequestedType != null)
5896 if (!(RequestedType is DelegateCreation))
5897 throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
5898 return RequestedType;
5901 if (type.IsAbstract && type.IsSealed) {
5902 Report.Error (712, loc, "Cannot create an instance of the static class '{0}'", TypeManager.CSharpName (type));
5906 if (type.IsInterface || type.IsAbstract){
5907 Error (144, "It is not possible to create instances of interfaces or abstract classes");
5911 bool is_struct = type.IsValueType;
5912 eclass = ExprClass.Value;
5915 // SRE returns a match for .ctor () on structs (the object constructor),
5916 // so we have to manually ignore it.
5918 if (is_struct && Arguments == null)
5922 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
5923 ml = MemberLookupFinal (ec, type, type, ".ctor",
5924 MemberTypes.Constructor,
5925 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5930 if (! (ml is MethodGroupExpr)){
5932 ml.Error_UnexpectedKind ("method group", loc);
5938 if (Arguments != null){
5939 foreach (Argument a in Arguments){
5940 if (!a.Resolve (ec, loc))
5945 method = Invocation.OverloadResolve (
5946 ec, (MethodGroupExpr) ml, Arguments, true, loc);
5950 if (method == null) {
5951 if (almostMatchedMembers.Count != 0) {
5952 MemberLookupFailed (ec, type, type, ".ctor", null, true, loc);
5956 if (!is_struct || Arguments.Count > 0) {
5957 Error (1501, String.Format (
5958 "New invocation: Can not find a constructor in `{0}' for this argument list",
5959 TypeManager.CSharpName (type)));
5968 // This DoEmit can be invoked in two contexts:
5969 // * As a mechanism that will leave a value on the stack (new object)
5970 // * As one that wont (init struct)
5972 // You can control whether a value is required on the stack by passing
5973 // need_value_on_stack. The code *might* leave a value on the stack
5974 // so it must be popped manually
5976 // If we are dealing with a ValueType, we have a few
5977 // situations to deal with:
5979 // * The target is a ValueType, and we have been provided
5980 // the instance (this is easy, we are being assigned).
5982 // * The target of New is being passed as an argument,
5983 // to a boxing operation or a function that takes a
5986 // In this case, we need to create a temporary variable
5987 // that is the argument of New.
5989 // Returns whether a value is left on the stack
5991 bool DoEmit (EmitContext ec, bool need_value_on_stack)
5993 bool is_value_type = type.IsValueType;
5994 ILGenerator ig = ec.ig;
5999 // Allow DoEmit() to be called multiple times.
6000 // We need to create a new LocalTemporary each time since
6001 // you can't share LocalBuilders among ILGeneators.
6002 if (!value_target_set)
6003 value_target = new LocalTemporary (ec, type);
6005 ml = (IMemoryLocation) value_target;
6006 ml.AddressOf (ec, AddressOp.Store);
6010 Invocation.EmitArguments (ec, method, Arguments, false, null);
6014 ig.Emit (OpCodes.Initobj, type);
6016 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6017 if (need_value_on_stack){
6018 value_target.Emit (ec);
6023 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
6028 public override void Emit (EmitContext ec)
6033 public override void EmitStatement (EmitContext ec)
6035 if (DoEmit (ec, false))
6036 ec.ig.Emit (OpCodes.Pop);
6039 public void AddressOf (EmitContext ec, AddressOp Mode)
6041 if (!type.IsValueType){
6043 // We throw an exception. So far, I believe we only need to support
6045 // foreach (int j in new StructType ())
6048 throw new Exception ("AddressOf should not be used for classes");
6051 if (!value_target_set)
6052 value_target = new LocalTemporary (ec, type);
6054 IMemoryLocation ml = (IMemoryLocation) value_target;
6055 ml.AddressOf (ec, AddressOp.Store);
6057 Invocation.EmitArguments (ec, method, Arguments, false, null);
6060 ec.ig.Emit (OpCodes.Initobj, type);
6062 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
6064 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
6069 /// 14.5.10.2: Represents an array creation expression.
6073 /// There are two possible scenarios here: one is an array creation
6074 /// expression that specifies the dimensions and optionally the
6075 /// initialization data and the other which does not need dimensions
6076 /// specified but where initialization data is mandatory.
6078 public class ArrayCreation : Expression {
6079 Expression requested_base_type;
6080 ArrayList initializers;
6083 // The list of Argument types.
6084 // This is used to construct the `newarray' or constructor signature
6086 ArrayList arguments;
6089 // Method used to create the array object.
6091 MethodBase new_method = null;
6093 Type array_element_type;
6094 Type underlying_type;
6095 bool is_one_dimensional = false;
6096 bool is_builtin_type = false;
6097 bool expect_initializers = false;
6098 int num_arguments = 0;
6102 ArrayList array_data;
6107 // The number of array initializers that we can handle
6108 // via the InitializeArray method - through EmitStaticInitializers
6110 int num_automatic_initializers;
6112 const int max_automatic_initializers = 6;
6114 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
6116 this.requested_base_type = requested_base_type;
6117 this.initializers = initializers;
6121 arguments = new ArrayList ();
6123 foreach (Expression e in exprs) {
6124 arguments.Add (new Argument (e, Argument.AType.Expression));
6129 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
6131 this.requested_base_type = requested_base_type;
6132 this.initializers = initializers;
6136 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
6138 //string tmp = rank.Substring (rank.LastIndexOf ('['));
6140 //dimensions = tmp.Length - 1;
6141 expect_initializers = true;
6144 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
6146 StringBuilder sb = new StringBuilder (rank);
6149 for (int i = 1; i < idx_count; i++)
6154 return new ComposedCast (base_type, sb.ToString (), loc);
6157 void Error_IncorrectArrayInitializer ()
6159 Error (178, "Incorrectly structured array initializer");
6162 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
6164 if (specified_dims) {
6165 Argument a = (Argument) arguments [idx];
6167 if (!a.Resolve (ec, loc))
6170 if (!(a.Expr is Constant)) {
6171 Error (150, "A constant value is expected");
6175 int value = (int) ((Constant) a.Expr).GetValue ();
6177 if (value != probe.Count) {
6178 Error_IncorrectArrayInitializer ();
6182 bounds [idx] = value;
6185 int child_bounds = -1;
6186 foreach (object o in probe) {
6187 if (o is ArrayList) {
6188 int current_bounds = ((ArrayList) o).Count;
6190 if (child_bounds == -1)
6191 child_bounds = current_bounds;
6193 else if (child_bounds != current_bounds){
6194 Error_IncorrectArrayInitializer ();
6197 if (specified_dims && (idx + 1 >= arguments.Count)){
6198 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
6202 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
6206 if (child_bounds != -1){
6207 Error_IncorrectArrayInitializer ();
6211 Expression tmp = (Expression) o;
6212 tmp = tmp.Resolve (ec);
6216 // Console.WriteLine ("I got: " + tmp);
6217 // Handle initialization from vars, fields etc.
6219 Expression conv = Convert.ImplicitConversionRequired (
6220 ec, tmp, underlying_type, loc);
6225 if (conv is StringConstant || conv is DecimalConstant || conv is NullCast) {
6226 // These are subclasses of Constant that can appear as elements of an
6227 // array that cannot be statically initialized (with num_automatic_initializers
6228 // > max_automatic_initializers), so num_automatic_initializers should be left as zero.
6229 array_data.Add (conv);
6230 } else if (conv is Constant) {
6231 // These are the types of Constant that can appear in arrays that can be
6232 // statically allocated.
6233 array_data.Add (conv);
6234 num_automatic_initializers++;
6236 array_data.Add (conv);
6243 public void UpdateIndices (EmitContext ec)
6246 for (ArrayList probe = initializers; probe != null;) {
6247 if (probe.Count > 0 && probe [0] is ArrayList) {
6248 Expression e = new IntConstant (probe.Count);
6249 arguments.Add (new Argument (e, Argument.AType.Expression));
6251 bounds [i++] = probe.Count;
6253 probe = (ArrayList) probe [0];
6256 Expression e = new IntConstant (probe.Count);
6257 arguments.Add (new Argument (e, Argument.AType.Expression));
6259 bounds [i++] = probe.Count;
6266 public bool ValidateInitializers (EmitContext ec, Type array_type)
6268 if (initializers == null) {
6269 if (expect_initializers)
6275 if (underlying_type == null)
6279 // We use this to store all the date values in the order in which we
6280 // will need to store them in the byte blob later
6282 array_data = new ArrayList ();
6283 bounds = new Hashtable ();
6287 if (arguments != null) {
6288 ret = CheckIndices (ec, initializers, 0, true);
6291 arguments = new ArrayList ();
6293 ret = CheckIndices (ec, initializers, 0, false);
6300 if (arguments.Count != dimensions) {
6301 Error_IncorrectArrayInitializer ();
6310 // Converts `source' to an int, uint, long or ulong.
6312 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
6316 bool old_checked = ec.CheckState;
6317 ec.CheckState = true;
6319 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
6320 if (target == null){
6321 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
6322 if (target == null){
6323 target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
6324 if (target == null){
6325 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
6327 Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
6331 ec.CheckState = old_checked;
6334 // Only positive constants are allowed at compile time
6336 if (target is Constant){
6337 if (target is IntConstant){
6338 if (((IntConstant) target).Value < 0){
6339 Expression.Error_NegativeArrayIndex (loc);
6344 if (target is LongConstant){
6345 if (((LongConstant) target).Value < 0){
6346 Expression.Error_NegativeArrayIndex (loc);
6357 // Creates the type of the array
6359 bool LookupType (EmitContext ec)
6361 StringBuilder array_qualifier = new StringBuilder (rank);
6364 // `In the first form allocates an array instace of the type that results
6365 // from deleting each of the individual expression from the expression list'
6367 if (num_arguments > 0) {
6368 array_qualifier.Append ("[");
6369 for (int i = num_arguments-1; i > 0; i--)
6370 array_qualifier.Append (",");
6371 array_qualifier.Append ("]");
6377 TypeExpr array_type_expr;
6378 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
6379 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec, false);
6380 if (array_type_expr == null)
6383 type = array_type_expr.ResolveType (ec);
6385 if (!type.IsArray) {
6386 Error (622, "Can only use array initializer expressions to assign to array types. Try using a new expression instead.");
6389 underlying_type = TypeManager.GetElementType (type);
6390 dimensions = type.GetArrayRank ();
6395 public override Expression DoResolve (EmitContext ec)
6399 if (!LookupType (ec))
6403 // First step is to validate the initializers and fill
6404 // in any missing bits
6406 if (!ValidateInitializers (ec, type))
6409 if (arguments == null)
6412 arg_count = arguments.Count;
6413 foreach (Argument a in arguments){
6414 if (!a.Resolve (ec, loc))
6417 Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
6418 if (real_arg == null)
6425 array_element_type = TypeManager.GetElementType (type);
6427 if (array_element_type.IsAbstract && array_element_type.IsSealed) {
6428 Report.Error (719, loc, "'{0}': array elements cannot be of static type", TypeManager.CSharpName (array_element_type));
6432 if (arg_count == 1) {
6433 is_one_dimensional = true;
6434 eclass = ExprClass.Value;
6438 is_builtin_type = TypeManager.IsBuiltinType (type);
6440 if (is_builtin_type) {
6443 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
6444 AllBindingFlags, loc);
6446 if (!(ml is MethodGroupExpr)) {
6447 ml.Error_UnexpectedKind ("method group", loc);
6452 Error (-6, "New invocation: Can not find a constructor for " +
6453 "this argument list");
6457 new_method = Invocation.OverloadResolve (
6458 ec, (MethodGroupExpr) ml, arguments, false, loc);
6460 if (new_method == null) {
6461 Error (-6, "New invocation: Can not find a constructor for " +
6462 "this argument list");
6466 eclass = ExprClass.Value;
6469 ModuleBuilder mb = CodeGen.Module.Builder;
6470 ArrayList args = new ArrayList ();
6472 if (arguments != null) {
6473 for (int i = 0; i < arg_count; i++)
6474 args.Add (TypeManager.int32_type);
6477 Type [] arg_types = null;
6480 arg_types = new Type [args.Count];
6482 args.CopyTo (arg_types, 0);
6484 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
6487 if (new_method == null) {
6488 Error (-6, "New invocation: Can not find a constructor for " +
6489 "this argument list");
6493 eclass = ExprClass.Value;
6498 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
6503 int count = array_data.Count;
6505 if (underlying_type.IsEnum)
6506 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
6508 factor = GetTypeSize (underlying_type);
6510 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
6512 data = new byte [(count * factor + 4) & ~3];
6515 for (int i = 0; i < count; ++i) {
6516 object v = array_data [i];
6518 if (v is EnumConstant)
6519 v = ((EnumConstant) v).Child;
6521 if (v is Constant && !(v is StringConstant))
6522 v = ((Constant) v).GetValue ();
6528 if (underlying_type == TypeManager.int64_type){
6529 if (!(v is Expression)){
6530 long val = (long) v;
6532 for (int j = 0; j < factor; ++j) {
6533 data [idx + j] = (byte) (val & 0xFF);
6537 } else if (underlying_type == TypeManager.uint64_type){
6538 if (!(v is Expression)){
6539 ulong val = (ulong) v;
6541 for (int j = 0; j < factor; ++j) {
6542 data [idx + j] = (byte) (val & 0xFF);
6546 } else if (underlying_type == TypeManager.float_type) {
6547 if (!(v is Expression)){
6548 element = BitConverter.GetBytes ((float) v);
6550 for (int j = 0; j < factor; ++j)
6551 data [idx + j] = element [j];
6553 } else if (underlying_type == TypeManager.double_type) {
6554 if (!(v is Expression)){
6555 element = BitConverter.GetBytes ((double) v);
6557 for (int j = 0; j < factor; ++j)
6558 data [idx + j] = element [j];
6560 } else if (underlying_type == TypeManager.char_type){
6561 if (!(v is Expression)){
6562 int val = (int) ((char) v);
6564 data [idx] = (byte) (val & 0xff);
6565 data [idx+1] = (byte) (val >> 8);
6567 } else if (underlying_type == TypeManager.short_type){
6568 if (!(v is Expression)){
6569 int val = (int) ((short) v);
6571 data [idx] = (byte) (val & 0xff);
6572 data [idx+1] = (byte) (val >> 8);
6574 } else if (underlying_type == TypeManager.ushort_type){
6575 if (!(v is Expression)){
6576 int val = (int) ((ushort) v);
6578 data [idx] = (byte) (val & 0xff);
6579 data [idx+1] = (byte) (val >> 8);
6581 } else if (underlying_type == TypeManager.int32_type) {
6582 if (!(v is Expression)){
6585 data [idx] = (byte) (val & 0xff);
6586 data [idx+1] = (byte) ((val >> 8) & 0xff);
6587 data [idx+2] = (byte) ((val >> 16) & 0xff);
6588 data [idx+3] = (byte) (val >> 24);
6590 } else if (underlying_type == TypeManager.uint32_type) {
6591 if (!(v is Expression)){
6592 uint val = (uint) v;
6594 data [idx] = (byte) (val & 0xff);
6595 data [idx+1] = (byte) ((val >> 8) & 0xff);
6596 data [idx+2] = (byte) ((val >> 16) & 0xff);
6597 data [idx+3] = (byte) (val >> 24);
6599 } else if (underlying_type == TypeManager.sbyte_type) {
6600 if (!(v is Expression)){
6601 sbyte val = (sbyte) v;
6602 data [idx] = (byte) val;
6604 } else if (underlying_type == TypeManager.byte_type) {
6605 if (!(v is Expression)){
6606 byte val = (byte) v;
6607 data [idx] = (byte) val;
6609 } else if (underlying_type == TypeManager.bool_type) {
6610 if (!(v is Expression)){
6611 bool val = (bool) v;
6612 data [idx] = (byte) (val ? 1 : 0);
6614 } else if (underlying_type == TypeManager.decimal_type){
6615 if (!(v is Expression)){
6616 int [] bits = Decimal.GetBits ((decimal) v);
6619 // FIXME: For some reason, this doesn't work on the MS runtime.
6620 int [] nbits = new int [4];
6621 nbits [0] = bits [3];
6622 nbits [1] = bits [2];
6623 nbits [2] = bits [0];
6624 nbits [3] = bits [1];
6626 for (int j = 0; j < 4; j++){
6627 data [p++] = (byte) (nbits [j] & 0xff);
6628 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6629 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6630 data [p++] = (byte) (nbits [j] >> 24);
6634 throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
6643 // Emits the initializers for the array
6645 void EmitStaticInitializers (EmitContext ec)
6648 // First, the static data
6651 ILGenerator ig = ec.ig;
6653 byte [] data = MakeByteBlob (array_data, underlying_type, loc);
6655 fb = RootContext.MakeStaticData (data);
6657 ig.Emit (OpCodes.Dup);
6658 ig.Emit (OpCodes.Ldtoken, fb);
6659 ig.Emit (OpCodes.Call,
6660 TypeManager.void_initializearray_array_fieldhandle);
6664 // Emits pieces of the array that can not be computed at compile
6665 // time (variables and string locations).
6667 // This always expect the top value on the stack to be the array
6669 void EmitDynamicInitializers (EmitContext ec)
6671 ILGenerator ig = ec.ig;
6672 int dims = bounds.Count;
6673 int [] current_pos = new int [dims];
6674 int top = array_data.Count;
6676 MethodInfo set = null;
6680 ModuleBuilder mb = null;
6681 mb = CodeGen.Module.Builder;
6682 args = new Type [dims + 1];
6685 for (j = 0; j < dims; j++)
6686 args [j] = TypeManager.int32_type;
6688 args [j] = array_element_type;
6690 set = mb.GetArrayMethod (
6692 CallingConventions.HasThis | CallingConventions.Standard,
6693 TypeManager.void_type, args);
6696 for (int i = 0; i < top; i++){
6698 Expression e = null;
6700 if (array_data [i] is Expression)
6701 e = (Expression) array_data [i];
6705 // Basically we do this for string literals and
6706 // other non-literal expressions
6708 if (e is EnumConstant){
6709 e = ((EnumConstant) e).Child;
6712 if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6713 num_automatic_initializers <= max_automatic_initializers) {
6714 Type etype = e.Type;
6716 ig.Emit (OpCodes.Dup);
6718 for (int idx = 0; idx < dims; idx++)
6719 IntConstant.EmitInt (ig, current_pos [idx]);
6722 // If we are dealing with a struct, get the
6723 // address of it, so we can store it.
6726 etype.IsSubclassOf (TypeManager.value_type) &&
6727 (!TypeManager.IsBuiltinOrEnum (etype) ||
6728 etype == TypeManager.decimal_type)) {
6733 // Let new know that we are providing
6734 // the address where to store the results
6736 n.DisableTemporaryValueType ();
6739 ig.Emit (OpCodes.Ldelema, etype);
6746 OpCode op = ArrayAccess.GetStoreOpcode (etype, out is_stobj);
6748 ig.Emit (OpCodes.Stobj, etype);
6752 ig.Emit (OpCodes.Call, set);
6760 for (int j = dims - 1; j >= 0; j--){
6762 if (current_pos [j] < (int) bounds [j])
6764 current_pos [j] = 0;
6769 void EmitArrayArguments (EmitContext ec)
6771 ILGenerator ig = ec.ig;
6773 foreach (Argument a in arguments) {
6774 Type atype = a.Type;
6777 if (atype == TypeManager.uint64_type)
6778 ig.Emit (OpCodes.Conv_Ovf_U4);
6779 else if (atype == TypeManager.int64_type)
6780 ig.Emit (OpCodes.Conv_Ovf_I4);
6784 public override void Emit (EmitContext ec)
6786 ILGenerator ig = ec.ig;
6788 EmitArrayArguments (ec);
6789 if (is_one_dimensional)
6790 ig.Emit (OpCodes.Newarr, array_element_type);
6792 if (is_builtin_type)
6793 ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6795 ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6798 if (initializers != null){
6800 // FIXME: Set this variable correctly.
6802 bool dynamic_initializers = true;
6804 // This will never be true for array types that cannot be statically
6805 // initialized. num_automatic_initializers will always be zero. See
6807 if (num_automatic_initializers > max_automatic_initializers)
6808 EmitStaticInitializers (ec);
6810 if (dynamic_initializers)
6811 EmitDynamicInitializers (ec);
6815 public object EncodeAsAttribute ()
6817 if (!is_one_dimensional){
6818 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6822 if (array_data == null){
6823 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6827 object [] ret = new object [array_data.Count];
6829 foreach (Expression e in array_data){
6832 if (e is NullLiteral)
6835 if (!Attribute.GetAttributeArgumentExpression (e, Location, array_element_type, out v))
6845 /// Represents the `this' construct
6847 public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6850 VariableInfo variable_info;
6852 public This (Block block, Location loc)
6858 public This (Location loc)
6863 public VariableInfo VariableInfo {
6864 get { return variable_info; }
6867 public bool VerifyFixed (bool is_expression)
6869 if ((variable_info == null) || (variable_info.LocalInfo == null))
6872 return variable_info.LocalInfo.IsFixed;
6875 public bool ResolveBase (EmitContext ec)
6877 eclass = ExprClass.Variable;
6878 type = ec.ContainerType;
6881 Error (26, "Keyword this not valid in static code");
6885 if ((block != null) && (block.ThisVariable != null))
6886 variable_info = block.ThisVariable.VariableInfo;
6888 if (ec.CurrentAnonymousMethod != null)
6894 public override Expression DoResolve (EmitContext ec)
6896 if (!ResolveBase (ec))
6899 if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
6900 Error (188, "The this object cannot be used before all " +
6901 "of its fields are assigned to");
6902 variable_info.SetAssigned (ec);
6906 if (ec.IsFieldInitializer) {
6907 Error (27, "Keyword `this' can't be used outside a constructor, " +
6908 "a method or a property.");
6915 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6917 if (!ResolveBase (ec))
6920 if (variable_info != null)
6921 variable_info.SetAssigned (ec);
6923 if (ec.TypeContainer is Class){
6924 Error (1604, "Cannot assign to 'this' because it is read-only");
6931 public void Emit (EmitContext ec, bool leave_copy)
6935 ec.ig.Emit (OpCodes.Dup);
6938 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
6940 ILGenerator ig = ec.ig;
6942 if (ec.TypeContainer is Struct){
6946 ec.ig.Emit (OpCodes.Dup);
6947 ig.Emit (OpCodes.Stobj, type);
6949 throw new Exception ("how did you get here");
6953 public override void Emit (EmitContext ec)
6955 ILGenerator ig = ec.ig;
6958 if (ec.TypeContainer is Struct)
6959 ig.Emit (OpCodes.Ldobj, type);
6962 public override int GetHashCode()
6964 return block.GetHashCode ();
6967 public override bool Equals (object obj)
6969 This t = obj as This;
6973 return block == t.block;
6976 public void AddressOf (EmitContext ec, AddressOp mode)
6981 // FIGURE OUT WHY LDARG_S does not work
6983 // consider: struct X { int val; int P { set { val = value; }}}
6985 // Yes, this looks very bad. Look at `NOTAS' for
6987 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
6992 /// Represents the `__arglist' construct
6994 public class ArglistAccess : Expression
6996 public ArglistAccess (Location loc)
7001 public bool ResolveBase (EmitContext ec)
7003 eclass = ExprClass.Variable;
7004 type = TypeManager.runtime_argument_handle_type;
7008 public override Expression DoResolve (EmitContext ec)
7010 if (!ResolveBase (ec))
7013 if (ec.IsFieldInitializer || !ec.CurrentBlock.HasVarargs) {
7014 Error (190, "The __arglist construct is valid only within " +
7015 "a variable argument method.");
7022 public override void Emit (EmitContext ec)
7024 ec.ig.Emit (OpCodes.Arglist);
7029 /// Represents the `__arglist (....)' construct
7031 public class Arglist : Expression
7033 public readonly Argument[] Arguments;
7035 public Arglist (Argument[] args, Location l)
7041 public Type[] ArgumentTypes {
7043 Type[] retval = new Type [Arguments.Length];
7044 for (int i = 0; i < Arguments.Length; i++)
7045 retval [i] = Arguments [i].Type;
7050 public override Expression DoResolve (EmitContext ec)
7052 eclass = ExprClass.Variable;
7053 type = TypeManager.runtime_argument_handle_type;
7055 foreach (Argument arg in Arguments) {
7056 if (!arg.Resolve (ec, loc))
7063 public override void Emit (EmitContext ec)
7065 foreach (Argument arg in Arguments)
7071 // This produces the value that renders an instance, used by the iterators code
7073 public class ProxyInstance : Expression, IMemoryLocation {
7074 public override Expression DoResolve (EmitContext ec)
7076 eclass = ExprClass.Variable;
7077 type = ec.ContainerType;
7081 public override void Emit (EmitContext ec)
7083 ec.ig.Emit (OpCodes.Ldarg_0);
7087 public void AddressOf (EmitContext ec, AddressOp mode)
7089 ec.ig.Emit (OpCodes.Ldarg_0);
7094 /// Implements the typeof operator
7096 public class TypeOf : Expression {
7097 public Expression QueriedType;
7098 protected Type typearg;
7100 public TypeOf (Expression queried_type, Location l)
7102 QueriedType = queried_type;
7106 public override Expression DoResolve (EmitContext ec)
7108 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
7112 typearg = texpr.ResolveType (ec);
7114 if (typearg == TypeManager.void_type) {
7115 Error (673, "System.Void cannot be used from C# - " +
7116 "use typeof (void) to get the void type object");
7120 if (typearg.IsPointer && !ec.InUnsafe){
7124 CheckObsoleteAttribute (typearg);
7126 type = TypeManager.type_type;
7127 eclass = ExprClass.Type;
7131 public override void Emit (EmitContext ec)
7133 ec.ig.Emit (OpCodes.Ldtoken, typearg);
7134 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
7137 public Type TypeArg {
7138 get { return typearg; }
7143 /// Implements the `typeof (void)' operator
7145 public class TypeOfVoid : TypeOf {
7146 public TypeOfVoid (Location l) : base (null, l)
7151 public override Expression DoResolve (EmitContext ec)
7153 type = TypeManager.type_type;
7154 typearg = TypeManager.void_type;
7155 eclass = ExprClass.Type;
7161 /// Implements the sizeof expression
7163 public class SizeOf : Expression {
7164 public Expression QueriedType;
7167 public SizeOf (Expression queried_type, Location l)
7169 this.QueriedType = queried_type;
7173 public override Expression DoResolve (EmitContext ec)
7175 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
7179 type_queried = texpr.ResolveType (ec);
7181 int size_of = GetTypeSize (type_queried);
7183 return new IntConstant (size_of);
7187 Report.Error (233, loc, "'{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)",
7188 TypeManager.CSharpName (type_queried));
7192 CheckObsoleteAttribute (type_queried);
7194 if (!TypeManager.IsUnmanagedType (type_queried)){
7195 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
7199 type = TypeManager.int32_type;
7200 eclass = ExprClass.Value;
7204 public override void Emit (EmitContext ec)
7206 int size = GetTypeSize (type_queried);
7209 ec.ig.Emit (OpCodes.Sizeof, type_queried);
7211 IntConstant.EmitInt (ec.ig, size);
7216 /// Implements the member access expression
7218 public class MemberAccess : Expression {
7219 public readonly string Identifier;
7222 public MemberAccess (Expression expr, string id, Location l)
7229 public Expression Expr {
7235 public static void error176 (Location loc, string name)
7237 Report.Error (176, loc, "Static member `" +
7238 name + "' cannot be accessed " +
7239 "with an instance reference, qualify with a " +
7240 "type name instead");
7243 public static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Expression left, Location loc)
7245 SimpleName sn = left_original as SimpleName;
7246 return sn != null && sn.IdenticalNameAndTypeName (ec, left, loc);
7249 // TODO: possible optimalization
7250 // Cache resolved constant result in FieldBuilder <-> expresion map
7251 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
7252 Expression left, Location loc,
7253 Expression left_original)
7255 bool left_is_type, left_is_explicit;
7257 // If `left' is null, then we're called from SimpleNameResolve and this is
7258 // a member in the currently defining class.
7260 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
7261 left_is_explicit = false;
7263 // Implicitly default to `this' unless we're static.
7264 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
7265 left = ec.GetThis (loc);
7267 left_is_type = left is TypeExpr;
7268 left_is_explicit = true;
7271 if (member_lookup is FieldExpr){
7272 FieldExpr fe = (FieldExpr) member_lookup;
7273 FieldInfo fi = fe.FieldInfo;
7274 Type decl_type = fi.DeclaringType;
7276 bool is_emitted = fi is FieldBuilder;
7277 Type t = fi.FieldType;
7280 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
7284 if (!c.LookupConstantValue (out o))
7287 object real_value = ((Constant) c.Expr).GetValue ();
7289 Expression exp = Constantify (real_value, t);
7291 if (left_is_explicit && !left_is_type && !IdenticalNameAndTypeName (ec, left_original, left, loc)) {
7292 Report.SymbolRelatedToPreviousError (c);
7293 error176 (loc, c.GetSignatureForError ());
7301 // IsInitOnly is because of MS compatibility, I don't know why but they emit decimal constant as InitOnly
7302 if (fi.IsInitOnly && !is_emitted && t == TypeManager.decimal_type) {
7303 object[] attrs = fi.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
7304 if (attrs.Length == 1)
7305 return new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
7312 o = TypeManager.GetValue ((FieldBuilder) fi);
7314 o = fi.GetValue (fi);
7316 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
7317 if (left_is_explicit && !left_is_type &&
7318 !IdenticalNameAndTypeName (ec, left_original, member_lookup, loc)) {
7319 error176 (loc, fe.FieldInfo.Name);
7323 Expression enum_member = MemberLookup (
7324 ec, decl_type, "value__", MemberTypes.Field,
7325 AllBindingFlags, loc);
7327 Enum en = TypeManager.LookupEnum (decl_type);
7331 c = Constantify (o, en.UnderlyingType);
7333 c = Constantify (o, enum_member.Type);
7335 return new EnumConstant (c, decl_type);
7338 Expression exp = Constantify (o, t);
7340 if (left_is_explicit && !left_is_type) {
7341 error176 (loc, fe.FieldInfo.Name);
7348 if (t.IsPointer && !ec.InUnsafe){
7354 if (member_lookup is EventExpr) {
7355 EventExpr ee = (EventExpr) member_lookup;
7358 // If the event is local to this class, we transform ourselves into
7362 if (ee.EventInfo.DeclaringType == ec.ContainerType ||
7363 TypeManager.IsNestedChildOf(ec.ContainerType, ee.EventInfo.DeclaringType)) {
7364 MemberInfo mi = GetFieldFromEvent (ee);
7368 // If this happens, then we have an event with its own
7369 // accessors and private field etc so there's no need
7370 // to transform ourselves.
7372 ee.InstanceExpression = left;
7376 Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
7379 Report.Error (-200, loc, "Internal error!!");
7383 if (!left_is_explicit)
7386 ee.InstanceExpression = left;
7388 return ResolveMemberAccess (ec, ml, left, loc, left_original);
7392 if (member_lookup is IMemberExpr) {
7393 IMemberExpr me = (IMemberExpr) member_lookup;
7394 MethodGroupExpr mg = me as MethodGroupExpr;
7397 if ((mg != null) && left_is_explicit && left.Type.IsInterface)
7398 mg.IsExplicitImpl = left_is_explicit;
7401 if ((ec.IsFieldInitializer || ec.IsStatic) &&
7402 IdenticalNameAndTypeName (ec, left_original, member_lookup, loc))
7403 return member_lookup;
7405 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
7410 if (!me.IsInstance) {
7411 if (IdenticalNameAndTypeName (ec, left_original, left, loc))
7412 return member_lookup;
7414 if (left_is_explicit) {
7415 error176 (loc, me.Name);
7421 // Since we can not check for instance objects in SimpleName,
7422 // becaue of the rule that allows types and variables to share
7423 // the name (as long as they can be de-ambiguated later, see
7424 // IdenticalNameAndTypeName), we have to check whether left
7425 // is an instance variable in a static context
7427 // However, if the left-hand value is explicitly given, then
7428 // it is already our instance expression, so we aren't in
7432 if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
7433 IMemberExpr mexp = (IMemberExpr) left;
7435 if (!mexp.IsStatic){
7436 SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
7441 if ((mg != null) && IdenticalNameAndTypeName (ec, left_original, left, loc))
7442 mg.IdenticalTypeName = true;
7444 me.InstanceExpression = left;
7447 return member_lookup;
7450 Console.WriteLine ("Left is: " + left);
7451 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
7452 Environment.Exit (1);
7456 public Expression DoResolve (EmitContext ec, Expression right_side, ResolveFlags flags)
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 Namespace) {
7474 Namespace ns = (Namespace) expr;
7475 FullNamedExpression retval = ns.Lookup (ec.DeclSpace, Identifier, loc);
7477 Report.Error (234, loc, "The type or namespace name `{0}' could not be found in namespace `{1}'", Identifier, ns.FullName);
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
7490 Type expr_type = expr.Type;
7491 if (expr is TypeExpr){
7492 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
7493 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", expr_type);
7497 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
7498 Enum en = TypeManager.LookupEnum (expr_type);
7501 object value = en.LookupEnumValue (ec, Identifier, loc);
7504 MemberCore mc = en.GetDefinition (Identifier);
7505 ObsoleteAttribute oa = mc.GetObsoleteAttribute (en);
7507 AttributeTester.Report_ObsoleteMessage (oa, mc.GetSignatureForError (), Location);
7509 oa = en.GetObsoleteAttribute (en);
7511 AttributeTester.Report_ObsoleteMessage (oa, en.GetSignatureForError (), Location);
7514 Constant c = Constantify (value, en.UnderlyingType);
7515 return new EnumConstant (c, expr_type);
7518 CheckObsoleteAttribute (expr_type);
7520 FieldInfo fi = expr_type.GetField (Identifier);
7522 ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
7524 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), Location);
7530 if (expr_type.IsPointer){
7531 Error (23, "The `.' operator can not be applied to pointer operands (" +
7532 TypeManager.CSharpName (expr_type) + ")");
7536 Expression member_lookup;
7537 member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
7538 if (member_lookup == null)
7541 if (member_lookup is TypeExpr) {
7542 if (!(expr is TypeExpr) &&
7543 !IdenticalNameAndTypeName (ec, original, expr, loc)) {
7544 Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
7545 member_lookup.Type + "' instead");
7549 return member_lookup;
7552 member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
7553 if (member_lookup == null)
7556 // The following DoResolve/DoResolveLValue will do the definite assignment
7559 if (right_side != null)
7560 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
7562 member_lookup = member_lookup.DoResolve (ec);
7564 return member_lookup;
7567 public override Expression DoResolve (EmitContext ec)
7569 return DoResolve (ec, null, ResolveFlags.VariableOrValue | ResolveFlags.Type);
7572 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7574 return DoResolve (ec, right_side, ResolveFlags.VariableOrValue | ResolveFlags.Type);
7577 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
7579 return ResolveNamespaceOrType (ec, false);
7582 public FullNamedExpression ResolveNamespaceOrType (EmitContext ec, bool silent)
7584 FullNamedExpression new_expr = expr.ResolveAsTypeStep (ec);
7586 if (new_expr == null)
7589 if (new_expr is Namespace) {
7590 Namespace ns = (Namespace) new_expr;
7591 FullNamedExpression retval = ns.Lookup (ec.DeclSpace, Identifier, loc);
7592 if (!silent && retval == null)
7593 Report.Error (234, loc, "The type or namespace name `{0}' could not be found in namespace `{1}'", Identifier, ns.FullName);
7597 Type expr_type = new_expr.Type;
7599 if (expr_type.IsPointer){
7600 Error (23, "The `.' operator can not be applied to pointer operands (" +
7601 TypeManager.CSharpName (expr_type) + ")");
7605 Expression member_lookup = MemberLookup (ec, expr_type, expr_type, Identifier, loc);
7606 if (member_lookup == null) {
7607 int errors = Report.Errors;
7608 MemberLookupFailed (ec, expr_type, expr_type, Identifier, null, false, loc);
7610 if (!silent && errors == Report.Errors)
7611 Report.Error (234, loc, "The type name `{0}' could not be found in type `{1}'",
7612 Identifier, new_expr.FullName);
7616 if (!(member_lookup is TypeExpr)) {
7617 Report.Error (118, loc, "'{0}.{1}' denotes a '{2}', where a type was expected",
7618 new_expr.FullName, Identifier, member_lookup.ExprClassName ());
7622 member_lookup = member_lookup.Resolve (ec, ResolveFlags.Type);
7623 return (member_lookup as TypeExpr);
7626 public override void Emit (EmitContext ec)
7628 throw new Exception ("Should not happen");
7631 public override string ToString ()
7633 return expr + "." + Identifier;
7638 /// Implements checked expressions
7640 public class CheckedExpr : Expression {
7642 public Expression Expr;
7644 public CheckedExpr (Expression e, Location l)
7650 public override Expression DoResolve (EmitContext ec)
7652 bool last_check = ec.CheckState;
7653 bool last_const_check = ec.ConstantCheckState;
7655 ec.CheckState = true;
7656 ec.ConstantCheckState = true;
7657 Expr = Expr.Resolve (ec);
7658 ec.CheckState = last_check;
7659 ec.ConstantCheckState = last_const_check;
7664 if (Expr is Constant)
7667 eclass = Expr.eclass;
7672 public override void Emit (EmitContext ec)
7674 bool last_check = ec.CheckState;
7675 bool last_const_check = ec.ConstantCheckState;
7677 ec.CheckState = true;
7678 ec.ConstantCheckState = true;
7680 ec.CheckState = last_check;
7681 ec.ConstantCheckState = last_const_check;
7687 /// Implements the unchecked expression
7689 public class UnCheckedExpr : Expression {
7691 public Expression Expr;
7693 public UnCheckedExpr (Expression e, Location l)
7699 public override Expression DoResolve (EmitContext ec)
7701 bool last_check = ec.CheckState;
7702 bool last_const_check = ec.ConstantCheckState;
7704 ec.CheckState = false;
7705 ec.ConstantCheckState = false;
7706 Expr = Expr.Resolve (ec);
7707 ec.CheckState = last_check;
7708 ec.ConstantCheckState = last_const_check;
7713 if (Expr is Constant)
7716 eclass = Expr.eclass;
7721 public override void Emit (EmitContext ec)
7723 bool last_check = ec.CheckState;
7724 bool last_const_check = ec.ConstantCheckState;
7726 ec.CheckState = false;
7727 ec.ConstantCheckState = false;
7729 ec.CheckState = last_check;
7730 ec.ConstantCheckState = last_const_check;
7736 /// An Element Access expression.
7738 /// During semantic analysis these are transformed into
7739 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7741 public class ElementAccess : Expression {
7742 public ArrayList Arguments;
7743 public Expression Expr;
7745 public ElementAccess (Expression e, ArrayList e_list, Location l)
7754 Arguments = new ArrayList ();
7755 foreach (Expression tmp in e_list)
7756 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
7760 bool CommonResolve (EmitContext ec)
7762 Expr = Expr.Resolve (ec);
7767 if (Arguments == null)
7770 foreach (Argument a in Arguments){
7771 if (!a.Resolve (ec, loc))
7778 Expression MakePointerAccess (EmitContext ec, Type t)
7780 if (t == TypeManager.void_ptr_type){
7781 Error (242, "The array index operation is not valid for void pointers");
7784 if (Arguments.Count != 1){
7785 Error (196, "A pointer must be indexed by a single value");
7790 p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc).Resolve (ec);
7793 return new Indirection (p, loc).Resolve (ec);
7796 public override Expression DoResolve (EmitContext ec)
7798 if (!CommonResolve (ec))
7802 // We perform some simple tests, and then to "split" the emit and store
7803 // code we create an instance of a different class, and return that.
7805 // I am experimenting with this pattern.
7809 if (t == TypeManager.array_type){
7810 Report.Error (21, loc, "Cannot use indexer on System.Array");
7815 return (new ArrayAccess (this, loc)).Resolve (ec);
7817 return MakePointerAccess (ec, Expr.Type);
7819 FieldExpr fe = Expr as FieldExpr;
7821 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
7823 return MakePointerAccess (ec, ff.ElementType);
7826 return (new IndexerAccess (this, loc)).Resolve (ec);
7829 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7831 if (!CommonResolve (ec))
7836 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
7839 return MakePointerAccess (ec, Expr.Type);
7841 FieldExpr fe = Expr as FieldExpr;
7843 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
7845 if (!(fe.InstanceExpression is LocalVariableReference) &&
7846 !(fe.InstanceExpression is This)) {
7847 Error (1708, "Fixed buffers can only be accessed through locals or fields");
7850 // TODO: not sure whether it is correct
7851 // if (!ec.InFixedInitializer) {
7852 // Error (1666, "You cannot use fixed sized buffers contained in unfixed expressions. Try using the fixed statement");
7855 return MakePointerAccess (ec, ff.ElementType);
7858 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
7861 public override void Emit (EmitContext ec)
7863 throw new Exception ("Should never be reached");
7868 /// Implements array access
7870 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7872 // Points to our "data" repository
7876 LocalTemporary temp;
7879 public ArrayAccess (ElementAccess ea_data, Location l)
7882 eclass = ExprClass.Variable;
7886 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7888 return DoResolve (ec);
7891 public override Expression DoResolve (EmitContext ec)
7894 ExprClass eclass = ea.Expr.eclass;
7896 // As long as the type is valid
7897 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7898 eclass == ExprClass.Value)) {
7899 ea.Expr.Error_UnexpectedKind ("variable or value");
7904 Type t = ea.Expr.Type;
7905 if (t.GetArrayRank () != ea.Arguments.Count){
7907 "Incorrect number of indexes for array " +
7908 " expected: " + t.GetArrayRank () + " got: " +
7909 ea.Arguments.Count);
7913 type = TypeManager.GetElementType (t);
7914 if (type.IsPointer && !ec.InUnsafe){
7915 UnsafeError (ea.Location);
7919 foreach (Argument a in ea.Arguments){
7920 Type argtype = a.Type;
7922 if (argtype == TypeManager.int32_type ||
7923 argtype == TypeManager.uint32_type ||
7924 argtype == TypeManager.int64_type ||
7925 argtype == TypeManager.uint64_type) {
7926 Constant c = a.Expr as Constant;
7927 if (c != null && c.IsNegative) {
7928 Report.Warning (251, 2, a.Expr.Location, "Indexing an array with a negative index (array indices always start at zero)");
7934 // Mhm. This is strage, because the Argument.Type is not the same as
7935 // Argument.Expr.Type: the value changes depending on the ref/out setting.
7937 // Wonder if I will run into trouble for this.
7939 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
7944 eclass = ExprClass.Variable;
7950 /// Emits the right opcode to load an object of Type `t'
7951 /// from an array of T
7953 static public void EmitLoadOpcode (ILGenerator ig, Type type)
7955 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7956 ig.Emit (OpCodes.Ldelem_U1);
7957 else if (type == TypeManager.sbyte_type)
7958 ig.Emit (OpCodes.Ldelem_I1);
7959 else if (type == TypeManager.short_type)
7960 ig.Emit (OpCodes.Ldelem_I2);
7961 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7962 ig.Emit (OpCodes.Ldelem_U2);
7963 else if (type == TypeManager.int32_type)
7964 ig.Emit (OpCodes.Ldelem_I4);
7965 else if (type == TypeManager.uint32_type)
7966 ig.Emit (OpCodes.Ldelem_U4);
7967 else if (type == TypeManager.uint64_type)
7968 ig.Emit (OpCodes.Ldelem_I8);
7969 else if (type == TypeManager.int64_type)
7970 ig.Emit (OpCodes.Ldelem_I8);
7971 else if (type == TypeManager.float_type)
7972 ig.Emit (OpCodes.Ldelem_R4);
7973 else if (type == TypeManager.double_type)
7974 ig.Emit (OpCodes.Ldelem_R8);
7975 else if (type == TypeManager.intptr_type)
7976 ig.Emit (OpCodes.Ldelem_I);
7977 else if (TypeManager.IsEnumType (type)){
7978 EmitLoadOpcode (ig, TypeManager.EnumToUnderlying (type));
7979 } else if (type.IsValueType){
7980 ig.Emit (OpCodes.Ldelema, type);
7981 ig.Emit (OpCodes.Ldobj, type);
7983 ig.Emit (OpCodes.Ldelem_Ref);
7987 /// Returns the right opcode to store an object of Type `t'
7988 /// from an array of T.
7990 static public OpCode GetStoreOpcode (Type t, out bool is_stobj)
7992 //Console.WriteLine (new System.Diagnostics.StackTrace ());
7994 t = TypeManager.TypeToCoreType (t);
7995 if (TypeManager.IsEnumType (t))
7996 t = TypeManager.EnumToUnderlying (t);
7997 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
7998 t == TypeManager.bool_type)
7999 return OpCodes.Stelem_I1;
8000 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
8001 t == TypeManager.char_type)
8002 return OpCodes.Stelem_I2;
8003 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
8004 return OpCodes.Stelem_I4;
8005 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
8006 return OpCodes.Stelem_I8;
8007 else if (t == TypeManager.float_type)
8008 return OpCodes.Stelem_R4;
8009 else if (t == TypeManager.double_type)
8010 return OpCodes.Stelem_R8;
8011 else if (t == TypeManager.intptr_type) {
8013 return OpCodes.Stobj;
8014 } else if (t.IsValueType) {
8016 return OpCodes.Stobj;
8018 return OpCodes.Stelem_Ref;
8021 MethodInfo FetchGetMethod ()
8023 ModuleBuilder mb = CodeGen.Module.Builder;
8024 int arg_count = ea.Arguments.Count;
8025 Type [] args = new Type [arg_count];
8028 for (int i = 0; i < arg_count; i++){
8029 //args [i++] = a.Type;
8030 args [i] = TypeManager.int32_type;
8033 get = mb.GetArrayMethod (
8034 ea.Expr.Type, "Get",
8035 CallingConventions.HasThis |
8036 CallingConventions.Standard,
8042 MethodInfo FetchAddressMethod ()
8044 ModuleBuilder mb = CodeGen.Module.Builder;
8045 int arg_count = ea.Arguments.Count;
8046 Type [] args = new Type [arg_count];
8050 ret_type = TypeManager.GetReferenceType (type);
8052 for (int i = 0; i < arg_count; i++){
8053 //args [i++] = a.Type;
8054 args [i] = TypeManager.int32_type;
8057 address = mb.GetArrayMethod (
8058 ea.Expr.Type, "Address",
8059 CallingConventions.HasThis |
8060 CallingConventions.Standard,
8067 // Load the array arguments into the stack.
8069 // If we have been requested to cache the values (cached_locations array
8070 // initialized), then load the arguments the first time and store them
8071 // in locals. otherwise load from local variables.
8073 void LoadArrayAndArguments (EmitContext ec)
8075 ILGenerator ig = ec.ig;
8078 foreach (Argument a in ea.Arguments){
8079 Type argtype = a.Expr.Type;
8083 if (argtype == TypeManager.int64_type)
8084 ig.Emit (OpCodes.Conv_Ovf_I);
8085 else if (argtype == TypeManager.uint64_type)
8086 ig.Emit (OpCodes.Conv_Ovf_I_Un);
8090 public void Emit (EmitContext ec, bool leave_copy)
8092 int rank = ea.Expr.Type.GetArrayRank ();
8093 ILGenerator ig = ec.ig;
8096 LoadArrayAndArguments (ec);
8099 EmitLoadOpcode (ig, type);
8103 method = FetchGetMethod ();
8104 ig.Emit (OpCodes.Call, method);
8107 LoadFromPtr (ec.ig, this.type);
8110 ec.ig.Emit (OpCodes.Dup);
8111 temp = new LocalTemporary (ec, this.type);
8116 public override void Emit (EmitContext ec)
8121 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8123 int rank = ea.Expr.Type.GetArrayRank ();
8124 ILGenerator ig = ec.ig;
8125 Type t = source.Type;
8126 prepared = prepare_for_load;
8128 if (prepare_for_load) {
8129 AddressOf (ec, AddressOp.LoadStore);
8130 ec.ig.Emit (OpCodes.Dup);
8133 ec.ig.Emit (OpCodes.Dup);
8134 temp = new LocalTemporary (ec, this.type);
8137 StoreFromPtr (ec.ig, t);
8145 LoadArrayAndArguments (ec);
8149 OpCode op = GetStoreOpcode (t, out is_stobj);
8151 // The stobj opcode used by value types will need
8152 // an address on the stack, not really an array/array
8156 ig.Emit (OpCodes.Ldelema, t);
8160 ec.ig.Emit (OpCodes.Dup);
8161 temp = new LocalTemporary (ec, this.type);
8166 ig.Emit (OpCodes.Stobj, t);
8170 ModuleBuilder mb = CodeGen.Module.Builder;
8171 int arg_count = ea.Arguments.Count;
8172 Type [] args = new Type [arg_count + 1];
8177 ec.ig.Emit (OpCodes.Dup);
8178 temp = new LocalTemporary (ec, this.type);
8182 for (int i = 0; i < arg_count; i++){
8183 //args [i++] = a.Type;
8184 args [i] = TypeManager.int32_type;
8187 args [arg_count] = type;
8189 set = mb.GetArrayMethod (
8190 ea.Expr.Type, "Set",
8191 CallingConventions.HasThis |
8192 CallingConventions.Standard,
8193 TypeManager.void_type, args);
8195 ig.Emit (OpCodes.Call, set);
8202 public void AddressOf (EmitContext ec, AddressOp mode)
8204 int rank = ea.Expr.Type.GetArrayRank ();
8205 ILGenerator ig = ec.ig;
8207 LoadArrayAndArguments (ec);
8210 ig.Emit (OpCodes.Ldelema, type);
8212 MethodInfo address = FetchAddressMethod ();
8213 ig.Emit (OpCodes.Call, address);
8220 public ArrayList Properties;
8221 static Hashtable map;
8223 public struct Indexer {
8224 public readonly Type Type;
8225 public readonly MethodInfo Getter, Setter;
8227 public Indexer (Type type, MethodInfo get, MethodInfo set)
8237 map = new Hashtable ();
8242 Properties = new ArrayList ();
8245 void Append (MemberInfo [] mi)
8247 foreach (PropertyInfo property in mi){
8248 MethodInfo get, set;
8250 get = property.GetGetMethod (true);
8251 set = property.GetSetMethod (true);
8252 Properties.Add (new Indexer (property.PropertyType, get, set));
8256 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
8258 string p_name = TypeManager.IndexerPropertyName (lookup_type);
8260 MemberInfo [] mi = TypeManager.MemberLookup (
8261 caller_type, caller_type, lookup_type, MemberTypes.Property,
8262 BindingFlags.Public | BindingFlags.Instance |
8263 BindingFlags.DeclaredOnly, p_name, null);
8265 if (mi == null || mi.Length == 0)
8271 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
8273 Indexers ix = (Indexers) map [lookup_type];
8278 Type copy = lookup_type;
8279 while (copy != TypeManager.object_type && copy != null){
8280 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
8284 ix = new Indexers ();
8289 copy = copy.BaseType;
8292 if (!lookup_type.IsInterface)
8295 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
8296 if (ifaces != null) {
8297 foreach (Type itype in ifaces) {
8298 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
8301 ix = new Indexers ();
8313 /// Expressions that represent an indexer call.
8315 public class IndexerAccess : Expression, IAssignMethod {
8317 // Points to our "data" repository
8319 MethodInfo get, set;
8320 ArrayList set_arguments;
8321 bool is_base_indexer;
8323 protected Type indexer_type;
8324 protected Type current_type;
8325 protected Expression instance_expr;
8326 protected ArrayList arguments;
8328 public IndexerAccess (ElementAccess ea, Location loc)
8329 : this (ea.Expr, false, loc)
8331 this.arguments = ea.Arguments;
8334 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
8337 this.instance_expr = instance_expr;
8338 this.is_base_indexer = is_base_indexer;
8339 this.eclass = ExprClass.Value;
8343 protected virtual bool CommonResolve (EmitContext ec)
8345 indexer_type = instance_expr.Type;
8346 current_type = ec.ContainerType;
8351 public override Expression DoResolve (EmitContext ec)
8353 ArrayList AllGetters = new ArrayList();
8354 if (!CommonResolve (ec))
8358 // Step 1: Query for all `Item' *properties*. Notice
8359 // that the actual methods are pointed from here.
8361 // This is a group of properties, piles of them.
8363 bool found_any = false, found_any_getters = false;
8364 Type lookup_type = indexer_type;
8367 ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
8368 if (ilist != null) {
8370 if (ilist.Properties != null) {
8371 foreach (Indexers.Indexer ix in ilist.Properties) {
8372 if (ix.Getter != null)
8373 AllGetters.Add(ix.Getter);
8378 if (AllGetters.Count > 0) {
8379 found_any_getters = true;
8380 get = (MethodInfo) Invocation.OverloadResolve (
8381 ec, new MethodGroupExpr (AllGetters, loc),
8382 arguments, false, loc);
8386 Report.Error (21, loc,
8387 "Type `" + TypeManager.CSharpName (indexer_type) +
8388 "' does not have any indexers defined");
8392 if (!found_any_getters) {
8393 Error (154, "indexer can not be used in this context, because " +
8394 "it lacks a `get' accessor");
8399 Error (1501, "No Overload for method `this' takes `" +
8400 arguments.Count + "' arguments");
8405 // Only base will allow this invocation to happen.
8407 if (get.IsAbstract && this is BaseIndexerAccess){
8408 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
8412 type = get.ReturnType;
8413 if (type.IsPointer && !ec.InUnsafe){
8418 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8420 eclass = ExprClass.IndexerAccess;
8424 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8426 ArrayList AllSetters = new ArrayList();
8427 if (!CommonResolve (ec))
8430 bool found_any = false, found_any_setters = false;
8432 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
8433 if (ilist != null) {
8435 if (ilist.Properties != null) {
8436 foreach (Indexers.Indexer ix in ilist.Properties) {
8437 if (ix.Setter != null)
8438 AllSetters.Add(ix.Setter);
8442 if (AllSetters.Count > 0) {
8443 found_any_setters = true;
8444 set_arguments = (ArrayList) arguments.Clone ();
8445 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
8446 set = (MethodInfo) Invocation.OverloadResolve (
8447 ec, new MethodGroupExpr (AllSetters, loc),
8448 set_arguments, false, loc);
8452 Report.Error (21, loc,
8453 "Type `" + TypeManager.CSharpName (indexer_type) +
8454 "' does not have any indexers defined");
8458 if (!found_any_setters) {
8459 Error (154, "indexer can not be used in this context, because " +
8460 "it lacks a `set' accessor");
8465 Error (1501, "No Overload for method `this' takes `" +
8466 arguments.Count + "' arguments");
8471 // Only base will allow this invocation to happen.
8473 if (set.IsAbstract && this is BaseIndexerAccess){
8474 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
8479 // Now look for the actual match in the list of indexers to set our "return" type
8481 type = TypeManager.void_type; // default value
8482 foreach (Indexers.Indexer ix in ilist.Properties){
8483 if (ix.Setter == set){
8489 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
8491 eclass = ExprClass.IndexerAccess;
8495 bool prepared = false;
8496 LocalTemporary temp;
8498 public void Emit (EmitContext ec, bool leave_copy)
8500 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc, prepared, false);
8502 ec.ig.Emit (OpCodes.Dup);
8503 temp = new LocalTemporary (ec, Type);
8509 // source is ignored, because we already have a copy of it from the
8510 // LValue resolution and we have already constructed a pre-cached
8511 // version of the arguments (ea.set_arguments);
8513 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8515 prepared = prepare_for_load;
8516 Argument a = (Argument) set_arguments [set_arguments.Count - 1];
8521 ec.ig.Emit (OpCodes.Dup);
8522 temp = new LocalTemporary (ec, Type);
8525 } else if (leave_copy) {
8526 temp = new LocalTemporary (ec, Type);
8532 Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc, false, prepared);
8539 public override void Emit (EmitContext ec)
8546 /// The base operator for method names
8548 public class BaseAccess : Expression {
8551 public BaseAccess (string member, Location l)
8553 this.member = member;
8557 public override Expression DoResolve (EmitContext ec)
8559 Expression c = CommonResolve (ec);
8565 // MethodGroups use this opportunity to flag an error on lacking ()
8567 if (!(c is MethodGroupExpr))
8568 return c.Resolve (ec);
8572 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
8574 Expression c = CommonResolve (ec);
8580 // MethodGroups use this opportunity to flag an error on lacking ()
8582 if (! (c is MethodGroupExpr))
8583 return c.DoResolveLValue (ec, right_side);
8588 Expression CommonResolve (EmitContext ec)
8590 Expression member_lookup;
8591 Type current_type = ec.ContainerType;
8592 Type base_type = current_type.BaseType;
8596 Error (1511, "Keyword base is not allowed in static method");
8600 if (ec.IsFieldInitializer){
8601 Error (1512, "Keyword base is not available in the current context");
8605 member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type, member,
8606 AllMemberTypes, AllBindingFlags, loc);
8607 if (member_lookup == null) {
8608 MemberLookupFailed (ec, base_type, base_type, member, null, true, loc);
8615 left = new TypeExpression (base_type, loc);
8617 left = ec.GetThis (loc);
8619 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
8621 if (e is PropertyExpr){
8622 PropertyExpr pe = (PropertyExpr) e;
8627 if (e is MethodGroupExpr)
8628 ((MethodGroupExpr) e).IsBase = true;
8633 public override void Emit (EmitContext ec)
8635 throw new Exception ("Should never be called");
8640 /// The base indexer operator
8642 public class BaseIndexerAccess : IndexerAccess {
8643 public BaseIndexerAccess (ArrayList args, Location loc)
8644 : base (null, true, loc)
8646 arguments = new ArrayList ();
8647 foreach (Expression tmp in args)
8648 arguments.Add (new Argument (tmp, Argument.AType.Expression));
8651 protected override bool CommonResolve (EmitContext ec)
8653 instance_expr = ec.GetThis (loc);
8655 current_type = ec.ContainerType.BaseType;
8656 indexer_type = current_type;
8658 foreach (Argument a in arguments){
8659 if (!a.Resolve (ec, loc))
8668 /// This class exists solely to pass the Type around and to be a dummy
8669 /// that can be passed to the conversion functions (this is used by
8670 /// foreach implementation to typecast the object return value from
8671 /// get_Current into the proper type. All code has been generated and
8672 /// we only care about the side effect conversions to be performed
8674 /// This is also now used as a placeholder where a no-action expression
8675 /// is needed (the `New' class).
8677 public class EmptyExpression : Expression {
8678 public static readonly EmptyExpression Null = new EmptyExpression ();
8680 // TODO: should be protected
8681 public EmptyExpression ()
8683 type = TypeManager.object_type;
8684 eclass = ExprClass.Value;
8685 loc = Location.Null;
8688 public EmptyExpression (Type t)
8691 eclass = ExprClass.Value;
8692 loc = Location.Null;
8695 public override Expression DoResolve (EmitContext ec)
8700 public override void Emit (EmitContext ec)
8702 // nothing, as we only exist to not do anything.
8706 // This is just because we might want to reuse this bad boy
8707 // instead of creating gazillions of EmptyExpressions.
8708 // (CanImplicitConversion uses it)
8710 public void SetType (Type t)
8716 public class UserCast : Expression {
8720 public UserCast (MethodInfo method, Expression source, Location l)
8722 this.method = method;
8723 this.source = source;
8724 type = method.ReturnType;
8725 eclass = ExprClass.Value;
8729 public Expression Source {
8735 public override Expression DoResolve (EmitContext ec)
8738 // We are born fully resolved
8743 public override void Emit (EmitContext ec)
8745 ILGenerator ig = ec.ig;
8749 if (method is MethodInfo)
8750 ig.Emit (OpCodes.Call, (MethodInfo) method);
8752 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
8758 // This class is used to "construct" the type during a typecast
8759 // operation. Since the Type.GetType class in .NET can parse
8760 // the type specification, we just use this to construct the type
8761 // one bit at a time.
8763 public class ComposedCast : TypeExpr {
8767 public ComposedCast (Expression left, string dim, Location l)
8774 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
8776 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec, false);
8780 Type ltype = lexpr.ResolveType (ec);
8782 if ((ltype == TypeManager.void_type) && (dim != "*")) {
8783 Report.Error (1547, Location,
8784 "Keyword 'void' cannot be used in this context");
8788 type = TypeManager.GetConstructedType (ltype, dim);
8790 throw new InternalErrorException ("Couldn't create computed type " + ltype + dim);
8793 if (!ec.InUnsafe && type.IsPointer){
8798 if (type.IsArray && (type.GetElementType () == TypeManager.arg_iterator_type ||
8799 type.GetElementType () == TypeManager.typed_reference_type)) {
8800 Report.Error (611, loc, "Array elements cannot be of type '{0}'", TypeManager.CSharpName (type.GetElementType ()));
8804 eclass = ExprClass.Type;
8808 public override string Name {
8814 public override string FullName {
8816 return type.FullName;
8821 public class FixedBufferPtr: Expression {
8824 public FixedBufferPtr (Expression array, Type array_type, Location l)
8829 type = TypeManager.GetPointerType (array_type);
8830 eclass = ExprClass.Value;
8833 public override void Emit(EmitContext ec)
8838 public override Expression DoResolve (EmitContext ec)
8841 // We are born fully resolved
8849 // This class is used to represent the address of an array, used
8850 // only by the Fixed statement, this generates "&a [0]" construct
8851 // for fixed (char *pa = a)
8853 public class ArrayPtr : FixedBufferPtr {
8856 public ArrayPtr (Expression array, Type array_type, Location l):
8857 base (array, array_type, l)
8859 this.array_type = array_type;
8862 public override void Emit (EmitContext ec)
8866 ILGenerator ig = ec.ig;
8867 IntLiteral.EmitInt (ig, 0);
8868 ig.Emit (OpCodes.Ldelema, array_type);
8873 // Used by the fixed statement
8875 public class StringPtr : Expression {
8878 public StringPtr (LocalBuilder b, Location l)
8881 eclass = ExprClass.Value;
8882 type = TypeManager.char_ptr_type;
8886 public override Expression DoResolve (EmitContext ec)
8888 // This should never be invoked, we are born in fully
8889 // initialized state.
8894 public override void Emit (EmitContext ec)
8896 ILGenerator ig = ec.ig;
8898 ig.Emit (OpCodes.Ldloc, b);
8899 ig.Emit (OpCodes.Conv_I);
8900 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
8901 ig.Emit (OpCodes.Add);
8906 // Implements the `stackalloc' keyword
8908 public class StackAlloc : Expression {
8913 public StackAlloc (Expression type, Expression count, Location l)
8920 public override Expression DoResolve (EmitContext ec)
8922 count = count.Resolve (ec);
8926 if (count.Type != TypeManager.int32_type){
8927 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8932 Constant c = count as Constant;
8933 if (c != null && c.IsNegative) {
8934 Report.Error (247, loc, "Cannot use a negative size with stackalloc");
8938 if (ec.CurrentBranching.InCatch () ||
8939 ec.CurrentBranching.InFinally (true)) {
8941 "stackalloc can not be used in a catch or finally block");
8945 TypeExpr texpr = t.ResolveAsTypeTerminal (ec, false);
8949 otype = texpr.ResolveType (ec);
8951 if (!TypeManager.VerifyUnManaged (otype, loc))
8954 type = TypeManager.GetPointerType (otype);
8955 eclass = ExprClass.Value;
8960 public override void Emit (EmitContext ec)
8962 int size = GetTypeSize (otype);
8963 ILGenerator ig = ec.ig;
8966 ig.Emit (OpCodes.Sizeof, otype);
8968 IntConstant.EmitInt (ig, size);
8970 ig.Emit (OpCodes.Mul);
8971 ig.Emit (OpCodes.Localloc);