2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Copyright 2001, 2002, 2003 Ximian, Inc.
9 // Copyright 2003-2008 Novell, Inc.
13 namespace Mono.CSharp {
15 using System.Collections;
16 using System.Reflection;
17 using System.Reflection.Emit;
21 using SLE = System.Linq.Expressions;
25 // This is an user operator expression, automatically created during
28 public class UserOperatorCall : Expression {
29 public delegate Expression ExpressionTreeExpression (ResolveContext ec, MethodGroupExpr mg);
31 protected readonly Arguments arguments;
32 protected readonly MethodGroupExpr mg;
33 readonly ExpressionTreeExpression expr_tree;
35 public UserOperatorCall (MethodGroupExpr mg, Arguments args, ExpressionTreeExpression expr_tree, Location loc)
38 this.arguments = args;
39 this.expr_tree = expr_tree;
41 type = TypeManager.TypeToCoreType (((MethodInfo) mg).ReturnType);
42 eclass = ExprClass.Value;
46 public override Expression CreateExpressionTree (ResolveContext ec)
48 if (expr_tree != null)
49 return expr_tree (ec, mg);
51 Arguments args = Arguments.CreateForExpressionTree (ec, arguments,
52 new NullLiteral (loc),
53 mg.CreateExpressionTree (ec));
55 return CreateExpressionFactoryCall (ec, "Call", args);
58 protected override void CloneTo (CloneContext context, Expression target)
63 public override Expression DoResolve (ResolveContext ec)
66 // We are born fully resolved
71 public override void Emit (EmitContext ec)
73 mg.EmitCall (ec, arguments);
77 public override SLE.Expression MakeExpression (BuilderContext ctx)
79 return SLE.Expression.Call ((MethodInfo) mg, Arguments.MakeExpression (arguments, ctx));
83 public MethodGroupExpr Method {
87 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
89 arguments.MutateHoistedGenericType (storey);
90 mg.MutateHoistedGenericType (storey);
94 public class ParenthesizedExpression : ShimExpression
96 public ParenthesizedExpression (Expression expr)
102 public override Expression DoResolve (ResolveContext ec)
104 return expr.Resolve (ec);
107 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
109 return expr.DoResolveLValue (ec, right_side);
114 // Unary implements unary expressions.
116 public class Unary : Expression
118 public enum Operator : byte {
119 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
123 static Type [] [] predefined_operators;
125 public readonly Operator Oper;
126 public Expression Expr;
127 Expression enum_conversion;
129 public Unary (Operator op, Expression expr)
137 // This routine will attempt to simplify the unary expression when the
138 // argument is a constant.
140 Constant TryReduceConstant (ResolveContext ec, Constant e)
142 if (e is EmptyConstantCast)
143 return TryReduceConstant (ec, ((EmptyConstantCast) e).child);
145 if (e is SideEffectConstant) {
146 Constant r = TryReduceConstant (ec, ((SideEffectConstant) e).value);
147 return r == null ? null : new SideEffectConstant (r, e, r.Location);
150 Type expr_type = e.Type;
153 case Operator.UnaryPlus:
154 // Unary numeric promotions
155 if (expr_type == TypeManager.byte_type)
156 return new IntConstant (((ByteConstant)e).Value, e.Location);
157 if (expr_type == TypeManager.sbyte_type)
158 return new IntConstant (((SByteConstant)e).Value, e.Location);
159 if (expr_type == TypeManager.short_type)
160 return new IntConstant (((ShortConstant)e).Value, e.Location);
161 if (expr_type == TypeManager.ushort_type)
162 return new IntConstant (((UShortConstant)e).Value, e.Location);
163 if (expr_type == TypeManager.char_type)
164 return new IntConstant (((CharConstant)e).Value, e.Location);
166 // Predefined operators
167 if (expr_type == TypeManager.int32_type || expr_type == TypeManager.uint32_type ||
168 expr_type == TypeManager.int64_type || expr_type == TypeManager.uint64_type ||
169 expr_type == TypeManager.float_type || expr_type == TypeManager.double_type ||
170 expr_type == TypeManager.decimal_type) {
176 case Operator.UnaryNegation:
177 // Unary numeric promotions
178 if (expr_type == TypeManager.byte_type)
179 return new IntConstant (-((ByteConstant)e).Value, e.Location);
180 if (expr_type == TypeManager.sbyte_type)
181 return new IntConstant (-((SByteConstant)e).Value, e.Location);
182 if (expr_type == TypeManager.short_type)
183 return new IntConstant (-((ShortConstant)e).Value, e.Location);
184 if (expr_type == TypeManager.ushort_type)
185 return new IntConstant (-((UShortConstant)e).Value, e.Location);
186 if (expr_type == TypeManager.char_type)
187 return new IntConstant (-((CharConstant)e).Value, e.Location);
189 // Predefined operators
190 if (expr_type == TypeManager.int32_type) {
191 int value = ((IntConstant)e).Value;
192 if (value == int.MinValue) {
193 if (ec.ConstantCheckState) {
194 ConstantFold.Error_CompileTimeOverflow (ec, loc);
199 return new IntConstant (-value, e.Location);
201 if (expr_type == TypeManager.int64_type) {
202 long value = ((LongConstant)e).Value;
203 if (value == long.MinValue) {
204 if (ec.ConstantCheckState) {
205 ConstantFold.Error_CompileTimeOverflow (ec, loc);
210 return new LongConstant (-value, e.Location);
213 if (expr_type == TypeManager.uint32_type) {
214 UIntLiteral uil = e as UIntLiteral;
216 if (uil.Value == 2147483648)
217 return new IntLiteral (int.MinValue, e.Location);
218 return new LongLiteral (-uil.Value, e.Location);
220 return new LongConstant (-((UIntConstant)e).Value, e.Location);
223 if (expr_type == TypeManager.uint64_type) {
224 ULongLiteral ull = e as ULongLiteral;
225 if (ull != null && ull.Value == 9223372036854775808)
226 return new LongLiteral (long.MinValue, e.Location);
230 if (expr_type == TypeManager.float_type) {
231 FloatLiteral fl = e as FloatLiteral;
232 // For better error reporting
234 return new FloatLiteral (-fl.Value, e.Location);
236 return new FloatConstant (-((FloatConstant)e).Value, e.Location);
238 if (expr_type == TypeManager.double_type) {
239 DoubleLiteral dl = e as DoubleLiteral;
240 // For better error reporting
242 return new DoubleLiteral (-dl.Value, e.Location);
244 return new DoubleConstant (-((DoubleConstant)e).Value, e.Location);
246 if (expr_type == TypeManager.decimal_type)
247 return new DecimalConstant (-((DecimalConstant)e).Value, e.Location);
251 case Operator.LogicalNot:
252 if (expr_type != TypeManager.bool_type)
255 bool b = (bool)e.GetValue ();
256 return new BoolConstant (!b, e.Location);
258 case Operator.OnesComplement:
259 // Unary numeric promotions
260 if (expr_type == TypeManager.byte_type)
261 return new IntConstant (~((ByteConstant)e).Value, e.Location);
262 if (expr_type == TypeManager.sbyte_type)
263 return new IntConstant (~((SByteConstant)e).Value, e.Location);
264 if (expr_type == TypeManager.short_type)
265 return new IntConstant (~((ShortConstant)e).Value, e.Location);
266 if (expr_type == TypeManager.ushort_type)
267 return new IntConstant (~((UShortConstant)e).Value, e.Location);
268 if (expr_type == TypeManager.char_type)
269 return new IntConstant (~((CharConstant)e).Value, e.Location);
271 // Predefined operators
272 if (expr_type == TypeManager.int32_type)
273 return new IntConstant (~((IntConstant)e).Value, e.Location);
274 if (expr_type == TypeManager.uint32_type)
275 return new UIntConstant (~((UIntConstant)e).Value, e.Location);
276 if (expr_type == TypeManager.int64_type)
277 return new LongConstant (~((LongConstant)e).Value, e.Location);
278 if (expr_type == TypeManager.uint64_type){
279 return new ULongConstant (~((ULongConstant)e).Value, e.Location);
281 if (e is EnumConstant) {
282 e = TryReduceConstant (ec, ((EnumConstant)e).Child);
284 e = new EnumConstant (e, expr_type);
289 throw new Exception ("Can not constant fold: " + Oper.ToString());
292 protected Expression ResolveOperator (ResolveContext ec, Expression expr)
294 eclass = ExprClass.Value;
296 if (predefined_operators == null)
297 CreatePredefinedOperatorsTable ();
299 Type expr_type = expr.Type;
300 Expression best_expr;
303 // Primitive types first
305 if (TypeManager.IsPrimitiveType (expr_type)) {
306 best_expr = ResolvePrimitivePredefinedType (expr);
307 if (best_expr == null)
310 type = best_expr.Type;
316 // E operator ~(E x);
318 if (Oper == Operator.OnesComplement && TypeManager.IsEnumType (expr_type))
319 return ResolveEnumOperator (ec, expr);
321 return ResolveUserType (ec, expr);
324 protected virtual Expression ResolveEnumOperator (ResolveContext ec, Expression expr)
326 Type underlying_type = TypeManager.GetEnumUnderlyingType (expr.Type);
327 Expression best_expr = ResolvePrimitivePredefinedType (EmptyCast.Create (expr, underlying_type));
328 if (best_expr == null)
332 enum_conversion = Convert.ExplicitNumericConversion (new EmptyExpression (best_expr.Type), underlying_type);
334 return EmptyCast.Create (this, type);
337 public override Expression CreateExpressionTree (ResolveContext ec)
339 return CreateExpressionTree (ec, null);
342 Expression CreateExpressionTree (ResolveContext ec, MethodGroupExpr user_op)
346 case Operator.AddressOf:
347 Error_PointerInsideExpressionTree (ec);
349 case Operator.UnaryNegation:
350 if (ec.HasSet (ResolveContext.Options.CheckedScope) && user_op == null && !IsFloat (type))
351 method_name = "NegateChecked";
353 method_name = "Negate";
355 case Operator.OnesComplement:
356 case Operator.LogicalNot:
359 case Operator.UnaryPlus:
360 method_name = "UnaryPlus";
363 throw new InternalErrorException ("Unknown unary operator " + Oper.ToString ());
366 Arguments args = new Arguments (2);
367 args.Add (new Argument (Expr.CreateExpressionTree (ec)));
369 args.Add (new Argument (user_op.CreateExpressionTree (ec)));
370 return CreateExpressionFactoryCall (ec, method_name, args);
373 static void CreatePredefinedOperatorsTable ()
375 predefined_operators = new Type [(int) Operator.TOP] [];
378 // 7.6.1 Unary plus operator
380 predefined_operators [(int) Operator.UnaryPlus] = new Type [] {
381 TypeManager.int32_type, TypeManager.uint32_type,
382 TypeManager.int64_type, TypeManager.uint64_type,
383 TypeManager.float_type, TypeManager.double_type,
384 TypeManager.decimal_type
388 // 7.6.2 Unary minus operator
390 predefined_operators [(int) Operator.UnaryNegation] = new Type [] {
391 TypeManager.int32_type,
392 TypeManager.int64_type,
393 TypeManager.float_type, TypeManager.double_type,
394 TypeManager.decimal_type
398 // 7.6.3 Logical negation operator
400 predefined_operators [(int) Operator.LogicalNot] = new Type [] {
401 TypeManager.bool_type
405 // 7.6.4 Bitwise complement operator
407 predefined_operators [(int) Operator.OnesComplement] = new Type [] {
408 TypeManager.int32_type, TypeManager.uint32_type,
409 TypeManager.int64_type, TypeManager.uint64_type
414 // Unary numeric promotions
416 static Expression DoNumericPromotion (Operator op, Expression expr)
418 Type expr_type = expr.Type;
419 if ((op == Operator.UnaryPlus || op == Operator.UnaryNegation || op == Operator.OnesComplement) &&
420 expr_type == TypeManager.byte_type || expr_type == TypeManager.sbyte_type ||
421 expr_type == TypeManager.short_type || expr_type == TypeManager.ushort_type ||
422 expr_type == TypeManager.char_type)
423 return Convert.ImplicitNumericConversion (expr, TypeManager.int32_type);
425 if (op == Operator.UnaryNegation && expr_type == TypeManager.uint32_type)
426 return Convert.ImplicitNumericConversion (expr, TypeManager.int64_type);
431 public override Expression DoResolve (ResolveContext ec)
433 if (Oper == Operator.AddressOf) {
434 return ResolveAddressOf (ec);
437 Expr = Expr.Resolve (ec);
441 if (TypeManager.IsDynamicType (Expr.Type)) {
442 Arguments args = new Arguments (1);
443 args.Add (new Argument (Expr));
444 return new DynamicUnaryConversion (GetOperatorExpressionTypeName (), args, loc).Resolve (ec);
447 if (TypeManager.IsNullableType (Expr.Type))
448 return new Nullable.LiftedUnaryOperator (Oper, Expr).Resolve (ec);
451 // Attempt to use a constant folding operation.
453 Constant cexpr = Expr as Constant;
455 cexpr = TryReduceConstant (ec, cexpr);
460 Expression expr = ResolveOperator (ec, Expr);
462 Error_OperatorCannotBeApplied (ec, loc, OperName (Oper), Expr.Type);
465 // Reduce unary operator on predefined types
467 if (expr == this && Oper == Operator.UnaryPlus)
473 public override Expression DoResolveLValue (ResolveContext ec, Expression right)
478 public override void Emit (EmitContext ec)
480 EmitOperator (ec, type);
483 protected void EmitOperator (EmitContext ec, Type type)
485 ILGenerator ig = ec.ig;
488 case Operator.UnaryPlus:
492 case Operator.UnaryNegation:
493 if (ec.HasSet (EmitContext.Options.CheckedScope) && !IsFloat (type)) {
494 ig.Emit (OpCodes.Ldc_I4_0);
495 if (type == TypeManager.int64_type)
496 ig.Emit (OpCodes.Conv_U8);
498 ig.Emit (OpCodes.Sub_Ovf);
501 ig.Emit (OpCodes.Neg);
506 case Operator.LogicalNot:
508 ig.Emit (OpCodes.Ldc_I4_0);
509 ig.Emit (OpCodes.Ceq);
512 case Operator.OnesComplement:
514 ig.Emit (OpCodes.Not);
517 case Operator.AddressOf:
518 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
522 throw new Exception ("This should not happen: Operator = "
527 // Same trick as in Binary expression
529 if (enum_conversion != null)
530 enum_conversion.Emit (ec);
533 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
535 if (Oper == Operator.LogicalNot)
536 Expr.EmitBranchable (ec, target, !on_true);
538 base.EmitBranchable (ec, target, on_true);
541 public override void EmitSideEffect (EmitContext ec)
543 Expr.EmitSideEffect (ec);
546 public static void Error_OperatorCannotBeApplied (ResolveContext ec, Location loc, string oper, Type t)
548 ec.Report.Error (23, loc, "The `{0}' operator cannot be applied to operand of type `{1}'",
549 oper, TypeManager.CSharpName (t));
553 // Converts operator to System.Linq.Expressions.ExpressionType enum name
555 string GetOperatorExpressionTypeName ()
558 case Operator.OnesComplement:
559 return "OnesComplement";
560 case Operator.LogicalNot:
562 case Operator.UnaryNegation:
564 case Operator.UnaryPlus:
567 throw new NotImplementedException ("Unknown express type operator " + Oper.ToString ());
571 static bool IsFloat (Type t)
573 return t == TypeManager.float_type || t == TypeManager.double_type;
577 // Returns a stringified representation of the Operator
579 public static string OperName (Operator oper)
582 case Operator.UnaryPlus:
584 case Operator.UnaryNegation:
586 case Operator.LogicalNot:
588 case Operator.OnesComplement:
590 case Operator.AddressOf:
594 throw new NotImplementedException (oper.ToString ());
598 public override SLE.Expression MakeExpression (BuilderContext ctx)
600 var expr = Expr.MakeExpression (ctx);
601 bool is_checked = ctx.HasSet (BuilderContext.Options.CheckedScope);
604 case Operator.UnaryNegation:
605 return is_checked ? SLE.Expression.NegateChecked (expr) : SLE.Expression.Negate (expr);
606 case Operator.LogicalNot:
607 return SLE.Expression.Not (expr);
608 case Operator.OnesComplement:
609 return SLE.Expression.OnesComplement (expr);
611 throw new NotImplementedException (Oper.ToString ());
616 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
618 type = storey.MutateType (type);
619 Expr.MutateHoistedGenericType (storey);
622 Expression ResolveAddressOf (ResolveContext ec)
625 UnsafeError (ec, loc);
627 Expr = Expr.DoResolveLValue (ec, EmptyExpression.UnaryAddress);
628 if (Expr == null || Expr.eclass != ExprClass.Variable) {
629 ec.Report.Error (211, loc, "Cannot take the address of the given expression");
633 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)) {
637 IVariableReference vr = Expr as IVariableReference;
640 VariableInfo vi = vr.VariableInfo;
642 if (vi.LocalInfo != null)
643 vi.LocalInfo.Used = true;
646 // A variable is considered definitely assigned if you take its address.
651 is_fixed = vr.IsFixed;
652 vr.SetHasAddressTaken ();
655 AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, vr, loc);
658 IFixedExpression fe = Expr as IFixedExpression;
659 is_fixed = fe != null && fe.IsFixed;
662 if (!is_fixed && !ec.HasSet (ResolveContext.Options.FixedInitializerScope)) {
663 ec.Report.Error (212, loc, "You can only take the address of unfixed expression inside of a fixed statement initializer");
666 type = TypeManager.GetPointerType (Expr.Type);
667 eclass = ExprClass.Value;
671 Expression ResolvePrimitivePredefinedType (Expression expr)
673 expr = DoNumericPromotion (Oper, expr);
674 Type expr_type = expr.Type;
675 Type[] predefined = predefined_operators [(int) Oper];
676 foreach (Type t in predefined) {
684 // Perform user-operator overload resolution
686 protected virtual Expression ResolveUserOperator (ResolveContext ec, Expression expr)
688 CSharp.Operator.OpType op_type;
690 case Operator.LogicalNot:
691 op_type = CSharp.Operator.OpType.LogicalNot; break;
692 case Operator.OnesComplement:
693 op_type = CSharp.Operator.OpType.OnesComplement; break;
694 case Operator.UnaryNegation:
695 op_type = CSharp.Operator.OpType.UnaryNegation; break;
696 case Operator.UnaryPlus:
697 op_type = CSharp.Operator.OpType.UnaryPlus; break;
699 throw new InternalErrorException (Oper.ToString ());
702 string op_name = CSharp.Operator.GetMetadataName (op_type);
703 MethodGroupExpr user_op = MemberLookup (ec.Compiler, ec.CurrentType, expr.Type, op_name, MemberTypes.Method, AllBindingFlags, expr.Location) as MethodGroupExpr;
707 Arguments args = new Arguments (1);
708 args.Add (new Argument (expr));
709 user_op = user_op.OverloadResolve (ec, ref args, false, expr.Location);
714 Expr = args [0].Expr;
715 return new UserOperatorCall (user_op, args, CreateExpressionTree, expr.Location);
719 // Unary user type overload resolution
721 Expression ResolveUserType (ResolveContext ec, Expression expr)
723 Expression best_expr = ResolveUserOperator (ec, expr);
724 if (best_expr != null)
727 Type[] predefined = predefined_operators [(int) Oper];
728 foreach (Type t in predefined) {
729 Expression oper_expr = Convert.UserDefinedConversion (ec, expr, t, expr.Location, false);
730 if (oper_expr == null)
734 // decimal type is predefined but has user-operators
736 if (oper_expr.Type == TypeManager.decimal_type)
737 oper_expr = ResolveUserType (ec, oper_expr);
739 oper_expr = ResolvePrimitivePredefinedType (oper_expr);
741 if (oper_expr == null)
744 if (best_expr == null) {
745 best_expr = oper_expr;
749 int result = MethodGroupExpr.BetterTypeConversion (ec, best_expr.Type, t);
751 ec.Report.Error (35, loc, "Operator `{0}' is ambiguous on an operand of type `{1}'",
752 OperName (Oper), TypeManager.CSharpName (expr.Type));
757 best_expr = oper_expr;
760 if (best_expr == null)
764 // HACK: Decimal user-operator is included in standard operators
766 if (best_expr.Type == TypeManager.decimal_type)
770 type = best_expr.Type;
774 protected override void CloneTo (CloneContext clonectx, Expression t)
776 Unary target = (Unary) t;
778 target.Expr = Expr.Clone (clonectx);
783 // Unary operators are turned into Indirection expressions
784 // after semantic analysis (this is so we can take the address
785 // of an indirection).
787 public class Indirection : Expression, IMemoryLocation, IAssignMethod, IFixedExpression {
789 LocalTemporary temporary;
792 public Indirection (Expression expr, Location l)
798 public override Expression CreateExpressionTree (ResolveContext ec)
800 Error_PointerInsideExpressionTree (ec);
804 protected override void CloneTo (CloneContext clonectx, Expression t)
806 Indirection target = (Indirection) t;
807 target.expr = expr.Clone (clonectx);
810 public override void Emit (EmitContext ec)
815 LoadFromPtr (ec.ig, Type);
818 public void Emit (EmitContext ec, bool leave_copy)
822 ec.ig.Emit (OpCodes.Dup);
823 temporary = new LocalTemporary (expr.Type);
824 temporary.Store (ec);
828 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
830 prepared = prepare_for_load;
834 if (prepare_for_load)
835 ec.ig.Emit (OpCodes.Dup);
839 ec.ig.Emit (OpCodes.Dup);
840 temporary = new LocalTemporary (expr.Type);
841 temporary.Store (ec);
844 StoreFromPtr (ec.ig, type);
846 if (temporary != null) {
848 temporary.Release (ec);
852 public void AddressOf (EmitContext ec, AddressOp Mode)
857 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
859 return DoResolve (ec);
862 public override Expression DoResolve (ResolveContext ec)
864 expr = expr.Resolve (ec);
869 UnsafeError (ec, loc);
871 if (!expr.Type.IsPointer) {
872 ec.Report.Error (193, loc, "The * or -> operator must be applied to a pointer");
876 if (expr.Type == TypeManager.void_ptr_type) {
877 ec.Report.Error (242, loc, "The operation in question is undefined on void pointers");
881 type = TypeManager.GetElementType (expr.Type);
882 eclass = ExprClass.Variable;
886 public bool IsFixed {
890 public override string ToString ()
892 return "*(" + expr + ")";
897 /// Unary Mutator expressions (pre and post ++ and --)
901 /// UnaryMutator implements ++ and -- expressions. It derives from
902 /// ExpressionStatement becuase the pre/post increment/decrement
903 /// operators can be used in a statement context.
905 /// FIXME: Idea, we could split this up in two classes, one simpler
906 /// for the common case, and one with the extra fields for more complex
907 /// classes (indexers require temporary access; overloaded require method)
910 public class UnaryMutator : ExpressionStatement {
912 public enum Mode : byte {
919 PreDecrement = IsDecrement,
920 PostIncrement = IsPost,
921 PostDecrement = IsPost | IsDecrement
925 bool is_expr = false;
926 bool recurse = false;
931 // This is expensive for the simplest case.
933 UserOperatorCall method;
935 public UnaryMutator (Mode m, Expression e)
945 Operator.GetName (Operator.OpType.Decrement) :
946 Operator.GetName (Operator.OpType.Increment);
950 /// Returns whether an object of type `t' can be incremented
951 /// or decremented with add/sub (ie, basically whether we can
952 /// use pre-post incr-decr operations on it, but it is not a
953 /// System.Decimal, which we require operator overloading to catch)
955 static bool IsIncrementableNumber (Type t)
957 return (t == TypeManager.sbyte_type) ||
958 (t == TypeManager.byte_type) ||
959 (t == TypeManager.short_type) ||
960 (t == TypeManager.ushort_type) ||
961 (t == TypeManager.int32_type) ||
962 (t == TypeManager.uint32_type) ||
963 (t == TypeManager.int64_type) ||
964 (t == TypeManager.uint64_type) ||
965 (t == TypeManager.char_type) ||
966 (TypeManager.IsSubclassOf (t, TypeManager.enum_type)) ||
967 (t == TypeManager.float_type) ||
968 (t == TypeManager.double_type) ||
969 (t.IsPointer && t != TypeManager.void_ptr_type);
972 Expression ResolveOperator (ResolveContext ec)
977 // The operand of the prefix/postfix increment decrement operators
978 // should be an expression that is classified as a variable,
979 // a property access or an indexer access
981 if (expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.IndexerAccess || expr.eclass == ExprClass.PropertyAccess) {
982 expr = expr.ResolveLValue (ec, expr);
984 ec.Report.Error (1059, loc, "The operand of an increment or decrement operator must be a variable, property or indexer");
988 // Step 1: Perform Operator Overload location
994 op_name = Operator.GetMetadataName (Operator.OpType.Decrement);
996 op_name = Operator.GetMetadataName (Operator.OpType.Increment);
998 mg = MemberLookup (ec.Compiler, ec.CurrentType, type, op_name, MemberTypes.Method, AllBindingFlags, loc) as MethodGroupExpr;
1001 Arguments args = new Arguments (1);
1002 args.Add (new Argument (expr));
1003 mg = mg.OverloadResolve (ec, ref args, false, loc);
1007 method = new UserOperatorCall (mg, args, null, loc);
1008 Convert.ImplicitConversionRequired (ec, method, type, loc);
1012 if (!IsIncrementableNumber (type)) {
1013 ec.Report.Error (187, loc, "No such operator '" + OperName () + "' defined for type '" +
1014 TypeManager.CSharpName (type) + "'");
1021 public override Expression CreateExpressionTree (ResolveContext ec)
1023 return new SimpleAssign (this, this).CreateExpressionTree (ec);
1026 public override Expression DoResolve (ResolveContext ec)
1028 expr = expr.Resolve (ec);
1033 if (TypeManager.IsDynamicType (expr.Type)) {
1034 Arguments args = new Arguments (1);
1035 args.Add (new Argument (expr));
1036 return new DynamicUnaryConversion (GetOperatorExpressionTypeName (), args, loc).Resolve (ec);
1039 eclass = ExprClass.Value;
1041 if (TypeManager.IsNullableType (expr.Type))
1042 return new Nullable.LiftedUnaryMutator (mode, expr, loc).Resolve (ec);
1044 return ResolveOperator (ec);
1048 // Loads the proper "1" into the stack based on the type, then it emits the
1049 // opcode for the operation requested
1051 void LoadOneAndEmitOp (EmitContext ec, Type t)
1054 // Measure if getting the typecode and using that is more/less efficient
1055 // that comparing types. t.GetTypeCode() is an internal call.
1057 ILGenerator ig = ec.ig;
1059 if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
1060 LongConstant.EmitLong (ig, 1);
1061 else if (t == TypeManager.double_type)
1062 ig.Emit (OpCodes.Ldc_R8, 1.0);
1063 else if (t == TypeManager.float_type)
1064 ig.Emit (OpCodes.Ldc_R4, 1.0F);
1065 else if (t.IsPointer){
1066 Type et = TypeManager.GetElementType (t);
1067 int n = GetTypeSize (et);
1070 ig.Emit (OpCodes.Sizeof, et);
1072 IntConstant.EmitInt (ig, n);
1073 ig.Emit (OpCodes.Conv_I);
1076 ig.Emit (OpCodes.Ldc_I4_1);
1079 // Now emit the operation
1082 Binary.Operator op = (mode & Mode.IsDecrement) != 0 ? Binary.Operator.Subtraction : Binary.Operator.Addition;
1083 Binary.EmitOperatorOpcode (ec, op, t);
1085 if (t == TypeManager.sbyte_type){
1086 if (ec.HasSet (EmitContext.Options.CheckedScope))
1087 ig.Emit (OpCodes.Conv_Ovf_I1);
1089 ig.Emit (OpCodes.Conv_I1);
1090 } else if (t == TypeManager.byte_type){
1091 if (ec.HasSet (EmitContext.Options.CheckedScope))
1092 ig.Emit (OpCodes.Conv_Ovf_U1);
1094 ig.Emit (OpCodes.Conv_U1);
1095 } else if (t == TypeManager.short_type){
1096 if (ec.HasSet (EmitContext.Options.CheckedScope))
1097 ig.Emit (OpCodes.Conv_Ovf_I2);
1099 ig.Emit (OpCodes.Conv_I2);
1100 } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
1101 if (ec.HasSet (EmitContext.Options.CheckedScope))
1102 ig.Emit (OpCodes.Conv_Ovf_U2);
1104 ig.Emit (OpCodes.Conv_U2);
1109 void EmitCode (EmitContext ec, bool is_expr)
1112 this.is_expr = is_expr;
1113 ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
1116 public override void Emit (EmitContext ec)
1119 // We use recurse to allow ourselfs to be the source
1120 // of an assignment. This little hack prevents us from
1121 // having to allocate another expression
1124 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
1126 LoadOneAndEmitOp (ec, expr.Type);
1128 ec.ig.Emit (OpCodes.Call, (MethodInfo)method.Method);
1133 EmitCode (ec, true);
1136 public override void EmitStatement (EmitContext ec)
1138 EmitCode (ec, false);
1142 // Converts operator to System.Linq.Expressions.ExpressionType enum name
1144 string GetOperatorExpressionTypeName ()
1146 return IsDecrement ? "Decrement" : "Increment";
1150 get { return (mode & Mode.IsDecrement) != 0; }
1154 public override SLE.Expression MakeExpression (BuilderContext ctx)
1157 return method.MakeExpression (ctx);
1159 bool is_checked = ctx.HasSet (BuilderContext.Options.CheckedScope);
1160 var one = SLE.Expression.Constant (1);
1161 var left = expr.MakeExpression (ctx);
1163 SLE.Expression binary;
1165 binary = is_checked ? SLE.Expression.SubtractChecked (left, one) : SLE.Expression.Subtract (left, one);
1167 binary = is_checked ? SLE.Expression.AddChecked (left, one) : SLE.Expression.Add (left, one);
1170 var target = ((RuntimeValueExpression) expr).MetaObject.Expression;
1171 binary = SLE.Expression.Convert (binary, target.Type);
1173 return SLE.Expression.Assign (target, binary);
1177 protected override void CloneTo (CloneContext clonectx, Expression t)
1179 UnaryMutator target = (UnaryMutator) t;
1181 target.expr = expr.Clone (clonectx);
1186 /// Base class for the `Is' and `As' classes.
1190 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1193 public abstract class Probe : Expression {
1194 public Expression ProbeType;
1195 protected Expression expr;
1196 protected TypeExpr probe_type_expr;
1198 public Probe (Expression expr, Expression probe_type, Location l)
1200 ProbeType = probe_type;
1205 public Expression Expr {
1211 public override Expression DoResolve (ResolveContext ec)
1213 probe_type_expr = ProbeType.ResolveAsTypeTerminal (ec, false);
1214 if (probe_type_expr == null)
1217 expr = expr.Resolve (ec);
1221 if ((probe_type_expr.Type.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
1222 ec.Report.Error (-244, loc, "The `{0}' operator cannot be applied to an operand of a static type",
1226 if (expr.Type.IsPointer || probe_type_expr.Type.IsPointer) {
1227 ec.Report.Error (244, loc, "The `{0}' operator cannot be applied to an operand of pointer type",
1232 if (expr.Type == InternalType.AnonymousMethod) {
1233 ec.Report.Error (837, loc, "The `{0}' operator cannot be applied to a lambda expression or anonymous method",
1241 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1243 expr.MutateHoistedGenericType (storey);
1244 probe_type_expr.MutateHoistedGenericType (storey);
1247 protected abstract string OperatorName { get; }
1249 protected override void CloneTo (CloneContext clonectx, Expression t)
1251 Probe target = (Probe) t;
1253 target.expr = expr.Clone (clonectx);
1254 target.ProbeType = ProbeType.Clone (clonectx);
1260 /// Implementation of the `is' operator.
1262 public class Is : Probe {
1263 Nullable.Unwrap expr_unwrap;
1265 public Is (Expression expr, Expression probe_type, Location l)
1266 : base (expr, probe_type, l)
1270 public override Expression CreateExpressionTree (ResolveContext ec)
1272 Arguments args = Arguments.CreateForExpressionTree (ec, null,
1273 expr.CreateExpressionTree (ec),
1274 new TypeOf (probe_type_expr, loc));
1276 return CreateExpressionFactoryCall (ec, "TypeIs", args);
1279 public override void Emit (EmitContext ec)
1281 ILGenerator ig = ec.ig;
1282 if (expr_unwrap != null) {
1283 expr_unwrap.EmitCheck (ec);
1288 ig.Emit (OpCodes.Isinst, probe_type_expr.Type);
1289 ig.Emit (OpCodes.Ldnull);
1290 ig.Emit (OpCodes.Cgt_Un);
1293 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
1295 ILGenerator ig = ec.ig;
1296 if (expr_unwrap != null) {
1297 expr_unwrap.EmitCheck (ec);
1300 ig.Emit (OpCodes.Isinst, probe_type_expr.Type);
1302 ig.Emit (on_true ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1305 Expression CreateConstantResult (ResolveContext ec, bool result)
1308 ec.Report.Warning (183, 1, loc, "The given expression is always of the provided (`{0}') type",
1309 TypeManager.CSharpName (probe_type_expr.Type));
1311 ec.Report.Warning (184, 1, loc, "The given expression is never of the provided (`{0}') type",
1312 TypeManager.CSharpName (probe_type_expr.Type));
1314 return ReducedExpression.Create (new BoolConstant (result, loc), this);
1317 public override Expression DoResolve (ResolveContext ec)
1319 if (base.DoResolve (ec) == null)
1323 bool d_is_nullable = false;
1326 // If E is a method group or the null literal, or if the type of E is a reference
1327 // type or a nullable type and the value of E is null, the result is false
1329 if (expr.IsNull || expr.eclass == ExprClass.MethodGroup)
1330 return CreateConstantResult (ec, false);
1332 if (TypeManager.IsNullableType (d) && !TypeManager.ContainsGenericParameters (d)) {
1333 d = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (d) [0]);
1334 d_is_nullable = true;
1337 type = TypeManager.bool_type;
1338 eclass = ExprClass.Value;
1339 Type t = probe_type_expr.Type;
1340 bool t_is_nullable = false;
1341 if (TypeManager.IsNullableType (t) && !TypeManager.ContainsGenericParameters (t)) {
1342 t = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (t) [0]);
1343 t_is_nullable = true;
1346 if (TypeManager.IsStruct (t)) {
1349 // D and T are the same value types but D can be null
1351 if (d_is_nullable && !t_is_nullable) {
1352 expr_unwrap = Nullable.Unwrap.Create (expr, false);
1357 // The result is true if D and T are the same value types
1359 return CreateConstantResult (ec, true);
1362 if (TypeManager.IsGenericParameter (d))
1363 return ResolveGenericParameter (ec, t, d);
1366 // An unboxing conversion exists
1368 if (Convert.ExplicitReferenceConversionExists (d, t))
1371 if (TypeManager.IsGenericParameter (t))
1372 return ResolveGenericParameter (ec, d, t);
1374 if (TypeManager.IsStruct (d)) {
1376 if (Convert.ImplicitBoxingConversionExists (expr, t, out temp))
1377 return CreateConstantResult (ec, true);
1379 if (TypeManager.IsGenericParameter (d))
1380 return ResolveGenericParameter (ec, t, d);
1382 if (TypeManager.ContainsGenericParameters (d))
1385 if (Convert.ImplicitReferenceConversionExists (expr, t) ||
1386 Convert.ExplicitReferenceConversionExists (d, t)) {
1392 return CreateConstantResult (ec, false);
1395 Expression ResolveGenericParameter (ResolveContext ec, Type d, Type t)
1397 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
1398 if (constraints != null) {
1399 if (constraints.IsReferenceType && TypeManager.IsStruct (d))
1400 return CreateConstantResult (ec, false);
1403 if (TypeManager.IsGenericParameter (expr.Type)) {
1404 if (constraints != null && constraints.IsValueType && expr.Type == t)
1405 return CreateConstantResult (ec, true);
1407 expr = new BoxedCast (expr, d);
1413 protected override string OperatorName {
1414 get { return "is"; }
1419 /// Implementation of the `as' operator.
1421 public class As : Probe {
1423 Expression resolved_type;
1425 public As (Expression expr, Expression probe_type, Location l)
1426 : base (expr, probe_type, l)
1430 public override Expression CreateExpressionTree (ResolveContext ec)
1432 Arguments args = Arguments.CreateForExpressionTree (ec, null,
1433 expr.CreateExpressionTree (ec),
1434 new TypeOf (probe_type_expr, loc));
1436 return CreateExpressionFactoryCall (ec, "TypeAs", args);
1439 public override void Emit (EmitContext ec)
1441 ILGenerator ig = ec.ig;
1446 ig.Emit (OpCodes.Isinst, type);
1449 if (TypeManager.IsGenericParameter (type) || TypeManager.IsNullableType (type))
1450 ig.Emit (OpCodes.Unbox_Any, type);
1454 public override Expression DoResolve (ResolveContext ec)
1456 // Because expr is modified
1457 if (eclass != ExprClass.Invalid)
1460 if (resolved_type == null) {
1461 resolved_type = base.DoResolve (ec);
1463 if (resolved_type == null)
1467 type = probe_type_expr.Type;
1468 eclass = ExprClass.Value;
1469 Type etype = expr.Type;
1471 if (!TypeManager.IsReferenceType (type) && !TypeManager.IsNullableType (type)) {
1472 if (TypeManager.IsGenericParameter (type)) {
1473 ec.Report.Error (413, loc,
1474 "The `as' operator cannot be used with a non-reference type parameter `{0}'. Consider adding `class' or a reference type constraint",
1475 probe_type_expr.GetSignatureForError ());
1477 ec.Report.Error (77, loc,
1478 "The `as' operator cannot be used with a non-nullable value type `{0}'",
1479 TypeManager.CSharpName (type));
1484 if (expr.IsNull && TypeManager.IsNullableType (type)) {
1485 return Nullable.LiftedNull.CreateFromExpression (ec, this);
1488 Expression e = Convert.ImplicitConversion (ec, expr, type, loc);
1495 if (Convert.ExplicitReferenceConversionExists (etype, type)){
1496 if (TypeManager.IsGenericParameter (etype))
1497 expr = new BoxedCast (expr, etype);
1503 if (TypeManager.ContainsGenericParameters (etype) ||
1504 TypeManager.ContainsGenericParameters (type)) {
1505 expr = new BoxedCast (expr, etype);
1510 ec.Report.Error (39, loc, "Cannot convert type `{0}' to `{1}' via a built-in conversion",
1511 TypeManager.CSharpName (etype), TypeManager.CSharpName (type));
1516 protected override string OperatorName {
1517 get { return "as"; }
1520 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1522 type = storey.MutateType (type);
1523 base.MutateHoistedGenericType (storey);
1526 public override bool GetAttributableValue (ResolveContext ec, Type value_type, out object value)
1528 return expr.GetAttributableValue (ec, value_type, out value);
1533 /// This represents a typecast in the source language.
1535 /// FIXME: Cast expressions have an unusual set of parsing
1536 /// rules, we need to figure those out.
1538 public class Cast : ShimExpression {
1539 Expression target_type;
1541 public Cast (Expression cast_type, Expression expr)
1542 : this (cast_type, expr, cast_type.Location)
1546 public Cast (Expression cast_type, Expression expr, Location loc)
1549 this.target_type = cast_type;
1553 public Expression TargetType {
1554 get { return target_type; }
1557 public override Expression DoResolve (ResolveContext ec)
1559 expr = expr.Resolve (ec);
1563 TypeExpr target = target_type.ResolveAsTypeTerminal (ec, false);
1569 if (type.IsAbstract && type.IsSealed) {
1570 ec.Report.Error (716, loc, "Cannot convert to static type `{0}'", TypeManager.CSharpName (type));
1574 eclass = ExprClass.Value;
1576 Constant c = expr as Constant;
1578 c = c.TryReduce (ec, type, loc);
1583 if (type.IsPointer && !ec.IsUnsafe) {
1584 UnsafeError (ec, loc);
1585 } else if (TypeManager.IsDynamicType (expr.Type)) {
1586 Arguments arg = new Arguments (1);
1587 arg.Add (new Argument (expr));
1588 return new DynamicConversion (type, true, arg, loc).Resolve (ec);
1591 expr = Convert.ExplicitConversion (ec, expr, type, loc);
1595 protected override void CloneTo (CloneContext clonectx, Expression t)
1597 Cast target = (Cast) t;
1599 target.target_type = target_type.Clone (clonectx);
1600 target.expr = expr.Clone (clonectx);
1604 public class ImplicitCast : ShimExpression
1606 public ImplicitCast (Expression expr, Type target)
1609 this.loc = expr.Location;
1613 public override Expression DoResolve (ResolveContext ec)
1615 expr = expr.Resolve (ec);
1617 expr = Convert.ImplicitConversionRequired (ec, expr, type, loc);
1624 // C# 2.0 Default value expression
1626 public class DefaultValueExpression : Expression
1628 sealed class DefaultValueNullLiteral : NullLiteral
1630 public DefaultValueNullLiteral (DefaultValueExpression expr)
1631 : base (expr.type, expr.loc)
1635 public override void Error_ValueCannotBeConverted (ResolveContext ec, Location loc, Type t, bool expl)
1637 Error_ValueCannotBeConvertedCore (ec, loc, t, expl);
1644 public DefaultValueExpression (Expression expr, Location loc)
1650 public override Expression CreateExpressionTree (ResolveContext ec)
1652 Arguments args = new Arguments (2);
1653 args.Add (new Argument (this));
1654 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
1655 return CreateExpressionFactoryCall (ec, "Constant", args);
1658 public override Expression DoResolve (ResolveContext ec)
1660 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
1666 if ((type.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
1667 ec.Report.Error (-244, loc, "The `default value' operator cannot be applied to an operand of a static type");
1671 return new NullLiteral (Location).ConvertImplicitly (type);
1673 if (TypeManager.IsReferenceType (type))
1674 return new DefaultValueNullLiteral (this);
1676 Constant c = New.Constantify (type);
1680 eclass = ExprClass.Variable;
1684 public override void Emit (EmitContext ec)
1686 LocalTemporary temp_storage = new LocalTemporary(type);
1688 temp_storage.AddressOf(ec, AddressOp.LoadStore);
1689 ec.ig.Emit(OpCodes.Initobj, type);
1690 temp_storage.Emit(ec);
1693 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1695 type = storey.MutateType (type);
1698 protected override void CloneTo (CloneContext clonectx, Expression t)
1700 DefaultValueExpression target = (DefaultValueExpression) t;
1702 target.expr = expr.Clone (clonectx);
1707 /// Binary operators
1709 public class Binary : Expression, IDynamicBinder
1712 protected class PredefinedOperator {
1713 protected readonly Type left;
1714 protected readonly Type right;
1715 public readonly Operator OperatorsMask;
1716 public Type ReturnType;
1718 public PredefinedOperator (Type ltype, Type rtype, Operator op_mask)
1719 : this (ltype, rtype, op_mask, ltype)
1723 public PredefinedOperator (Type type, Operator op_mask, Type return_type)
1724 : this (type, type, op_mask, return_type)
1728 public PredefinedOperator (Type type, Operator op_mask)
1729 : this (type, type, op_mask, type)
1733 public PredefinedOperator (Type ltype, Type rtype, Operator op_mask, Type return_type)
1735 if ((op_mask & Operator.ValuesOnlyMask) != 0)
1736 throw new InternalErrorException ("Only masked values can be used");
1740 this.OperatorsMask = op_mask;
1741 this.ReturnType = return_type;
1744 public virtual Expression ConvertResult (ResolveContext ec, Binary b)
1746 b.type = ReturnType;
1748 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1749 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
1752 // A user operators does not support multiple user conversions, but decimal type
1753 // is considered to be predefined type therefore we apply predefined operators rules
1754 // and then look for decimal user-operator implementation
1756 if (left == TypeManager.decimal_type)
1757 return b.ResolveUserOperator (ec, b.left.Type, b.right.Type);
1762 public bool IsPrimitiveApplicable (Type ltype, Type rtype)
1765 // We are dealing with primitive types only
1767 return left == ltype && ltype == rtype;
1770 public virtual bool IsApplicable (ResolveContext ec, Expression lexpr, Expression rexpr)
1772 if (TypeManager.IsEqual (left, lexpr.Type) &&
1773 TypeManager.IsEqual (right, rexpr.Type))
1776 return Convert.ImplicitConversionExists (ec, lexpr, left) &&
1777 Convert.ImplicitConversionExists (ec, rexpr, right);
1780 public PredefinedOperator ResolveBetterOperator (ResolveContext ec, PredefinedOperator best_operator)
1783 if (left != null && best_operator.left != null) {
1784 result = MethodGroupExpr.BetterTypeConversion (ec, best_operator.left, left);
1788 // When second arguments are same as the first one, the result is same
1790 if (right != null && (left != right || best_operator.left != best_operator.right)) {
1791 result |= MethodGroupExpr.BetterTypeConversion (ec, best_operator.right, right);
1794 if (result == 0 || result > 2)
1797 return result == 1 ? best_operator : this;
1801 class PredefinedStringOperator : PredefinedOperator {
1802 public PredefinedStringOperator (Type type, Operator op_mask)
1803 : base (type, op_mask, type)
1805 ReturnType = TypeManager.string_type;
1808 public PredefinedStringOperator (Type ltype, Type rtype, Operator op_mask)
1809 : base (ltype, rtype, op_mask)
1811 ReturnType = TypeManager.string_type;
1814 public override Expression ConvertResult (ResolveContext ec, Binary b)
1817 // Use original expression for nullable arguments
1819 Nullable.Unwrap unwrap = b.left as Nullable.Unwrap;
1821 b.left = unwrap.Original;
1823 unwrap = b.right as Nullable.Unwrap;
1825 b.right = unwrap.Original;
1827 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1828 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
1831 // Start a new concat expression using converted expression
1833 return new StringConcat (b.loc, b.left, b.right).Resolve (ec);
1837 class PredefinedShiftOperator : PredefinedOperator {
1838 public PredefinedShiftOperator (Type ltype, Operator op_mask) :
1839 base (ltype, TypeManager.int32_type, op_mask)
1843 public override Expression ConvertResult (ResolveContext ec, Binary b)
1845 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1847 Expression expr_tree_expr = Convert.ImplicitConversion (ec, b.right, TypeManager.int32_type, b.right.Location);
1849 int right_mask = left == TypeManager.int32_type || left == TypeManager.uint32_type ? 0x1f : 0x3f;
1852 // b = b.left >> b.right & (0x1f|0x3f)
1854 b.right = new Binary (Operator.BitwiseAnd,
1855 b.right, new IntConstant (right_mask, b.right.Location)).Resolve (ec);
1858 // Expression tree representation does not use & mask
1860 b.right = ReducedExpression.Create (b.right, expr_tree_expr).Resolve (ec);
1861 b.type = ReturnType;
1866 class PredefinedPointerOperator : PredefinedOperator {
1867 public PredefinedPointerOperator (Type ltype, Type rtype, Operator op_mask)
1868 : base (ltype, rtype, op_mask)
1872 public PredefinedPointerOperator (Type ltype, Type rtype, Operator op_mask, Type retType)
1873 : base (ltype, rtype, op_mask, retType)
1877 public PredefinedPointerOperator (Type type, Operator op_mask, Type return_type)
1878 : base (type, op_mask, return_type)
1882 public override bool IsApplicable (ResolveContext ec, Expression lexpr, Expression rexpr)
1885 if (!lexpr.Type.IsPointer)
1888 if (!Convert.ImplicitConversionExists (ec, lexpr, left))
1892 if (right == null) {
1893 if (!rexpr.Type.IsPointer)
1896 if (!Convert.ImplicitConversionExists (ec, rexpr, right))
1903 public override Expression ConvertResult (ResolveContext ec, Binary b)
1906 b.left = EmptyCast.Create (b.left, left);
1907 } else if (right != null) {
1908 b.right = EmptyCast.Create (b.right, right);
1911 Type r_type = ReturnType;
1912 Expression left_arg, right_arg;
1913 if (r_type == null) {
1916 right_arg = b.right;
1917 r_type = b.left.Type;
1921 r_type = b.right.Type;
1925 right_arg = b.right;
1928 return new PointerArithmetic (b.oper, left_arg, right_arg, r_type, b.loc).Resolve (ec);
1933 public enum Operator {
1934 Multiply = 0 | ArithmeticMask,
1935 Division = 1 | ArithmeticMask,
1936 Modulus = 2 | ArithmeticMask,
1937 Addition = 3 | ArithmeticMask | AdditionMask,
1938 Subtraction = 4 | ArithmeticMask | SubtractionMask,
1940 LeftShift = 5 | ShiftMask,
1941 RightShift = 6 | ShiftMask,
1943 LessThan = 7 | ComparisonMask | RelationalMask,
1944 GreaterThan = 8 | ComparisonMask | RelationalMask,
1945 LessThanOrEqual = 9 | ComparisonMask | RelationalMask,
1946 GreaterThanOrEqual = 10 | ComparisonMask | RelationalMask,
1947 Equality = 11 | ComparisonMask | EqualityMask,
1948 Inequality = 12 | ComparisonMask | EqualityMask,
1950 BitwiseAnd = 13 | BitwiseMask,
1951 ExclusiveOr = 14 | BitwiseMask,
1952 BitwiseOr = 15 | BitwiseMask,
1954 LogicalAnd = 16 | LogicalMask,
1955 LogicalOr = 17 | LogicalMask,
1960 ValuesOnlyMask = ArithmeticMask - 1,
1961 ArithmeticMask = 1 << 5,
1963 ComparisonMask = 1 << 7,
1964 EqualityMask = 1 << 8,
1965 BitwiseMask = 1 << 9,
1966 LogicalMask = 1 << 10,
1967 AdditionMask = 1 << 11,
1968 SubtractionMask = 1 << 12,
1969 RelationalMask = 1 << 13
1972 readonly Operator oper;
1973 protected Expression left, right;
1974 readonly bool is_compound;
1975 Expression enum_conversion;
1977 static PredefinedOperator [] standard_operators;
1978 static PredefinedOperator [] pointer_operators;
1980 public Binary (Operator oper, Expression left, Expression right, bool isCompound)
1981 : this (oper, left, right)
1983 this.is_compound = isCompound;
1986 public Binary (Operator oper, Expression left, Expression right)
1991 this.loc = left.Location;
1994 public Operator Oper {
2001 /// Returns a stringified representation of the Operator
2003 string OperName (Operator oper)
2007 case Operator.Multiply:
2010 case Operator.Division:
2013 case Operator.Modulus:
2016 case Operator.Addition:
2019 case Operator.Subtraction:
2022 case Operator.LeftShift:
2025 case Operator.RightShift:
2028 case Operator.LessThan:
2031 case Operator.GreaterThan:
2034 case Operator.LessThanOrEqual:
2037 case Operator.GreaterThanOrEqual:
2040 case Operator.Equality:
2043 case Operator.Inequality:
2046 case Operator.BitwiseAnd:
2049 case Operator.BitwiseOr:
2052 case Operator.ExclusiveOr:
2055 case Operator.LogicalOr:
2058 case Operator.LogicalAnd:
2062 s = oper.ToString ();
2072 public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, Operator oper, Location loc)
2074 new Binary (oper, left, right).Error_OperatorCannotBeApplied (ec, left, right);
2077 public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, string oper, Location loc)
2080 l = TypeManager.CSharpName (left.Type);
2081 r = TypeManager.CSharpName (right.Type);
2083 ec.Report.Error (19, loc, "Operator `{0}' cannot be applied to operands of type `{1}' and `{2}'",
2087 protected void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right)
2089 Error_OperatorCannotBeApplied (ec, left, right, OperName (oper), loc);
2093 // Converts operator to System.Linq.Expressions.ExpressionType enum name
2095 string GetOperatorExpressionTypeName ()
2098 case Operator.Addition:
2099 return is_compound ? "AddAssign" : "Add";
2100 case Operator.BitwiseAnd:
2101 return is_compound ? "AndAssign" : "And";
2102 case Operator.BitwiseOr:
2103 return is_compound ? "OrAssign" : "Or";
2104 case Operator.Division:
2105 return is_compound ? "DivideAssign" : "Divide";
2106 case Operator.ExclusiveOr:
2107 return is_compound ? "ExclusiveOrAssign" : "ExclusiveOr";
2108 case Operator.Equality:
2110 case Operator.GreaterThan:
2111 return "GreaterThan";
2112 case Operator.GreaterThanOrEqual:
2113 return "GreaterThanOrEqual";
2114 case Operator.Inequality:
2116 case Operator.LeftShift:
2117 return is_compound ? "LeftShiftAssign" : "LeftShift";
2118 case Operator.LessThan:
2120 case Operator.LessThanOrEqual:
2121 return "LessThanOrEqual";
2122 case Operator.LogicalAnd:
2124 case Operator.LogicalOr:
2126 case Operator.Modulus:
2127 return is_compound ? "ModuloAssign" : "Modulo";
2128 case Operator.Multiply:
2129 return is_compound ? "MultiplyAssign" : "Multiply";
2130 case Operator.RightShift:
2131 return is_compound ? "RightShiftAssign" : "RightShift";
2132 case Operator.Subtraction:
2133 return is_compound ? "SubtractAssign" : "Subtract";
2135 throw new NotImplementedException ("Unknown expression type operator " + oper.ToString ());
2139 static string GetOperatorMetadataName (Operator op)
2141 CSharp.Operator.OpType op_type;
2143 case Operator.Addition:
2144 op_type = CSharp.Operator.OpType.Addition; break;
2145 case Operator.BitwiseAnd:
2146 op_type = CSharp.Operator.OpType.BitwiseAnd; break;
2147 case Operator.BitwiseOr:
2148 op_type = CSharp.Operator.OpType.BitwiseOr; break;
2149 case Operator.Division:
2150 op_type = CSharp.Operator.OpType.Division; break;
2151 case Operator.Equality:
2152 op_type = CSharp.Operator.OpType.Equality; break;
2153 case Operator.ExclusiveOr:
2154 op_type = CSharp.Operator.OpType.ExclusiveOr; break;
2155 case Operator.GreaterThan:
2156 op_type = CSharp.Operator.OpType.GreaterThan; break;
2157 case Operator.GreaterThanOrEqual:
2158 op_type = CSharp.Operator.OpType.GreaterThanOrEqual; break;
2159 case Operator.Inequality:
2160 op_type = CSharp.Operator.OpType.Inequality; break;
2161 case Operator.LeftShift:
2162 op_type = CSharp.Operator.OpType.LeftShift; break;
2163 case Operator.LessThan:
2164 op_type = CSharp.Operator.OpType.LessThan; break;
2165 case Operator.LessThanOrEqual:
2166 op_type = CSharp.Operator.OpType.LessThanOrEqual; break;
2167 case Operator.Modulus:
2168 op_type = CSharp.Operator.OpType.Modulus; break;
2169 case Operator.Multiply:
2170 op_type = CSharp.Operator.OpType.Multiply; break;
2171 case Operator.RightShift:
2172 op_type = CSharp.Operator.OpType.RightShift; break;
2173 case Operator.Subtraction:
2174 op_type = CSharp.Operator.OpType.Subtraction; break;
2176 throw new InternalErrorException (op.ToString ());
2179 return CSharp.Operator.GetMetadataName (op_type);
2182 public static void EmitOperatorOpcode (EmitContext ec, Operator oper, Type l)
2185 ILGenerator ig = ec.ig;
2188 case Operator.Multiply:
2189 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2190 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2191 opcode = OpCodes.Mul_Ovf;
2192 else if (!IsFloat (l))
2193 opcode = OpCodes.Mul_Ovf_Un;
2195 opcode = OpCodes.Mul;
2197 opcode = OpCodes.Mul;
2201 case Operator.Division:
2203 opcode = OpCodes.Div_Un;
2205 opcode = OpCodes.Div;
2208 case Operator.Modulus:
2210 opcode = OpCodes.Rem_Un;
2212 opcode = OpCodes.Rem;
2215 case Operator.Addition:
2216 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2217 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2218 opcode = OpCodes.Add_Ovf;
2219 else if (!IsFloat (l))
2220 opcode = OpCodes.Add_Ovf_Un;
2222 opcode = OpCodes.Add;
2224 opcode = OpCodes.Add;
2227 case Operator.Subtraction:
2228 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2229 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2230 opcode = OpCodes.Sub_Ovf;
2231 else if (!IsFloat (l))
2232 opcode = OpCodes.Sub_Ovf_Un;
2234 opcode = OpCodes.Sub;
2236 opcode = OpCodes.Sub;
2239 case Operator.RightShift:
2241 opcode = OpCodes.Shr_Un;
2243 opcode = OpCodes.Shr;
2246 case Operator.LeftShift:
2247 opcode = OpCodes.Shl;
2250 case Operator.Equality:
2251 opcode = OpCodes.Ceq;
2254 case Operator.Inequality:
2255 ig.Emit (OpCodes.Ceq);
2256 ig.Emit (OpCodes.Ldc_I4_0);
2258 opcode = OpCodes.Ceq;
2261 case Operator.LessThan:
2263 opcode = OpCodes.Clt_Un;
2265 opcode = OpCodes.Clt;
2268 case Operator.GreaterThan:
2270 opcode = OpCodes.Cgt_Un;
2272 opcode = OpCodes.Cgt;
2275 case Operator.LessThanOrEqual:
2276 if (IsUnsigned (l) || IsFloat (l))
2277 ig.Emit (OpCodes.Cgt_Un);
2279 ig.Emit (OpCodes.Cgt);
2280 ig.Emit (OpCodes.Ldc_I4_0);
2282 opcode = OpCodes.Ceq;
2285 case Operator.GreaterThanOrEqual:
2286 if (IsUnsigned (l) || IsFloat (l))
2287 ig.Emit (OpCodes.Clt_Un);
2289 ig.Emit (OpCodes.Clt);
2291 ig.Emit (OpCodes.Ldc_I4_0);
2293 opcode = OpCodes.Ceq;
2296 case Operator.BitwiseOr:
2297 opcode = OpCodes.Or;
2300 case Operator.BitwiseAnd:
2301 opcode = OpCodes.And;
2304 case Operator.ExclusiveOr:
2305 opcode = OpCodes.Xor;
2309 throw new InternalErrorException (oper.ToString ());
2315 static bool IsUnsigned (Type t)
2320 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2321 t == TypeManager.ushort_type || t == TypeManager.byte_type);
2324 static bool IsFloat (Type t)
2326 return t == TypeManager.float_type || t == TypeManager.double_type;
2329 Expression ResolveOperator (ResolveContext ec)
2332 Type r = right.Type;
2334 bool primitives_only = false;
2336 if (standard_operators == null)
2337 CreateStandardOperatorsTable ();
2340 // Handles predefined primitive types
2342 if (TypeManager.IsPrimitiveType (l) && TypeManager.IsPrimitiveType (r)) {
2343 if ((oper & Operator.ShiftMask) == 0) {
2344 if (l != TypeManager.bool_type && !DoBinaryOperatorPromotion (ec))
2347 primitives_only = true;
2351 if (l.IsPointer || r.IsPointer)
2352 return ResolveOperatorPointer (ec, l, r);
2355 bool lenum = TypeManager.IsEnumType (l);
2356 bool renum = TypeManager.IsEnumType (r);
2357 if (lenum || renum) {
2358 expr = ResolveOperatorEnum (ec, lenum, renum, l, r);
2360 // TODO: Can this be ambiguous
2366 if ((oper == Operator.Addition || oper == Operator.Subtraction || (oper & Operator.EqualityMask) != 0) &&
2367 (TypeManager.IsDelegateType (l) || TypeManager.IsDelegateType (r))) {
2369 expr = ResolveOperatorDelegate (ec, l, r);
2371 // TODO: Can this be ambiguous
2377 expr = ResolveUserOperator (ec, l, r);
2381 // Predefined reference types equality
2382 if ((oper & Operator.EqualityMask) != 0) {
2383 expr = ResolveOperatorEqualityRerefence (ec, l, r);
2389 return ResolveOperatorPredefined (ec, standard_operators, primitives_only, null);
2392 // at least one of 'left' or 'right' is an enumeration constant (EnumConstant or SideEffectConstant or ...)
2393 // if 'left' is not an enumeration constant, create one from the type of 'right'
2394 Constant EnumLiftUp (ResolveContext ec, Constant left, Constant right, Location loc)
2397 case Operator.BitwiseOr:
2398 case Operator.BitwiseAnd:
2399 case Operator.ExclusiveOr:
2400 case Operator.Equality:
2401 case Operator.Inequality:
2402 case Operator.LessThan:
2403 case Operator.LessThanOrEqual:
2404 case Operator.GreaterThan:
2405 case Operator.GreaterThanOrEqual:
2406 if (TypeManager.IsEnumType (left.Type))
2409 if (left.IsZeroInteger)
2410 return left.TryReduce (ec, right.Type, loc);
2414 case Operator.Addition:
2415 case Operator.Subtraction:
2418 case Operator.Multiply:
2419 case Operator.Division:
2420 case Operator.Modulus:
2421 case Operator.LeftShift:
2422 case Operator.RightShift:
2423 if (TypeManager.IsEnumType (right.Type) || TypeManager.IsEnumType (left.Type))
2427 Error_OperatorCannotBeApplied (ec, this.left, this.right);
2432 // The `|' operator used on types which were extended is dangerous
2434 void CheckBitwiseOrOnSignExtended (ResolveContext ec)
2436 OpcodeCast lcast = left as OpcodeCast;
2437 if (lcast != null) {
2438 if (IsUnsigned (lcast.UnderlyingType))
2442 OpcodeCast rcast = right as OpcodeCast;
2443 if (rcast != null) {
2444 if (IsUnsigned (rcast.UnderlyingType))
2448 if (lcast == null && rcast == null)
2451 // FIXME: consider constants
2453 ec.Report.Warning (675, 3, loc,
2454 "The operator `|' used on the sign-extended type `{0}'. Consider casting to a smaller unsigned type first",
2455 TypeManager.CSharpName (lcast != null ? lcast.UnderlyingType : rcast.UnderlyingType));
2458 static void CreatePointerOperatorsTable ()
2460 ArrayList temp = new ArrayList ();
2463 // Pointer arithmetic:
2465 // T* operator + (T* x, int y); T* operator - (T* x, int y);
2466 // T* operator + (T* x, uint y); T* operator - (T* x, uint y);
2467 // T* operator + (T* x, long y); T* operator - (T* x, long y);
2468 // T* operator + (T* x, ulong y); T* operator - (T* x, ulong y);
2470 temp.Add (new PredefinedPointerOperator (null, TypeManager.int32_type, Operator.AdditionMask | Operator.SubtractionMask));
2471 temp.Add (new PredefinedPointerOperator (null, TypeManager.uint32_type, Operator.AdditionMask | Operator.SubtractionMask));
2472 temp.Add (new PredefinedPointerOperator (null, TypeManager.int64_type, Operator.AdditionMask | Operator.SubtractionMask));
2473 temp.Add (new PredefinedPointerOperator (null, TypeManager.uint64_type, Operator.AdditionMask | Operator.SubtractionMask));
2476 // T* operator + (int y, T* x);
2477 // T* operator + (uint y, T *x);
2478 // T* operator + (long y, T *x);
2479 // T* operator + (ulong y, T *x);
2481 temp.Add (new PredefinedPointerOperator (TypeManager.int32_type, null, Operator.AdditionMask, null));
2482 temp.Add (new PredefinedPointerOperator (TypeManager.uint32_type, null, Operator.AdditionMask, null));
2483 temp.Add (new PredefinedPointerOperator (TypeManager.int64_type, null, Operator.AdditionMask, null));
2484 temp.Add (new PredefinedPointerOperator (TypeManager.uint64_type, null, Operator.AdditionMask, null));
2487 // long operator - (T* x, T *y)
2489 temp.Add (new PredefinedPointerOperator (null, Operator.SubtractionMask, TypeManager.int64_type));
2491 pointer_operators = (PredefinedOperator []) temp.ToArray (typeof (PredefinedOperator));
2494 static void CreateStandardOperatorsTable ()
2496 ArrayList temp = new ArrayList ();
2497 Type bool_type = TypeManager.bool_type;
2499 temp.Add (new PredefinedOperator (TypeManager.int32_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2500 temp.Add (new PredefinedOperator (TypeManager.uint32_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2501 temp.Add (new PredefinedOperator (TypeManager.int64_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2502 temp.Add (new PredefinedOperator (TypeManager.uint64_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2503 temp.Add (new PredefinedOperator (TypeManager.float_type, Operator.ArithmeticMask));
2504 temp.Add (new PredefinedOperator (TypeManager.double_type, Operator.ArithmeticMask));
2505 temp.Add (new PredefinedOperator (TypeManager.decimal_type, Operator.ArithmeticMask));
2507 temp.Add (new PredefinedOperator (TypeManager.int32_type, Operator.ComparisonMask, bool_type));
2508 temp.Add (new PredefinedOperator (TypeManager.uint32_type, Operator.ComparisonMask, bool_type));
2509 temp.Add (new PredefinedOperator (TypeManager.int64_type, Operator.ComparisonMask, bool_type));
2510 temp.Add (new PredefinedOperator (TypeManager.uint64_type, Operator.ComparisonMask, bool_type));
2511 temp.Add (new PredefinedOperator (TypeManager.float_type, Operator.ComparisonMask, bool_type));
2512 temp.Add (new PredefinedOperator (TypeManager.double_type, Operator.ComparisonMask, bool_type));
2513 temp.Add (new PredefinedOperator (TypeManager.decimal_type, Operator.ComparisonMask, bool_type));
2515 temp.Add (new PredefinedOperator (TypeManager.string_type, Operator.EqualityMask, bool_type));
2517 temp.Add (new PredefinedStringOperator (TypeManager.string_type, Operator.AdditionMask));
2518 temp.Add (new PredefinedStringOperator (TypeManager.string_type, TypeManager.object_type, Operator.AdditionMask));
2519 temp.Add (new PredefinedStringOperator (TypeManager.object_type, TypeManager.string_type, Operator.AdditionMask));
2521 temp.Add (new PredefinedOperator (bool_type,
2522 Operator.BitwiseMask | Operator.LogicalMask | Operator.EqualityMask, bool_type));
2524 temp.Add (new PredefinedShiftOperator (TypeManager.int32_type, Operator.ShiftMask));
2525 temp.Add (new PredefinedShiftOperator (TypeManager.uint32_type, Operator.ShiftMask));
2526 temp.Add (new PredefinedShiftOperator (TypeManager.int64_type, Operator.ShiftMask));
2527 temp.Add (new PredefinedShiftOperator (TypeManager.uint64_type, Operator.ShiftMask));
2529 standard_operators = (PredefinedOperator []) temp.ToArray (typeof (PredefinedOperator));
2533 // Rules used during binary numeric promotion
2535 static bool DoNumericPromotion (ref Expression prim_expr, ref Expression second_expr, Type type)
2540 Constant c = prim_expr as Constant;
2542 temp = c.ConvertImplicitly (type);
2549 if (type == TypeManager.uint32_type) {
2550 etype = prim_expr.Type;
2551 if (etype == TypeManager.int32_type || etype == TypeManager.short_type || etype == TypeManager.sbyte_type) {
2552 type = TypeManager.int64_type;
2554 if (type != second_expr.Type) {
2555 c = second_expr as Constant;
2557 temp = c.ConvertImplicitly (type);
2559 temp = Convert.ImplicitNumericConversion (second_expr, type);
2565 } else if (type == TypeManager.uint64_type) {
2567 // A compile-time error occurs if the other operand is of type sbyte, short, int, or long
2569 if (type == TypeManager.int32_type || type == TypeManager.int64_type ||
2570 type == TypeManager.sbyte_type || type == TypeManager.sbyte_type)
2574 temp = Convert.ImplicitNumericConversion (prim_expr, type);
2583 // 7.2.6.2 Binary numeric promotions
2585 public bool DoBinaryOperatorPromotion (ResolveContext ec)
2587 Type ltype = left.Type;
2588 Type rtype = right.Type;
2591 foreach (Type t in ConstantFold.binary_promotions) {
2593 return t == rtype || DoNumericPromotion (ref right, ref left, t);
2596 return t == ltype || DoNumericPromotion (ref left, ref right, t);
2599 Type int32 = TypeManager.int32_type;
2600 if (ltype != int32) {
2601 Constant c = left as Constant;
2603 temp = c.ConvertImplicitly (int32);
2605 temp = Convert.ImplicitNumericConversion (left, int32);
2612 if (rtype != int32) {
2613 Constant c = right as Constant;
2615 temp = c.ConvertImplicitly (int32);
2617 temp = Convert.ImplicitNumericConversion (right, int32);
2627 public override Expression DoResolve (ResolveContext ec)
2632 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2633 left = ((ParenthesizedExpression) left).Expr;
2634 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2638 if (left.eclass == ExprClass.Type) {
2639 ec.Report.Error (75, loc, "To cast a negative value, you must enclose the value in parentheses");
2643 left = left.Resolve (ec);
2648 Constant lc = left as Constant;
2650 if (lc != null && lc.Type == TypeManager.bool_type &&
2651 ((oper == Operator.LogicalAnd && lc.IsDefaultValue) ||
2652 (oper == Operator.LogicalOr && !lc.IsDefaultValue))) {
2654 // FIXME: resolve right expression as unreachable
2655 // right.Resolve (ec);
2657 ec.Report.Warning (429, 4, loc, "Unreachable expression code detected");
2661 right = right.Resolve (ec);
2665 eclass = ExprClass.Value;
2666 Constant rc = right as Constant;
2668 // The conversion rules are ignored in enum context but why
2669 if (!ec.HasSet (ResolveContext.Options.EnumScope) && lc != null && rc != null && (TypeManager.IsEnumType (left.Type) || TypeManager.IsEnumType (right.Type))) {
2670 lc = EnumLiftUp (ec, lc, rc, loc);
2672 rc = EnumLiftUp (ec, rc, lc, loc);
2675 if (rc != null && lc != null) {
2676 int prev_e = ec.Report.Errors;
2677 Expression e = ConstantFold.BinaryFold (
2678 ec, oper, lc, rc, loc);
2679 if (e != null || ec.Report.Errors != prev_e)
2681 } else if ((oper == Operator.BitwiseAnd || oper == Operator.LogicalAnd) && !TypeManager.IsDynamicType (left.Type) &&
2682 ((lc != null && lc.IsDefaultValue && !(lc is NullLiteral)) || (rc != null && rc.IsDefaultValue && !(rc is NullLiteral)))) {
2684 if ((ResolveOperator (ec)) == null) {
2685 Error_OperatorCannotBeApplied (ec, left, right);
2690 // The result is a constant with side-effect
2692 Constant side_effect = rc == null ?
2693 new SideEffectConstant (lc, right, loc) :
2694 new SideEffectConstant (rc, left, loc);
2696 return ReducedExpression.Create (side_effect, this);
2699 // Comparison warnings
2700 if ((oper & Operator.ComparisonMask) != 0) {
2701 if (left.Equals (right)) {
2702 ec.Report.Warning (1718, 3, loc, "A comparison made to same variable. Did you mean to compare something else?");
2704 CheckUselessComparison (ec, lc, right.Type);
2705 CheckUselessComparison (ec, rc, left.Type);
2708 if (TypeManager.IsDynamicType (left.Type) || TypeManager.IsDynamicType (right.Type)) {
2709 Arguments args = new Arguments (2);
2710 args.Add (new Argument (left));
2711 args.Add (new Argument (right));
2712 return new DynamicExpressionStatement (this, args, loc).Resolve (ec);
2715 if (RootContext.Version >= LanguageVersion.ISO_2 &&
2716 ((TypeManager.IsNullableType (left.Type) && (right is NullLiteral || TypeManager.IsNullableType (right.Type) || TypeManager.IsValueType (right.Type))) ||
2717 (TypeManager.IsValueType (left.Type) && right is NullLiteral) ||
2718 (TypeManager.IsNullableType (right.Type) && (left is NullLiteral || TypeManager.IsNullableType (left.Type) || TypeManager.IsValueType (left.Type))) ||
2719 (TypeManager.IsValueType (right.Type) && left is NullLiteral)))
2720 return new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
2722 return DoResolveCore (ec, left, right);
2725 protected Expression DoResolveCore (ResolveContext ec, Expression left_orig, Expression right_orig)
2727 Expression expr = ResolveOperator (ec);
2729 Error_OperatorCannotBeApplied (ec, left_orig, right_orig);
2731 if (left == null || right == null)
2732 throw new InternalErrorException ("Invalid conversion");
2734 if (oper == Operator.BitwiseOr)
2735 CheckBitwiseOrOnSignExtended (ec);
2741 public override SLE.Expression MakeExpression (BuilderContext ctx)
2743 var le = left.MakeExpression (ctx);
2744 var re = right.MakeExpression (ctx);
2745 bool is_checked = ctx.HasSet (BuilderContext.Options.CheckedScope);
2748 case Operator.Addition:
2749 return is_checked ? SLE.Expression.AddChecked (le, re) : SLE.Expression.Add (le, re);
2750 case Operator.BitwiseAnd:
2751 return SLE.Expression.And (le, re);
2752 case Operator.BitwiseOr:
2753 return SLE.Expression.Or (le, re);
2754 case Operator.Division:
2755 return SLE.Expression.Divide (le, re);
2756 case Operator.Equality:
2757 return SLE.Expression.Equal (le, re);
2758 case Operator.ExclusiveOr:
2759 return SLE.Expression.ExclusiveOr (le, re);
2760 case Operator.GreaterThan:
2761 return SLE.Expression.GreaterThan (le, re);
2762 case Operator.GreaterThanOrEqual:
2763 return SLE.Expression.GreaterThanOrEqual (le, re);
2764 case Operator.Inequality:
2765 return SLE.Expression.NotEqual (le, re);
2766 case Operator.LeftShift:
2767 return SLE.Expression.LeftShift (le, re);
2768 case Operator.LessThan:
2769 return SLE.Expression.LessThan (le, re);
2770 case Operator.LessThanOrEqual:
2771 return SLE.Expression.LessThanOrEqual (le, re);
2772 case Operator.LogicalAnd:
2773 return SLE.Expression.AndAlso (le, re);
2774 case Operator.LogicalOr:
2775 return SLE.Expression.OrElse (le, re);
2776 case Operator.Modulus:
2777 return SLE.Expression.Modulo (le, re);
2778 case Operator.Multiply:
2779 return is_checked ? SLE.Expression.MultiplyChecked (le, re) : SLE.Expression.Multiply (le, re);
2780 case Operator.RightShift:
2781 return SLE.Expression.RightShift (le, re);
2782 case Operator.Subtraction:
2783 return is_checked ? SLE.Expression.SubtractChecked (le, re) : SLE.Expression.Subtract (le, re);
2785 throw new NotImplementedException (oper.ToString ());
2790 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
2792 left.MutateHoistedGenericType (storey);
2793 right.MutateHoistedGenericType (storey);
2797 // D operator + (D x, D y)
2798 // D operator - (D x, D y)
2799 // bool operator == (D x, D y)
2800 // bool operator != (D x, D y)
2802 Expression ResolveOperatorDelegate (ResolveContext ec, Type l, Type r)
2804 bool is_equality = (oper & Operator.EqualityMask) != 0;
2805 if (!TypeManager.IsEqual (l, r) && !TypeManager.IsVariantOf (r, l)) {
2807 if (right.eclass == ExprClass.MethodGroup || (r == InternalType.AnonymousMethod && !is_equality)) {
2808 tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2813 } else if (left.eclass == ExprClass.MethodGroup || (l == InternalType.AnonymousMethod && !is_equality)) {
2814 tmp = Convert.ImplicitConversionRequired (ec, left, r, loc);
2825 // Resolve delegate equality as a user operator
2828 return ResolveUserOperator (ec, l, r);
2831 Arguments args = new Arguments (2);
2832 args.Add (new Argument (left));
2833 args.Add (new Argument (right));
2835 if (oper == Operator.Addition) {
2836 if (TypeManager.delegate_combine_delegate_delegate == null) {
2837 TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
2838 TypeManager.delegate_type, "Combine", loc, TypeManager.delegate_type, TypeManager.delegate_type);
2841 method = TypeManager.delegate_combine_delegate_delegate;
2843 if (TypeManager.delegate_remove_delegate_delegate == null) {
2844 TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
2845 TypeManager.delegate_type, "Remove", loc, TypeManager.delegate_type, TypeManager.delegate_type);
2848 method = TypeManager.delegate_remove_delegate_delegate;
2851 MethodGroupExpr mg = new MethodGroupExpr (new MemberInfo [] { method }, TypeManager.delegate_type, loc);
2852 mg = mg.OverloadResolve (ec, ref args, false, loc);
2854 return new ClassCast (new UserOperatorCall (mg, args, CreateExpressionTree, loc), l);
2858 // Enumeration operators
2860 Expression ResolveOperatorEnum (ResolveContext ec, bool lenum, bool renum, Type ltype, Type rtype)
2863 // bool operator == (E x, E y);
2864 // bool operator != (E x, E y);
2865 // bool operator < (E x, E y);
2866 // bool operator > (E x, E y);
2867 // bool operator <= (E x, E y);
2868 // bool operator >= (E x, E y);
2870 // E operator & (E x, E y);
2871 // E operator | (E x, E y);
2872 // E operator ^ (E x, E y);
2874 // U operator - (E e, E f)
2875 // E operator - (E e, U x)
2877 // E operator + (U x, E e)
2878 // E operator + (E e, U x)
2880 if (!((oper & (Operator.ComparisonMask | Operator.BitwiseMask)) != 0 ||
2881 (oper == Operator.Subtraction && lenum) ||
2882 (oper == Operator.Addition && (lenum != renum || type != null)))) // type != null for lifted null
2885 Expression ltemp = left;
2886 Expression rtemp = right;
2887 Type underlying_type;
2890 if ((oper & (Operator.ComparisonMask | Operator.BitwiseMask)) != 0) {
2892 expr = Convert.ImplicitConversion (ec, left, rtype, loc);
2898 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
2906 if (TypeManager.IsEqual (ltype, rtype)) {
2907 underlying_type = TypeManager.GetEnumUnderlyingType (ltype);
2909 if (left is Constant)
2910 left = ((Constant) left).ConvertExplicitly (false, underlying_type);
2912 left = EmptyCast.Create (left, underlying_type);
2914 if (right is Constant)
2915 right = ((Constant) right).ConvertExplicitly (false, underlying_type);
2917 right = EmptyCast.Create (right, underlying_type);
2919 underlying_type = TypeManager.GetEnumUnderlyingType (ltype);
2921 if (oper != Operator.Subtraction && oper != Operator.Addition) {
2922 Constant c = right as Constant;
2923 if (c == null || !c.IsDefaultValue)
2926 if (!Convert.ImplicitStandardConversionExists (right, underlying_type))
2929 right = Convert.ImplicitConversionStandard (ec, right, underlying_type, right.Location);
2932 if (left is Constant)
2933 left = ((Constant) left).ConvertExplicitly (false, underlying_type);
2935 left = EmptyCast.Create (left, underlying_type);
2938 underlying_type = TypeManager.GetEnumUnderlyingType (rtype);
2940 if (oper != Operator.Addition) {
2941 Constant c = left as Constant;
2942 if (c == null || !c.IsDefaultValue)
2945 if (!Convert.ImplicitStandardConversionExists (left, underlying_type))
2948 left = Convert.ImplicitConversionStandard (ec, left, underlying_type, left.Location);
2951 if (right is Constant)
2952 right = ((Constant) right).ConvertExplicitly (false, underlying_type);
2954 right = EmptyCast.Create (right, underlying_type);
2961 // C# specification uses explicit cast syntax which means binary promotion
2962 // should happen, however it seems that csc does not do that
2964 if (!DoBinaryOperatorPromotion (ec)) {
2970 Type res_type = null;
2971 if ((oper & Operator.BitwiseMask) != 0 || oper == Operator.Subtraction || oper == Operator.Addition) {
2972 Type promoted_type = lenum ? left.Type : right.Type;
2973 enum_conversion = Convert.ExplicitNumericConversion (
2974 new EmptyExpression (promoted_type), underlying_type);
2976 if (oper == Operator.Subtraction && renum && lenum)
2977 res_type = underlying_type;
2978 else if (oper == Operator.Addition && renum)
2984 expr = ResolveOperatorPredefined (ec, standard_operators, true, res_type);
2985 if (!is_compound || expr == null)
2993 // If the return type of the selected operator is implicitly convertible to the type of x
2995 if (Convert.ImplicitConversionExists (ec, expr, ltype))
2999 // Otherwise, if the selected operator is a predefined operator, if the return type of the
3000 // selected operator is explicitly convertible to the type of x, and if y is implicitly
3001 // convertible to the type of x or the operator is a shift operator, then the operation
3002 // is evaluated as x = (T)(x op y), where T is the type of x
3004 expr = Convert.ExplicitConversion (ec, expr, ltype, loc);
3008 if (Convert.ImplicitConversionExists (ec, ltemp, ltype))
3015 // 7.9.6 Reference type equality operators
3017 Binary ResolveOperatorEqualityRerefence (ResolveContext ec, Type l, Type r)
3020 // operator != (object a, object b)
3021 // operator == (object a, object b)
3024 // TODO: this method is almost equivalent to Convert.ImplicitReferenceConversion
3026 if (left.eclass == ExprClass.MethodGroup || right.eclass == ExprClass.MethodGroup)
3029 type = TypeManager.bool_type;
3030 GenericConstraints constraints;
3032 bool lgen = TypeManager.IsGenericParameter (l);
3034 if (TypeManager.IsEqual (l, r)) {
3037 // Only allow to compare same reference type parameter
3039 if (TypeManager.IsReferenceType (l)) {
3040 left = new BoxedCast (left, TypeManager.object_type);
3041 right = new BoxedCast (right, TypeManager.object_type);
3048 if (l == InternalType.AnonymousMethod)
3051 if (TypeManager.IsValueType (l))
3057 bool rgen = TypeManager.IsGenericParameter (r);
3060 // a, Both operands are reference-type values or the value null
3061 // b, One operand is a value of type T where T is a type-parameter and
3062 // the other operand is the value null. Furthermore T does not have the
3063 // value type constrain
3065 if (left is NullLiteral || right is NullLiteral) {
3067 constraints = TypeManager.GetTypeParameterConstraints (l);
3068 if (constraints != null && constraints.HasValueTypeConstraint)
3071 left = new BoxedCast (left, TypeManager.object_type);
3076 constraints = TypeManager.GetTypeParameterConstraints (r);
3077 if (constraints != null && constraints.HasValueTypeConstraint)
3080 right = new BoxedCast (right, TypeManager.object_type);
3086 // An interface is converted to the object before the
3087 // standard conversion is applied. It's not clear from the
3088 // standard but it looks like it works like that.
3091 if (!TypeManager.IsReferenceType (l))
3093 left = new BoxedCast (left, TypeManager.object_type);
3094 } else if (l.IsInterface) {
3095 l = TypeManager.object_type;
3096 } else if (TypeManager.IsStruct (l)) {
3101 if (!TypeManager.IsReferenceType (r))
3103 right = new BoxedCast (right, TypeManager.object_type);
3104 } else if (r.IsInterface) {
3105 r = TypeManager.object_type;
3106 } else if (TypeManager.IsStruct (r)) {
3111 const string ref_comparison = "Possible unintended reference comparison. " +
3112 "Consider casting the {0} side of the expression to `string' to compare the values";
3115 // A standard implicit conversion exists from the type of either
3116 // operand to the type of the other operand
3118 if (Convert.ImplicitReferenceConversionExists (left, r)) {
3119 if (l == TypeManager.string_type)
3120 ec.Report.Warning (253, 2, loc, ref_comparison, "right");
3125 if (Convert.ImplicitReferenceConversionExists (right, l)) {
3126 if (r == TypeManager.string_type)
3127 ec.Report.Warning (252, 2, loc, ref_comparison, "left");
3136 Expression ResolveOperatorPointer (ResolveContext ec, Type l, Type r)
3139 // bool operator == (void* x, void* y);
3140 // bool operator != (void* x, void* y);
3141 // bool operator < (void* x, void* y);
3142 // bool operator > (void* x, void* y);
3143 // bool operator <= (void* x, void* y);
3144 // bool operator >= (void* x, void* y);
3146 if ((oper & Operator.ComparisonMask) != 0) {
3149 temp = Convert.ImplicitConversion (ec, left, r, left.Location);
3156 temp = Convert.ImplicitConversion (ec, right, l, right.Location);
3162 type = TypeManager.bool_type;
3166 if (pointer_operators == null)
3167 CreatePointerOperatorsTable ();
3169 return ResolveOperatorPredefined (ec, pointer_operators, false, null);
3173 // Build-in operators method overloading
3175 protected virtual Expression ResolveOperatorPredefined (ResolveContext ec, PredefinedOperator [] operators, bool primitives_only, Type enum_type)
3177 PredefinedOperator best_operator = null;
3179 Type r = right.Type;
3180 Operator oper_mask = oper & ~Operator.ValuesOnlyMask;
3182 foreach (PredefinedOperator po in operators) {
3183 if ((po.OperatorsMask & oper_mask) == 0)
3186 if (primitives_only) {
3187 if (!po.IsPrimitiveApplicable (l, r))
3190 if (!po.IsApplicable (ec, left, right))
3194 if (best_operator == null) {
3196 if (primitives_only)
3202 best_operator = po.ResolveBetterOperator (ec, best_operator);
3204 if (best_operator == null) {
3205 ec.Report.Error (34, loc, "Operator `{0}' is ambiguous on operands of type `{1}' and `{2}'",
3206 OperName (oper), left.GetSignatureForError (), right.GetSignatureForError ());
3213 if (best_operator == null)
3216 Expression expr = best_operator.ConvertResult (ec, this);
3217 if (enum_type == null)
3221 // HACK: required by enum_conversion
3223 expr.Type = enum_type;
3224 return EmptyCast.Create (expr, enum_type);
3228 // Performs user-operator overloading
3230 protected virtual Expression ResolveUserOperator (ResolveContext ec, Type l, Type r)
3233 if (oper == Operator.LogicalAnd)
3234 user_oper = Operator.BitwiseAnd;
3235 else if (oper == Operator.LogicalOr)
3236 user_oper = Operator.BitwiseOr;
3240 string op = GetOperatorMetadataName (user_oper);
3242 MethodGroupExpr left_operators = MemberLookup (ec.Compiler, ec.CurrentType, l, op, MemberTypes.Method, AllBindingFlags, loc) as MethodGroupExpr;
3243 MethodGroupExpr right_operators = null;
3245 if (!TypeManager.IsEqual (r, l)) {
3246 right_operators = MemberLookup (ec.Compiler, ec.CurrentType, r, op, MemberTypes.Method, AllBindingFlags, loc) as MethodGroupExpr;
3247 if (right_operators == null && left_operators == null)
3249 } else if (left_operators == null) {
3253 Arguments args = new Arguments (2);
3254 Argument larg = new Argument (left);
3256 Argument rarg = new Argument (right);
3259 MethodGroupExpr union;
3262 // User-defined operator implementations always take precedence
3263 // over predefined operator implementations
3265 if (left_operators != null && right_operators != null) {
3266 if (IsPredefinedUserOperator (l, user_oper)) {
3267 union = right_operators.OverloadResolve (ec, ref args, true, loc);
3269 union = left_operators;
3270 } else if (IsPredefinedUserOperator (r, user_oper)) {
3271 union = left_operators.OverloadResolve (ec, ref args, true, loc);
3273 union = right_operators;
3275 union = MethodGroupExpr.MakeUnionSet (left_operators, right_operators, loc);
3277 } else if (left_operators != null) {
3278 union = left_operators;
3280 union = right_operators;
3283 union = union.OverloadResolve (ec, ref args, true, loc);
3287 Expression oper_expr;
3289 // TODO: CreateExpressionTree is allocated every time
3290 if (user_oper != oper) {
3291 oper_expr = new ConditionalLogicalOperator (union, args, CreateExpressionTree,
3292 oper == Operator.LogicalAnd, loc).Resolve (ec);
3294 oper_expr = new UserOperatorCall (union, args, CreateExpressionTree, loc);
3297 // This is used to check if a test 'x == null' can be optimized to a reference equals,
3298 // and not invoke user operator
3300 if ((oper & Operator.EqualityMask) != 0) {
3301 if ((left is NullLiteral && IsBuildInEqualityOperator (r)) ||
3302 (right is NullLiteral && IsBuildInEqualityOperator (l))) {
3303 type = TypeManager.bool_type;
3304 if (left is NullLiteral || right is NullLiteral)
3305 oper_expr = ReducedExpression.Create (this, oper_expr).Resolve (ec);
3306 } else if (l != r) {
3307 MethodInfo mi = (MethodInfo) union;
3310 // Two System.Delegate(s) are never equal
3312 if (mi.DeclaringType == TypeManager.multicast_delegate_type)
3323 public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
3328 private void CheckUselessComparison (ResolveContext ec, Constant c, Type type)
3330 if (c == null || !IsTypeIntegral (type)
3331 || c is StringConstant
3332 || c is BoolConstant
3333 || c is FloatConstant
3334 || c is DoubleConstant
3335 || c is DecimalConstant
3341 if (c is ULongConstant) {
3342 ulong uvalue = ((ULongConstant) c).Value;
3343 if (uvalue > long.MaxValue) {
3344 if (type == TypeManager.byte_type ||
3345 type == TypeManager.sbyte_type ||
3346 type == TypeManager.short_type ||
3347 type == TypeManager.ushort_type ||
3348 type == TypeManager.int32_type ||
3349 type == TypeManager.uint32_type ||
3350 type == TypeManager.int64_type ||
3351 type == TypeManager.char_type)
3352 WarnUselessComparison (ec, type);
3355 value = (long) uvalue;
3357 else if (c is ByteConstant)
3358 value = ((ByteConstant) c).Value;
3359 else if (c is SByteConstant)
3360 value = ((SByteConstant) c).Value;
3361 else if (c is ShortConstant)
3362 value = ((ShortConstant) c).Value;
3363 else if (c is UShortConstant)
3364 value = ((UShortConstant) c).Value;
3365 else if (c is IntConstant)
3366 value = ((IntConstant) c).Value;
3367 else if (c is UIntConstant)
3368 value = ((UIntConstant) c).Value;
3369 else if (c is LongConstant)
3370 value = ((LongConstant) c).Value;
3371 else if (c is CharConstant)
3372 value = ((CharConstant)c).Value;
3377 if (IsValueOutOfRange (value, type))
3378 WarnUselessComparison (ec, type);
3381 static bool IsValueOutOfRange (long value, Type type)
3383 if (IsTypeUnsigned (type) && value < 0)
3385 return type == TypeManager.sbyte_type && (value >= 0x80 || value < -0x80) ||
3386 type == TypeManager.byte_type && value >= 0x100 ||
3387 type == TypeManager.short_type && (value >= 0x8000 || value < -0x8000) ||
3388 type == TypeManager.ushort_type && value >= 0x10000 ||
3389 type == TypeManager.int32_type && (value >= 0x80000000 || value < -0x80000000) ||
3390 type == TypeManager.uint32_type && value >= 0x100000000;
3393 static bool IsBuildInEqualityOperator (Type t)
3395 return t == TypeManager.object_type || t == TypeManager.string_type ||
3396 t == TypeManager.delegate_type || TypeManager.IsDelegateType (t);
3399 static bool IsPredefinedUserOperator (Type t, Operator op)
3402 // Some predefined types have user operators
3404 return (op & Operator.EqualityMask) != 0 && (t == TypeManager.string_type || t == TypeManager.decimal_type);
3407 private static bool IsTypeIntegral (Type type)
3409 return type == TypeManager.uint64_type ||
3410 type == TypeManager.int64_type ||
3411 type == TypeManager.uint32_type ||
3412 type == TypeManager.int32_type ||
3413 type == TypeManager.ushort_type ||
3414 type == TypeManager.short_type ||
3415 type == TypeManager.sbyte_type ||
3416 type == TypeManager.byte_type ||
3417 type == TypeManager.char_type;
3420 private static bool IsTypeUnsigned (Type type)
3422 return type == TypeManager.uint64_type ||
3423 type == TypeManager.uint32_type ||
3424 type == TypeManager.ushort_type ||
3425 type == TypeManager.byte_type ||
3426 type == TypeManager.char_type;
3429 private void WarnUselessComparison (ResolveContext ec, Type type)
3431 ec.Report.Warning (652, 2, loc, "A comparison between a constant and a variable is useless. The constant is out of the range of the variable type `{0}'",
3432 TypeManager.CSharpName (type));
3436 /// EmitBranchable is called from Statement.EmitBoolExpression in the
3437 /// context of a conditional bool expression. This function will return
3438 /// false if it is was possible to use EmitBranchable, or true if it was.
3440 /// The expression's code is generated, and we will generate a branch to `target'
3441 /// if the resulting expression value is equal to isTrue
3443 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
3445 ILGenerator ig = ec.ig;
3448 // This is more complicated than it looks, but its just to avoid
3449 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
3450 // but on top of that we want for == and != to use a special path
3451 // if we are comparing against null
3453 if ((oper == Operator.Equality || oper == Operator.Inequality) && (left is Constant || right is Constant)) {
3454 bool my_on_true = oper == Operator.Inequality ? on_true : !on_true;
3457 // put the constant on the rhs, for simplicity
3459 if (left is Constant) {
3460 Expression swap = right;
3465 if (((Constant) right).IsZeroInteger) {
3466 left.EmitBranchable (ec, target, my_on_true);
3469 if (right.Type == TypeManager.bool_type) {
3470 // right is a boolean, and it's not 'false' => it is 'true'
3471 left.EmitBranchable (ec, target, !my_on_true);
3475 } else if (oper == Operator.LogicalAnd) {
3478 Label tests_end = ig.DefineLabel ();
3480 left.EmitBranchable (ec, tests_end, false);
3481 right.EmitBranchable (ec, target, true);
3482 ig.MarkLabel (tests_end);
3485 // This optimizes code like this
3486 // if (true && i > 4)
3488 if (!(left is Constant))
3489 left.EmitBranchable (ec, target, false);
3491 if (!(right is Constant))
3492 right.EmitBranchable (ec, target, false);
3497 } else if (oper == Operator.LogicalOr){
3499 left.EmitBranchable (ec, target, true);
3500 right.EmitBranchable (ec, target, true);
3503 Label tests_end = ig.DefineLabel ();
3504 left.EmitBranchable (ec, tests_end, true);
3505 right.EmitBranchable (ec, target, false);
3506 ig.MarkLabel (tests_end);
3511 } else if (!(oper == Operator.LessThan || oper == Operator.GreaterThan ||
3512 oper == Operator.LessThanOrEqual || oper == Operator.GreaterThanOrEqual ||
3513 oper == Operator.Equality || oper == Operator.Inequality)) {
3514 base.EmitBranchable (ec, target, on_true);
3522 bool is_float = IsFloat (t);
3523 bool is_unsigned = is_float || IsUnsigned (t);
3526 case Operator.Equality:
3528 ig.Emit (OpCodes.Beq, target);
3530 ig.Emit (OpCodes.Bne_Un, target);
3533 case Operator.Inequality:
3535 ig.Emit (OpCodes.Bne_Un, target);
3537 ig.Emit (OpCodes.Beq, target);
3540 case Operator.LessThan:
3542 if (is_unsigned && !is_float)
3543 ig.Emit (OpCodes.Blt_Un, target);
3545 ig.Emit (OpCodes.Blt, target);
3548 ig.Emit (OpCodes.Bge_Un, target);
3550 ig.Emit (OpCodes.Bge, target);
3553 case Operator.GreaterThan:
3555 if (is_unsigned && !is_float)
3556 ig.Emit (OpCodes.Bgt_Un, target);
3558 ig.Emit (OpCodes.Bgt, target);
3561 ig.Emit (OpCodes.Ble_Un, target);
3563 ig.Emit (OpCodes.Ble, target);
3566 case Operator.LessThanOrEqual:
3568 if (is_unsigned && !is_float)
3569 ig.Emit (OpCodes.Ble_Un, target);
3571 ig.Emit (OpCodes.Ble, target);
3574 ig.Emit (OpCodes.Bgt_Un, target);
3576 ig.Emit (OpCodes.Bgt, target);
3580 case Operator.GreaterThanOrEqual:
3582 if (is_unsigned && !is_float)
3583 ig.Emit (OpCodes.Bge_Un, target);
3585 ig.Emit (OpCodes.Bge, target);
3588 ig.Emit (OpCodes.Blt_Un, target);
3590 ig.Emit (OpCodes.Blt, target);
3593 throw new InternalErrorException (oper.ToString ());
3597 public override void Emit (EmitContext ec)
3599 EmitOperator (ec, left.Type);
3602 protected virtual void EmitOperator (EmitContext ec, Type l)
3604 ILGenerator ig = ec.ig;
3607 // Handle short-circuit operators differently
3610 if ((oper & Operator.LogicalMask) != 0) {
3611 Label load_result = ig.DefineLabel ();
3612 Label end = ig.DefineLabel ();
3614 bool is_or = oper == Operator.LogicalOr;
3615 left.EmitBranchable (ec, load_result, is_or);
3617 ig.Emit (OpCodes.Br_S, end);
3619 ig.MarkLabel (load_result);
3620 ig.Emit (is_or ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
3628 // Optimize zero-based operations
3630 // TODO: Implement more optimizations, but it should probably go to PredefinedOperators
3632 if ((oper & Operator.ShiftMask) != 0 || oper == Operator.Addition || oper == Operator.Subtraction) {
3633 Constant rc = right as Constant;
3634 if (rc != null && rc.IsDefaultValue) {
3640 EmitOperatorOpcode (ec, oper, l);
3643 // Nullable enum could require underlying type cast and we cannot simply wrap binary
3644 // expression because that would wrap lifted binary operation
3646 if (enum_conversion != null)
3647 enum_conversion.Emit (ec);
3650 public override void EmitSideEffect (EmitContext ec)
3652 if ((oper & Operator.LogicalMask) != 0 ||
3653 (ec.HasSet (EmitContext.Options.CheckedScope) && (oper == Operator.Multiply || oper == Operator.Addition || oper == Operator.Subtraction))) {
3654 base.EmitSideEffect (ec);
3656 left.EmitSideEffect (ec);
3657 right.EmitSideEffect (ec);
3661 protected override void CloneTo (CloneContext clonectx, Expression t)
3663 Binary target = (Binary) t;
3665 target.left = left.Clone (clonectx);
3666 target.right = right.Clone (clonectx);
3669 public Expression CreateCallSiteBinder (ResolveContext ec, Arguments args)
3671 Arguments binder_args = new Arguments (4);
3673 MemberAccess sle = new MemberAccess (new MemberAccess (
3674 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Linq", loc), "Expressions", loc);
3676 MemberAccess binder = DynamicExpressionStatement.GetBinderNamespace (loc);
3678 binder_args.Add (new Argument (new MemberAccess (new MemberAccess (sle, "ExpressionType", loc), GetOperatorExpressionTypeName (), loc)));
3679 binder_args.Add (new Argument (new BoolLiteral (ec.HasSet (ResolveContext.Options.CheckedScope), loc)));
3681 bool member_access = left is DynamicMemberBinder || right is DynamicMemberBinder;
3682 binder_args.Add (new Argument (new BoolLiteral (member_access, loc)));
3683 binder_args.Add (new Argument (new ImplicitlyTypedArrayCreation ("[]", args.CreateDynamicBinderArguments (), loc)));
3685 return new New (new MemberAccess (binder, "CSharpBinaryOperationBinder", loc), binder_args, loc);
3688 public override Expression CreateExpressionTree (ResolveContext ec)
3690 return CreateExpressionTree (ec, null);
3693 Expression CreateExpressionTree (ResolveContext ec, MethodGroupExpr method)
3696 bool lift_arg = false;
3699 case Operator.Addition:
3700 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
3701 method_name = "AddChecked";
3703 method_name = "Add";
3705 case Operator.BitwiseAnd:
3706 method_name = "And";
3708 case Operator.BitwiseOr:
3711 case Operator.Division:
3712 method_name = "Divide";
3714 case Operator.Equality:
3715 method_name = "Equal";
3718 case Operator.ExclusiveOr:
3719 method_name = "ExclusiveOr";
3721 case Operator.GreaterThan:
3722 method_name = "GreaterThan";
3725 case Operator.GreaterThanOrEqual:
3726 method_name = "GreaterThanOrEqual";
3729 case Operator.Inequality:
3730 method_name = "NotEqual";
3733 case Operator.LeftShift:
3734 method_name = "LeftShift";
3736 case Operator.LessThan:
3737 method_name = "LessThan";
3740 case Operator.LessThanOrEqual:
3741 method_name = "LessThanOrEqual";
3744 case Operator.LogicalAnd:
3745 method_name = "AndAlso";
3747 case Operator.LogicalOr:
3748 method_name = "OrElse";
3750 case Operator.Modulus:
3751 method_name = "Modulo";
3753 case Operator.Multiply:
3754 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
3755 method_name = "MultiplyChecked";
3757 method_name = "Multiply";
3759 case Operator.RightShift:
3760 method_name = "RightShift";
3762 case Operator.Subtraction:
3763 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
3764 method_name = "SubtractChecked";
3766 method_name = "Subtract";
3770 throw new InternalErrorException ("Unknown expression tree binary operator " + oper);
3773 Arguments args = new Arguments (2);
3774 args.Add (new Argument (left.CreateExpressionTree (ec)));
3775 args.Add (new Argument (right.CreateExpressionTree (ec)));
3776 if (method != null) {
3778 args.Add (new Argument (new BoolConstant (false, loc)));
3780 args.Add (new Argument (method.CreateExpressionTree (ec)));
3783 return CreateExpressionFactoryCall (ec, method_name, args);
3788 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3789 // b, c, d... may be strings or objects.
3791 public class StringConcat : Expression {
3792 Arguments arguments;
3794 public StringConcat (Location loc, Expression left, Expression right)
3797 type = TypeManager.string_type;
3798 eclass = ExprClass.Value;
3800 arguments = new Arguments (2);
3805 public override Expression CreateExpressionTree (ResolveContext ec)
3807 Argument arg = arguments [0];
3808 return CreateExpressionAddCall (ec, arg, arg.CreateExpressionTree (ec), 1);
3812 // Creates nested calls tree from an array of arguments used for IL emit
3814 Expression CreateExpressionAddCall (ResolveContext ec, Argument left, Expression left_etree, int pos)
3816 Arguments concat_args = new Arguments (2);
3817 Arguments add_args = new Arguments (3);
3819 concat_args.Add (left);
3820 add_args.Add (new Argument (left_etree));
3822 concat_args.Add (arguments [pos]);
3823 add_args.Add (new Argument (arguments [pos].CreateExpressionTree (ec)));
3825 MethodGroupExpr method = CreateConcatMemberExpression ().Resolve (ec) as MethodGroupExpr;
3829 method = method.OverloadResolve (ec, ref concat_args, false, loc);
3833 add_args.Add (new Argument (method.CreateExpressionTree (ec)));
3835 Expression expr = CreateExpressionFactoryCall (ec, "Add", add_args);
3836 if (++pos == arguments.Count)
3839 left = new Argument (new EmptyExpression (((MethodInfo)method).ReturnType));
3840 return CreateExpressionAddCall (ec, left, expr, pos);
3843 public override Expression DoResolve (ResolveContext ec)
3848 public void Append (Expression operand)
3853 StringConstant sc = operand as StringConstant;
3855 if (arguments.Count != 0) {
3856 Argument last_argument = arguments [arguments.Count - 1];
3857 StringConstant last_expr_constant = last_argument.Expr as StringConstant;
3858 if (last_expr_constant != null) {
3859 last_argument.Expr = new StringConstant (
3860 last_expr_constant.Value + sc.Value, sc.Location);
3866 // Multiple (3+) concatenation are resolved as multiple StringConcat instances
3868 StringConcat concat_oper = operand as StringConcat;
3869 if (concat_oper != null) {
3870 arguments.AddRange (concat_oper.arguments);
3875 arguments.Add (new Argument (operand));
3878 Expression CreateConcatMemberExpression ()
3880 return new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "String", loc), "Concat", loc);
3883 public override void Emit (EmitContext ec)
3885 Expression concat = new Invocation (CreateConcatMemberExpression (), arguments, true);
3886 concat = concat.Resolve (new ResolveContext (ec.MemberContext));
3892 public override SLE.Expression MakeExpression (BuilderContext ctx)
3894 if (arguments.Count != 2)
3895 throw new NotImplementedException ("arguments.Count != 2");
3897 var concat = TypeManager.string_type.GetMethod ("Concat", new[] { typeof (object), typeof (object) });
3898 return SLE.Expression.Add (arguments[0].Expr.MakeExpression (ctx), arguments[1].Expr.MakeExpression (ctx), concat);
3902 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
3904 arguments.MutateHoistedGenericType (storey);
3909 // User-defined conditional logical operator
3911 public class ConditionalLogicalOperator : UserOperatorCall {
3912 readonly bool is_and;
3915 public ConditionalLogicalOperator (MethodGroupExpr oper_method, Arguments arguments,
3916 ExpressionTreeExpression expr_tree, bool is_and, Location loc)
3917 : base (oper_method, arguments, expr_tree, loc)
3919 this.is_and = is_and;
3922 public override Expression DoResolve (ResolveContext ec)
3924 MethodInfo method = (MethodInfo)mg;
3925 type = TypeManager.TypeToCoreType (method.ReturnType);
3926 AParametersCollection pd = TypeManager.GetParameterData (method);
3927 if (!TypeManager.IsEqual (type, type) || !TypeManager.IsEqual (type, pd.Types [0]) || !TypeManager.IsEqual (type, pd.Types [1])) {
3928 ec.Report.Error (217, loc,
3929 "A user-defined operator `{0}' must have parameters and return values of the same type in order to be applicable as a short circuit operator",
3930 TypeManager.CSharpSignature (method));
3934 Expression left_dup = new EmptyExpression (type);
3935 Expression op_true = GetOperatorTrue (ec, left_dup, loc);
3936 Expression op_false = GetOperatorFalse (ec, left_dup, loc);
3937 if (op_true == null || op_false == null) {
3938 ec.Report.Error (218, loc,
3939 "The type `{0}' must have operator `true' and operator `false' defined when `{1}' is used as a short circuit operator",
3940 TypeManager.CSharpName (type), TypeManager.CSharpSignature (method));
3944 oper = is_and ? op_false : op_true;
3945 eclass = ExprClass.Value;
3949 public override void Emit (EmitContext ec)
3951 ILGenerator ig = ec.ig;
3952 Label end_target = ig.DefineLabel ();
3955 // Emit and duplicate left argument
3957 arguments [0].Expr.Emit (ec);
3958 ig.Emit (OpCodes.Dup);
3959 arguments.RemoveAt (0);
3961 oper.EmitBranchable (ec, end_target, true);
3963 ig.MarkLabel (end_target);
3967 public class PointerArithmetic : Expression {
3968 Expression left, right;
3972 // We assume that `l' is always a pointer
3974 public PointerArithmetic (Binary.Operator op, Expression l, Expression r, Type t, Location loc)
3983 public override Expression CreateExpressionTree (ResolveContext ec)
3985 Error_PointerInsideExpressionTree (ec);
3989 public override Expression DoResolve (ResolveContext ec)
3991 eclass = ExprClass.Variable;
3993 if (left.Type == TypeManager.void_ptr_type) {
3994 ec.Report.Error (242, loc, "The operation in question is undefined on void pointers");
4001 public override void Emit (EmitContext ec)
4003 Type op_type = left.Type;
4004 ILGenerator ig = ec.ig;
4006 // It must be either array or fixed buffer
4008 if (TypeManager.HasElementType (op_type)) {
4009 element = TypeManager.GetElementType (op_type);
4011 FieldExpr fe = left as FieldExpr;
4013 element = AttributeTester.GetFixedBuffer (fe.FieldInfo).ElementType;
4018 int size = GetTypeSize (element);
4019 Type rtype = right.Type;
4021 if ((op & Binary.Operator.SubtractionMask) != 0 && rtype.IsPointer){
4023 // handle (pointer - pointer)
4027 ig.Emit (OpCodes.Sub);
4031 ig.Emit (OpCodes.Sizeof, element);
4033 IntLiteral.EmitInt (ig, size);
4034 ig.Emit (OpCodes.Div);
4036 ig.Emit (OpCodes.Conv_I8);
4039 // handle + and - on (pointer op int)
4041 Constant left_const = left as Constant;
4042 if (left_const != null) {
4044 // Optimize ((T*)null) pointer operations
4046 if (left_const.IsDefaultValue) {
4047 left = EmptyExpression.Null;
4055 Constant right_const = right as Constant;
4056 if (right_const != null) {
4058 // Optimize 0-based arithmetic
4060 if (right_const.IsDefaultValue)
4064 // TODO: Should be the checks resolve context sensitive?
4065 ResolveContext rc = new ResolveContext (ec.MemberContext);
4066 right = ConstantFold.BinaryFold (rc, Binary.Operator.Multiply, new IntConstant (size, right.Location), right_const, loc);
4070 ig.Emit (OpCodes.Sizeof, element);
4071 right = EmptyExpression.Null;
4076 if (rtype == TypeManager.sbyte_type || rtype == TypeManager.byte_type ||
4077 rtype == TypeManager.short_type || rtype == TypeManager.ushort_type) {
4078 ig.Emit (OpCodes.Conv_I);
4079 } else if (rtype == TypeManager.uint32_type) {
4080 ig.Emit (OpCodes.Conv_U);
4083 if (right_const == null && size != 1){
4085 ig.Emit (OpCodes.Sizeof, element);
4087 IntLiteral.EmitInt (ig, size);
4088 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
4089 ig.Emit (OpCodes.Conv_I8);
4091 Binary.EmitOperatorOpcode (ec, Binary.Operator.Multiply, rtype);
4094 if (left_const == null) {
4095 if (rtype == TypeManager.int64_type)
4096 ig.Emit (OpCodes.Conv_I);
4097 else if (rtype == TypeManager.uint64_type)
4098 ig.Emit (OpCodes.Conv_U);
4100 Binary.EmitOperatorOpcode (ec, op, op_type);
4107 // A boolean-expression is an expression that yields a result
4110 public class BooleanExpression : Expression
4114 public BooleanExpression (Expression expr)
4117 this.loc = expr.Location;
4120 protected override void CloneTo (CloneContext clonectx, Expression t)
4122 BooleanExpression target = (BooleanExpression) t;
4123 target.expr = expr.Clone (clonectx);
4126 public override Expression CreateExpressionTree (ResolveContext ec)
4128 // TODO: We should emit IsTrue (v4) instead of direct user operator
4129 // call but that would break csc compatibility
4130 throw new NotSupportedException ();
4133 public override Expression DoResolve (ResolveContext ec)
4135 // A boolean-expression is required to be of a type
4136 // that can be implicitly converted to bool or of
4137 // a type that implements operator true
4139 expr = expr.Resolve (ec);
4143 Assign ass = expr as Assign;
4144 if (ass != null && ass.Source is Constant) {
4145 ec.Report.Warning (665, 3, expr.Location,
4146 "Assignment in conditional expression is always constant. Did you mean to use `==' instead ?");
4149 if (expr.Type == TypeManager.bool_type)
4152 if (TypeManager.IsDynamicType (expr.Type)) {
4153 Arguments args = new Arguments (1);
4154 args.Add (new Argument (expr));
4155 return new DynamicUnaryConversion ("IsTrue", args, loc).Resolve (ec);
4158 type = TypeManager.bool_type;
4159 Expression converted = Convert.ImplicitConversion (ec, expr, type, loc);
4160 if (converted != null)
4164 // If no implicit conversion to bool exists, try using `operator true'
4166 converted = GetOperatorTrue (ec, expr, loc);
4167 if (converted == null) {
4168 expr.Error_ValueCannotBeConverted (ec, loc, type, false);
4175 public override void Emit (EmitContext ec)
4177 throw new InternalErrorException ("Should not be reached");
4182 /// Implements the ternary conditional operator (?:)
4184 public class Conditional : Expression {
4185 Expression expr, true_expr, false_expr;
4187 public Conditional (BooleanExpression expr, Expression true_expr, Expression false_expr)
4190 this.true_expr = true_expr;
4191 this.false_expr = false_expr;
4192 this.loc = expr.Location;
4195 public Expression Expr {
4201 public Expression TrueExpr {
4207 public Expression FalseExpr {
4213 public override Expression CreateExpressionTree (ResolveContext ec)
4215 Arguments args = new Arguments (3);
4216 args.Add (new Argument (expr.CreateExpressionTree (ec)));
4217 args.Add (new Argument (true_expr.CreateExpressionTree (ec)));
4218 args.Add (new Argument (false_expr.CreateExpressionTree (ec)));
4219 return CreateExpressionFactoryCall (ec, "Condition", args);
4222 public override Expression DoResolve (ResolveContext ec)
4224 expr = expr.Resolve (ec);
4225 true_expr = true_expr.Resolve (ec);
4226 false_expr = false_expr.Resolve (ec);
4228 if (true_expr == null || false_expr == null || expr == null)
4231 eclass = ExprClass.Value;
4232 Type true_type = true_expr.Type;
4233 Type false_type = false_expr.Type;
4237 // First, if an implicit conversion exists from true_expr
4238 // to false_expr, then the result type is of type false_expr.Type
4240 if (!TypeManager.IsEqual (true_type, false_type)) {
4241 Expression conv = Convert.ImplicitConversion (ec, true_expr, false_type, loc);
4244 // Check if both can convert implicitl to each other's type
4246 if (Convert.ImplicitConversion (ec, false_expr, true_type, loc) != null) {
4247 ec.Report.Error (172, loc,
4248 "Can not compute type of conditional expression " +
4249 "as `" + TypeManager.CSharpName (true_expr.Type) +
4250 "' and `" + TypeManager.CSharpName (false_expr.Type) +
4251 "' convert implicitly to each other");
4256 } else if ((conv = Convert.ImplicitConversion (ec, false_expr, true_type, loc)) != null) {
4259 ec.Report.Error (173, loc,
4260 "Type of conditional expression cannot be determined because there is no implicit conversion between `{0}' and `{1}'",
4261 true_expr.GetSignatureForError (), false_expr.GetSignatureForError ());
4266 // Dead code optimalization
4267 Constant c = expr as Constant;
4269 bool is_false = c.IsDefaultValue;
4270 ec.Report.Warning (429, 4, is_false ? true_expr.Location : false_expr.Location, "Unreachable expression code detected");
4271 return ReducedExpression.Create (is_false ? false_expr : true_expr, this).Resolve (ec);
4277 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
4279 expr.MutateHoistedGenericType (storey);
4280 true_expr.MutateHoistedGenericType (storey);
4281 false_expr.MutateHoistedGenericType (storey);
4282 type = storey.MutateType (type);
4285 public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
4290 public override void Emit (EmitContext ec)
4292 ILGenerator ig = ec.ig;
4293 Label false_target = ig.DefineLabel ();
4294 Label end_target = ig.DefineLabel ();
4296 expr.EmitBranchable (ec, false_target, false);
4297 true_expr.Emit (ec);
4299 if (type.IsInterface) {
4300 LocalBuilder temp = ec.GetTemporaryLocal (type);
4301 ig.Emit (OpCodes.Stloc, temp);
4302 ig.Emit (OpCodes.Ldloc, temp);
4303 ec.FreeTemporaryLocal (temp, type);
4306 ig.Emit (OpCodes.Br, end_target);
4307 ig.MarkLabel (false_target);
4308 false_expr.Emit (ec);
4309 ig.MarkLabel (end_target);
4312 protected override void CloneTo (CloneContext clonectx, Expression t)
4314 Conditional target = (Conditional) t;
4316 target.expr = expr.Clone (clonectx);
4317 target.true_expr = true_expr.Clone (clonectx);
4318 target.false_expr = false_expr.Clone (clonectx);
4322 public abstract class VariableReference : Expression, IAssignMethod, IMemoryLocation, IVariableReference {
4323 LocalTemporary temp;
4326 public abstract HoistedVariable GetHoistedVariable (AnonymousExpression ae);
4327 public abstract bool IsFixed { get; }
4328 public abstract bool IsRef { get; }
4329 public abstract string Name { get; }
4330 public abstract void SetHasAddressTaken ();
4333 // Variable IL data, it has to be protected to encapsulate hoisted variables
4335 protected abstract ILocalVariable Variable { get; }
4338 // Variable flow-analysis data
4340 public abstract VariableInfo VariableInfo { get; }
4343 public void AddressOf (EmitContext ec, AddressOp mode)
4345 HoistedVariable hv = GetHoistedVariable (ec);
4347 hv.AddressOf (ec, mode);
4351 Variable.EmitAddressOf (ec);
4354 public HoistedVariable GetHoistedVariable (ResolveContext rc)
4356 return GetHoistedVariable (rc.CurrentAnonymousMethod);
4359 public HoistedVariable GetHoistedVariable (EmitContext ec)
4361 return GetHoistedVariable (ec.CurrentAnonymousMethod);
4364 public override void Emit (EmitContext ec)
4369 public override void EmitSideEffect (EmitContext ec)
4375 // This method is used by parameters that are references, that are
4376 // being passed as references: we only want to pass the pointer (that
4377 // is already stored in the parameter, not the address of the pointer,
4378 // and not the value of the variable).
4380 public void EmitLoad (EmitContext ec)
4385 public void Emit (EmitContext ec, bool leave_copy)
4387 Report.Debug (64, "VARIABLE EMIT", this, Variable, type, IsRef, loc);
4389 HoistedVariable hv = GetHoistedVariable (ec);
4391 hv.Emit (ec, leave_copy);
4399 // If we are a reference, we loaded on the stack a pointer
4400 // Now lets load the real value
4402 LoadFromPtr (ec.ig, type);
4406 ec.ig.Emit (OpCodes.Dup);
4409 temp = new LocalTemporary (Type);
4415 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy,
4416 bool prepare_for_load)
4418 HoistedVariable hv = GetHoistedVariable (ec);
4420 hv.EmitAssign (ec, source, leave_copy, prepare_for_load);
4424 New n_source = source as New;
4425 if (n_source != null) {
4426 if (!n_source.Emit (ec, this)) {
4439 ec.ig.Emit (OpCodes.Dup);
4441 temp = new LocalTemporary (Type);
4447 StoreFromPtr (ec.ig, type);
4449 Variable.EmitAssign (ec);
4457 public bool IsHoisted {
4458 get { return GetHoistedVariable ((AnonymousExpression) null) != null; }
4461 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
4463 type = storey.MutateType (type);
4470 public class LocalVariableReference : VariableReference {
4471 readonly string name;
4473 public LocalInfo local_info;
4475 bool resolved; // TODO: merge with eclass
4477 public LocalVariableReference (Block block, string name, Location l)
4485 // Setting `is_readonly' to false will allow you to create a writable
4486 // reference to a read-only variable. This is used by foreach and using.
4488 public LocalVariableReference (Block block, string name, Location l,
4489 LocalInfo local_info, bool is_readonly)
4490 : this (block, name, l)
4492 this.local_info = local_info;
4493 this.is_readonly = is_readonly;
4496 public override VariableInfo VariableInfo {
4497 get { return local_info.VariableInfo; }
4500 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
4502 return local_info.HoistedVariableReference;
4506 // A local variable is always fixed
4508 public override bool IsFixed {
4509 get { return true; }
4512 public override bool IsRef {
4513 get { return false; }
4516 public bool IsReadOnly {
4517 get { return is_readonly; }
4520 public override string Name {
4521 get { return name; }
4524 public bool VerifyAssigned (ResolveContext ec)
4526 VariableInfo variable_info = local_info.VariableInfo;
4527 return variable_info == null || variable_info.IsAssigned (ec, loc);
4530 void ResolveLocalInfo ()
4532 if (local_info == null) {
4533 local_info = Block.GetLocalInfo (Name);
4534 type = local_info.VariableType;
4535 is_readonly = local_info.ReadOnly;
4539 public override void SetHasAddressTaken ()
4541 local_info.AddressTaken = true;
4544 public override Expression CreateExpressionTree (ResolveContext ec)
4546 HoistedVariable hv = GetHoistedVariable (ec);
4548 return hv.CreateExpressionTree (ec);
4550 Arguments arg = new Arguments (1);
4551 arg.Add (new Argument (this));
4552 return CreateExpressionFactoryCall (ec, "Constant", arg);
4555 Expression DoResolveBase (ResolveContext ec)
4557 type = local_info.VariableType;
4559 Expression e = Block.GetConstantExpression (Name);
4561 return e.Resolve (ec);
4563 VerifyAssigned (ec);
4566 // If we are referencing a variable from the external block
4567 // flag it for capturing
4569 if (ec.MustCaptureVariable (local_info)) {
4570 if (local_info.AddressTaken)
4571 AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, this, loc);
4573 if (ec.IsVariableCapturingRequired) {
4574 AnonymousMethodStorey storey = local_info.Block.Explicit.CreateAnonymousMethodStorey (ec);
4575 storey.CaptureLocalVariable (ec, local_info);
4579 resolved |= ec.DoFlowAnalysis;
4580 eclass = ExprClass.Variable;
4584 public override Expression DoResolve (ResolveContext ec)
4589 ResolveLocalInfo ();
4590 local_info.Used = true;
4592 if (type == null && local_info.Type is VarExpr) {
4593 local_info.VariableType = TypeManager.object_type;
4594 Error_VariableIsUsedBeforeItIsDeclared (ec.Report, Name);
4598 return DoResolveBase (ec);
4601 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
4603 ResolveLocalInfo ();
4606 if (right_side == EmptyExpression.OutAccess)
4607 local_info.Used = true;
4609 // Infer implicitly typed local variable
4611 VarExpr ve = local_info.Type as VarExpr;
4613 if (!ve.InferType (ec, right_side))
4615 type = local_info.VariableType = ve.Type;
4622 if (right_side == EmptyExpression.OutAccess) {
4623 code = 1657; msg = "Cannot pass `{0}' as a ref or out argument because it is a `{1}'";
4624 } else if (right_side == EmptyExpression.LValueMemberAccess) {
4625 code = 1654; msg = "Cannot assign to members of `{0}' because it is a `{1}'";
4626 } else if (right_side == EmptyExpression.LValueMemberOutAccess) {
4627 code = 1655; msg = "Cannot pass members of `{0}' as ref or out arguments because it is a `{1}'";
4628 } else if (right_side == EmptyExpression.UnaryAddress) {
4629 code = 459; msg = "Cannot take the address of {1} `{0}'";
4631 code = 1656; msg = "Cannot assign to `{0}' because it is a `{1}'";
4633 ec.Report.Error (code, loc, msg, Name, local_info.GetReadOnlyContext ());
4634 } else if (VariableInfo != null) {
4635 VariableInfo.SetAssigned (ec);
4638 return DoResolveBase (ec);
4641 public override int GetHashCode ()
4643 return Name.GetHashCode ();
4646 public override bool Equals (object obj)
4648 LocalVariableReference lvr = obj as LocalVariableReference;
4652 return Name == lvr.Name && Block == lvr.Block;
4655 protected override ILocalVariable Variable {
4656 get { return local_info; }
4659 public override string ToString ()
4661 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
4664 protected override void CloneTo (CloneContext clonectx, Expression t)
4666 LocalVariableReference target = (LocalVariableReference) t;
4668 target.Block = clonectx.LookupBlock (Block);
4669 if (local_info != null)
4670 target.local_info = clonectx.LookupVariable (local_info);
4675 /// This represents a reference to a parameter in the intermediate
4678 public class ParameterReference : VariableReference {
4679 readonly ToplevelParameterInfo pi;
4681 public ParameterReference (ToplevelParameterInfo pi, Location loc)
4687 public override bool IsRef {
4688 get { return (pi.Parameter.ModFlags & Parameter.Modifier.ISBYREF) != 0; }
4691 bool HasOutModifier {
4692 get { return pi.Parameter.ModFlags == Parameter.Modifier.OUT; }
4695 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
4697 return pi.Parameter.HoistedVariableReference;
4701 // A ref or out parameter is classified as a moveable variable, even
4702 // if the argument given for the parameter is a fixed variable
4704 public override bool IsFixed {
4705 get { return !IsRef; }
4708 public override string Name {
4709 get { return Parameter.Name; }
4712 public Parameter Parameter {
4713 get { return pi.Parameter; }
4716 public override VariableInfo VariableInfo {
4717 get { return pi.VariableInfo; }
4720 protected override ILocalVariable Variable {
4721 get { return Parameter; }
4724 public bool IsAssigned (ResolveContext ec, Location loc)
4726 // HACK: Variables are not captured in probing mode
4727 if (ec.IsInProbingMode)
4730 if (!ec.DoFlowAnalysis || !HasOutModifier || ec.CurrentBranching.IsAssigned (VariableInfo))
4733 ec.Report.Error (269, loc, "Use of unassigned out parameter `{0}'", Name);
4737 public override void SetHasAddressTaken ()
4739 Parameter.HasAddressTaken = true;
4742 void SetAssigned (ResolveContext ec)
4744 if (HasOutModifier && ec.DoFlowAnalysis)
4745 ec.CurrentBranching.SetAssigned (VariableInfo);
4748 bool DoResolveBase (ResolveContext ec)
4750 type = pi.ParameterType;
4751 eclass = ExprClass.Variable;
4753 AnonymousExpression am = ec.CurrentAnonymousMethod;
4757 Block b = ec.CurrentBlock;
4759 IParameterData[] p = b.Toplevel.Parameters.FixedParameters;
4760 for (int i = 0; i < p.Length; ++i) {
4761 if (p [i] != Parameter)
4765 // Skip closest anonymous method parameters
4767 if (b == ec.CurrentBlock && !am.IsIterator)
4771 ec.Report.Error (1628, loc,
4772 "Parameter `{0}' cannot be used inside `{1}' when using `ref' or `out' modifier",
4773 Name, am.ContainerType);
4781 b = b.Toplevel.Parent;
4784 if (pi.Parameter.HasAddressTaken)
4785 AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, this, loc);
4787 if (ec.IsVariableCapturingRequired) {
4788 AnonymousMethodStorey storey = pi.Block.CreateAnonymousMethodStorey (ec);
4789 storey.CaptureParameter (ec, this);
4795 public override int GetHashCode ()
4797 return Name.GetHashCode ();
4800 public override bool Equals (object obj)
4802 ParameterReference pr = obj as ParameterReference;
4806 return Name == pr.Name;
4809 protected override void CloneTo (CloneContext clonectx, Expression target)
4814 public override Expression CreateExpressionTree (ResolveContext ec)
4816 HoistedVariable hv = GetHoistedVariable (ec);
4818 return hv.CreateExpressionTree (ec);
4820 return Parameter.ExpressionTreeVariableReference ();
4824 // Notice that for ref/out parameters, the type exposed is not the
4825 // same type exposed externally.
4828 // externally we expose "int&"
4829 // here we expose "int".
4831 // We record this in "is_ref". This means that the type system can treat
4832 // the type as it is expected, but when we generate the code, we generate
4833 // the alternate kind of code.
4835 public override Expression DoResolve (ResolveContext ec)
4837 if (!DoResolveBase (ec))
4840 // HACK: Variables are not captured in probing mode
4841 if (ec.IsInProbingMode)
4844 if (HasOutModifier && ec.DoFlowAnalysis &&
4845 (!ec.OmitStructFlowAnalysis || !VariableInfo.TypeInfo.IsStruct) && !IsAssigned (ec, loc))
4851 override public Expression DoResolveLValue (ResolveContext ec, Expression right_side)
4853 if (!DoResolveBase (ec))
4856 // HACK: parameters are not captured when probing is on
4857 if (!ec.IsInProbingMode)
4863 static public void EmitLdArg (ILGenerator ig, int x)
4866 case 0: ig.Emit (OpCodes.Ldarg_0); break;
4867 case 1: ig.Emit (OpCodes.Ldarg_1); break;
4868 case 2: ig.Emit (OpCodes.Ldarg_2); break;
4869 case 3: ig.Emit (OpCodes.Ldarg_3); break;
4871 if (x > byte.MaxValue)
4872 ig.Emit (OpCodes.Ldarg, x);
4874 ig.Emit (OpCodes.Ldarg_S, (byte) x);
4881 /// Invocation of methods or delegates.
4883 public class Invocation : ExpressionStatement
4885 protected Arguments arguments;
4886 protected Expression expr;
4887 protected MethodGroupExpr mg;
4888 bool arguments_resolved;
4891 // arguments is an ArrayList, but we do not want to typecast,
4892 // as it might be null.
4894 public Invocation (Expression expr, Arguments arguments)
4896 SimpleName sn = expr as SimpleName;
4898 this.expr = sn.GetMethodGroup ();
4902 this.arguments = arguments;
4904 loc = expr.Location;
4907 public Invocation (Expression expr, Arguments arguments, bool arguments_resolved)
4908 : this (expr, arguments)
4910 this.arguments_resolved = arguments_resolved;
4913 public override Expression CreateExpressionTree (ResolveContext ec)
4918 // Special conversion for nested expression trees
4920 if (TypeManager.DropGenericTypeArguments (type) == TypeManager.expression_type) {
4921 args = new Arguments (1);
4922 args.Add (new Argument (this));
4923 return CreateExpressionFactoryCall (ec, "Quote", args);
4926 Expression instance = mg.IsInstance ?
4927 mg.InstanceExpression.CreateExpressionTree (ec) :
4928 new NullLiteral (loc);
4930 args = Arguments.CreateForExpressionTree (ec, arguments,
4932 mg.CreateExpressionTree (ec));
4935 MemberExpr.Error_BaseAccessInExpressionTree (ec, loc);
4937 return CreateExpressionFactoryCall (ec, "Call", args);
4940 public override Expression DoResolve (ResolveContext ec)
4942 // Don't resolve already resolved expression
4943 if (eclass != ExprClass.Invalid)
4946 Expression expr_resolved = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4947 if (expr_resolved == null)
4951 // Next, evaluate all the expressions in the argument list
4953 bool dynamic_arg = false;
4954 if (arguments != null && !arguments_resolved)
4955 arguments.Resolve (ec, out dynamic_arg);
4957 Type expr_type = expr_resolved.Type;
4958 mg = expr_resolved as MethodGroupExpr;
4960 if (dynamic_arg || TypeManager.IsDynamicType (expr_type)) {
4962 DynamicMemberBinder dmb = expr_resolved as DynamicMemberBinder;
4964 args = dmb.Arguments;
4965 if (arguments != null)
4966 args.AddRange (arguments);
4967 } else if (mg == null) {
4968 if (arguments == null)
4969 args = new Arguments (1);
4973 args.Insert (0, new Argument (expr_resolved));
4977 ec.Report.Error (1971, loc,
4978 "The base call to method `{0}' cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access",
4985 if (mg.IsStatic != mg.IsInstance) {
4987 args = new Arguments (1);
4990 args.Insert (0, new Argument (new TypeOf (new TypeExpression (mg.DeclaringType, loc), loc).Resolve (ec), Argument.AType.DynamicStatic));
4992 MemberAccess ma = expr as MemberAccess;
4994 args.Insert (0, new Argument (ma.Left.Resolve (ec)));
4996 args.Insert (0, new Argument (new This (loc).Resolve (ec)));
5001 return new DynamicInvocation (expr as ATypeNameExpression, args, loc).Resolve (ec);
5005 if (expr_type != null && TypeManager.IsDelegateType (expr_type)){
5006 return (new DelegateInvocation (
5007 expr_resolved, arguments, loc)).Resolve (ec);
5010 MemberExpr me = expr_resolved as MemberExpr;
5012 expr_resolved.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup, loc);
5016 mg = ec.LookupExtensionMethod (me.Type, me.Name, loc);
5018 ec.Report.Error (1955, loc, "The member `{0}' cannot be used as method or delegate",
5019 expr_resolved.GetSignatureForError ());
5023 ((ExtensionMethodGroupExpr)mg).ExtensionExpression = me.InstanceExpression;
5026 mg = DoResolveOverload (ec);
5030 MethodInfo method = (MethodInfo)mg;
5031 if (method != null) {
5032 type = TypeManager.TypeToCoreType (method.ReturnType);
5034 // TODO: this is a copy of mg.ResolveMemberAccess method
5035 Expression iexpr = mg.InstanceExpression;
5036 if (method.IsStatic) {
5037 if (iexpr == null ||
5038 iexpr is This || iexpr is EmptyExpression ||
5039 mg.IdenticalTypeName) {
5040 mg.InstanceExpression = null;
5042 MemberExpr.error176 (ec, loc, mg.GetSignatureForError ());
5046 if (iexpr == null || iexpr == EmptyExpression.Null) {
5047 SimpleName.Error_ObjectRefRequired (ec, loc, mg.GetSignatureForError ());
5052 if (type.IsPointer){
5054 UnsafeError (ec, loc);
5060 // Only base will allow this invocation to happen.
5062 if (mg.IsBase && method.IsAbstract){
5063 Error_CannotCallAbstractBase (ec, TypeManager.CSharpSignature (method));
5067 if (arguments == null && method.DeclaringType == TypeManager.object_type && method.Name == Destructor.MetadataName) {
5069 ec.Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
5071 ec.Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
5075 IsSpecialMethodInvocation (ec, method, loc);
5077 if (mg.InstanceExpression != null)
5078 mg.InstanceExpression.CheckMarshalByRefAccess (ec);
5080 eclass = ExprClass.Value;
5084 protected virtual MethodGroupExpr DoResolveOverload (ResolveContext ec)
5086 return mg.OverloadResolve (ec, ref arguments, false, loc);
5089 public static bool IsSpecialMethodInvocation (ResolveContext ec, MethodBase method, Location loc)
5091 if (!TypeManager.IsSpecialMethod (method))
5094 ec.Report.SymbolRelatedToPreviousError (method);
5095 ec.Report.Error (571, loc, "`{0}': cannot explicitly call operator or accessor",
5096 TypeManager.CSharpSignature (method, true));
5101 static Type[] GetVarargsTypes (MethodBase mb, Arguments arguments)
5103 AParametersCollection pd = TypeManager.GetParameterData (mb);
5105 Argument a = arguments [pd.Count - 1];
5106 Arglist list = (Arglist) a.Expr;
5108 return list.ArgumentTypes;
5112 /// This checks the ConditionalAttribute on the method
5114 public static bool IsMethodExcluded (MethodBase method, Location loc)
5116 if (method.IsConstructor)
5119 method = TypeManager.DropGenericMethodArguments (method);
5120 if (method.DeclaringType.Module == RootContext.ToplevelTypes.Builder) {
5121 IMethodData md = TypeManager.GetMethod (method);
5123 return md.IsExcluded ();
5125 // For some methods (generated by delegate class) GetMethod returns null
5126 // because they are not included in builder_to_method table
5130 return AttributeTester.IsConditionalMethodExcluded (method, loc);
5134 /// is_base tells whether we want to force the use of the `call'
5135 /// opcode instead of using callvirt. Call is required to call
5136 /// a specific method, while callvirt will always use the most
5137 /// recent method in the vtable.
5139 /// is_static tells whether this is an invocation on a static method
5141 /// instance_expr is an expression that represents the instance
5142 /// it must be non-null if is_static is false.
5144 /// method is the method to invoke.
5146 /// Arguments is the list of arguments to pass to the method or constructor.
5148 public static void EmitCall (EmitContext ec, bool is_base,
5149 Expression instance_expr,
5150 MethodBase method, Arguments Arguments, Location loc)
5152 EmitCall (ec, is_base, instance_expr, method, Arguments, loc, false, false);
5155 // `dup_args' leaves an extra copy of the arguments on the stack
5156 // `omit_args' does not leave any arguments at all.
5157 // So, basically, you could make one call with `dup_args' set to true,
5158 // and then another with `omit_args' set to true, and the two calls
5159 // would have the same set of arguments. However, each argument would
5160 // only have been evaluated once.
5161 public static void EmitCall (EmitContext ec, bool is_base,
5162 Expression instance_expr,
5163 MethodBase method, Arguments Arguments, Location loc,
5164 bool dup_args, bool omit_args)
5166 ILGenerator ig = ec.ig;
5167 bool struct_call = false;
5168 bool this_call = false;
5169 LocalTemporary this_arg = null;
5171 Type decl_type = method.DeclaringType;
5173 if (IsMethodExcluded (method, loc))
5176 bool is_static = method.IsStatic;
5178 this_call = instance_expr is This;
5179 if (TypeManager.IsStruct (decl_type) || TypeManager.IsEnumType (decl_type))
5183 // If this is ourselves, push "this"
5187 Type iexpr_type = instance_expr.Type;
5190 // Push the instance expression
5192 if (TypeManager.IsValueType (iexpr_type) || TypeManager.IsGenericParameter (iexpr_type)) {
5194 // Special case: calls to a function declared in a
5195 // reference-type with a value-type argument need
5196 // to have their value boxed.
5197 if (TypeManager.IsStruct (decl_type) ||
5198 TypeManager.IsGenericParameter (iexpr_type)) {
5200 // If the expression implements IMemoryLocation, then
5201 // we can optimize and use AddressOf on the
5204 // If not we have to use some temporary storage for
5206 if (instance_expr is IMemoryLocation) {
5207 ((IMemoryLocation)instance_expr).
5208 AddressOf (ec, AddressOp.LoadStore);
5210 LocalTemporary temp = new LocalTemporary (iexpr_type);
5211 instance_expr.Emit (ec);
5213 temp.AddressOf (ec, AddressOp.Load);
5216 // avoid the overhead of doing this all the time.
5218 t = TypeManager.GetReferenceType (iexpr_type);
5220 instance_expr.Emit (ec);
5222 // FIXME: should use instance_expr is IMemoryLocation + constraint.
5223 // to help JIT to produce better code
5224 ig.Emit (OpCodes.Box, instance_expr.Type);
5225 t = TypeManager.object_type;
5228 instance_expr.Emit (ec);
5229 t = instance_expr.Type;
5233 ig.Emit (OpCodes.Dup);
5234 if (Arguments != null && Arguments.Count != 0) {
5235 this_arg = new LocalTemporary (t);
5236 this_arg.Store (ec);
5242 if (!omit_args && Arguments != null)
5243 Arguments.Emit (ec, dup_args, this_arg);
5246 if (is_static || struct_call || is_base || (this_call && !method.IsVirtual)) {
5247 call_op = OpCodes.Call;
5249 call_op = OpCodes.Callvirt;
5252 if ((instance_expr != null) && (instance_expr.Type.IsGenericParameter))
5253 ig.Emit (OpCodes.Constrained, instance_expr.Type);
5257 if ((method.CallingConvention & CallingConventions.VarArgs) != 0) {
5258 Type[] varargs_types = GetVarargsTypes (method, Arguments);
5259 ig.EmitCall (call_op, (MethodInfo) method, varargs_types);
5266 // and DoFoo is not virtual, you can omit the callvirt,
5267 // because you don't need the null checking behavior.
5269 if (method is MethodInfo)
5270 ig.Emit (call_op, (MethodInfo) method);
5272 ig.Emit (call_op, (ConstructorInfo) method);
5275 public override void Emit (EmitContext ec)
5277 mg.EmitCall (ec, arguments);
5280 public override void EmitStatement (EmitContext ec)
5285 // Pop the return value if there is one
5287 if (TypeManager.TypeToCoreType (type) != TypeManager.void_type)
5288 ec.ig.Emit (OpCodes.Pop);
5291 protected override void CloneTo (CloneContext clonectx, Expression t)
5293 Invocation target = (Invocation) t;
5295 if (arguments != null)
5296 target.arguments = arguments.Clone (clonectx);
5298 target.expr = expr.Clone (clonectx);
5301 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
5303 mg.MutateHoistedGenericType (storey);
5304 type = storey.MutateType (type);
5305 if (arguments != null) {
5306 arguments.MutateHoistedGenericType (storey);
5312 // It's either a cast or delegate invocation
5314 public class InvocationOrCast : ExpressionStatement
5317 Expression argument;
5319 public InvocationOrCast (Expression expr, Expression argument)
5322 this.argument = argument;
5323 this.loc = expr.Location;
5326 public override Expression CreateExpressionTree (ResolveContext ec)
5328 throw new NotSupportedException ("ET");
5331 public override Expression DoResolve (ResolveContext ec)
5333 Expression e = ResolveCore (ec);
5337 return e.Resolve (ec);
5340 Expression ResolveCore (EmitContext ec)
5343 // First try to resolve it as a cast.
5345 TypeExpr te = expr.ResolveAsBaseTerminal (ec, true);
5347 return new Cast (te, argument, loc);
5351 // This can either be a type or a delegate invocation.
5352 // Let's just resolve it and see what we'll get.
5354 expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5359 // Ok, so it's a Cast.
5361 if (expr.eclass == ExprClass.Type || expr.eclass == ExprClass.TypeParameter) {
5362 return new Cast (expr, argument, loc);
5365 if (expr.eclass == ExprClass.Namespace) {
5366 expr.Error_UnexpectedKind (null, "type", loc);
5371 // It's a delegate invocation.
5373 if (!TypeManager.IsDelegateType (expr.Type)) {
5374 Error (149, "Method name expected");
5378 ArrayList args = new ArrayList (1);
5379 args.Add (new Argument (argument, Argument.AType.Expression));
5380 return new DelegateInvocation (expr, args, loc);
5383 public override ExpressionStatement ResolveStatement (EmitContext ec)
5385 Expression e = ResolveCore (ec);
5389 ExpressionStatement s = e as ExpressionStatement;
5391 Error_InvalidExpressionStatement ();
5395 return s.ResolveStatement (ec);
5398 public override void Emit (EmitContext ec)
5400 throw new Exception ("Cannot happen");
5403 public override void EmitStatement (EmitContext ec)
5405 throw new Exception ("Cannot happen");
5408 protected override void CloneTo (CloneContext clonectx, Expression t)
5410 InvocationOrCast target = (InvocationOrCast) t;
5412 target.expr = expr.Clone (clonectx);
5413 target.argument = argument.Clone (clonectx);
5419 /// Implements the new expression
5421 public class New : ExpressionStatement, IMemoryLocation {
5422 Arguments Arguments;
5425 // During bootstrap, it contains the RequestedType,
5426 // but if `type' is not null, it *might* contain a NewDelegate
5427 // (because of field multi-initialization)
5429 Expression RequestedType;
5431 MethodGroupExpr method;
5433 bool is_type_parameter;
5435 public New (Expression requested_type, Arguments arguments, Location l)
5437 RequestedType = requested_type;
5438 Arguments = arguments;
5443 /// Converts complex core type syntax like 'new int ()' to simple constant
5445 public static Constant Constantify (Type t)
5447 if (t == TypeManager.int32_type)
5448 return new IntConstant (0, Location.Null);
5449 if (t == TypeManager.uint32_type)
5450 return new UIntConstant (0, Location.Null);
5451 if (t == TypeManager.int64_type)
5452 return new LongConstant (0, Location.Null);
5453 if (t == TypeManager.uint64_type)
5454 return new ULongConstant (0, Location.Null);
5455 if (t == TypeManager.float_type)
5456 return new FloatConstant (0, Location.Null);
5457 if (t == TypeManager.double_type)
5458 return new DoubleConstant (0, Location.Null);
5459 if (t == TypeManager.short_type)
5460 return new ShortConstant (0, Location.Null);
5461 if (t == TypeManager.ushort_type)
5462 return new UShortConstant (0, Location.Null);
5463 if (t == TypeManager.sbyte_type)
5464 return new SByteConstant (0, Location.Null);
5465 if (t == TypeManager.byte_type)
5466 return new ByteConstant (0, Location.Null);
5467 if (t == TypeManager.char_type)
5468 return new CharConstant ('\0', Location.Null);
5469 if (t == TypeManager.bool_type)
5470 return new BoolConstant (false, Location.Null);
5471 if (t == TypeManager.decimal_type)
5472 return new DecimalConstant (0, Location.Null);
5473 if (TypeManager.IsEnumType (t))
5474 return new EnumConstant (Constantify (TypeManager.GetEnumUnderlyingType (t)), t);
5475 if (TypeManager.IsNullableType (t))
5476 return Nullable.LiftedNull.Create (t, Location.Null);
5482 // Checks whether the type is an interface that has the
5483 // [ComImport, CoClass] attributes and must be treated
5486 public Expression CheckComImport (ResolveContext ec)
5488 if (!type.IsInterface)
5492 // Turn the call into:
5493 // (the-interface-stated) (new class-referenced-in-coclassattribute ())
5495 Type real_class = AttributeTester.GetCoClassAttribute (type);
5496 if (real_class == null)
5499 New proxy = new New (new TypeExpression (real_class, loc), Arguments, loc);
5500 Cast cast = new Cast (new TypeExpression (type, loc), proxy, loc);
5501 return cast.Resolve (ec);
5504 public override Expression CreateExpressionTree (ResolveContext ec)
5507 if (method == null) {
5508 args = new Arguments (1);
5509 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
5511 args = Arguments.CreateForExpressionTree (ec, Arguments,
5512 method.CreateExpressionTree (ec));
5515 return CreateExpressionFactoryCall (ec, "New", args);
5518 public override Expression DoResolve (ResolveContext ec)
5521 // The New DoResolve might be called twice when initializing field
5522 // expressions (see EmitFieldInitializers, the call to
5523 // GetInitializerExpression will perform a resolve on the expression,
5524 // and later the assign will trigger another resolution
5526 // This leads to bugs (#37014)
5529 if (RequestedType is NewDelegate)
5530 return RequestedType;
5534 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec, false);
5540 if (type.IsPointer) {
5541 ec.Report.Error (1919, loc, "Unsafe type `{0}' cannot be used in an object creation expression",
5542 TypeManager.CSharpName (type));
5546 if (Arguments == null) {
5547 Constant c = Constantify (type);
5549 return ReducedExpression.Create (c, this);
5552 if (TypeManager.IsDelegateType (type)) {
5553 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5556 if (TypeManager.IsGenericParameter (type)) {
5557 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (type);
5559 if ((gc == null) || (!gc.HasConstructorConstraint && !gc.IsValueType)) {
5560 ec.Report.Error (304, loc,
5561 "Cannot create an instance of the variable type '{0}' because it doesn't have the new() constraint",
5562 TypeManager.CSharpName (type));
5566 if ((Arguments != null) && (Arguments.Count != 0)) {
5567 ec.Report.Error (417, loc,
5568 "`{0}': cannot provide arguments when creating an instance of a variable type",
5569 TypeManager.CSharpName (type));
5573 if (TypeManager.activator_create_instance == null) {
5574 Type activator_type = TypeManager.CoreLookupType (ec.Compiler, "System", "Activator", Kind.Class, true);
5575 if (activator_type != null) {
5576 TypeManager.activator_create_instance = TypeManager.GetPredefinedMethod (
5577 activator_type, "CreateInstance", loc, Type.EmptyTypes);
5581 is_type_parameter = true;
5582 eclass = ExprClass.Value;
5586 if (type.IsAbstract && type.IsSealed) {
5587 ec.Report.SymbolRelatedToPreviousError (type);
5588 ec.Report.Error (712, loc, "Cannot create an instance of the static class `{0}'", TypeManager.CSharpName (type));
5592 if (type.IsInterface || type.IsAbstract){
5593 if (!TypeManager.IsGenericType (type)) {
5594 RequestedType = CheckComImport (ec);
5595 if (RequestedType != null)
5596 return RequestedType;
5599 ec.Report.SymbolRelatedToPreviousError (type);
5600 ec.Report.Error (144, loc, "Cannot create an instance of the abstract class or interface `{0}'", TypeManager.CSharpName (type));
5604 bool is_struct = TypeManager.IsStruct (type);
5605 eclass = ExprClass.Value;
5608 // SRE returns a match for .ctor () on structs (the object constructor),
5609 // so we have to manually ignore it.
5611 if (is_struct && Arguments == null)
5614 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
5615 Expression ml = MemberLookupFinal (ec, type, type, ConstructorInfo.ConstructorName,
5616 MemberTypes.Constructor, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5618 if (Arguments != null) {
5620 Arguments.Resolve (ec, out dynamic);
5623 Arguments.Insert (0, new Argument (new TypeOf (texpr, loc).Resolve (ec)));
5624 return new DynamicInvocation (new SimpleName (ConstructorInfo.ConstructorName, loc), Arguments, type, loc).Resolve (ec);
5631 method = ml as MethodGroupExpr;
5632 if (method == null) {
5633 ml.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup, loc);
5637 method = method.OverloadResolve (ec, ref Arguments, false, loc);
5644 bool DoEmitTypeParameter (EmitContext ec)
5647 ILGenerator ig = ec.ig;
5648 // IMemoryLocation ml;
5650 MethodInfo ci = TypeManager.activator_create_instance.MakeGenericMethod (
5651 new Type [] { type });
5653 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (type);
5654 if (gc.HasReferenceTypeConstraint || gc.HasClassConstraint) {
5655 ig.Emit (OpCodes.Call, ci);
5659 // Allow DoEmit() to be called multiple times.
5660 // We need to create a new LocalTemporary each time since
5661 // you can't share LocalBuilders among ILGeneators.
5662 LocalTemporary temp = new LocalTemporary (type);
5664 Label label_activator = ig.DefineLabel ();
5665 Label label_end = ig.DefineLabel ();
5667 temp.AddressOf (ec, AddressOp.Store);
5668 ig.Emit (OpCodes.Initobj, type);
5671 ig.Emit (OpCodes.Box, type);
5672 ig.Emit (OpCodes.Brfalse, label_activator);
5674 temp.AddressOf (ec, AddressOp.Store);
5675 ig.Emit (OpCodes.Initobj, type);
5677 ig.Emit (OpCodes.Br_S, label_end);
5679 ig.MarkLabel (label_activator);
5681 ig.Emit (OpCodes.Call, ci);
5682 ig.MarkLabel (label_end);
5685 throw new InternalErrorException ();
5690 // This Emit can be invoked in two contexts:
5691 // * As a mechanism that will leave a value on the stack (new object)
5692 // * As one that wont (init struct)
5694 // If we are dealing with a ValueType, we have a few
5695 // situations to deal with:
5697 // * The target is a ValueType, and we have been provided
5698 // the instance (this is easy, we are being assigned).
5700 // * The target of New is being passed as an argument,
5701 // to a boxing operation or a function that takes a
5704 // In this case, we need to create a temporary variable
5705 // that is the argument of New.
5707 // Returns whether a value is left on the stack
5709 // *** Implementation note ***
5711 // To benefit from this optimization, each assignable expression
5712 // has to manually cast to New and call this Emit.
5714 // TODO: It's worth to implement it for arrays and fields
5716 public virtual bool Emit (EmitContext ec, IMemoryLocation target)
5718 bool is_value_type = TypeManager.IsValueType (type);
5719 ILGenerator ig = ec.ig;
5720 VariableReference vr = target as VariableReference;
5722 if (target != null && is_value_type && (vr != null || method == null)) {
5723 target.AddressOf (ec, AddressOp.Store);
5724 } else if (vr != null && vr.IsRef) {
5728 if (Arguments != null)
5729 Arguments.Emit (ec);
5731 if (is_value_type) {
5732 if (method == null) {
5733 ig.Emit (OpCodes.Initobj, type);
5738 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5743 if (is_type_parameter)
5744 return DoEmitTypeParameter (ec);
5746 ConstructorInfo ci = (ConstructorInfo) method;
5748 if (TypeManager.IsGenericType (type) && type.IsGenericTypeDefinition)
5749 ci = TypeBuilder.GetConstructor (type, ci);
5752 ig.Emit (OpCodes.Newobj, ci);
5756 public override void Emit (EmitContext ec)
5758 LocalTemporary v = null;
5759 if (method == null && TypeManager.IsValueType (type)) {
5760 // TODO: Use temporary variable from pool
5761 v = new LocalTemporary (type);
5768 public override void EmitStatement (EmitContext ec)
5770 LocalTemporary v = null;
5771 if (method == null && TypeManager.IsValueType (type)) {
5772 // TODO: Use temporary variable from pool
5773 v = new LocalTemporary (type);
5777 ec.ig.Emit (OpCodes.Pop);
5780 public bool IsDefaultValueType {
5782 return TypeManager.IsValueType (type) && !HasInitializer && Arguments == null;
5786 public virtual bool HasInitializer {
5792 public void AddressOf (EmitContext ec, AddressOp mode)
5794 EmitAddressOf (ec, mode);
5797 protected virtual IMemoryLocation EmitAddressOf (EmitContext ec, AddressOp mode)
5799 LocalTemporary value_target = new LocalTemporary (type);
5801 if (is_type_parameter) {
5802 DoEmitTypeParameter (ec);
5803 value_target.Store (ec);
5804 value_target.AddressOf (ec, mode);
5805 return value_target;
5808 if (!TypeManager.IsStruct (type)){
5810 // We throw an exception. So far, I believe we only need to support
5812 // foreach (int j in new StructType ())
5815 throw new Exception ("AddressOf should not be used for classes");
5818 value_target.AddressOf (ec, AddressOp.Store);
5820 if (method == null) {
5821 ec.ig.Emit (OpCodes.Initobj, type);
5823 if (Arguments != null)
5824 Arguments.Emit (ec);
5826 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5829 value_target.AddressOf (ec, mode);
5830 return value_target;
5833 protected override void CloneTo (CloneContext clonectx, Expression t)
5835 New target = (New) t;
5837 target.RequestedType = RequestedType.Clone (clonectx);
5838 if (Arguments != null){
5839 target.Arguments = Arguments.Clone (clonectx);
5843 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
5845 if (method != null) {
5846 method.MutateHoistedGenericType (storey);
5847 if (Arguments != null) {
5848 Arguments.MutateHoistedGenericType (storey);
5852 type = storey.MutateType (type);
5857 /// 14.5.10.2: Represents an array creation expression.
5861 /// There are two possible scenarios here: one is an array creation
5862 /// expression that specifies the dimensions and optionally the
5863 /// initialization data and the other which does not need dimensions
5864 /// specified but where initialization data is mandatory.
5866 public class ArrayCreation : Expression {
5867 FullNamedExpression requested_base_type;
5868 ArrayList initializers;
5871 // The list of Argument types.
5872 // This is used to construct the `newarray' or constructor signature
5874 protected ArrayList arguments;
5876 protected Type array_element_type;
5877 bool expect_initializers = false;
5878 int num_arguments = 0;
5879 protected int dimensions;
5880 protected readonly string rank;
5882 protected ArrayList array_data;
5886 // The number of constants in array initializers
5887 int const_initializers_count;
5888 bool only_constant_initializers;
5890 public ArrayCreation (FullNamedExpression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
5892 this.requested_base_type = requested_base_type;
5893 this.initializers = initializers;
5897 arguments = new ArrayList (exprs.Count);
5899 foreach (Expression e in exprs) {
5905 public ArrayCreation (FullNamedExpression requested_base_type, string rank, ArrayList initializers, Location l)
5907 this.requested_base_type = requested_base_type;
5908 this.initializers = initializers;
5912 //this.rank = rank.Substring (0, rank.LastIndexOf ('['));
5914 //string tmp = rank.Substring (rank.LastIndexOf ('['));
5916 //dimensions = tmp.Length - 1;
5917 expect_initializers = true;
5920 protected override void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
5922 ec.Report.Error (248, loc, "Cannot create an array with a negative size");
5925 bool CheckIndices (ResolveContext ec, ArrayList probe, int idx, bool specified_dims, int child_bounds)
5927 if (specified_dims) {
5928 Expression a = (Expression) arguments [idx];
5933 Constant c = a as Constant;
5935 c = c.ImplicitConversionRequired (ec, TypeManager.int32_type, a.Location);
5939 ec.Report.Error (150, a.Location, "A constant value is expected");
5943 int value = (int) c.GetValue ();
5945 if (value != probe.Count) {
5946 ec.Report.Error (847, loc, "An array initializer of length `{0}' was expected", value);
5950 bounds [idx] = value;
5953 only_constant_initializers = true;
5954 for (int i = 0; i < probe.Count; ++i) {
5955 object o = probe [i];
5956 if (o is ArrayList) {
5957 ArrayList sub_probe = o as ArrayList;
5958 if (idx + 1 >= dimensions){
5959 ec.Report.Error (623, loc, "Array initializers can only be used in a variable or field initializer. Try using a new expression instead");
5963 bool ret = CheckIndices (ec, sub_probe, idx + 1, specified_dims, child_bounds - 1);
5966 } else if (child_bounds > 1) {
5967 ec.Report.Error (846, ((Expression) o).Location, "A nested array initializer was expected");
5969 Expression element = ResolveArrayElement (ec, (Expression) o);
5970 if (element == null)
5973 // Initializers with the default values can be ignored
5974 Constant c = element as Constant;
5976 if (c.IsDefaultInitializer (array_element_type)) {
5980 ++const_initializers_count;
5983 only_constant_initializers = false;
5986 array_data.Add (element);
5993 public override Expression CreateExpressionTree (ResolveContext ec)
5997 if (array_data == null) {
5998 args = new Arguments (arguments.Count + 1);
5999 args.Add (new Argument (new TypeOf (new TypeExpression (array_element_type, loc), loc)));
6000 foreach (Expression a in arguments)
6001 args.Add (new Argument (a.CreateExpressionTree (ec)));
6003 return CreateExpressionFactoryCall (ec, "NewArrayBounds", args);
6006 if (dimensions > 1) {
6007 ec.Report.Error (838, loc, "An expression tree cannot contain a multidimensional array initializer");
6011 args = new Arguments (array_data == null ? 1 : array_data.Count + 1);
6012 args.Add (new Argument (new TypeOf (new TypeExpression (array_element_type, loc), loc)));
6013 if (array_data != null) {
6014 for (int i = 0; i < array_data.Count; ++i) {
6015 Expression e = (Expression) array_data [i];
6017 e = Convert.ImplicitConversion (ec, (Expression) initializers [i], array_element_type, loc);
6019 args.Add (new Argument (e.CreateExpressionTree (ec)));
6023 return CreateExpressionFactoryCall (ec, "NewArrayInit", args);
6026 public void UpdateIndices ()
6029 for (ArrayList probe = initializers; probe != null;) {
6030 if (probe.Count > 0 && probe [0] is ArrayList) {
6031 Expression e = new IntConstant (probe.Count, Location.Null);
6034 bounds [i++] = probe.Count;
6036 probe = (ArrayList) probe [0];
6039 Expression e = new IntConstant (probe.Count, Location.Null);
6042 bounds [i++] = probe.Count;
6049 Expression first_emit;
6050 LocalTemporary first_emit_temp;
6052 protected virtual Expression ResolveArrayElement (ResolveContext ec, Expression element)
6054 element = element.Resolve (ec);
6055 if (element == null)
6058 if (element is CompoundAssign.TargetExpression) {
6059 if (first_emit != null)
6060 throw new InternalErrorException ("Can only handle one mutator at a time");
6061 first_emit = element;
6062 element = first_emit_temp = new LocalTemporary (element.Type);
6065 return Convert.ImplicitConversionRequired (
6066 ec, element, array_element_type, loc);
6069 protected bool ResolveInitializers (ResolveContext ec)
6071 if (initializers == null) {
6072 return !expect_initializers;
6076 // We use this to store all the date values in the order in which we
6077 // will need to store them in the byte blob later
6079 array_data = new ArrayList ();
6080 bounds = new System.Collections.Specialized.HybridDictionary ();
6082 if (arguments != null)
6083 return CheckIndices (ec, initializers, 0, true, dimensions);
6085 arguments = new ArrayList ();
6087 if (!CheckIndices (ec, initializers, 0, false, dimensions))
6096 // Resolved the type of the array
6098 bool ResolveArrayType (ResolveContext ec)
6100 if (requested_base_type == null) {
6101 ec.Report.Error (622, loc, "Can only use array initializer expressions to assign to array types. Try using a new expression instead");
6105 if (requested_base_type is VarExpr) {
6106 ec.Report.Error (820, loc, "An implicitly typed local variable declarator cannot use an array initializer");
6110 StringBuilder array_qualifier = new StringBuilder (rank);
6113 // `In the first form allocates an array instace of the type that results
6114 // from deleting each of the individual expression from the expression list'
6116 if (num_arguments > 0) {
6117 array_qualifier.Append ("[");
6118 for (int i = num_arguments-1; i > 0; i--)
6119 array_qualifier.Append (",");
6120 array_qualifier.Append ("]");
6126 TypeExpr array_type_expr;
6127 array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
6128 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec, false);
6129 if (array_type_expr == null)
6132 type = array_type_expr.Type;
6133 array_element_type = TypeManager.GetElementType (type);
6134 dimensions = type.GetArrayRank ();
6139 public override Expression DoResolve (ResolveContext ec)
6144 if (!ResolveArrayType (ec))
6148 // First step is to validate the initializers and fill
6149 // in any missing bits
6151 if (!ResolveInitializers (ec))
6154 for (int i = 0; i < arguments.Count; ++i) {
6155 Expression e = ((Expression) arguments[i]).Resolve (ec);
6159 arguments [i] = ConvertExpressionToArrayIndex (ec, e);
6162 eclass = ExprClass.Value;
6166 MethodInfo GetArrayMethod (int arguments)
6168 ModuleBuilder mb = RootContext.ToplevelTypes.Builder;
6170 Type[] arg_types = new Type[arguments];
6171 for (int i = 0; i < arguments; i++)
6172 arg_types[i] = TypeManager.int32_type;
6174 MethodInfo mi = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
6178 RootContext.ToplevelTypes.Compiler.Report.Error (-6, "New invocation: Can not find a constructor for " +
6179 "this argument list");
6186 byte [] MakeByteBlob ()
6191 int count = array_data.Count;
6193 if (TypeManager.IsEnumType (array_element_type))
6194 array_element_type = TypeManager.GetEnumUnderlyingType (array_element_type);
6196 factor = GetTypeSize (array_element_type);
6198 throw new Exception ("unrecognized type in MakeByteBlob: " + array_element_type);
6200 data = new byte [(count * factor + 3) & ~3];
6203 for (int i = 0; i < count; ++i) {
6204 object v = array_data [i];
6206 if (v is EnumConstant)
6207 v = ((EnumConstant) v).Child;
6209 if (v is Constant && !(v is StringConstant))
6210 v = ((Constant) v).GetValue ();
6216 if (array_element_type == TypeManager.int64_type){
6217 if (!(v is Expression)){
6218 long val = (long) v;
6220 for (int j = 0; j < factor; ++j) {
6221 data [idx + j] = (byte) (val & 0xFF);
6225 } else if (array_element_type == TypeManager.uint64_type){
6226 if (!(v is Expression)){
6227 ulong val = (ulong) v;
6229 for (int j = 0; j < factor; ++j) {
6230 data [idx + j] = (byte) (val & 0xFF);
6234 } else if (array_element_type == TypeManager.float_type) {
6235 if (!(v is Expression)){
6236 element = BitConverter.GetBytes ((float) v);
6238 for (int j = 0; j < factor; ++j)
6239 data [idx + j] = element [j];
6240 if (!BitConverter.IsLittleEndian)
6241 System.Array.Reverse (data, idx, 4);
6243 } else if (array_element_type == TypeManager.double_type) {
6244 if (!(v is Expression)){
6245 element = BitConverter.GetBytes ((double) v);
6247 for (int j = 0; j < factor; ++j)
6248 data [idx + j] = element [j];
6250 // FIXME: Handle the ARM float format.
6251 if (!BitConverter.IsLittleEndian)
6252 System.Array.Reverse (data, idx, 8);
6254 } else if (array_element_type == TypeManager.char_type){
6255 if (!(v is Expression)){
6256 int val = (int) ((char) v);
6258 data [idx] = (byte) (val & 0xff);
6259 data [idx+1] = (byte) (val >> 8);
6261 } else if (array_element_type == TypeManager.short_type){
6262 if (!(v is Expression)){
6263 int val = (int) ((short) v);
6265 data [idx] = (byte) (val & 0xff);
6266 data [idx+1] = (byte) (val >> 8);
6268 } else if (array_element_type == TypeManager.ushort_type){
6269 if (!(v is Expression)){
6270 int val = (int) ((ushort) v);
6272 data [idx] = (byte) (val & 0xff);
6273 data [idx+1] = (byte) (val >> 8);
6275 } else if (array_element_type == TypeManager.int32_type) {
6276 if (!(v is Expression)){
6279 data [idx] = (byte) (val & 0xff);
6280 data [idx+1] = (byte) ((val >> 8) & 0xff);
6281 data [idx+2] = (byte) ((val >> 16) & 0xff);
6282 data [idx+3] = (byte) (val >> 24);
6284 } else if (array_element_type == TypeManager.uint32_type) {
6285 if (!(v is Expression)){
6286 uint val = (uint) v;
6288 data [idx] = (byte) (val & 0xff);
6289 data [idx+1] = (byte) ((val >> 8) & 0xff);
6290 data [idx+2] = (byte) ((val >> 16) & 0xff);
6291 data [idx+3] = (byte) (val >> 24);
6293 } else if (array_element_type == TypeManager.sbyte_type) {
6294 if (!(v is Expression)){
6295 sbyte val = (sbyte) v;
6296 data [idx] = (byte) val;
6298 } else if (array_element_type == TypeManager.byte_type) {
6299 if (!(v is Expression)){
6300 byte val = (byte) v;
6301 data [idx] = (byte) val;
6303 } else if (array_element_type == TypeManager.bool_type) {
6304 if (!(v is Expression)){
6305 bool val = (bool) v;
6306 data [idx] = (byte) (val ? 1 : 0);
6308 } else if (array_element_type == TypeManager.decimal_type){
6309 if (!(v is Expression)){
6310 int [] bits = Decimal.GetBits ((decimal) v);
6313 // FIXME: For some reason, this doesn't work on the MS runtime.
6314 int [] nbits = new int [4];
6315 nbits [0] = bits [3];
6316 nbits [1] = bits [2];
6317 nbits [2] = bits [0];
6318 nbits [3] = bits [1];
6320 for (int j = 0; j < 4; j++){
6321 data [p++] = (byte) (nbits [j] & 0xff);
6322 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6323 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6324 data [p++] = (byte) (nbits [j] >> 24);
6328 throw new Exception ("Unrecognized type in MakeByteBlob: " + array_element_type);
6336 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
6338 array_element_type = storey.MutateType (array_element_type);
6339 type = storey.MutateType (type);
6340 if (arguments != null) {
6341 foreach (Expression e in arguments)
6342 e.MutateHoistedGenericType (storey);
6345 if (array_data != null) {
6346 foreach (Expression e in array_data) {
6347 // Don't mutate values optimized away
6351 e.MutateHoistedGenericType (storey);
6357 // Emits the initializers for the array
6359 void EmitStaticInitializers (EmitContext ec)
6361 // FIXME: This should go to Resolve !
6362 if (TypeManager.void_initializearray_array_fieldhandle == null) {
6363 TypeManager.void_initializearray_array_fieldhandle = TypeManager.GetPredefinedMethod (
6364 TypeManager.runtime_helpers_type, "InitializeArray", loc,
6365 TypeManager.array_type, TypeManager.runtime_field_handle_type);
6366 if (TypeManager.void_initializearray_array_fieldhandle == null)
6371 // First, the static data
6374 ILGenerator ig = ec.ig;
6376 byte [] data = MakeByteBlob ();
6378 fb = RootContext.MakeStaticData (data);
6380 ig.Emit (OpCodes.Dup);
6381 ig.Emit (OpCodes.Ldtoken, fb);
6382 ig.Emit (OpCodes.Call,
6383 TypeManager.void_initializearray_array_fieldhandle);
6387 // Emits pieces of the array that can not be computed at compile
6388 // time (variables and string locations).
6390 // This always expect the top value on the stack to be the array
6392 void EmitDynamicInitializers (EmitContext ec, bool emitConstants)
6394 ILGenerator ig = ec.ig;
6395 int dims = bounds.Count;
6396 int [] current_pos = new int [dims];
6398 MethodInfo set = null;
6401 Type [] args = new Type [dims + 1];
6403 for (int j = 0; j < dims; j++)
6404 args [j] = TypeManager.int32_type;
6405 args [dims] = array_element_type;
6407 set = RootContext.ToplevelTypes.Builder.GetArrayMethod (
6409 CallingConventions.HasThis | CallingConventions.Standard,
6410 TypeManager.void_type, args);
6413 for (int i = 0; i < array_data.Count; i++){
6415 Expression e = (Expression)array_data [i];
6417 // Constant can be initialized via StaticInitializer
6418 if (e != null && !(!emitConstants && e is Constant)) {
6419 Type etype = e.Type;
6421 ig.Emit (OpCodes.Dup);
6423 for (int idx = 0; idx < dims; idx++)
6424 IntConstant.EmitInt (ig, current_pos [idx]);
6427 // If we are dealing with a struct, get the
6428 // address of it, so we can store it.
6430 if ((dims == 1) && TypeManager.IsStruct (etype) &&
6431 (!TypeManager.IsBuiltinOrEnum (etype) ||
6432 etype == TypeManager.decimal_type)) {
6434 ig.Emit (OpCodes.Ldelema, etype);
6440 bool is_stobj, has_type_arg;
6441 OpCode op = ArrayAccess.GetStoreOpcode (etype, out is_stobj, out has_type_arg);
6443 ig.Emit (OpCodes.Stobj, etype);
6444 else if (has_type_arg)
6445 ig.Emit (op, etype);
6449 ig.Emit (OpCodes.Call, set);
6456 for (int j = dims - 1; j >= 0; j--){
6458 if (current_pos [j] < (int) bounds [j])
6460 current_pos [j] = 0;
6465 public override void Emit (EmitContext ec)
6467 ILGenerator ig = ec.ig;
6469 if (first_emit != null) {
6470 first_emit.Emit (ec);
6471 first_emit_temp.Store (ec);
6474 foreach (Expression e in arguments)
6477 if (arguments.Count == 1)
6478 ig.Emit (OpCodes.Newarr, TypeManager.TypeToReflectionType (array_element_type));
6480 ig.Emit (OpCodes.Newobj, GetArrayMethod (arguments.Count));
6483 if (initializers == null)
6486 // Emit static initializer for arrays which have contain more than 4 items and
6487 // the static initializer will initialize at least 25% of array values.
6488 // NOTE: const_initializers_count does not contain default constant values.
6489 if (const_initializers_count >= 4 && const_initializers_count * 4 > (array_data.Count) &&
6490 TypeManager.IsPrimitiveType (array_element_type)) {
6491 EmitStaticInitializers (ec);
6493 if (!only_constant_initializers)
6494 EmitDynamicInitializers (ec, false);
6496 EmitDynamicInitializers (ec, true);
6499 if (first_emit_temp != null)
6500 first_emit_temp.Release (ec);
6503 public override bool GetAttributableValue (ResolveContext ec, Type value_type, out object value)
6505 if (arguments.Count != 1) {
6506 // ec.Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6507 return base.GetAttributableValue (ec, null, out value);
6510 if (array_data == null) {
6511 Expression arg = (Expression) arguments[0];
6513 if (arg.GetAttributableValue (ec, arg.Type, out arg_value) && arg_value is int && (int)arg_value == 0) {
6514 value = Array.CreateInstance (array_element_type, 0);
6518 // ec.Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6519 return base.GetAttributableValue (ec, null, out value);
6522 Array ret = Array.CreateInstance (array_element_type, array_data.Count);
6523 object element_value;
6524 for (int i = 0; i < ret.Length; ++i)
6526 Expression e = (Expression)array_data [i];
6528 // Is null when an initializer is optimized (value == predefined value)
6532 if (!e.GetAttributableValue (ec, array_element_type, out element_value)) {
6536 ret.SetValue (element_value, i);
6542 protected override void CloneTo (CloneContext clonectx, Expression t)
6544 ArrayCreation target = (ArrayCreation) t;
6546 if (requested_base_type != null)
6547 target.requested_base_type = (FullNamedExpression)requested_base_type.Clone (clonectx);
6549 if (arguments != null){
6550 target.arguments = new ArrayList (arguments.Count);
6551 foreach (Expression e in arguments)
6552 target.arguments.Add (e.Clone (clonectx));
6555 if (initializers != null){
6556 target.initializers = new ArrayList (initializers.Count);
6557 foreach (object initializer in initializers)
6558 if (initializer is ArrayList) {
6559 ArrayList this_al = (ArrayList)initializer;
6560 ArrayList al = new ArrayList (this_al.Count);
6561 target.initializers.Add (al);
6562 foreach (Expression e in this_al)
6563 al.Add (e.Clone (clonectx));
6565 target.initializers.Add (((Expression)initializer).Clone (clonectx));
6572 // Represents an implicitly typed array epxression
6574 public class ImplicitlyTypedArrayCreation : ArrayCreation
6576 public ImplicitlyTypedArrayCreation (string rank, ArrayList initializers, Location loc)
6577 : base (null, rank, initializers, loc)
6579 if (rank.Length > 2) {
6580 while (rank [++dimensions] == ',');
6586 public override Expression DoResolve (ResolveContext ec)
6591 if (!ResolveInitializers (ec))
6594 if (array_element_type == null || array_element_type == TypeManager.null_type ||
6595 array_element_type == TypeManager.void_type || array_element_type == InternalType.AnonymousMethod ||
6596 array_element_type == InternalType.MethodGroup ||
6597 arguments.Count != dimensions) {
6598 Error_NoBestType (ec);
6603 // At this point we found common base type for all initializer elements
6604 // but we have to be sure that all static initializer elements are of
6607 UnifyInitializerElement (ec);
6609 type = TypeManager.GetConstructedType (array_element_type, rank);
6610 eclass = ExprClass.Value;
6614 void Error_NoBestType (ResolveContext ec)
6616 ec.Report.Error (826, loc,
6617 "The type of an implicitly typed array cannot be inferred from the initializer. Try specifying array type explicitly");
6621 // Converts static initializer only
6623 void UnifyInitializerElement (ResolveContext ec)
6625 for (int i = 0; i < array_data.Count; ++i) {
6626 Expression e = (Expression)array_data[i];
6628 array_data [i] = Convert.ImplicitConversion (ec, e, array_element_type, Location.Null);
6632 protected override Expression ResolveArrayElement (ResolveContext ec, Expression element)
6634 element = element.Resolve (ec);
6635 if (element == null)
6638 if (array_element_type == null) {
6639 if (element.Type != TypeManager.null_type)
6640 array_element_type = element.Type;
6645 if (Convert.ImplicitConversionExists (ec, element, array_element_type)) {
6649 if (Convert.ImplicitConversionExists (ec, new TypeExpression (array_element_type, loc), element.Type)) {
6650 array_element_type = element.Type;
6654 Error_NoBestType (ec);
6659 public sealed class CompilerGeneratedThis : This
6661 public static This Instance = new CompilerGeneratedThis ();
6663 private CompilerGeneratedThis ()
6664 : base (Location.Null)
6668 public CompilerGeneratedThis (Type type, Location loc)
6674 public override Expression DoResolve (ResolveContext ec)
6676 eclass = ExprClass.Variable;
6678 type = ec.CurrentType;
6680 is_struct = type.IsValueType;
6684 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
6691 /// Represents the `this' construct
6694 public class This : VariableReference
6696 sealed class ThisVariable : ILocalVariable
6698 public static readonly ILocalVariable Instance = new ThisVariable ();
6700 public void Emit (EmitContext ec)
6702 ec.ig.Emit (OpCodes.Ldarg_0);
6705 public void EmitAssign (EmitContext ec)
6707 throw new InvalidOperationException ();
6710 public void EmitAddressOf (EmitContext ec)
6712 ec.ig.Emit (OpCodes.Ldarg_0);
6717 VariableInfo variable_info;
6718 protected bool is_struct;
6720 public This (Block block, Location loc)
6726 public This (Location loc)
6731 public override VariableInfo VariableInfo {
6732 get { return variable_info; }
6735 public override bool IsFixed {
6736 get { return false; }
6739 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
6744 AnonymousMethodStorey storey = ae.Storey;
6745 while (storey != null) {
6746 AnonymousMethodStorey temp = storey.Parent as AnonymousMethodStorey;
6748 return storey.HoistedThis;
6756 public override bool IsRef {
6757 get { return is_struct; }
6760 protected override ILocalVariable Variable {
6761 get { return ThisVariable.Instance; }
6764 public static bool IsThisAvailable (ResolveContext ec)
6766 if (ec.IsStatic || ec.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.BaseInitializer | ResolveContext.Options.ConstantScope))
6769 if (ec.CurrentAnonymousMethod == null)
6772 if (ec.CurrentType.IsValueType && ec.CurrentIterator == null)
6778 public bool ResolveBase (ResolveContext ec)
6780 if (eclass != ExprClass.Invalid)
6783 eclass = ExprClass.Variable;
6784 type = ec.CurrentType;
6786 if (!IsThisAvailable (ec)) {
6787 if (ec.IsStatic && !ec.HasSet (ResolveContext.Options.ConstantScope)) {
6788 ec.Report.Error (26, loc, "Keyword `this' is not valid in a static property, static method, or static field initializer");
6789 } else if (ec.CurrentAnonymousMethod != null) {
6790 ec.Report.Error (1673, loc,
6791 "Anonymous methods inside structs cannot access instance members of `this'. " +
6792 "Consider copying `this' to a local variable outside the anonymous method and using the local instead");
6794 ec.Report.Error (27, loc, "Keyword `this' is not available in the current context");
6798 is_struct = type.IsValueType;
6800 if (block != null) {
6801 if (block.Toplevel.ThisVariable != null)
6802 variable_info = block.Toplevel.ThisVariable.VariableInfo;
6804 AnonymousExpression am = ec.CurrentAnonymousMethod;
6805 if (am != null && ec.IsVariableCapturingRequired) {
6806 am.SetHasThisAccess ();
6814 // Called from Invocation to check if the invocation is correct
6816 public override void CheckMarshalByRefAccess (ResolveContext ec)
6818 if ((variable_info != null) && !(TypeManager.IsStruct (type) && ec.OmitStructFlowAnalysis) &&
6819 !variable_info.IsAssigned (ec)) {
6820 ec.Report.Error (188, loc,
6821 "The `this' object cannot be used before all of its fields are assigned to");
6822 variable_info.SetAssigned (ec);
6826 public override Expression CreateExpressionTree (ResolveContext ec)
6828 Arguments args = new Arguments (1);
6829 args.Add (new Argument (this));
6831 // Use typeless constant for ldarg.0 to save some
6832 // space and avoid problems with anonymous stories
6833 return CreateExpressionFactoryCall (ec, "Constant", args);
6836 public override Expression DoResolve (ResolveContext ec)
6842 override public Expression DoResolveLValue (ResolveContext ec, Expression right_side)
6844 if (!ResolveBase (ec))
6847 if (variable_info != null)
6848 variable_info.SetAssigned (ec);
6850 if (ec.CurrentType.IsClass){
6851 if (right_side == EmptyExpression.UnaryAddress)
6852 ec.Report.Error (459, loc, "Cannot take the address of `this' because it is read-only");
6853 else if (right_side == EmptyExpression.OutAccess)
6854 ec.Report.Error (1605, loc, "Cannot pass `this' as a ref or out argument because it is read-only");
6856 ec.Report.Error (1604, loc, "Cannot assign to `this' because it is read-only");
6862 public override int GetHashCode()
6864 return block.GetHashCode ();
6867 public override string Name {
6868 get { return "this"; }
6871 public override bool Equals (object obj)
6873 This t = obj as This;
6877 return block == t.block;
6880 protected override void CloneTo (CloneContext clonectx, Expression t)
6882 This target = (This) t;
6884 target.block = clonectx.LookupBlock (block);
6887 public override void SetHasAddressTaken ()
6894 /// Represents the `__arglist' construct
6896 public class ArglistAccess : Expression
6898 public ArglistAccess (Location loc)
6903 public override Expression CreateExpressionTree (ResolveContext ec)
6905 throw new NotSupportedException ("ET");
6908 public override Expression DoResolve (ResolveContext ec)
6910 eclass = ExprClass.Variable;
6911 type = TypeManager.runtime_argument_handle_type;
6913 if (ec.HasSet (ResolveContext.Options.FieldInitializerScope) || !ec.CurrentBlock.Toplevel.Parameters.HasArglist) {
6914 ec.Report.Error (190, loc,
6915 "The __arglist construct is valid only within a variable argument method");
6921 public override void Emit (EmitContext ec)
6923 ec.ig.Emit (OpCodes.Arglist);
6926 protected override void CloneTo (CloneContext clonectx, Expression target)
6933 /// Represents the `__arglist (....)' construct
6935 class Arglist : Expression
6937 Arguments Arguments;
6939 public Arglist (Location loc)
6944 public Arglist (Arguments args, Location l)
6950 public Type[] ArgumentTypes {
6952 if (Arguments == null)
6953 return Type.EmptyTypes;
6955 Type[] retval = new Type [Arguments.Count];
6956 for (int i = 0; i < retval.Length; i++)
6957 retval [i] = Arguments [i].Expr.Type;
6963 public override Expression CreateExpressionTree (ResolveContext ec)
6965 ec.Report.Error (1952, loc, "An expression tree cannot contain a method with variable arguments");
6969 public override Expression DoResolve (ResolveContext ec)
6971 eclass = ExprClass.Variable;
6972 type = InternalType.Arglist;
6973 if (Arguments != null) {
6974 bool dynamic; // Can be ignored as there is always only 1 overload
6975 Arguments.Resolve (ec, out dynamic);
6981 public override void Emit (EmitContext ec)
6983 if (Arguments != null)
6984 Arguments.Emit (ec);
6987 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
6989 if (Arguments != null)
6990 Arguments.MutateHoistedGenericType (storey);
6993 protected override void CloneTo (CloneContext clonectx, Expression t)
6995 Arglist target = (Arglist) t;
6997 if (Arguments != null)
6998 target.Arguments = Arguments.Clone (clonectx);
7003 /// Implements the typeof operator
7005 public class TypeOf : Expression {
7006 Expression QueriedType;
7007 protected Type typearg;
7009 public TypeOf (Expression queried_type, Location l)
7011 QueriedType = queried_type;
7015 public override Expression CreateExpressionTree (ResolveContext ec)
7017 Arguments args = new Arguments (2);
7018 args.Add (new Argument (this));
7019 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
7020 return CreateExpressionFactoryCall (ec, "Constant", args);
7023 public override Expression DoResolve (ResolveContext ec)
7025 if (eclass != ExprClass.Invalid)
7028 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
7032 typearg = texpr.Type;
7034 if (typearg == TypeManager.void_type) {
7035 ec.Report.Error (673, loc, "System.Void cannot be used from C#. Use typeof (void) to get the void type object");
7036 } else if (typearg.IsPointer && !ec.IsUnsafe){
7037 UnsafeError (ec, loc);
7038 } else if (texpr is DynamicTypeExpr) {
7039 ec.Report.Error (1962, QueriedType.Location,
7040 "The typeof operator cannot be used on the dynamic type");
7043 type = TypeManager.type_type;
7045 return DoResolveBase ();
7048 protected Expression DoResolveBase ()
7050 if (TypeManager.system_type_get_type_from_handle == null) {
7051 TypeManager.system_type_get_type_from_handle = TypeManager.GetPredefinedMethod (
7052 TypeManager.type_type, "GetTypeFromHandle", loc, TypeManager.runtime_handle_type);
7055 // Even though what is returned is a type object, it's treated as a value by the compiler.
7056 // In particular, 'typeof (Foo).X' is something totally different from 'Foo.X'.
7057 eclass = ExprClass.Value;
7061 public override void Emit (EmitContext ec)
7063 ec.ig.Emit (OpCodes.Ldtoken, TypeManager.TypeToReflectionType (typearg));
7064 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
7067 public override bool GetAttributableValue (ResolveContext ec, Type value_type, out object value)
7069 if (TypeManager.ContainsGenericParameters (typearg) &&
7070 !TypeManager.IsGenericTypeDefinition (typearg)) {
7071 ec.Report.SymbolRelatedToPreviousError (typearg);
7072 ec.Report.Error (416, loc, "`{0}': an attribute argument cannot use type parameters",
7073 TypeManager.CSharpName (typearg));
7078 if (value_type == TypeManager.object_type) {
7079 value = (object)typearg;
7086 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
7088 typearg = storey.MutateType (typearg);
7091 public Type TypeArgument {
7097 protected override void CloneTo (CloneContext clonectx, Expression t)
7099 TypeOf target = (TypeOf) t;
7100 if (QueriedType != null)
7101 target.QueriedType = QueriedType.Clone (clonectx);
7106 /// Implements the `typeof (void)' operator
7108 public class TypeOfVoid : TypeOf {
7109 public TypeOfVoid (Location l) : base (null, l)
7114 public override Expression DoResolve (ResolveContext ec)
7116 type = TypeManager.type_type;
7117 typearg = TypeManager.void_type;
7119 return DoResolveBase ();
7123 class TypeOfMethod : TypeOfMember
7125 public TypeOfMethod (MethodBase method, Location loc)
7126 : base (method, loc)
7130 public override Expression DoResolve (ResolveContext ec)
7132 if (member is MethodInfo) {
7133 type = TypeManager.methodinfo_type;
7135 type = TypeManager.methodinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", "MethodInfo", Kind.Class, true);
7137 type = TypeManager.ctorinfo_type;
7139 type = TypeManager.ctorinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", "ConstructorInfo", Kind.Class, true);
7142 return base.DoResolve (ec);
7145 public override void Emit (EmitContext ec)
7147 if (member is ConstructorInfo)
7148 ec.ig.Emit (OpCodes.Ldtoken, (ConstructorInfo) member);
7150 ec.ig.Emit (OpCodes.Ldtoken, (MethodInfo) member);
7153 ec.ig.Emit (OpCodes.Castclass, type);
7156 protected override string GetMethodName {
7157 get { return "GetMethodFromHandle"; }
7160 protected override string RuntimeHandleName {
7161 get { return "RuntimeMethodHandle"; }
7164 protected override MethodInfo TypeFromHandle {
7166 return TypeManager.methodbase_get_type_from_handle;
7169 TypeManager.methodbase_get_type_from_handle = value;
7173 protected override MethodInfo TypeFromHandleGeneric {
7175 return TypeManager.methodbase_get_type_from_handle_generic;
7178 TypeManager.methodbase_get_type_from_handle_generic = value;
7182 protected override string TypeName {
7183 get { return "MethodBase"; }
7187 abstract class TypeOfMember : Expression
7189 protected readonly MemberInfo member;
7191 protected TypeOfMember (MemberInfo member, Location loc)
7193 this.member = member;
7197 public override Expression CreateExpressionTree (ResolveContext ec)
7199 Arguments args = new Arguments (2);
7200 args.Add (new Argument (this));
7201 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
7202 return CreateExpressionFactoryCall (ec, "Constant", args);
7205 public override Expression DoResolve (ResolveContext ec)
7207 bool is_generic = TypeManager.IsGenericType (member.DeclaringType);
7208 MethodInfo mi = is_generic ? TypeFromHandleGeneric : TypeFromHandle;
7211 Type t = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", TypeName, Kind.Class, true);
7212 Type handle_type = TypeManager.CoreLookupType (ec.Compiler, "System", RuntimeHandleName, Kind.Class, true);
7214 if (t == null || handle_type == null)
7217 mi = TypeManager.GetPredefinedMethod (t, GetMethodName, loc,
7219 new Type[] { handle_type, TypeManager.runtime_handle_type } :
7220 new Type[] { handle_type } );
7223 TypeFromHandleGeneric = mi;
7225 TypeFromHandle = mi;
7228 eclass = ExprClass.Value;
7232 public override void Emit (EmitContext ec)
7234 bool is_generic = TypeManager.IsGenericType (member.DeclaringType);
7237 mi = TypeFromHandleGeneric;
7238 ec.ig.Emit (OpCodes.Ldtoken, member.DeclaringType);
7240 mi = TypeFromHandle;
7243 ec.ig.Emit (OpCodes.Call, mi);
7246 protected abstract string GetMethodName { get; }
7247 protected abstract string RuntimeHandleName { get; }
7248 protected abstract MethodInfo TypeFromHandle { get; set; }
7249 protected abstract MethodInfo TypeFromHandleGeneric { get; set; }
7250 protected abstract string TypeName { get; }
7253 class TypeOfField : TypeOfMember
7255 public TypeOfField (FieldInfo field, Location loc)
7260 public override Expression DoResolve (ResolveContext ec)
7262 if (TypeManager.fieldinfo_type == null)
7263 TypeManager.fieldinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", TypeName, Kind.Class, true);
7265 type = TypeManager.fieldinfo_type;
7266 return base.DoResolve (ec);
7269 public override void Emit (EmitContext ec)
7271 ec.ig.Emit (OpCodes.Ldtoken, (FieldInfo) member);
7275 protected override string GetMethodName {
7276 get { return "GetFieldFromHandle"; }
7279 protected override string RuntimeHandleName {
7280 get { return "RuntimeFieldHandle"; }
7283 protected override MethodInfo TypeFromHandle {
7285 return TypeManager.fieldinfo_get_field_from_handle;
7288 TypeManager.fieldinfo_get_field_from_handle = value;
7292 protected override MethodInfo TypeFromHandleGeneric {
7294 return TypeManager.fieldinfo_get_field_from_handle_generic;
7297 TypeManager.fieldinfo_get_field_from_handle_generic = value;
7301 protected override string TypeName {
7302 get { return "FieldInfo"; }
7307 /// Implements the sizeof expression
7309 public class SizeOf : Expression {
7310 readonly Expression QueriedType;
7313 public SizeOf (Expression queried_type, Location l)
7315 this.QueriedType = queried_type;
7319 public override Expression CreateExpressionTree (ResolveContext ec)
7321 Error_PointerInsideExpressionTree (ec);
7325 public override Expression DoResolve (ResolveContext ec)
7327 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
7331 type_queried = texpr.Type;
7332 if (TypeManager.IsEnumType (type_queried))
7333 type_queried = TypeManager.GetEnumUnderlyingType (type_queried);
7335 int size_of = GetTypeSize (type_queried);
7337 return new IntConstant (size_of, loc);
7340 if (!TypeManager.VerifyUnManaged (type_queried, loc)){
7345 ec.Report.Error (233, loc,
7346 "`{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)",
7347 TypeManager.CSharpName (type_queried));
7350 type = TypeManager.int32_type;
7351 eclass = ExprClass.Value;
7355 public override void Emit (EmitContext ec)
7357 int size = GetTypeSize (type_queried);
7360 ec.ig.Emit (OpCodes.Sizeof, type_queried);
7362 IntConstant.EmitInt (ec.ig, size);
7365 protected override void CloneTo (CloneContext clonectx, Expression t)
7371 /// Implements the qualified-alias-member (::) expression.
7373 public class QualifiedAliasMember : MemberAccess
7375 readonly string alias;
7376 public static readonly string GlobalAlias = "global";
7378 public QualifiedAliasMember (string alias, string identifier, TypeArguments targs, Location l)
7379 : base (null, identifier, targs, l)
7384 public QualifiedAliasMember (string alias, string identifier, Location l)
7385 : base (null, identifier, l)
7390 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
7392 if (alias == GlobalAlias) {
7393 expr = GlobalRootNamespace.Instance;
7394 return base.ResolveAsTypeStep (ec, silent);
7397 int errors = ec.Compiler.Report.Errors;
7398 expr = ec.LookupNamespaceAlias (alias);
7400 if (errors == ec.Compiler.Report.Errors)
7401 ec.Compiler.Report.Error (432, loc, "Alias `{0}' not found", alias);
7405 FullNamedExpression fne = base.ResolveAsTypeStep (ec, silent);
7409 if (expr.eclass == ExprClass.Type) {
7411 ec.Compiler.Report.Error (431, loc,
7412 "Alias `{0}' cannot be used with '::' since it denotes a type. Consider replacing '::' with '.'", alias);
7420 public override Expression DoResolve (ResolveContext ec)
7422 return ResolveAsTypeStep (ec, false);
7425 protected override void Error_IdentifierNotFound (IMemberContext rc, FullNamedExpression expr_type, string identifier)
7427 rc.Compiler.Report.Error (687, loc,
7428 "A namespace alias qualifier `{0}' did not resolve to a namespace or a type",
7429 GetSignatureForError ());
7432 public override string GetSignatureForError ()
7435 if (targs != null) {
7436 name = TypeManager.RemoveGenericArity (Name) + "<" +
7437 targs.GetSignatureForError () + ">";
7440 return alias + "::" + name;
7443 protected override void CloneTo (CloneContext clonectx, Expression t)
7450 /// Implements the member access expression
7452 public class MemberAccess : ATypeNameExpression {
7453 protected Expression expr;
7455 public MemberAccess (Expression expr, string id)
7456 : base (id, expr.Location)
7461 public MemberAccess (Expression expr, string identifier, Location loc)
7462 : base (identifier, loc)
7467 public MemberAccess (Expression expr, string identifier, TypeArguments args, Location loc)
7468 : base (identifier, args, loc)
7473 Expression DoResolve (ResolveContext ec, Expression right_side)
7476 throw new Exception ();
7479 // Resolve the expression with flow analysis turned off, we'll do the definite
7480 // assignment checks later. This is because we don't know yet what the expression
7481 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7482 // definite assignment check on the actual field and not on the whole struct.
7485 SimpleName original = expr as SimpleName;
7486 Expression expr_resolved = expr.Resolve (ec,
7487 ResolveFlags.VariableOrValue | ResolveFlags.Type |
7488 ResolveFlags.Intermediate | ResolveFlags.DisableStructFlowAnalysis);
7490 if (expr_resolved == null)
7493 string LookupIdentifier = MemberName.MakeName (Name, targs);
7495 Namespace ns = expr_resolved as Namespace;
7497 FullNamedExpression retval = ns.Lookup (ec.Compiler, LookupIdentifier, loc);
7500 ns.Error_NamespaceDoesNotExist (loc, LookupIdentifier, ec.Report);
7501 else if (targs != null)
7502 retval = new GenericTypeExpr (retval.Type, targs, loc).ResolveAsTypeStep (ec, false);
7507 Type expr_type = expr_resolved.Type;
7508 if (TypeManager.IsDynamicType (expr_type)) {
7509 Arguments args = new Arguments (2);
7510 args.Add (new Argument (expr_resolved.Resolve (ec)));
7511 if (right_side != null)
7512 args.Add (new Argument (right_side));
7514 return new DynamicMemberBinder (right_side != null, Name, args, loc).Resolve (ec);
7517 if (expr_type.IsPointer || expr_type == TypeManager.void_type ||
7518 expr_type == TypeManager.null_type || expr_type == InternalType.AnonymousMethod) {
7519 Unary.Error_OperatorCannotBeApplied (ec, loc, ".", expr_type);
7523 Constant c = expr_resolved as Constant;
7524 if (c != null && c.GetValue () == null) {
7525 ec.Report.Warning (1720, 1, loc, "Expression will always cause a `{0}'",
7526 "System.NullReferenceException");
7529 if (targs != null) {
7530 if (!targs.Resolve (ec))
7534 Expression member_lookup;
7535 member_lookup = MemberLookup (ec.Compiler,
7536 ec.CurrentType, expr_type, expr_type, Name, loc);
7538 if (member_lookup == null && targs != null) {
7539 member_lookup = MemberLookup (ec.Compiler,
7540 ec.CurrentType, expr_type, expr_type, LookupIdentifier, loc);
7543 if (member_lookup == null) {
7544 ExprClass expr_eclass = expr_resolved.eclass;
7547 // Extension methods are not allowed on all expression types
7549 if (expr_eclass == ExprClass.Value || expr_eclass == ExprClass.Variable ||
7550 expr_eclass == ExprClass.IndexerAccess || expr_eclass == ExprClass.PropertyAccess ||
7551 expr_eclass == ExprClass.EventAccess) {
7552 ExtensionMethodGroupExpr ex_method_lookup = ec.LookupExtensionMethod (expr_type, Name, loc);
7553 if (ex_method_lookup != null) {
7554 ex_method_lookup.ExtensionExpression = expr_resolved;
7556 if (targs != null) {
7557 ex_method_lookup.SetTypeArguments (ec, targs);
7560 return ex_method_lookup.DoResolve (ec);
7564 expr = expr_resolved;
7565 member_lookup = Error_MemberLookupFailed (ec,
7566 ec.CurrentType, expr_type, expr_type, Name, null,
7567 AllMemberTypes, AllBindingFlags);
7568 if (member_lookup == null)
7572 TypeExpr texpr = member_lookup as TypeExpr;
7573 if (texpr != null) {
7574 if (!(expr_resolved is TypeExpr) &&
7575 (original == null || !original.IdenticalNameAndTypeName (ec, expr_resolved, loc))) {
7576 ec.Report.Error (572, loc, "`{0}': cannot reference a type through an expression; try `{1}' instead",
7577 Name, member_lookup.GetSignatureForError ());
7581 if (!texpr.CheckAccessLevel (ec.MemberContext)) {
7582 ec.Report.SymbolRelatedToPreviousError (member_lookup.Type);
7583 ErrorIsInaccesible (loc, TypeManager.CSharpName (member_lookup.Type), ec.Report);
7587 GenericTypeExpr ct = expr_resolved as GenericTypeExpr;
7590 // When looking up a nested type in a generic instance
7591 // via reflection, we always get a generic type definition
7592 // and not a generic instance - so we have to do this here.
7594 // See gtest-172-lib.cs and gtest-172.cs for an example.
7597 TypeArguments nested_targs;
7598 if (HasTypeArguments) {
7599 nested_targs = ct.TypeArguments.Clone ();
7600 nested_targs.Add (targs);
7602 nested_targs = ct.TypeArguments;
7605 ct = new GenericTypeExpr (member_lookup.Type, nested_targs, loc);
7607 return ct.ResolveAsTypeStep (ec, false);
7610 return member_lookup;
7613 MemberExpr me = (MemberExpr) member_lookup;
7614 me = me.ResolveMemberAccess (ec, expr_resolved, loc, original);
7618 if (targs != null) {
7619 me.SetTypeArguments (ec, targs);
7622 if (original != null && !TypeManager.IsValueType (expr_type)) {
7623 if (me.IsInstance) {
7624 LocalVariableReference var = expr_resolved as LocalVariableReference;
7625 if (var != null && !var.VerifyAssigned (ec))
7630 // The following DoResolve/DoResolveLValue will do the definite assignment
7633 if (right_side != null)
7634 return me.DoResolveLValue (ec, right_side);
7636 return me.DoResolve (ec);
7639 public override Expression DoResolve (ResolveContext ec)
7641 return DoResolve (ec, null);
7644 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
7646 return DoResolve (ec, right_side);
7649 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
7651 return ResolveNamespaceOrType (ec, silent);
7654 public FullNamedExpression ResolveNamespaceOrType (IMemberContext rc, bool silent)
7656 FullNamedExpression expr_resolved = expr.ResolveAsTypeStep (rc, silent);
7658 if (expr_resolved == null)
7661 string LookupIdentifier = MemberName.MakeName (Name, targs);
7663 Namespace ns = expr_resolved as Namespace;
7665 FullNamedExpression retval = ns.Lookup (rc.Compiler, LookupIdentifier, loc);
7667 if (retval == null && !silent)
7668 ns.Error_NamespaceDoesNotExist (loc, LookupIdentifier, rc.Compiler.Report);
7669 else if (targs != null)
7670 retval = new GenericTypeExpr (retval.Type, targs, loc).ResolveAsTypeStep (rc, silent);
7675 TypeExpr tnew_expr = expr_resolved.ResolveAsTypeTerminal (rc, false);
7676 if (tnew_expr == null)
7679 Type expr_type = tnew_expr.Type;
7680 if (TypeManager.IsGenericParameter (expr_type)) {
7681 rc.Compiler.Report.Error (704, loc, "A nested type cannot be specified through a type parameter `{0}'",
7682 tnew_expr.GetSignatureForError ());
7686 Expression member_lookup = MemberLookup (rc.Compiler,
7687 rc.CurrentType, expr_type, expr_type, LookupIdentifier,
7688 MemberTypes.NestedType, BindingFlags.Public | BindingFlags.NonPublic, loc);
7689 if (member_lookup == null) {
7693 Error_IdentifierNotFound (rc, expr_resolved, LookupIdentifier);
7697 TypeExpr texpr = member_lookup.ResolveAsTypeTerminal (rc, false);
7701 TypeArguments the_args = targs;
7702 Type declaring_type = texpr.Type.DeclaringType;
7703 if (TypeManager.HasGenericArguments (declaring_type) && !TypeManager.IsGenericTypeDefinition (expr_type)) {
7704 while (!TypeManager.IsEqual (TypeManager.DropGenericTypeArguments (expr_type), declaring_type)) {
7705 expr_type = expr_type.BaseType;
7708 TypeArguments new_args = new TypeArguments ();
7709 foreach (Type decl in TypeManager.GetTypeArguments (expr_type))
7710 new_args.Add (new TypeExpression (TypeManager.TypeToCoreType (decl), loc));
7713 new_args.Add (targs);
7715 the_args = new_args;
7718 if (the_args != null) {
7719 GenericTypeExpr ctype = new GenericTypeExpr (texpr.Type, the_args, loc);
7720 return ctype.ResolveAsTypeStep (rc, false);
7726 protected virtual void Error_IdentifierNotFound (IMemberContext rc, FullNamedExpression expr_type, string identifier)
7728 Expression member_lookup = MemberLookup (rc.Compiler,
7729 rc.CurrentType, expr_type.Type, expr_type.Type, SimpleName.RemoveGenericArity (identifier),
7730 MemberTypes.NestedType, BindingFlags.Public | BindingFlags.NonPublic, loc);
7732 if (member_lookup != null) {
7733 expr_type = member_lookup.ResolveAsTypeTerminal (rc, false);
7734 if (expr_type == null)
7737 Namespace.Error_TypeArgumentsCannotBeUsed (expr_type, loc);
7741 member_lookup = MemberLookup (rc.Compiler,
7742 rc.CurrentType, expr_type.Type, expr_type.Type, identifier,
7743 MemberTypes.All, BindingFlags.Public | BindingFlags.NonPublic, loc);
7745 if (member_lookup == null) {
7746 rc.Compiler.Report.Error (426, loc, "The nested type `{0}' does not exist in the type `{1}'",
7747 Name, expr_type.GetSignatureForError ());
7749 // TODO: Report.SymbolRelatedToPreviousError
7750 member_lookup.Error_UnexpectedKind (rc.Compiler.Report, null, "type", loc);
7754 protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, Type type, string name)
7756 if (RootContext.Version > LanguageVersion.ISO_2 &&
7757 ((expr.eclass & (ExprClass.Value | ExprClass.Variable)) != 0)) {
7758 ec.Report.Error (1061, loc, "Type `{0}' does not contain a definition for `{1}' and no " +
7759 "extension method `{1}' of type `{0}' could be found " +
7760 "(are you missing a using directive or an assembly reference?)",
7761 TypeManager.CSharpName (type), name);
7765 base.Error_TypeDoesNotContainDefinition (ec, type, name);
7768 public override string GetSignatureForError ()
7770 return expr.GetSignatureForError () + "." + base.GetSignatureForError ();
7773 public Expression Left {
7779 protected override void CloneTo (CloneContext clonectx, Expression t)
7781 MemberAccess target = (MemberAccess) t;
7783 target.expr = expr.Clone (clonectx);
7788 /// Implements checked expressions
7790 public class CheckedExpr : Expression {
7792 public Expression Expr;
7794 public CheckedExpr (Expression e, Location l)
7800 public override Expression CreateExpressionTree (ResolveContext ec)
7802 using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
7803 return Expr.CreateExpressionTree (ec);
7806 public override Expression DoResolve (ResolveContext ec)
7808 using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
7809 Expr = Expr.Resolve (ec);
7814 if (Expr is Constant || Expr is MethodGroupExpr || Expr is AnonymousMethodExpression || Expr is DefaultValueExpression)
7817 eclass = Expr.eclass;
7822 public override void Emit (EmitContext ec)
7824 using (ec.With (EmitContext.Options.AllCheckStateFlags, true))
7828 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
7830 using (ec.With (EmitContext.Options.AllCheckStateFlags, true))
7831 Expr.EmitBranchable (ec, target, on_true);
7835 public override SLE.Expression MakeExpression (BuilderContext ctx)
7837 using (ctx.With (BuilderContext.Options.AllCheckStateFlags, true)) {
7838 return Expr.MakeExpression (ctx);
7843 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
7845 Expr.MutateHoistedGenericType (storey);
7848 protected override void CloneTo (CloneContext clonectx, Expression t)
7850 CheckedExpr target = (CheckedExpr) t;
7852 target.Expr = Expr.Clone (clonectx);
7857 /// Implements the unchecked expression
7859 public class UnCheckedExpr : Expression {
7861 public Expression Expr;
7863 public UnCheckedExpr (Expression e, Location l)
7869 public override Expression CreateExpressionTree (ResolveContext ec)
7871 using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
7872 return Expr.CreateExpressionTree (ec);
7875 public override Expression DoResolve (ResolveContext ec)
7877 using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
7878 Expr = Expr.Resolve (ec);
7883 if (Expr is Constant || Expr is MethodGroupExpr || Expr is AnonymousMethodExpression || Expr is DefaultValueExpression)
7886 eclass = Expr.eclass;
7891 public override void Emit (EmitContext ec)
7893 using (ec.With (EmitContext.Options.AllCheckStateFlags, false))
7897 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
7899 using (ec.With (EmitContext.Options.AllCheckStateFlags, false))
7900 Expr.EmitBranchable (ec, target, on_true);
7903 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
7905 Expr.MutateHoistedGenericType (storey);
7908 protected override void CloneTo (CloneContext clonectx, Expression t)
7910 UnCheckedExpr target = (UnCheckedExpr) t;
7912 target.Expr = Expr.Clone (clonectx);
7917 /// An Element Access expression.
7919 /// During semantic analysis these are transformed into
7920 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7922 public class ElementAccess : Expression {
7923 public Arguments Arguments;
7924 public Expression Expr;
7926 public ElementAccess (Expression e, Arguments args)
7930 this.Arguments = args;
7933 public override Expression CreateExpressionTree (ResolveContext ec)
7935 Arguments args = Arguments.CreateForExpressionTree (ec, Arguments,
7936 Expr.CreateExpressionTree (ec));
7938 return CreateExpressionFactoryCall (ec, "ArrayIndex", args);
7941 Expression MakePointerAccess (ResolveContext ec, Type t)
7943 if (Arguments.Count != 1){
7944 ec.Report.Error (196, loc, "A pointer must be indexed by only one value");
7948 if (Arguments [0] is NamedArgument)
7949 Error_NamedArgument ((NamedArgument) Arguments[0], ec.Report);
7951 Expression p = new PointerArithmetic (Binary.Operator.Addition, Expr, Arguments [0].Expr.Resolve (ec), t, loc);
7952 return new Indirection (p, loc).Resolve (ec);
7955 public override Expression DoResolve (ResolveContext ec)
7957 Expr = Expr.Resolve (ec);
7962 // We perform some simple tests, and then to "split" the emit and store
7963 // code we create an instance of a different class, and return that.
7965 // I am experimenting with this pattern.
7969 if (t == TypeManager.array_type){
7970 ec.Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `System.Array'");
7975 return (new ArrayAccess (this, loc)).Resolve (ec);
7977 return MakePointerAccess (ec, t);
7979 FieldExpr fe = Expr as FieldExpr;
7981 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
7983 return MakePointerAccess (ec, ff.ElementType);
7986 return (new IndexerAccess (this, loc)).Resolve (ec);
7989 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
7991 Expr = Expr.Resolve (ec);
7997 return (new ArrayAccess (this, loc)).DoResolveLValue (ec, right_side);
8000 return MakePointerAccess (ec, type);
8002 if (Expr.eclass != ExprClass.Variable && TypeManager.IsStruct (type))
8003 Error_CannotModifyIntermediateExpressionValue (ec);
8005 return (new IndexerAccess (this, loc)).DoResolveLValue (ec, right_side);
8008 public override void Emit (EmitContext ec)
8010 throw new Exception ("Should never be reached");
8013 public static void Error_NamedArgument (NamedArgument na, Report Report)
8015 Report.Error (1742, na.Name.Location, "An element access expression cannot use named argument");
8018 public override string GetSignatureForError ()
8020 return Expr.GetSignatureForError ();
8023 protected override void CloneTo (CloneContext clonectx, Expression t)
8025 ElementAccess target = (ElementAccess) t;
8027 target.Expr = Expr.Clone (clonectx);
8028 if (Arguments != null)
8029 target.Arguments = Arguments.Clone (clonectx);
8034 /// Implements array access
8036 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
8038 // Points to our "data" repository
8042 LocalTemporary temp;
8046 public ArrayAccess (ElementAccess ea_data, Location l)
8052 public override Expression CreateExpressionTree (ResolveContext ec)
8054 return ea.CreateExpressionTree (ec);
8057 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
8059 return DoResolve (ec);
8062 public override Expression DoResolve (ResolveContext ec)
8065 ExprClass eclass = ea.Expr.eclass;
8067 // As long as the type is valid
8068 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
8069 eclass == ExprClass.Value)) {
8070 ea.Expr.Error_UnexpectedKind ("variable or value");
8075 if (eclass != ExprClass.Invalid)
8078 // dynamic is used per argument in ConvertExpressionToArrayIndex case
8080 ea.Arguments.Resolve (ec, out dynamic);
8082 Type t = ea.Expr.Type;
8083 int rank = ea.Arguments.Count;
8084 if (t.GetArrayRank () != rank) {
8085 ec.Report.Error (22, ea.Location, "Wrong number of indexes `{0}' inside [], expected `{1}'",
8086 ea.Arguments.Count.ToString (), t.GetArrayRank ().ToString ());
8090 type = TypeManager.GetElementType (t);
8091 if (type.IsPointer && !ec.IsUnsafe) {
8092 UnsafeError (ec, ea.Location);
8095 foreach (Argument a in ea.Arguments) {
8096 if (a is NamedArgument)
8097 ElementAccess.Error_NamedArgument ((NamedArgument) a, ec.Report);
8099 a.Expr = ConvertExpressionToArrayIndex (ec, a.Expr);
8102 eclass = ExprClass.Variable;
8108 /// Emits the right opcode to load an object of Type `t'
8109 /// from an array of T
8111 void EmitLoadOpcode (ILGenerator ig, Type type, int rank)
8114 MethodInfo get = FetchGetMethod ();
8115 ig.Emit (OpCodes.Call, get);
8119 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
8120 ig.Emit (OpCodes.Ldelem_U1);
8121 else if (type == TypeManager.sbyte_type)
8122 ig.Emit (OpCodes.Ldelem_I1);
8123 else if (type == TypeManager.short_type)
8124 ig.Emit (OpCodes.Ldelem_I2);
8125 else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
8126 ig.Emit (OpCodes.Ldelem_U2);
8127 else if (type == TypeManager.int32_type)
8128 ig.Emit (OpCodes.Ldelem_I4);
8129 else if (type == TypeManager.uint32_type)
8130 ig.Emit (OpCodes.Ldelem_U4);
8131 else if (type == TypeManager.uint64_type)
8132 ig.Emit (OpCodes.Ldelem_I8);
8133 else if (type == TypeManager.int64_type)
8134 ig.Emit (OpCodes.Ldelem_I8);
8135 else if (type == TypeManager.float_type)
8136 ig.Emit (OpCodes.Ldelem_R4);
8137 else if (type == TypeManager.double_type)
8138 ig.Emit (OpCodes.Ldelem_R8);
8139 else if (type == TypeManager.intptr_type)
8140 ig.Emit (OpCodes.Ldelem_I);
8141 else if (TypeManager.IsEnumType (type)){
8142 EmitLoadOpcode (ig, TypeManager.GetEnumUnderlyingType (type), rank);
8143 } else if (TypeManager.IsStruct (type)){
8144 ig.Emit (OpCodes.Ldelema, type);
8145 ig.Emit (OpCodes.Ldobj, type);
8147 } else if (type.IsGenericParameter) {
8148 ig.Emit (OpCodes.Ldelem, type);
8150 } else if (type.IsPointer)
8151 ig.Emit (OpCodes.Ldelem_I);
8153 ig.Emit (OpCodes.Ldelem_Ref);
8156 protected override void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
8158 ec.Report.Warning (251, 2, loc, "Indexing an array with a negative index (array indices always start at zero)");
8162 /// Returns the right opcode to store an object of Type `t'
8163 /// from an array of T.
8165 static public OpCode GetStoreOpcode (Type t, out bool is_stobj, out bool has_type_arg)
8167 has_type_arg = false; is_stobj = false;
8168 t = TypeManager.TypeToCoreType (t);
8169 if (TypeManager.IsEnumType (t))
8170 t = TypeManager.GetEnumUnderlyingType (t);
8171 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
8172 t == TypeManager.bool_type)
8173 return OpCodes.Stelem_I1;
8174 else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
8175 t == TypeManager.char_type)
8176 return OpCodes.Stelem_I2;
8177 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
8178 return OpCodes.Stelem_I4;
8179 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
8180 return OpCodes.Stelem_I8;
8181 else if (t == TypeManager.float_type)
8182 return OpCodes.Stelem_R4;
8183 else if (t == TypeManager.double_type)
8184 return OpCodes.Stelem_R8;
8185 else if (t == TypeManager.intptr_type) {
8186 has_type_arg = true;
8188 return OpCodes.Stobj;
8189 } else if (TypeManager.IsStruct (t)) {
8190 has_type_arg = true;
8192 return OpCodes.Stobj;
8194 } else if (t.IsGenericParameter) {
8195 has_type_arg = true;
8196 return OpCodes.Stelem;
8199 } else if (t.IsPointer)
8200 return OpCodes.Stelem_I;
8202 return OpCodes.Stelem_Ref;
8205 MethodInfo FetchGetMethod ()
8207 ModuleBuilder mb = RootContext.ToplevelTypes.Builder;
8208 int arg_count = ea.Arguments.Count;
8209 Type [] args = new Type [arg_count];
8212 for (int i = 0; i < arg_count; i++){
8213 //args [i++] = a.Type;
8214 args [i] = TypeManager.int32_type;
8217 get = mb.GetArrayMethod (
8218 ea.Expr.Type, "Get",
8219 CallingConventions.HasThis |
8220 CallingConventions.Standard,
8226 MethodInfo FetchAddressMethod ()
8228 ModuleBuilder mb = RootContext.ToplevelTypes.Builder;
8229 int arg_count = ea.Arguments.Count;
8230 Type [] args = new Type [arg_count];
8234 ret_type = TypeManager.GetReferenceType (type);
8236 for (int i = 0; i < arg_count; i++){
8237 //args [i++] = a.Type;
8238 args [i] = TypeManager.int32_type;
8241 address = mb.GetArrayMethod (
8242 ea.Expr.Type, "Address",
8243 CallingConventions.HasThis |
8244 CallingConventions.Standard,
8251 // Load the array arguments into the stack.
8253 void LoadArrayAndArguments (EmitContext ec)
8257 for (int i = 0; i < ea.Arguments.Count; ++i) {
8258 ea.Arguments [i].Emit (ec);
8262 public void Emit (EmitContext ec, bool leave_copy)
8264 int rank = ea.Expr.Type.GetArrayRank ();
8265 ILGenerator ig = ec.ig;
8268 LoadFromPtr (ig, this.type);
8270 LoadArrayAndArguments (ec);
8271 EmitLoadOpcode (ig, type, rank);
8275 ig.Emit (OpCodes.Dup);
8276 temp = new LocalTemporary (this.type);
8281 public override void Emit (EmitContext ec)
8286 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8288 int rank = ea.Expr.Type.GetArrayRank ();
8289 ILGenerator ig = ec.ig;
8290 Type t = source.Type;
8291 prepared = prepare_for_load;
8294 AddressOf (ec, AddressOp.LoadStore);
8295 ec.ig.Emit (OpCodes.Dup);
8297 LoadArrayAndArguments (ec);
8301 bool is_stobj, has_type_arg;
8302 OpCode op = GetStoreOpcode (t, out is_stobj, out has_type_arg);
8306 // The stobj opcode used by value types will need
8307 // an address on the stack, not really an array/array
8311 ig.Emit (OpCodes.Ldelema, t);
8316 ec.ig.Emit (OpCodes.Dup);
8317 temp = new LocalTemporary (this.type);
8322 StoreFromPtr (ig, t);
8324 ig.Emit (OpCodes.Stobj, t);
8325 else if (has_type_arg)
8332 ec.ig.Emit (OpCodes.Dup);
8333 temp = new LocalTemporary (this.type);
8338 StoreFromPtr (ig, t);
8340 int arg_count = ea.Arguments.Count;
8341 Type [] args = new Type [arg_count + 1];
8342 for (int i = 0; i < arg_count; i++) {
8343 //args [i++] = a.Type;
8344 args [i] = TypeManager.int32_type;
8346 args [arg_count] = type;
8348 MethodInfo set = RootContext.ToplevelTypes.Builder.GetArrayMethod (
8349 ea.Expr.Type, "Set",
8350 CallingConventions.HasThis |
8351 CallingConventions.Standard,
8352 TypeManager.void_type, args);
8354 ig.Emit (OpCodes.Call, set);
8364 public void EmitNew (EmitContext ec, New source, bool leave_copy)
8366 if (!source.Emit (ec, this)) {
8368 throw new NotImplementedException ();
8373 throw new NotImplementedException ();
8376 public void AddressOf (EmitContext ec, AddressOp mode)
8378 int rank = ea.Expr.Type.GetArrayRank ();
8379 ILGenerator ig = ec.ig;
8381 LoadArrayAndArguments (ec);
8384 ig.Emit (OpCodes.Ldelema, type);
8386 MethodInfo address = FetchAddressMethod ();
8387 ig.Emit (OpCodes.Call, address);
8391 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
8393 type = storey.MutateType (type);
8394 ea.Expr.Type = storey.MutateType (ea.Expr.Type);
8399 /// Expressions that represent an indexer call.
8401 public class IndexerAccess : Expression, IAssignMethod
8403 class IndexerMethodGroupExpr : MethodGroupExpr
8405 public IndexerMethodGroupExpr (Indexers indexers, Location loc)
8408 Methods = (MethodBase []) indexers.Methods.ToArray (typeof (MethodBase));
8411 public override string Name {
8417 protected override int GetApplicableParametersCount (MethodBase method, AParametersCollection parameters)
8420 // Here is the trick, decrease number of arguments by 1 when only
8421 // available property method is setter. This makes overload resolution
8422 // work correctly for indexers.
8425 if (method.Name [0] == 'g')
8426 return parameters.Count;
8428 return parameters.Count - 1;
8434 // Contains either property getter or setter
8435 public ArrayList Methods;
8436 public ArrayList Properties;
8442 void Append (Type caller_type, MemberInfo [] mi)
8447 foreach (PropertyInfo property in mi) {
8448 MethodInfo accessor = property.GetGetMethod (true);
8449 if (accessor == null)
8450 accessor = property.GetSetMethod (true);
8452 if (Methods == null) {
8453 Methods = new ArrayList ();
8454 Properties = new ArrayList ();
8457 Methods.Add (accessor);
8458 Properties.Add (property);
8462 static MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
8464 string p_name = TypeManager.IndexerPropertyName (lookup_type);
8466 return TypeManager.MemberLookup (
8467 caller_type, caller_type, lookup_type, MemberTypes.Property,
8468 BindingFlags.Public | BindingFlags.Instance |
8469 BindingFlags.DeclaredOnly, p_name, null);
8472 public static Indexers GetIndexersForType (Type caller_type, Type lookup_type)
8474 Indexers ix = new Indexers ();
8476 if (TypeManager.IsGenericParameter (lookup_type)) {
8477 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (lookup_type);
8481 if (gc.HasClassConstraint) {
8482 Type class_contraint = gc.ClassConstraint;
8483 while (class_contraint != TypeManager.object_type && class_contraint != null) {
8484 ix.Append (caller_type, GetIndexersForTypeOrInterface (caller_type, class_contraint));
8485 class_contraint = class_contraint.BaseType;
8489 Type[] ifaces = gc.InterfaceConstraints;
8490 foreach (Type itype in ifaces)
8491 ix.Append (caller_type, GetIndexersForTypeOrInterface (caller_type, itype));
8496 Type copy = lookup_type;
8497 while (copy != TypeManager.object_type && copy != null){
8498 ix.Append (caller_type, GetIndexersForTypeOrInterface (caller_type, copy));
8499 copy = copy.BaseType;
8502 if (lookup_type.IsInterface) {
8503 Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
8504 if (ifaces != null) {
8505 foreach (Type itype in ifaces)
8506 ix.Append (caller_type, GetIndexersForTypeOrInterface (caller_type, itype));
8515 // Points to our "data" repository
8517 MethodInfo get, set;
8518 bool is_base_indexer;
8520 LocalTemporary temp;
8521 LocalTemporary prepared_value;
8522 Expression set_expr;
8524 protected Type indexer_type;
8525 protected Type current_type;
8526 protected Expression instance_expr;
8527 protected Arguments arguments;
8529 public IndexerAccess (ElementAccess ea, Location loc)
8530 : this (ea.Expr, false, loc)
8532 this.arguments = ea.Arguments;
8535 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
8538 this.instance_expr = instance_expr;
8539 this.is_base_indexer = is_base_indexer;
8540 this.eclass = ExprClass.Value;
8544 static string GetAccessorName (bool isSet)
8546 return isSet ? "set" : "get";
8549 public override Expression CreateExpressionTree (ResolveContext ec)
8551 Arguments args = Arguments.CreateForExpressionTree (ec, arguments,
8552 instance_expr.CreateExpressionTree (ec),
8553 new TypeOfMethod (get, loc));
8555 return CreateExpressionFactoryCall (ec, "Call", args);
8558 protected virtual void CommonResolve (ResolveContext ec)
8560 indexer_type = instance_expr.Type;
8561 current_type = ec.CurrentType;
8564 public override Expression DoResolve (ResolveContext ec)
8566 return ResolveAccessor (ec, null);
8569 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
8571 if (right_side == EmptyExpression.OutAccess) {
8572 ec.Report.Error (206, loc,
8573 "A property or indexer may not be passed as an out or ref parameter");
8577 // if the indexer returns a value type, and we try to set a field in it
8578 if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess) {
8579 Error_CannotModifyIntermediateExpressionValue (ec);
8582 return ResolveAccessor (ec, right_side);
8585 Expression ResolveAccessor (ResolveContext ec, Expression right_side)
8590 arguments.Resolve (ec, out dynamic);
8591 if (dynamic || TypeManager.IsDynamicType (indexer_type)) {
8592 int additional = right_side == null ? 1 : 2;
8593 Arguments args = new Arguments (arguments.Count + additional);
8594 if (is_base_indexer) {
8595 ec.Report.Error (1972, loc, "The indexer base access cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access");
8597 args.Add (new Argument (instance_expr));
8599 args.AddRange (arguments);
8600 if (right_side != null)
8601 args.Add (new Argument (right_side));
8603 return new DynamicIndexBinder (right_side != null, args, loc).Resolve (ec);
8606 Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type);
8607 if (ilist.Methods == null) {
8608 ec.Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
8609 TypeManager.CSharpName (indexer_type));
8613 MethodGroupExpr mg = new IndexerMethodGroupExpr (ilist, loc);
8614 mg = mg.OverloadResolve (ec, ref arguments, false, loc);
8618 MethodInfo mi = (MethodInfo) mg;
8619 PropertyInfo pi = null;
8620 for (int i = 0; i < ilist.Methods.Count; ++i) {
8621 if (ilist.Methods [i] == mi) {
8622 pi = (PropertyInfo) ilist.Properties [i];
8627 type = TypeManager.TypeToCoreType (pi.PropertyType);
8628 if (type.IsPointer && !ec.IsUnsafe)
8629 UnsafeError (ec, loc);
8631 MethodInfo accessor;
8632 if (right_side == null) {
8633 accessor = get = pi.GetGetMethod (true);
8635 accessor = set = pi.GetSetMethod (true);
8636 if (accessor == null && pi.GetGetMethod (true) != null) {
8637 ec.Report.SymbolRelatedToPreviousError (pi);
8638 ec.Report.Error (200, loc, "The read only property or indexer `{0}' cannot be assigned to",
8639 TypeManager.GetFullNameSignature (pi));
8643 set_expr = Convert.ImplicitConversion (ec, right_side, type, loc);
8646 if (accessor == null) {
8647 ec.Report.SymbolRelatedToPreviousError (pi);
8648 ec.Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks a `{1}' accessor",
8649 TypeManager.GetFullNameSignature (pi), GetAccessorName (right_side != null));
8654 // Only base will allow this invocation to happen.
8656 if (accessor.IsAbstract && this is BaseIndexerAccess) {
8657 Error_CannotCallAbstractBase (ec, TypeManager.GetFullNameSignature (pi));
8660 bool must_do_cs1540_check;
8661 if (!IsAccessorAccessible (ec.CurrentType, accessor, out must_do_cs1540_check)) {
8663 set = pi.GetSetMethod (true);
8665 get = pi.GetGetMethod (true);
8667 if (set != null && get != null &&
8668 (set.Attributes & MethodAttributes.MemberAccessMask) != (get.Attributes & MethodAttributes.MemberAccessMask)) {
8669 ec.Report.SymbolRelatedToPreviousError (accessor);
8670 ec.Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because a `{1}' accessor is inaccessible",
8671 TypeManager.GetFullNameSignature (pi), GetAccessorName (right_side != null));
8673 ec.Report.SymbolRelatedToPreviousError (pi);
8674 ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (pi), ec.Report);
8678 instance_expr.CheckMarshalByRefAccess (ec);
8679 eclass = ExprClass.IndexerAccess;
8683 public void Emit (EmitContext ec, bool leave_copy)
8686 prepared_value.Emit (ec);
8688 Invocation.EmitCall (ec, is_base_indexer, instance_expr, get,
8689 arguments, loc, false, false);
8693 ec.ig.Emit (OpCodes.Dup);
8694 temp = new LocalTemporary (Type);
8700 // source is ignored, because we already have a copy of it from the
8701 // LValue resolution and we have already constructed a pre-cached
8702 // version of the arguments (ea.set_arguments);
8704 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8706 prepared = prepare_for_load;
8707 Expression value = set_expr;
8710 Invocation.EmitCall (ec, is_base_indexer, instance_expr, get,
8711 arguments, loc, true, false);
8713 prepared_value = new LocalTemporary (type);
8714 prepared_value.Store (ec);
8716 prepared_value.Release (ec);
8719 ec.ig.Emit (OpCodes.Dup);
8720 temp = new LocalTemporary (Type);
8723 } else if (leave_copy) {
8724 temp = new LocalTemporary (Type);
8731 arguments.Add (new Argument (value));
8733 Invocation.EmitCall (ec, is_base_indexer, instance_expr, set, arguments, loc, false, prepared);
8741 public override void Emit (EmitContext ec)
8746 public override string GetSignatureForError ()
8748 return TypeManager.CSharpSignature (get != null ? get : set, false);
8751 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
8754 get = storey.MutateGenericMethod (get);
8756 set = storey.MutateGenericMethod (set);
8758 instance_expr.MutateHoistedGenericType (storey);
8759 if (arguments != null)
8760 arguments.MutateHoistedGenericType (storey);
8762 type = storey.MutateType (type);
8765 protected override void CloneTo (CloneContext clonectx, Expression t)
8767 IndexerAccess target = (IndexerAccess) t;
8769 if (arguments != null)
8770 target.arguments = arguments.Clone (clonectx);
8772 if (instance_expr != null)
8773 target.instance_expr = instance_expr.Clone (clonectx);
8778 /// The base operator for method names
8780 public class BaseAccess : Expression {
8781 public readonly string Identifier;
8784 public BaseAccess (string member, Location l)
8786 this.Identifier = member;
8790 public BaseAccess (string member, TypeArguments args, Location l)
8796 public override Expression CreateExpressionTree (ResolveContext ec)
8798 throw new NotSupportedException ("ET");
8801 public override Expression DoResolve (ResolveContext ec)
8803 Expression c = CommonResolve (ec);
8809 // MethodGroups use this opportunity to flag an error on lacking ()
8811 if (!(c is MethodGroupExpr))
8812 return c.Resolve (ec);
8816 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
8818 Expression c = CommonResolve (ec);
8824 // MethodGroups use this opportunity to flag an error on lacking ()
8826 if (! (c is MethodGroupExpr))
8827 return c.DoResolveLValue (ec, right_side);
8832 Expression CommonResolve (ResolveContext ec)
8834 Expression member_lookup;
8835 Type current_type = ec.CurrentType;
8836 Type base_type = current_type.BaseType;
8838 if (!This.IsThisAvailable (ec)) {
8840 ec.Report.Error (1511, loc, "Keyword `base' is not available in a static method");
8842 ec.Report.Error (1512, loc, "Keyword `base' is not available in the current context");
8847 member_lookup = MemberLookup (ec.Compiler, ec.CurrentType, null, base_type, Identifier,
8848 AllMemberTypes, AllBindingFlags, loc);
8849 if (member_lookup == null) {
8850 Error_MemberLookupFailed (ec, ec.CurrentType, base_type, base_type, Identifier,
8851 null, AllMemberTypes, AllBindingFlags);
8858 left = new TypeExpression (base_type, loc);
8860 left = ec.GetThis (loc);
8862 MemberExpr me = member_lookup as MemberExpr;
8864 if (member_lookup is TypeExpression){
8865 ec.Report.Error (582, loc, "{0}: Can not reference a type through an expression, try `{1}' instead",
8866 Identifier, member_lookup.GetSignatureForError ());
8868 ec.Report.Error (582, loc, "{0}: Can not reference a {1} through an expression",
8869 Identifier, member_lookup.ExprClassName);
8875 me = me.ResolveMemberAccess (ec, left, loc, null);
8882 me.SetTypeArguments (ec, args);
8888 public override void Emit (EmitContext ec)
8890 throw new Exception ("Should never be called");
8893 protected override void CloneTo (CloneContext clonectx, Expression t)
8895 BaseAccess target = (BaseAccess) t;
8898 target.args = args.Clone ();
8903 /// The base indexer operator
8905 public class BaseIndexerAccess : IndexerAccess {
8906 public BaseIndexerAccess (Arguments args, Location loc)
8907 : base (null, true, loc)
8909 this.arguments = args;
8912 protected override void CommonResolve (ResolveContext ec)
8914 instance_expr = ec.GetThis (loc);
8916 current_type = ec.CurrentType.BaseType;
8917 indexer_type = current_type;
8920 public override Expression CreateExpressionTree (ResolveContext ec)
8922 MemberExpr.Error_BaseAccessInExpressionTree (ec, loc);
8923 return base.CreateExpressionTree (ec);
8928 /// This class exists solely to pass the Type around and to be a dummy
8929 /// that can be passed to the conversion functions (this is used by
8930 /// foreach implementation to typecast the object return value from
8931 /// get_Current into the proper type. All code has been generated and
8932 /// we only care about the side effect conversions to be performed
8934 /// This is also now used as a placeholder where a no-action expression
8935 /// is needed (the `New' class).
8937 public class EmptyExpression : Expression {
8938 public static readonly Expression Null = new EmptyExpression ();
8940 public static readonly EmptyExpression OutAccess = new EmptyExpression ();
8941 public static readonly EmptyExpression LValueMemberAccess = new EmptyExpression ();
8942 public static readonly EmptyExpression LValueMemberOutAccess = new EmptyExpression ();
8943 public static readonly EmptyExpression UnaryAddress = new EmptyExpression ();
8945 static EmptyExpression temp = new EmptyExpression ();
8946 public static EmptyExpression Grab ()
8948 EmptyExpression retval = temp == null ? new EmptyExpression () : temp;
8953 public static void Release (EmptyExpression e)
8960 // FIXME: Don't set to object
8961 type = TypeManager.object_type;
8962 eclass = ExprClass.Value;
8963 loc = Location.Null;
8966 public EmptyExpression (Type t)
8969 eclass = ExprClass.Value;
8970 loc = Location.Null;
8973 public override Expression CreateExpressionTree (ResolveContext ec)
8975 throw new NotSupportedException ("ET");
8978 public override Expression DoResolve (ResolveContext ec)
8983 public override void Emit (EmitContext ec)
8985 // nothing, as we only exist to not do anything.
8988 public override void EmitSideEffect (EmitContext ec)
8993 // This is just because we might want to reuse this bad boy
8994 // instead of creating gazillions of EmptyExpressions.
8995 // (CanImplicitConversion uses it)
8997 public void SetType (Type t)
9004 // Empty statement expression
9006 public sealed class EmptyExpressionStatement : ExpressionStatement
9008 public static readonly EmptyExpressionStatement Instance = new EmptyExpressionStatement ();
9010 private EmptyExpressionStatement ()
9012 eclass = ExprClass.Value;
9013 loc = Location.Null;
9016 public override Expression CreateExpressionTree (ResolveContext ec)
9021 public override void EmitStatement (EmitContext ec)
9026 public override Expression DoResolve (ResolveContext ec)
9028 type = TypeManager.object_type;
9032 public override void Emit (EmitContext ec)
9038 public class UserCast : Expression {
9042 public UserCast (MethodInfo method, Expression source, Location l)
9044 this.method = method;
9045 this.source = source;
9046 type = TypeManager.TypeToCoreType (method.ReturnType);
9050 public Expression Source {
9056 public override Expression CreateExpressionTree (ResolveContext ec)
9058 Arguments args = new Arguments (3);
9059 args.Add (new Argument (source.CreateExpressionTree (ec)));
9060 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
9061 args.Add (new Argument (new TypeOfMethod (method, loc)));
9062 return CreateExpressionFactoryCall (ec, "Convert", args);
9065 public override Expression DoResolve (ResolveContext ec)
9067 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
9069 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
9071 eclass = ExprClass.Value;
9075 public override void Emit (EmitContext ec)
9078 ec.ig.Emit (OpCodes.Call, method);
9081 public override string GetSignatureForError ()
9083 return TypeManager.CSharpSignature (method);
9087 public override SLE.Expression MakeExpression (BuilderContext ctx)
9089 return SLE.Expression.Convert (source.MakeExpression (ctx), type, method);
9093 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
9095 source.MutateHoistedGenericType (storey);
9096 method = storey.MutateGenericMethod (method);
9101 // This class is used to "construct" the type during a typecast
9102 // operation. Since the Type.GetType class in .NET can parse
9103 // the type specification, we just use this to construct the type
9104 // one bit at a time.
9106 public class ComposedCast : TypeExpr {
9107 FullNamedExpression left;
9110 public ComposedCast (FullNamedExpression left, string dim)
9111 : this (left, dim, left.Location)
9115 public ComposedCast (FullNamedExpression left, string dim, Location l)
9122 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
9124 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec, false);
9128 Type ltype = lexpr.Type;
9129 if ((dim.Length > 0) && (dim [0] == '?')) {
9130 TypeExpr nullable = new Nullable.NullableType (lexpr, loc);
9132 nullable = new ComposedCast (nullable, dim.Substring (1), loc);
9133 return nullable.ResolveAsTypeTerminal (ec, false);
9136 if (dim == "*" && !TypeManager.VerifyUnManaged (ltype, loc))
9139 if (dim.Length != 0 && dim [0] == '[') {
9140 if (TypeManager.IsSpecialType (ltype)) {
9141 ec.Compiler.Report.Error (611, loc, "Array elements cannot be of type `{0}'", TypeManager.CSharpName (ltype));
9145 if ((ltype.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
9146 ec.Compiler.Report.SymbolRelatedToPreviousError (ltype);
9147 ec.Compiler.Report.Error (719, loc, "Array elements cannot be of static type `{0}'",
9148 TypeManager.CSharpName (ltype));
9153 type = TypeManager.GetConstructedType (ltype, dim);
9158 throw new InternalErrorException ("Couldn't create computed type " + ltype + dim);
9160 if (type.IsPointer && !ec.IsUnsafe){
9161 UnsafeError (ec.Compiler.Report, loc);
9164 eclass = ExprClass.Type;
9168 public override string GetSignatureForError ()
9170 return left.GetSignatureForError () + dim;
9173 public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
9175 return ResolveAsBaseTerminal (ec, silent);
9179 public class FixedBufferPtr : Expression {
9182 public FixedBufferPtr (Expression array, Type array_type, Location l)
9187 type = TypeManager.GetPointerType (array_type);
9188 eclass = ExprClass.Value;
9191 public override Expression CreateExpressionTree (ResolveContext ec)
9193 Error_PointerInsideExpressionTree (ec);
9197 public override void Emit(EmitContext ec)
9202 public override Expression DoResolve (ResolveContext ec)
9205 // We are born fully resolved
9213 // This class is used to represent the address of an array, used
9214 // only by the Fixed statement, this generates "&a [0]" construct
9215 // for fixed (char *pa = a)
9217 public class ArrayPtr : FixedBufferPtr {
9220 public ArrayPtr (Expression array, Type array_type, Location l):
9221 base (array, array_type, l)
9223 this.array_type = array_type;
9226 public override void Emit (EmitContext ec)
9230 ILGenerator ig = ec.ig;
9231 IntLiteral.EmitInt (ig, 0);
9232 ig.Emit (OpCodes.Ldelema, array_type);
9237 // Encapsulates a conversion rules required for array indexes
9239 public class ArrayIndexCast : TypeCast
9241 public ArrayIndexCast (Expression expr)
9242 : base (expr, expr.Type)
9244 if (type == TypeManager.int32_type)
9245 throw new ArgumentException ("unnecessary conversion");
9248 public override Expression CreateExpressionTree (ResolveContext ec)
9250 Arguments args = new Arguments (2);
9251 args.Add (new Argument (child.CreateExpressionTree (ec)));
9252 args.Add (new Argument (new TypeOf (new TypeExpression (TypeManager.int32_type, loc), loc)));
9253 return CreateExpressionFactoryCall (ec, "ConvertChecked", args);
9256 public override void Emit (EmitContext ec)
9260 if (type == TypeManager.uint32_type)
9261 ec.ig.Emit (OpCodes.Conv_U);
9262 else if (type == TypeManager.int64_type)
9263 ec.ig.Emit (OpCodes.Conv_Ovf_I);
9264 else if (type == TypeManager.uint64_type)
9265 ec.ig.Emit (OpCodes.Conv_Ovf_I_Un);
9267 throw new InternalErrorException ("Cannot emit cast to unknown array element type", type);
9270 public override bool GetAttributableValue (ResolveContext ec, Type value_type, out object value)
9272 return child.GetAttributableValue (ec, value_type, out value);
9277 // Implements the `stackalloc' keyword
9279 public class StackAlloc : Expression {
9284 public StackAlloc (Expression type, Expression count, Location l)
9291 public override Expression CreateExpressionTree (ResolveContext ec)
9293 throw new NotSupportedException ("ET");
9296 public override Expression DoResolve (ResolveContext ec)
9298 count = count.Resolve (ec);
9302 if (count.Type != TypeManager.uint32_type){
9303 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
9308 Constant c = count as Constant;
9309 if (c != null && c.IsNegative) {
9310 ec.Report.Error (247, loc, "Cannot use a negative size with stackalloc");
9314 if (ec.HasAny (ResolveContext.Options.CatchScope | ResolveContext.Options.FinallyScope)) {
9315 ec.Report.Error (255, loc, "Cannot use stackalloc in finally or catch");
9318 TypeExpr texpr = t.ResolveAsTypeTerminal (ec, false);
9324 if (!TypeManager.VerifyUnManaged (otype, loc))
9327 type = TypeManager.GetPointerType (otype);
9328 eclass = ExprClass.Value;
9333 public override void Emit (EmitContext ec)
9335 int size = GetTypeSize (otype);
9336 ILGenerator ig = ec.ig;
9341 ig.Emit (OpCodes.Sizeof, otype);
9343 IntConstant.EmitInt (ig, size);
9345 ig.Emit (OpCodes.Mul_Ovf_Un);
9346 ig.Emit (OpCodes.Localloc);
9349 protected override void CloneTo (CloneContext clonectx, Expression t)
9351 StackAlloc target = (StackAlloc) t;
9352 target.count = count.Clone (clonectx);
9353 target.t = t.Clone (clonectx);
9358 // An object initializer expression
9360 public class ElementInitializer : Assign
9362 public readonly string Name;
9364 public ElementInitializer (string name, Expression initializer, Location loc)
9365 : base (null, initializer, loc)
9370 protected override void CloneTo (CloneContext clonectx, Expression t)
9372 ElementInitializer target = (ElementInitializer) t;
9373 target.source = source.Clone (clonectx);
9376 public override Expression CreateExpressionTree (ResolveContext ec)
9378 Arguments args = new Arguments (2);
9379 FieldExpr fe = target as FieldExpr;
9381 args.Add (new Argument (fe.CreateTypeOfExpression ()));
9383 args.Add (new Argument (((PropertyExpr)target).CreateSetterTypeOfExpression ()));
9385 args.Add (new Argument (source.CreateExpressionTree (ec)));
9386 return CreateExpressionFactoryCall (ec,
9387 source is CollectionOrObjectInitializers ? "ListBind" : "Bind",
9391 public override Expression DoResolve (ResolveContext ec)
9394 return EmptyExpressionStatement.Instance;
9396 MemberExpr me = MemberLookupFinal (ec, ec.CurrentInitializerVariable.Type, ec.CurrentInitializerVariable.Type,
9397 Name, MemberTypes.Field | MemberTypes.Property, BindingFlags.Public | BindingFlags.Instance, loc) as MemberExpr;
9403 me.InstanceExpression = ec.CurrentInitializerVariable;
9405 if (source is CollectionOrObjectInitializers) {
9406 Expression previous = ec.CurrentInitializerVariable;
9407 ec.CurrentInitializerVariable = target;
9408 source = source.Resolve (ec);
9409 ec.CurrentInitializerVariable = previous;
9413 eclass = source.eclass;
9418 Expression expr = base.DoResolve (ec);
9423 // Ignore field initializers with default value
9425 Constant c = source as Constant;
9426 if (c != null && c.IsDefaultInitializer (type) && target.eclass == ExprClass.Variable)
9427 return EmptyExpressionStatement.Instance.DoResolve (ec);
9432 protected override Expression Error_MemberLookupFailed (ResolveContext ec, Type type, MemberInfo[] members)
9434 MemberInfo member = members [0];
9435 if (member.MemberType != MemberTypes.Property && member.MemberType != MemberTypes.Field)
9436 ec.Report.Error (1913, loc, "Member `{0}' cannot be initialized. An object " +
9437 "initializer may only be used for fields, or properties", TypeManager.GetFullNameSignature (member));
9439 ec.Report.Error (1914, loc, " Static field or property `{0}' cannot be assigned in an object initializer",
9440 TypeManager.GetFullNameSignature (member));
9445 public override void EmitStatement (EmitContext ec)
9447 if (source is CollectionOrObjectInitializers)
9450 base.EmitStatement (ec);
9455 // A collection initializer expression
9457 class CollectionElementInitializer : Invocation
9459 public class ElementInitializerArgument : Argument
9461 public ElementInitializerArgument (Expression e)
9467 sealed class AddMemberAccess : MemberAccess
9469 public AddMemberAccess (Expression expr, Location loc)
9470 : base (expr, "Add", loc)
9474 protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, Type type, string name)
9476 if (TypeManager.HasElementType (type))
9479 base.Error_TypeDoesNotContainDefinition (ec, type, name);
9483 public CollectionElementInitializer (Expression argument)
9484 : base (null, new Arguments (1))
9486 base.arguments.Add (new ElementInitializerArgument (argument));
9487 this.loc = argument.Location;
9490 public CollectionElementInitializer (ArrayList arguments, Location loc)
9491 : base (null, new Arguments (arguments.Count))
9493 foreach (Expression e in arguments)
9494 base.arguments.Add (new ElementInitializerArgument (e));
9499 public override Expression CreateExpressionTree (ResolveContext ec)
9501 Arguments args = new Arguments (2);
9502 args.Add (new Argument (mg.CreateExpressionTree (ec)));
9504 ArrayList expr_initializers = new ArrayList (arguments.Count);
9505 foreach (Argument a in arguments)
9506 expr_initializers.Add (a.CreateExpressionTree (ec));
9508 args.Add (new Argument (new ArrayCreation (
9509 CreateExpressionTypeExpression (ec, loc), "[]", expr_initializers, loc)));
9510 return CreateExpressionFactoryCall (ec, "ElementInit", args);
9513 protected override void CloneTo (CloneContext clonectx, Expression t)
9515 CollectionElementInitializer target = (CollectionElementInitializer) t;
9516 if (arguments != null)
9517 target.arguments = arguments.Clone (clonectx);
9520 public override Expression DoResolve (ResolveContext ec)
9522 if (eclass != ExprClass.Invalid)
9525 base.expr = new AddMemberAccess (ec.CurrentInitializerVariable, loc);
9527 return base.DoResolve (ec);
9532 // A block of object or collection initializers
9534 public class CollectionOrObjectInitializers : ExpressionStatement
9536 ArrayList initializers;
9537 bool is_collection_initialization;
9539 public static readonly CollectionOrObjectInitializers Empty =
9540 new CollectionOrObjectInitializers (new ArrayList (0), Location.Null);
9542 public CollectionOrObjectInitializers (ArrayList initializers, Location loc)
9544 this.initializers = initializers;
9548 public bool IsEmpty {
9550 return initializers.Count == 0;
9554 public bool IsCollectionInitializer {
9556 return is_collection_initialization;
9560 protected override void CloneTo (CloneContext clonectx, Expression target)
9562 CollectionOrObjectInitializers t = (CollectionOrObjectInitializers) target;
9564 t.initializers = new ArrayList (initializers.Count);
9565 foreach (Expression e in initializers)
9566 t.initializers.Add (e.Clone (clonectx));
9569 public override Expression CreateExpressionTree (ResolveContext ec)
9571 ArrayList expr_initializers = new ArrayList (initializers.Count);
9572 foreach (Expression e in initializers) {
9573 Expression expr = e.CreateExpressionTree (ec);
9575 expr_initializers.Add (expr);
9578 return new ImplicitlyTypedArrayCreation ("[]", expr_initializers, loc);
9581 public override Expression DoResolve (ResolveContext ec)
9583 if (eclass != ExprClass.Invalid)
9586 ArrayList element_names = null;
9587 for (int i = 0; i < initializers.Count; ++i) {
9588 Expression initializer = (Expression) initializers [i];
9589 ElementInitializer element_initializer = initializer as ElementInitializer;
9592 if (element_initializer != null) {
9593 element_names = new ArrayList (initializers.Count);
9594 element_names.Add (element_initializer.Name);
9595 } else if (initializer is CompletingExpression){
9596 initializer.Resolve (ec);
9597 throw new InternalErrorException ("This line should never be reached");
9599 if (!TypeManager.ImplementsInterface (ec.CurrentInitializerVariable.Type, TypeManager.ienumerable_type)) {
9600 ec.Report.Error (1922, loc, "A field or property `{0}' cannot be initialized with a collection " +
9601 "object initializer because type `{1}' does not implement `{2}' interface",
9602 ec.CurrentInitializerVariable.GetSignatureForError (),
9603 TypeManager.CSharpName (ec.CurrentInitializerVariable.Type),
9604 TypeManager.CSharpName (TypeManager.ienumerable_type));
9607 is_collection_initialization = true;
9610 if (is_collection_initialization != (element_initializer == null)) {
9611 ec.Report.Error (747, initializer.Location, "Inconsistent `{0}' member declaration",
9612 is_collection_initialization ? "collection initializer" : "object initializer");
9616 if (!is_collection_initialization) {
9617 if (element_names.Contains (element_initializer.Name)) {
9618 ec.Report.Error (1912, element_initializer.Location,
9619 "An object initializer includes more than one member `{0}' initialization",
9620 element_initializer.Name);
9622 element_names.Add (element_initializer.Name);
9627 Expression e = initializer.Resolve (ec);
9628 if (e == EmptyExpressionStatement.Instance)
9629 initializers.RemoveAt (i--);
9631 initializers [i] = e;
9634 type = ec.CurrentInitializerVariable.Type;
9635 if (is_collection_initialization) {
9636 if (TypeManager.HasElementType (type)) {
9637 ec.Report.Error (1925, loc, "Cannot initialize object of type `{0}' with a collection initializer",
9638 TypeManager.CSharpName (type));
9642 eclass = ExprClass.Variable;
9646 public override void Emit (EmitContext ec)
9651 public override void EmitStatement (EmitContext ec)
9653 foreach (ExpressionStatement e in initializers)
9654 e.EmitStatement (ec);
9657 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
9659 foreach (Expression e in initializers)
9660 e.MutateHoistedGenericType (storey);
9665 // New expression with element/object initializers
9667 public class NewInitialize : New
9670 // This class serves as a proxy for variable initializer target instances.
9671 // A real variable is assigned later when we resolve left side of an
9674 sealed class InitializerTargetExpression : Expression, IMemoryLocation
9676 NewInitialize new_instance;
9678 public InitializerTargetExpression (NewInitialize newInstance)
9680 this.type = newInstance.type;
9681 this.loc = newInstance.loc;
9682 this.eclass = newInstance.eclass;
9683 this.new_instance = newInstance;
9686 public override Expression CreateExpressionTree (ResolveContext ec)
9688 // Should not be reached
9689 throw new NotSupportedException ("ET");
9692 public override Expression DoResolve (ResolveContext ec)
9697 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
9702 public override void Emit (EmitContext ec)
9704 Expression e = (Expression) new_instance.instance;
9708 #region IMemoryLocation Members
9710 public void AddressOf (EmitContext ec, AddressOp mode)
9712 new_instance.instance.AddressOf (ec, mode);
9718 CollectionOrObjectInitializers initializers;
9719 IMemoryLocation instance;
9721 public NewInitialize (Expression requested_type, Arguments arguments, CollectionOrObjectInitializers initializers, Location l)
9722 : base (requested_type, arguments, l)
9724 this.initializers = initializers;
9727 protected override IMemoryLocation EmitAddressOf (EmitContext ec, AddressOp Mode)
9729 instance = base.EmitAddressOf (ec, Mode);
9731 if (!initializers.IsEmpty)
9732 initializers.Emit (ec);
9737 protected override void CloneTo (CloneContext clonectx, Expression t)
9739 base.CloneTo (clonectx, t);
9741 NewInitialize target = (NewInitialize) t;
9742 target.initializers = (CollectionOrObjectInitializers) initializers.Clone (clonectx);
9745 public override Expression CreateExpressionTree (ResolveContext ec)
9747 Arguments args = new Arguments (2);
9748 args.Add (new Argument (base.CreateExpressionTree (ec)));
9749 if (!initializers.IsEmpty)
9750 args.Add (new Argument (initializers.CreateExpressionTree (ec)));
9752 return CreateExpressionFactoryCall (ec,
9753 initializers.IsCollectionInitializer ? "ListInit" : "MemberInit",
9757 public override Expression DoResolve (ResolveContext ec)
9759 if (eclass != ExprClass.Invalid)
9762 Expression e = base.DoResolve (ec);
9766 Expression previous = ec.CurrentInitializerVariable;
9767 ec.CurrentInitializerVariable = new InitializerTargetExpression (this);
9768 initializers.Resolve (ec);
9769 ec.CurrentInitializerVariable = previous;
9773 public override bool Emit (EmitContext ec, IMemoryLocation target)
9775 bool left_on_stack = base.Emit (ec, target);
9777 if (initializers.IsEmpty)
9778 return left_on_stack;
9780 LocalTemporary temp = target as LocalTemporary;
9782 if (!left_on_stack) {
9783 VariableReference vr = target as VariableReference;
9785 // FIXME: This still does not work correctly for pre-set variables
9786 if (vr != null && vr.IsRef)
9787 target.AddressOf (ec, AddressOp.Load);
9789 ((Expression) target).Emit (ec);
9790 left_on_stack = true;
9793 temp = new LocalTemporary (type);
9800 initializers.Emit (ec);
9802 if (left_on_stack) {
9807 return left_on_stack;
9810 public override bool HasInitializer {
9812 return !initializers.IsEmpty;
9816 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
9818 base.MutateHoistedGenericType (storey);
9819 initializers.MutateHoistedGenericType (storey);
9823 public class AnonymousTypeDeclaration : Expression
9825 ArrayList parameters;
9826 readonly TypeContainer parent;
9827 static readonly ArrayList EmptyParameters = new ArrayList (0);
9829 public AnonymousTypeDeclaration (ArrayList parameters, TypeContainer parent, Location loc)
9831 this.parameters = parameters;
9832 this.parent = parent;
9836 protected override void CloneTo (CloneContext clonectx, Expression target)
9838 if (parameters == null)
9841 AnonymousTypeDeclaration t = (AnonymousTypeDeclaration) target;
9842 t.parameters = new ArrayList (parameters.Count);
9843 foreach (AnonymousTypeParameter atp in parameters)
9844 t.parameters.Add (atp.Clone (clonectx));
9847 AnonymousTypeClass CreateAnonymousType (ResolveContext ec, ArrayList parameters)
9849 AnonymousTypeClass type = parent.Module.GetAnonymousType (parameters);
9853 type = AnonymousTypeClass.Create (ec.Compiler, parent, parameters, loc);
9860 if (ec.Report.Errors == 0)
9863 parent.Module.AddAnonymousType (type);
9867 public override Expression CreateExpressionTree (ResolveContext ec)
9869 throw new NotSupportedException ("ET");
9872 public override Expression DoResolve (ResolveContext ec)
9874 AnonymousTypeClass anonymous_type;
9876 if (ec.HasSet (ResolveContext.Options.ConstantScope)) {
9877 ec.Report.Error (836, loc, "Anonymous types cannot be used in this expression");
9881 if (parameters == null) {
9882 anonymous_type = CreateAnonymousType (ec, EmptyParameters);
9883 return new New (new TypeExpression (anonymous_type.TypeBuilder, loc),
9884 null, loc).Resolve (ec);
9888 Arguments arguments = new Arguments (parameters.Count);
9889 TypeExpression [] t_args = new TypeExpression [parameters.Count];
9890 for (int i = 0; i < parameters.Count; ++i) {
9891 Expression e = ((AnonymousTypeParameter) parameters [i]).Resolve (ec);
9897 arguments.Add (new Argument (e));
9898 t_args [i] = new TypeExpression (e.Type, e.Location);
9904 anonymous_type = CreateAnonymousType (ec, parameters);
9905 if (anonymous_type == null)
9908 GenericTypeExpr te = new GenericTypeExpr (anonymous_type.TypeBuilder,
9909 new TypeArguments (t_args), loc);
9911 return new New (te, arguments, loc).Resolve (ec);
9914 public override void Emit (EmitContext ec)
9916 throw new InternalErrorException ("Should not be reached");
9920 public class AnonymousTypeParameter : ShimExpression
9922 public readonly string Name;
9924 public AnonymousTypeParameter (Expression initializer, string name, Location loc)
9925 : base (initializer)
9931 public AnonymousTypeParameter (Parameter parameter)
9932 : base (new SimpleName (parameter.Name, parameter.Location))
9934 this.Name = parameter.Name;
9935 this.loc = parameter.Location;
9938 public override bool Equals (object o)
9940 AnonymousTypeParameter other = o as AnonymousTypeParameter;
9941 return other != null && Name == other.Name;
9944 public override int GetHashCode ()
9946 return Name.GetHashCode ();
9949 public override Expression DoResolve (ResolveContext ec)
9951 Expression e = expr.Resolve (ec);
9955 if (e.eclass == ExprClass.MethodGroup) {
9956 Error_InvalidInitializer (ec, e.ExprClassName);
9961 if (type == TypeManager.void_type || type == TypeManager.null_type ||
9962 type == InternalType.AnonymousMethod || type.IsPointer) {
9963 Error_InvalidInitializer (ec, e.GetSignatureForError ());
9970 protected virtual void Error_InvalidInitializer (ResolveContext ec, string initializer)
9972 ec.Report.Error (828, loc, "An anonymous type property `{0}' cannot be initialized with `{1}'",