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.Generic;
16 using System.Reflection;
17 using System.Reflection.Emit;
20 using SLE = System.Linq.Expressions;
23 // This is an user operator expression, automatically created during
26 public class UserOperatorCall : Expression {
27 protected readonly Arguments arguments;
28 protected readonly MethodSpec oper;
29 readonly Func<ResolveContext, Expression, Expression> expr_tree;
31 public UserOperatorCall (MethodSpec oper, Arguments args, Func<ResolveContext, Expression, Expression> expr_tree, Location loc)
34 this.arguments = args;
35 this.expr_tree = expr_tree;
37 type = oper.ReturnType;
38 eclass = ExprClass.Value;
42 public override Expression CreateExpressionTree (ResolveContext ec)
44 if (expr_tree != null)
45 return expr_tree (ec, new TypeOfMethod (oper, loc));
47 Arguments args = Arguments.CreateForExpressionTree (ec, arguments,
48 new NullLiteral (loc),
49 new TypeOfMethod (oper, loc));
51 return CreateExpressionFactoryCall (ec, "Call", args);
54 protected override void CloneTo (CloneContext context, Expression target)
59 protected override Expression DoResolve (ResolveContext ec)
62 // We are born fully resolved
67 public override void Emit (EmitContext ec)
69 Invocation.EmitCall (ec, null, oper, arguments, loc);
72 public override SLE.Expression MakeExpression (BuilderContext ctx)
74 var method = oper.GetMetaInfo () as MethodInfo;
75 return SLE.Expression.Call (method, Arguments.MakeExpression (arguments, ctx));
79 public class ParenthesizedExpression : ShimExpression
81 public ParenthesizedExpression (Expression expr)
87 protected override Expression DoResolve (ResolveContext ec)
89 return expr.Resolve (ec);
92 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
94 return expr.DoResolveLValue (ec, right_side);
99 // Unary implements unary expressions.
101 public class Unary : Expression
103 public enum Operator : byte {
104 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
108 static TypeSpec[][] predefined_operators;
110 public readonly Operator Oper;
111 public Expression Expr;
112 Expression enum_conversion;
114 public Unary (Operator op, Expression expr, Location loc)
122 // This routine will attempt to simplify the unary expression when the
123 // argument is a constant.
125 Constant TryReduceConstant (ResolveContext ec, Constant e)
127 if (e is EmptyConstantCast)
128 return TryReduceConstant (ec, ((EmptyConstantCast) e).child);
130 if (e is SideEffectConstant) {
131 Constant r = TryReduceConstant (ec, ((SideEffectConstant) e).value);
132 return r == null ? null : new SideEffectConstant (r, e, r.Location);
135 TypeSpec expr_type = e.Type;
138 case Operator.UnaryPlus:
139 // Unary numeric promotions
140 if (expr_type == TypeManager.byte_type)
141 return new IntConstant (((ByteConstant)e).Value, e.Location);
142 if (expr_type == TypeManager.sbyte_type)
143 return new IntConstant (((SByteConstant)e).Value, e.Location);
144 if (expr_type == TypeManager.short_type)
145 return new IntConstant (((ShortConstant)e).Value, e.Location);
146 if (expr_type == TypeManager.ushort_type)
147 return new IntConstant (((UShortConstant)e).Value, e.Location);
148 if (expr_type == TypeManager.char_type)
149 return new IntConstant (((CharConstant)e).Value, e.Location);
151 // Predefined operators
152 if (expr_type == TypeManager.int32_type || expr_type == TypeManager.uint32_type ||
153 expr_type == TypeManager.int64_type || expr_type == TypeManager.uint64_type ||
154 expr_type == TypeManager.float_type || expr_type == TypeManager.double_type ||
155 expr_type == TypeManager.decimal_type) {
161 case Operator.UnaryNegation:
162 // Unary numeric promotions
163 if (expr_type == TypeManager.byte_type)
164 return new IntConstant (-((ByteConstant)e).Value, e.Location);
165 if (expr_type == TypeManager.sbyte_type)
166 return new IntConstant (-((SByteConstant)e).Value, e.Location);
167 if (expr_type == TypeManager.short_type)
168 return new IntConstant (-((ShortConstant)e).Value, e.Location);
169 if (expr_type == TypeManager.ushort_type)
170 return new IntConstant (-((UShortConstant)e).Value, e.Location);
171 if (expr_type == TypeManager.char_type)
172 return new IntConstant (-((CharConstant)e).Value, e.Location);
174 // Predefined operators
175 if (expr_type == TypeManager.int32_type) {
176 int value = ((IntConstant)e).Value;
177 if (value == int.MinValue) {
178 if (ec.ConstantCheckState) {
179 ConstantFold.Error_CompileTimeOverflow (ec, loc);
184 return new IntConstant (-value, e.Location);
186 if (expr_type == TypeManager.int64_type) {
187 long value = ((LongConstant)e).Value;
188 if (value == long.MinValue) {
189 if (ec.ConstantCheckState) {
190 ConstantFold.Error_CompileTimeOverflow (ec, loc);
195 return new LongConstant (-value, e.Location);
198 if (expr_type == TypeManager.uint32_type) {
199 UIntLiteral uil = e as UIntLiteral;
201 if (uil.Value == int.MaxValue + (uint) 1)
202 return new IntLiteral (int.MinValue, e.Location);
203 return new LongLiteral (-uil.Value, e.Location);
205 return new LongConstant (-((UIntConstant)e).Value, e.Location);
208 if (expr_type == TypeManager.uint64_type) {
209 ULongLiteral ull = e as ULongLiteral;
210 if (ull != null && ull.Value == 9223372036854775808)
211 return new LongLiteral (long.MinValue, e.Location);
215 if (expr_type == TypeManager.float_type) {
216 FloatLiteral fl = e as FloatLiteral;
217 // For better error reporting
219 return new FloatLiteral (-fl.Value, e.Location);
221 return new FloatConstant (-((FloatConstant)e).Value, e.Location);
223 if (expr_type == TypeManager.double_type) {
224 DoubleLiteral dl = e as DoubleLiteral;
225 // For better error reporting
227 return new DoubleLiteral (-dl.Value, e.Location);
229 return new DoubleConstant (-((DoubleConstant)e).Value, e.Location);
231 if (expr_type == TypeManager.decimal_type)
232 return new DecimalConstant (-((DecimalConstant)e).Value, e.Location);
236 case Operator.LogicalNot:
237 if (expr_type != TypeManager.bool_type)
240 bool b = (bool)e.GetValue ();
241 return new BoolConstant (!b, e.Location);
243 case Operator.OnesComplement:
244 // Unary numeric promotions
245 if (expr_type == TypeManager.byte_type)
246 return new IntConstant (~((ByteConstant)e).Value, e.Location);
247 if (expr_type == TypeManager.sbyte_type)
248 return new IntConstant (~((SByteConstant)e).Value, e.Location);
249 if (expr_type == TypeManager.short_type)
250 return new IntConstant (~((ShortConstant)e).Value, e.Location);
251 if (expr_type == TypeManager.ushort_type)
252 return new IntConstant (~((UShortConstant)e).Value, e.Location);
253 if (expr_type == TypeManager.char_type)
254 return new IntConstant (~((CharConstant)e).Value, e.Location);
256 // Predefined operators
257 if (expr_type == TypeManager.int32_type)
258 return new IntConstant (~((IntConstant)e).Value, e.Location);
259 if (expr_type == TypeManager.uint32_type)
260 return new UIntConstant (~((UIntConstant)e).Value, e.Location);
261 if (expr_type == TypeManager.int64_type)
262 return new LongConstant (~((LongConstant)e).Value, e.Location);
263 if (expr_type == TypeManager.uint64_type){
264 return new ULongConstant (~((ULongConstant)e).Value, e.Location);
266 if (e is EnumConstant) {
267 e = TryReduceConstant (ec, ((EnumConstant)e).Child);
269 e = new EnumConstant (e, expr_type);
274 throw new Exception ("Can not constant fold: " + Oper.ToString());
277 protected Expression ResolveOperator (ResolveContext ec, Expression expr)
279 eclass = ExprClass.Value;
281 if (predefined_operators == null)
282 CreatePredefinedOperatorsTable ();
284 TypeSpec expr_type = expr.Type;
285 Expression best_expr;
288 // Primitive types first
290 if (TypeManager.IsPrimitiveType (expr_type)) {
291 best_expr = ResolvePrimitivePredefinedType (expr);
292 if (best_expr == null)
295 type = best_expr.Type;
301 // E operator ~(E x);
303 if (Oper == Operator.OnesComplement && TypeManager.IsEnumType (expr_type))
304 return ResolveEnumOperator (ec, expr);
306 return ResolveUserType (ec, expr);
309 protected virtual Expression ResolveEnumOperator (ResolveContext ec, Expression expr)
311 TypeSpec underlying_type = EnumSpec.GetUnderlyingType (expr.Type);
312 Expression best_expr = ResolvePrimitivePredefinedType (EmptyCast.Create (expr, underlying_type));
313 if (best_expr == null)
317 enum_conversion = Convert.ExplicitNumericConversion (new EmptyExpression (best_expr.Type), underlying_type);
319 return EmptyCast.Create (this, type);
322 public override Expression CreateExpressionTree (ResolveContext ec)
324 return CreateExpressionTree (ec, null);
327 Expression CreateExpressionTree (ResolveContext ec, Expression user_op)
331 case Operator.AddressOf:
332 Error_PointerInsideExpressionTree (ec);
334 case Operator.UnaryNegation:
335 if (ec.HasSet (ResolveContext.Options.CheckedScope) && user_op == null && !IsFloat (type))
336 method_name = "NegateChecked";
338 method_name = "Negate";
340 case Operator.OnesComplement:
341 case Operator.LogicalNot:
344 case Operator.UnaryPlus:
345 method_name = "UnaryPlus";
348 throw new InternalErrorException ("Unknown unary operator " + Oper.ToString ());
351 Arguments args = new Arguments (2);
352 args.Add (new Argument (Expr.CreateExpressionTree (ec)));
354 args.Add (new Argument (user_op));
356 return CreateExpressionFactoryCall (ec, method_name, args);
359 static void CreatePredefinedOperatorsTable ()
361 predefined_operators = new TypeSpec [(int) Operator.TOP] [];
364 // 7.6.1 Unary plus operator
366 predefined_operators [(int) Operator.UnaryPlus] = new TypeSpec [] {
367 TypeManager.int32_type, TypeManager.uint32_type,
368 TypeManager.int64_type, TypeManager.uint64_type,
369 TypeManager.float_type, TypeManager.double_type,
370 TypeManager.decimal_type
374 // 7.6.2 Unary minus operator
376 predefined_operators [(int) Operator.UnaryNegation] = new TypeSpec [] {
377 TypeManager.int32_type,
378 TypeManager.int64_type,
379 TypeManager.float_type, TypeManager.double_type,
380 TypeManager.decimal_type
384 // 7.6.3 Logical negation operator
386 predefined_operators [(int) Operator.LogicalNot] = new TypeSpec [] {
387 TypeManager.bool_type
391 // 7.6.4 Bitwise complement operator
393 predefined_operators [(int) Operator.OnesComplement] = new TypeSpec [] {
394 TypeManager.int32_type, TypeManager.uint32_type,
395 TypeManager.int64_type, TypeManager.uint64_type
400 // Unary numeric promotions
402 static Expression DoNumericPromotion (Operator op, Expression expr)
404 TypeSpec expr_type = expr.Type;
405 if ((op == Operator.UnaryPlus || op == Operator.UnaryNegation || op == Operator.OnesComplement) &&
406 expr_type == TypeManager.byte_type || expr_type == TypeManager.sbyte_type ||
407 expr_type == TypeManager.short_type || expr_type == TypeManager.ushort_type ||
408 expr_type == TypeManager.char_type)
409 return Convert.ImplicitNumericConversion (expr, TypeManager.int32_type);
411 if (op == Operator.UnaryNegation && expr_type == TypeManager.uint32_type)
412 return Convert.ImplicitNumericConversion (expr, TypeManager.int64_type);
417 protected override Expression DoResolve (ResolveContext ec)
419 if (Oper == Operator.AddressOf) {
420 return ResolveAddressOf (ec);
423 Expr = Expr.Resolve (ec);
427 if (Expr.Type == InternalType.Dynamic) {
428 Arguments args = new Arguments (1);
429 args.Add (new Argument (Expr));
430 return new DynamicUnaryConversion (GetOperatorExpressionTypeName (), args, loc).Resolve (ec);
433 if (TypeManager.IsNullableType (Expr.Type))
434 return new Nullable.LiftedUnaryOperator (Oper, Expr, loc).Resolve (ec);
437 // Attempt to use a constant folding operation.
439 Constant cexpr = Expr as Constant;
441 cexpr = TryReduceConstant (ec, cexpr);
443 return cexpr.Resolve (ec);
446 Expression expr = ResolveOperator (ec, Expr);
448 Error_OperatorCannotBeApplied (ec, loc, OperName (Oper), Expr.Type);
451 // Reduce unary operator on predefined types
453 if (expr == this && Oper == Operator.UnaryPlus)
459 public override Expression DoResolveLValue (ResolveContext ec, Expression right)
464 public override void Emit (EmitContext ec)
466 EmitOperator (ec, type);
469 protected void EmitOperator (EmitContext ec, TypeSpec type)
472 case Operator.UnaryPlus:
476 case Operator.UnaryNegation:
477 if (ec.HasSet (EmitContext.Options.CheckedScope) && !IsFloat (type)) {
478 ec.Emit (OpCodes.Ldc_I4_0);
479 if (type == TypeManager.int64_type)
480 ec.Emit (OpCodes.Conv_U8);
482 ec.Emit (OpCodes.Sub_Ovf);
485 ec.Emit (OpCodes.Neg);
490 case Operator.LogicalNot:
492 ec.Emit (OpCodes.Ldc_I4_0);
493 ec.Emit (OpCodes.Ceq);
496 case Operator.OnesComplement:
498 ec.Emit (OpCodes.Not);
501 case Operator.AddressOf:
502 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
506 throw new Exception ("This should not happen: Operator = "
511 // Same trick as in Binary expression
513 if (enum_conversion != null)
514 enum_conversion.Emit (ec);
517 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
519 if (Oper == Operator.LogicalNot)
520 Expr.EmitBranchable (ec, target, !on_true);
522 base.EmitBranchable (ec, target, on_true);
525 public override void EmitSideEffect (EmitContext ec)
527 Expr.EmitSideEffect (ec);
530 public static void Error_OperatorCannotBeApplied (ResolveContext ec, Location loc, string oper, TypeSpec t)
532 ec.Report.Error (23, loc, "The `{0}' operator cannot be applied to operand of type `{1}'",
533 oper, TypeManager.CSharpName (t));
537 // Converts operator to System.Linq.Expressions.ExpressionType enum name
539 string GetOperatorExpressionTypeName ()
542 case Operator.OnesComplement:
543 return "OnesComplement";
544 case Operator.LogicalNot:
546 case Operator.UnaryNegation:
548 case Operator.UnaryPlus:
551 throw new NotImplementedException ("Unknown express type operator " + Oper.ToString ());
555 static bool IsFloat (TypeSpec t)
557 return t == TypeManager.float_type || t == TypeManager.double_type;
561 // Returns a stringified representation of the Operator
563 public static string OperName (Operator oper)
566 case Operator.UnaryPlus:
568 case Operator.UnaryNegation:
570 case Operator.LogicalNot:
572 case Operator.OnesComplement:
574 case Operator.AddressOf:
578 throw new NotImplementedException (oper.ToString ());
581 public override SLE.Expression MakeExpression (BuilderContext ctx)
583 var expr = Expr.MakeExpression (ctx);
584 bool is_checked = ctx.HasSet (BuilderContext.Options.CheckedScope);
587 case Operator.UnaryNegation:
588 return is_checked ? SLE.Expression.NegateChecked (expr) : SLE.Expression.Negate (expr);
589 case Operator.LogicalNot:
590 return SLE.Expression.Not (expr);
592 case Operator.OnesComplement:
593 return SLE.Expression.OnesComplement (expr);
596 throw new NotImplementedException (Oper.ToString ());
600 public static void Reset ()
602 predefined_operators = null;
605 Expression ResolveAddressOf (ResolveContext ec)
608 UnsafeError (ec, loc);
610 Expr = Expr.DoResolveLValue (ec, EmptyExpression.UnaryAddress);
611 if (Expr == null || Expr.eclass != ExprClass.Variable) {
612 ec.Report.Error (211, loc, "Cannot take the address of the given expression");
616 if (!TypeManager.VerifyUnmanaged (ec.Compiler, Expr.Type, loc)) {
620 IVariableReference vr = Expr as IVariableReference;
623 VariableInfo vi = vr.VariableInfo;
625 if (vi.LocalInfo != null)
626 vi.LocalInfo.Used = true;
629 // A variable is considered definitely assigned if you take its address.
634 is_fixed = vr.IsFixed;
635 vr.SetHasAddressTaken ();
638 AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, vr, loc);
641 IFixedExpression fe = Expr as IFixedExpression;
642 is_fixed = fe != null && fe.IsFixed;
645 if (!is_fixed && !ec.HasSet (ResolveContext.Options.FixedInitializerScope)) {
646 ec.Report.Error (212, loc, "You can only take the address of unfixed expression inside of a fixed statement initializer");
649 type = PointerContainer.MakeType (Expr.Type);
650 eclass = ExprClass.Value;
654 Expression ResolvePrimitivePredefinedType (Expression expr)
656 expr = DoNumericPromotion (Oper, expr);
657 TypeSpec expr_type = expr.Type;
658 TypeSpec[] predefined = predefined_operators [(int) Oper];
659 foreach (TypeSpec t in predefined) {
667 // Perform user-operator overload resolution
669 protected virtual Expression ResolveUserOperator (ResolveContext ec, Expression expr)
671 CSharp.Operator.OpType op_type;
673 case Operator.LogicalNot:
674 op_type = CSharp.Operator.OpType.LogicalNot; break;
675 case Operator.OnesComplement:
676 op_type = CSharp.Operator.OpType.OnesComplement; break;
677 case Operator.UnaryNegation:
678 op_type = CSharp.Operator.OpType.UnaryNegation; break;
679 case Operator.UnaryPlus:
680 op_type = CSharp.Operator.OpType.UnaryPlus; break;
682 throw new InternalErrorException (Oper.ToString ());
685 var methods = MemberCache.GetUserOperator (expr.Type, op_type, false);
689 var user_op = new MethodGroupExpr (methods, expr.Type, loc);
691 Arguments args = new Arguments (1);
692 args.Add (new Argument (expr));
693 user_op = user_op.OverloadResolve (ec, ref args, false, expr.Location);
698 Expr = args [0].Expr;
699 return new UserOperatorCall (user_op.BestCandidate, args, CreateExpressionTree, expr.Location);
703 // Unary user type overload resolution
705 Expression ResolveUserType (ResolveContext ec, Expression expr)
707 Expression best_expr = ResolveUserOperator (ec, expr);
708 if (best_expr != null)
711 TypeSpec[] predefined = predefined_operators [(int) Oper];
712 foreach (TypeSpec t in predefined) {
713 Expression oper_expr = Convert.ImplicitUserConversion (ec, expr, t, expr.Location);
714 if (oper_expr == null)
718 // decimal type is predefined but has user-operators
720 if (oper_expr.Type == TypeManager.decimal_type)
721 oper_expr = ResolveUserType (ec, oper_expr);
723 oper_expr = ResolvePrimitivePredefinedType (oper_expr);
725 if (oper_expr == null)
728 if (best_expr == null) {
729 best_expr = oper_expr;
733 int result = MethodGroupExpr.BetterTypeConversion (ec, best_expr.Type, t);
735 ec.Report.Error (35, loc, "Operator `{0}' is ambiguous on an operand of type `{1}'",
736 OperName (Oper), TypeManager.CSharpName (expr.Type));
741 best_expr = oper_expr;
744 if (best_expr == null)
748 // HACK: Decimal user-operator is included in standard operators
750 if (best_expr.Type == TypeManager.decimal_type)
754 type = best_expr.Type;
758 protected override void CloneTo (CloneContext clonectx, Expression t)
760 Unary target = (Unary) t;
762 target.Expr = Expr.Clone (clonectx);
767 // Unary operators are turned into Indirection expressions
768 // after semantic analysis (this is so we can take the address
769 // of an indirection).
771 public class Indirection : Expression, IMemoryLocation, IAssignMethod, IFixedExpression {
773 LocalTemporary temporary;
776 public Indirection (Expression expr, Location l)
782 public override Expression CreateExpressionTree (ResolveContext ec)
784 Error_PointerInsideExpressionTree (ec);
788 protected override void CloneTo (CloneContext clonectx, Expression t)
790 Indirection target = (Indirection) t;
791 target.expr = expr.Clone (clonectx);
794 public override void Emit (EmitContext ec)
799 ec.EmitLoadFromPtr (Type);
802 public void Emit (EmitContext ec, bool leave_copy)
806 ec.Emit (OpCodes.Dup);
807 temporary = new LocalTemporary (expr.Type);
808 temporary.Store (ec);
812 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
814 prepared = prepare_for_load;
818 if (prepare_for_load)
819 ec.Emit (OpCodes.Dup);
823 ec.Emit (OpCodes.Dup);
824 temporary = new LocalTemporary (expr.Type);
825 temporary.Store (ec);
828 ec.EmitStoreFromPtr (type);
830 if (temporary != null) {
832 temporary.Release (ec);
836 public void AddressOf (EmitContext ec, AddressOp Mode)
841 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
843 return DoResolve (ec);
846 protected override Expression DoResolve (ResolveContext ec)
848 expr = expr.Resolve (ec);
853 UnsafeError (ec, loc);
855 if (!expr.Type.IsPointer) {
856 ec.Report.Error (193, loc, "The * or -> operator must be applied to a pointer");
860 if (expr.Type == TypeManager.void_ptr_type) {
861 ec.Report.Error (242, loc, "The operation in question is undefined on void pointers");
865 type = TypeManager.GetElementType (expr.Type);
866 eclass = ExprClass.Variable;
870 public bool IsFixed {
874 public override string ToString ()
876 return "*(" + expr + ")";
881 /// Unary Mutator expressions (pre and post ++ and --)
885 /// UnaryMutator implements ++ and -- expressions. It derives from
886 /// ExpressionStatement becuase the pre/post increment/decrement
887 /// operators can be used in a statement context.
889 /// FIXME: Idea, we could split this up in two classes, one simpler
890 /// for the common case, and one with the extra fields for more complex
891 /// classes (indexers require temporary access; overloaded require method)
894 public class UnaryMutator : ExpressionStatement
896 class DynamicPostMutator : Expression, IAssignMethod
901 public DynamicPostMutator (Expression expr)
904 this.type = expr.Type;
905 this.loc = expr.Location;
908 public override Expression CreateExpressionTree (ResolveContext ec)
910 throw new NotImplementedException ("ET");
913 protected override Expression DoResolve (ResolveContext rc)
915 eclass = expr.eclass;
919 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
921 expr.DoResolveLValue (ec, right_side);
922 return DoResolve (ec);
925 public override void Emit (EmitContext ec)
930 public void Emit (EmitContext ec, bool leave_copy)
932 throw new NotImplementedException ();
936 // Emits target assignment using unmodified source value
938 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
941 // Allocate temporary variable to keep original value before it's modified
943 temp = new LocalTemporary (type);
947 ((IAssignMethod) expr).EmitAssign (ec, source, false, prepare_for_load);
958 public enum Mode : byte {
965 PreDecrement = IsDecrement,
966 PostIncrement = IsPost,
967 PostDecrement = IsPost | IsDecrement
971 bool is_expr, recurse;
975 // Holds the real operation
976 Expression operation;
978 public UnaryMutator (Mode m, Expression e, Location loc)
985 public override Expression CreateExpressionTree (ResolveContext ec)
987 return new SimpleAssign (this, this).CreateExpressionTree (ec);
990 protected override Expression DoResolve (ResolveContext ec)
992 expr = expr.Resolve (ec);
997 if (expr.Type == InternalType.Dynamic) {
999 // Handle postfix unary operators using local
1000 // temporary variable
1002 if ((mode & Mode.IsPost) != 0)
1003 expr = new DynamicPostMutator (expr);
1005 Arguments args = new Arguments (1);
1006 args.Add (new Argument (expr));
1007 return new SimpleAssign (expr, new DynamicUnaryConversion (GetOperatorExpressionTypeName (), args, loc)).Resolve (ec);
1010 if (TypeManager.IsNullableType (expr.Type))
1011 return new Nullable.LiftedUnaryMutator (mode, expr, loc).Resolve (ec);
1013 eclass = ExprClass.Value;
1015 return ResolveOperator (ec);
1018 void EmitCode (EmitContext ec, bool is_expr)
1021 this.is_expr = is_expr;
1022 ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
1025 public override void Emit (EmitContext ec)
1028 // We use recurse to allow ourselfs to be the source
1029 // of an assignment. This little hack prevents us from
1030 // having to allocate another expression
1033 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
1035 operation.Emit (ec);
1041 EmitCode (ec, true);
1044 public override void EmitStatement (EmitContext ec)
1046 EmitCode (ec, false);
1050 // Converts operator to System.Linq.Expressions.ExpressionType enum name
1052 string GetOperatorExpressionTypeName ()
1054 return IsDecrement ? "Decrement" : "Increment";
1058 get { return (mode & Mode.IsDecrement) != 0; }
1062 // Returns whether an object of type `t' can be incremented
1063 // or decremented with add/sub (ie, basically whether we can
1064 // use pre-post incr-decr operations on it, but it is not a
1065 // System.Decimal, which we require operator overloading to catch)
1067 static bool IsPredefinedOperator (TypeSpec t)
1069 return (TypeManager.IsPrimitiveType (t) && t != TypeManager.bool_type) ||
1070 TypeManager.IsEnumType (t) ||
1071 t.IsPointer && t != TypeManager.void_ptr_type;
1075 public override SLE.Expression MakeExpression (BuilderContext ctx)
1077 var target = ((RuntimeValueExpression) expr).MetaObject.Expression;
1078 var source = SLE.Expression.Convert (operation.MakeExpression (ctx), target.Type);
1079 return SLE.Expression.Assign (target, source);
1083 protected override void CloneTo (CloneContext clonectx, Expression t)
1085 UnaryMutator target = (UnaryMutator) t;
1087 target.expr = expr.Clone (clonectx);
1090 Expression ResolveOperator (ResolveContext ec)
1092 if (expr is RuntimeValueExpression) {
1095 // Use itself at the top of the stack
1096 operation = new EmptyExpression (type);
1100 // The operand of the prefix/postfix increment decrement operators
1101 // should be an expression that is classified as a variable,
1102 // a property access or an indexer access
1104 if (expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.IndexerAccess || expr.eclass == ExprClass.PropertyAccess) {
1105 expr = expr.ResolveLValue (ec, expr);
1107 ec.Report.Error (1059, loc, "The operand of an increment or decrement operator must be a variable, property or indexer");
1111 // 1. Check predefined types
1113 if (IsPredefinedOperator (type)) {
1114 // TODO: Move to IntConstant once I get rid of int32_type
1115 var one = new IntConstant (1, loc);
1117 // TODO: Cache this based on type when using EmptyExpression in
1119 Binary.Operator op = IsDecrement ? Binary.Operator.Subtraction : Binary.Operator.Addition;
1120 operation = new Binary (op, operation, one, loc);
1121 operation = operation.Resolve (ec);
1122 if (operation != null && operation.Type != type)
1123 operation = Convert.ExplicitNumericConversion (operation, type);
1129 // Step 2: Perform Operator Overload location
1131 var user_op = IsDecrement ? Operator.OpType.Decrement : Operator.OpType.Increment;
1132 var methods = MemberCache.GetUserOperator (type, user_op, false);
1134 if (methods != null) {
1135 Arguments args = new Arguments (1);
1136 args.Add (new Argument (expr));
1138 var mg = new MethodGroupExpr (methods, type, loc);
1139 mg = mg.OverloadResolve (ec, ref args, false, loc);
1143 args[0].Expr = operation;
1144 operation = new UserOperatorCall (mg.BestCandidate, args, null, loc);
1145 operation = Convert.ImplicitConversionRequired (ec, operation, type, loc);
1149 string name = IsDecrement ?
1150 Operator.GetName (Operator.OpType.Decrement) :
1151 Operator.GetName (Operator.OpType.Increment);
1153 Unary.Error_OperatorCannotBeApplied (ec, loc, name, type);
1159 /// Base class for the `Is' and `As' classes.
1163 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1166 public abstract class Probe : Expression {
1167 public Expression ProbeType;
1168 protected Expression expr;
1169 protected TypeExpr probe_type_expr;
1171 public Probe (Expression expr, Expression probe_type, Location l)
1173 ProbeType = probe_type;
1178 public Expression Expr {
1184 protected override Expression DoResolve (ResolveContext ec)
1186 probe_type_expr = ProbeType.ResolveAsTypeTerminal (ec, false);
1187 if (probe_type_expr == null)
1190 expr = expr.Resolve (ec);
1194 if (probe_type_expr.Type.IsStatic) {
1195 ec.Report.Error (-244, loc, "The `{0}' operator cannot be applied to an operand of a static type",
1199 if (expr.Type.IsPointer || probe_type_expr.Type.IsPointer) {
1200 ec.Report.Error (244, loc, "The `{0}' operator cannot be applied to an operand of pointer type",
1205 if (expr.Type == InternalType.AnonymousMethod) {
1206 ec.Report.Error (837, loc, "The `{0}' operator cannot be applied to a lambda expression or anonymous method",
1214 protected abstract string OperatorName { get; }
1216 protected override void CloneTo (CloneContext clonectx, Expression t)
1218 Probe target = (Probe) t;
1220 target.expr = expr.Clone (clonectx);
1221 target.ProbeType = ProbeType.Clone (clonectx);
1227 /// Implementation of the `is' operator.
1229 public class Is : Probe {
1230 Nullable.Unwrap expr_unwrap;
1232 public Is (Expression expr, Expression probe_type, Location l)
1233 : base (expr, probe_type, l)
1237 public override Expression CreateExpressionTree (ResolveContext ec)
1239 Arguments args = Arguments.CreateForExpressionTree (ec, null,
1240 expr.CreateExpressionTree (ec),
1241 new TypeOf (probe_type_expr, loc));
1243 return CreateExpressionFactoryCall (ec, "TypeIs", args);
1246 public override void Emit (EmitContext ec)
1248 if (expr_unwrap != null) {
1249 expr_unwrap.EmitCheck (ec);
1254 ec.Emit (OpCodes.Isinst, probe_type_expr.Type);
1255 ec.Emit (OpCodes.Ldnull);
1256 ec.Emit (OpCodes.Cgt_Un);
1259 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
1261 if (expr_unwrap != null) {
1262 expr_unwrap.EmitCheck (ec);
1265 ec.Emit (OpCodes.Isinst, probe_type_expr.Type);
1267 ec.Emit (on_true ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1270 Expression CreateConstantResult (ResolveContext ec, bool result)
1273 ec.Report.Warning (183, 1, loc, "The given expression is always of the provided (`{0}') type",
1274 TypeManager.CSharpName (probe_type_expr.Type));
1276 ec.Report.Warning (184, 1, loc, "The given expression is never of the provided (`{0}') type",
1277 TypeManager.CSharpName (probe_type_expr.Type));
1279 return ReducedExpression.Create (new BoolConstant (result, loc).Resolve (ec), this);
1282 protected override Expression DoResolve (ResolveContext ec)
1284 if (base.DoResolve (ec) == null)
1287 TypeSpec d = expr.Type;
1288 bool d_is_nullable = false;
1291 // If E is a method group or the null literal, or if the type of E is a reference
1292 // type or a nullable type and the value of E is null, the result is false
1294 if (expr.IsNull || expr.eclass == ExprClass.MethodGroup)
1295 return CreateConstantResult (ec, false);
1297 if (TypeManager.IsNullableType (d)) {
1298 var ut = Nullable.NullableInfo.GetUnderlyingType (d);
1299 if (!ut.IsGenericParameter) {
1301 d_is_nullable = true;
1305 type = TypeManager.bool_type;
1306 eclass = ExprClass.Value;
1307 TypeSpec t = probe_type_expr.Type;
1308 bool t_is_nullable = false;
1309 if (TypeManager.IsNullableType (t)) {
1310 var ut = Nullable.NullableInfo.GetUnderlyingType (t);
1311 if (!ut.IsGenericParameter) {
1313 t_is_nullable = true;
1317 if (TypeManager.IsStruct (t)) {
1320 // D and T are the same value types but D can be null
1322 if (d_is_nullable && !t_is_nullable) {
1323 expr_unwrap = Nullable.Unwrap.Create (expr, false);
1328 // The result is true if D and T are the same value types
1330 return CreateConstantResult (ec, true);
1333 var tp = d as TypeParameterSpec;
1335 return ResolveGenericParameter (ec, t, tp);
1338 // An unboxing conversion exists
1340 if (Convert.ExplicitReferenceConversionExists (d, t))
1343 if (TypeManager.IsGenericParameter (t))
1344 return ResolveGenericParameter (ec, d, (TypeParameterSpec) t);
1346 if (TypeManager.IsStruct (d)) {
1347 if (Convert.ImplicitBoxingConversion (null, d, t) != null)
1348 return CreateConstantResult (ec, true);
1350 if (TypeManager.IsGenericParameter (d))
1351 return ResolveGenericParameter (ec, t, (TypeParameterSpec) d);
1353 if (TypeManager.ContainsGenericParameters (d))
1356 if (Convert.ImplicitReferenceConversionExists (expr, t) ||
1357 Convert.ExplicitReferenceConversionExists (d, t)) {
1363 return CreateConstantResult (ec, false);
1366 Expression ResolveGenericParameter (ResolveContext ec, TypeSpec d, TypeParameterSpec t)
1368 if (t.IsReferenceType) {
1369 if (TypeManager.IsStruct (d))
1370 return CreateConstantResult (ec, false);
1373 if (TypeManager.IsGenericParameter (expr.Type)) {
1374 if (t.IsValueType && expr.Type == t)
1375 return CreateConstantResult (ec, true);
1377 expr = new BoxedCast (expr, d);
1383 protected override string OperatorName {
1384 get { return "is"; }
1389 /// Implementation of the `as' operator.
1391 public class As : Probe {
1393 Expression resolved_type;
1395 public As (Expression expr, Expression probe_type, Location l)
1396 : base (expr, probe_type, l)
1400 public override Expression CreateExpressionTree (ResolveContext ec)
1402 Arguments args = Arguments.CreateForExpressionTree (ec, null,
1403 expr.CreateExpressionTree (ec),
1404 new TypeOf (probe_type_expr, loc));
1406 return CreateExpressionFactoryCall (ec, "TypeAs", args);
1409 public override void Emit (EmitContext ec)
1414 ec.Emit (OpCodes.Isinst, type);
1416 if (TypeManager.IsGenericParameter (type) || TypeManager.IsNullableType (type))
1417 ec.Emit (OpCodes.Unbox_Any, type);
1420 protected override Expression DoResolve (ResolveContext ec)
1422 if (resolved_type == null) {
1423 resolved_type = base.DoResolve (ec);
1425 if (resolved_type == null)
1429 type = probe_type_expr.Type;
1430 eclass = ExprClass.Value;
1431 TypeSpec etype = expr.Type;
1433 if (!TypeManager.IsReferenceType (type) && !TypeManager.IsNullableType (type)) {
1434 if (TypeManager.IsGenericParameter (type)) {
1435 ec.Report.Error (413, loc,
1436 "The `as' operator cannot be used with a non-reference type parameter `{0}'. Consider adding `class' or a reference type constraint",
1437 probe_type_expr.GetSignatureForError ());
1439 ec.Report.Error (77, loc,
1440 "The `as' operator cannot be used with a non-nullable value type `{0}'",
1441 TypeManager.CSharpName (type));
1446 if (expr.IsNull && TypeManager.IsNullableType (type)) {
1447 return Nullable.LiftedNull.CreateFromExpression (ec, this);
1450 Expression e = Convert.ImplicitConversion (ec, expr, type, loc);
1457 if (Convert.ExplicitReferenceConversionExists (etype, type)){
1458 if (TypeManager.IsGenericParameter (etype))
1459 expr = new BoxedCast (expr, etype);
1465 if (TypeManager.ContainsGenericParameters (etype) ||
1466 TypeManager.ContainsGenericParameters (type)) {
1467 expr = new BoxedCast (expr, etype);
1472 ec.Report.Error (39, loc, "Cannot convert type `{0}' to `{1}' via a built-in conversion",
1473 TypeManager.CSharpName (etype), TypeManager.CSharpName (type));
1478 protected override string OperatorName {
1479 get { return "as"; }
1484 // This represents a typecast in the source language.
1486 public class Cast : ShimExpression {
1487 Expression target_type;
1489 public Cast (Expression cast_type, Expression expr, Location loc)
1492 this.target_type = cast_type;
1496 public Expression TargetType {
1497 get { return target_type; }
1500 protected override Expression DoResolve (ResolveContext ec)
1502 expr = expr.Resolve (ec);
1506 TypeExpr target = target_type.ResolveAsTypeTerminal (ec, false);
1512 if (type.IsStatic) {
1513 ec.Report.Error (716, loc, "Cannot convert to static type `{0}'", TypeManager.CSharpName (type));
1517 eclass = ExprClass.Value;
1519 Constant c = expr as Constant;
1521 c = c.TryReduce (ec, type, loc);
1526 if (type.IsPointer && !ec.IsUnsafe) {
1527 UnsafeError (ec, loc);
1528 } else if (expr.Type == InternalType.Dynamic) {
1529 Arguments arg = new Arguments (1);
1530 arg.Add (new Argument (expr));
1531 return new DynamicConversion (type, CSharpBinderFlags.ConvertExplicit, arg, loc).Resolve (ec);
1534 var res = Convert.ExplicitConversion (ec, expr, type, loc);
1536 return EmptyCast.Create (res, type);
1541 protected override void CloneTo (CloneContext clonectx, Expression t)
1543 Cast target = (Cast) t;
1545 target.target_type = target_type.Clone (clonectx);
1546 target.expr = expr.Clone (clonectx);
1550 public class ImplicitCast : ShimExpression
1554 public ImplicitCast (Expression expr, TypeSpec target, bool arrayAccess)
1557 this.loc = expr.Location;
1559 this.arrayAccess = arrayAccess;
1562 protected override Expression DoResolve (ResolveContext ec)
1564 expr = expr.Resolve (ec);
1569 expr = ConvertExpressionToArrayIndex (ec, expr);
1571 expr = Convert.ImplicitConversionRequired (ec, expr, type, loc);
1578 // C# 2.0 Default value expression
1580 public class DefaultValueExpression : Expression
1584 public DefaultValueExpression (Expression expr, Location loc)
1590 public override Expression CreateExpressionTree (ResolveContext ec)
1592 Arguments args = new Arguments (2);
1593 args.Add (new Argument (this));
1594 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
1595 return CreateExpressionFactoryCall (ec, "Constant", args);
1598 protected override Expression DoResolve (ResolveContext ec)
1600 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
1606 if (type.IsStatic) {
1607 ec.Report.Error (-244, loc, "The `default value' operator cannot be applied to an operand of a static type");
1611 return new NullLiteral (Location).ConvertImplicitly (ec, type);
1613 if (TypeManager.IsReferenceType (type))
1614 return new NullConstant (type, loc);
1616 Constant c = New.Constantify (type);
1618 return c.Resolve (ec);
1620 eclass = ExprClass.Variable;
1624 public override void Emit (EmitContext ec)
1626 LocalTemporary temp_storage = new LocalTemporary(type);
1628 temp_storage.AddressOf(ec, AddressOp.LoadStore);
1629 ec.Emit(OpCodes.Initobj, type);
1630 temp_storage.Emit(ec);
1633 protected override void CloneTo (CloneContext clonectx, Expression t)
1635 DefaultValueExpression target = (DefaultValueExpression) t;
1637 target.expr = expr.Clone (clonectx);
1642 /// Binary operators
1644 public class Binary : Expression, IDynamicBinder
1646 protected class PredefinedOperator {
1647 protected readonly TypeSpec left;
1648 protected readonly TypeSpec right;
1649 public readonly Operator OperatorsMask;
1650 public TypeSpec ReturnType;
1652 public PredefinedOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
1653 : this (ltype, rtype, op_mask, ltype)
1657 public PredefinedOperator (TypeSpec type, Operator op_mask, TypeSpec return_type)
1658 : this (type, type, op_mask, return_type)
1662 public PredefinedOperator (TypeSpec type, Operator op_mask)
1663 : this (type, type, op_mask, type)
1667 public PredefinedOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask, TypeSpec return_type)
1669 if ((op_mask & Operator.ValuesOnlyMask) != 0)
1670 throw new InternalErrorException ("Only masked values can be used");
1674 this.OperatorsMask = op_mask;
1675 this.ReturnType = return_type;
1678 public virtual Expression ConvertResult (ResolveContext ec, Binary b)
1680 b.type = ReturnType;
1682 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1683 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
1686 // A user operators does not support multiple user conversions, but decimal type
1687 // is considered to be predefined type therefore we apply predefined operators rules
1688 // and then look for decimal user-operator implementation
1690 if (left == TypeManager.decimal_type)
1691 return b.ResolveUserOperator (ec, b.left.Type, b.right.Type);
1693 var c = b.right as Constant;
1695 if (c.IsDefaultValue && (b.oper == Operator.Addition || b.oper == Operator.BitwiseOr || b.oper == Operator.Subtraction))
1696 return ReducedExpression.Create (b.left, b).Resolve (ec);
1697 if ((b.oper == Operator.Multiply || b.oper == Operator.Division) && c.IsOneInteger)
1698 return ReducedExpression.Create (b.left, b).Resolve (ec);
1702 c = b.left as Constant;
1704 if (c.IsDefaultValue && (b.oper == Operator.Addition || b.oper == Operator.BitwiseOr))
1705 return ReducedExpression.Create (b.right, b).Resolve (ec);
1706 if (b.oper == Operator.Multiply && c.IsOneInteger)
1707 return ReducedExpression.Create (b.right, b).Resolve (ec);
1714 public bool IsPrimitiveApplicable (TypeSpec ltype, TypeSpec rtype)
1717 // We are dealing with primitive types only
1719 return left == ltype && ltype == rtype;
1722 public virtual bool IsApplicable (ResolveContext ec, Expression lexpr, Expression rexpr)
1724 if (TypeManager.IsEqual (left, lexpr.Type) &&
1725 TypeManager.IsEqual (right, rexpr.Type))
1728 return Convert.ImplicitConversionExists (ec, lexpr, left) &&
1729 Convert.ImplicitConversionExists (ec, rexpr, right);
1732 public PredefinedOperator ResolveBetterOperator (ResolveContext ec, PredefinedOperator best_operator)
1735 if (left != null && best_operator.left != null) {
1736 result = MethodGroupExpr.BetterTypeConversion (ec, best_operator.left, left);
1740 // When second argument is same as the first one, the result is same
1742 if (right != null && (left != right || best_operator.left != best_operator.right)) {
1743 result |= MethodGroupExpr.BetterTypeConversion (ec, best_operator.right, right);
1746 if (result == 0 || result > 2)
1749 return result == 1 ? best_operator : this;
1753 class PredefinedStringOperator : PredefinedOperator {
1754 public PredefinedStringOperator (TypeSpec type, Operator op_mask)
1755 : base (type, op_mask, type)
1757 ReturnType = TypeManager.string_type;
1760 public PredefinedStringOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
1761 : base (ltype, rtype, op_mask)
1763 ReturnType = TypeManager.string_type;
1766 public override Expression ConvertResult (ResolveContext ec, Binary b)
1769 // Use original expression for nullable arguments
1771 Nullable.Unwrap unwrap = b.left as Nullable.Unwrap;
1773 b.left = unwrap.Original;
1775 unwrap = b.right as Nullable.Unwrap;
1777 b.right = unwrap.Original;
1779 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1780 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
1783 // Start a new concat expression using converted expression
1785 return StringConcat.Create (ec, b.left, b.right, b.loc);
1789 class PredefinedShiftOperator : PredefinedOperator {
1790 public PredefinedShiftOperator (TypeSpec ltype, Operator op_mask) :
1791 base (ltype, TypeManager.int32_type, op_mask)
1795 public override Expression ConvertResult (ResolveContext ec, Binary b)
1797 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1799 Expression expr_tree_expr = Convert.ImplicitConversion (ec, b.right, TypeManager.int32_type, b.right.Location);
1801 int right_mask = left == TypeManager.int32_type || left == TypeManager.uint32_type ? 0x1f : 0x3f;
1804 // b = b.left >> b.right & (0x1f|0x3f)
1806 b.right = new Binary (Operator.BitwiseAnd,
1807 b.right, new IntConstant (right_mask, b.right.Location), b.loc).Resolve (ec);
1810 // Expression tree representation does not use & mask
1812 b.right = ReducedExpression.Create (b.right, expr_tree_expr).Resolve (ec);
1813 b.type = ReturnType;
1816 // Optimize shift by 0
1818 var c = b.right as Constant;
1819 if (c != null && c.IsDefaultValue)
1820 return ReducedExpression.Create (b.left, b).Resolve (ec);
1826 class PredefinedEqualityOperator : PredefinedOperator
1828 MethodSpec equal_method, inequal_method;
1830 public PredefinedEqualityOperator (TypeSpec arg, TypeSpec retType)
1831 : base (arg, arg, Operator.EqualityMask, retType)
1835 public override Expression ConvertResult (ResolveContext ec, Binary b)
1837 b.type = ReturnType;
1839 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1840 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
1842 Arguments args = new Arguments (2);
1843 args.Add (new Argument (b.left));
1844 args.Add (new Argument (b.right));
1847 if (b.oper == Operator.Equality) {
1848 if (equal_method == null) {
1849 equal_method = TypeManager.GetPredefinedMethod (left,
1850 new MemberFilter (CSharp.Operator.GetMetadataName (CSharp.Operator.OpType.Equality), 0, MemberKind.Operator, null, ReturnType), b.loc);
1853 method = equal_method;
1855 if (inequal_method == null) {
1856 inequal_method = TypeManager.GetPredefinedMethod (left,
1857 new MemberFilter (CSharp.Operator.GetMetadataName (CSharp.Operator.OpType.Inequality), 0, MemberKind.Operator, null, ReturnType), b.loc);
1860 method = inequal_method;
1863 return new UserOperatorCall (method, args, b.CreateExpressionTree, b.loc);
1867 class PredefinedPointerOperator : PredefinedOperator
1869 public PredefinedPointerOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
1870 : base (ltype, rtype, op_mask)
1874 public PredefinedPointerOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask, TypeSpec retType)
1875 : base (ltype, rtype, op_mask, retType)
1879 public PredefinedPointerOperator (TypeSpec type, Operator op_mask, TypeSpec return_type)
1880 : base (type, op_mask, return_type)
1884 public override bool IsApplicable (ResolveContext ec, Expression lexpr, Expression rexpr)
1887 if (!lexpr.Type.IsPointer)
1890 if (!Convert.ImplicitConversionExists (ec, lexpr, left))
1894 if (right == null) {
1895 if (!rexpr.Type.IsPointer)
1898 if (!Convert.ImplicitConversionExists (ec, rexpr, right))
1905 public override Expression ConvertResult (ResolveContext ec, Binary b)
1908 b.left = EmptyCast.Create (b.left, left);
1909 } else if (right != null) {
1910 b.right = EmptyCast.Create (b.right, right);
1913 TypeSpec r_type = ReturnType;
1914 Expression left_arg, right_arg;
1915 if (r_type == null) {
1918 right_arg = b.right;
1919 r_type = b.left.Type;
1923 r_type = b.right.Type;
1927 right_arg = b.right;
1930 return new PointerArithmetic (b.oper, left_arg, right_arg, r_type, b.loc).Resolve (ec);
1935 public enum Operator {
1936 Multiply = 0 | ArithmeticMask,
1937 Division = 1 | ArithmeticMask,
1938 Modulus = 2 | ArithmeticMask,
1939 Addition = 3 | ArithmeticMask | AdditionMask,
1940 Subtraction = 4 | ArithmeticMask | SubtractionMask,
1942 LeftShift = 5 | ShiftMask,
1943 RightShift = 6 | ShiftMask,
1945 LessThan = 7 | ComparisonMask | RelationalMask,
1946 GreaterThan = 8 | ComparisonMask | RelationalMask,
1947 LessThanOrEqual = 9 | ComparisonMask | RelationalMask,
1948 GreaterThanOrEqual = 10 | ComparisonMask | RelationalMask,
1949 Equality = 11 | ComparisonMask | EqualityMask,
1950 Inequality = 12 | ComparisonMask | EqualityMask,
1952 BitwiseAnd = 13 | BitwiseMask,
1953 ExclusiveOr = 14 | BitwiseMask,
1954 BitwiseOr = 15 | BitwiseMask,
1956 LogicalAnd = 16 | LogicalMask,
1957 LogicalOr = 17 | LogicalMask,
1962 ValuesOnlyMask = ArithmeticMask - 1,
1963 ArithmeticMask = 1 << 5,
1965 ComparisonMask = 1 << 7,
1966 EqualityMask = 1 << 8,
1967 BitwiseMask = 1 << 9,
1968 LogicalMask = 1 << 10,
1969 AdditionMask = 1 << 11,
1970 SubtractionMask = 1 << 12,
1971 RelationalMask = 1 << 13
1974 readonly Operator oper;
1975 protected Expression left, right;
1976 readonly bool is_compound;
1977 Expression enum_conversion;
1979 static PredefinedOperator[] standard_operators;
1980 static PredefinedOperator[] equality_operators;
1981 static PredefinedOperator[] pointer_operators;
1983 public Binary (Operator oper, Expression left, Expression right, bool isCompound, Location loc)
1984 : this (oper, left, right, loc)
1986 this.is_compound = isCompound;
1989 public Binary (Operator oper, Expression left, Expression right, Location loc)
1997 public Operator Oper {
2004 /// Returns a stringified representation of the Operator
2006 string OperName (Operator oper)
2010 case Operator.Multiply:
2013 case Operator.Division:
2016 case Operator.Modulus:
2019 case Operator.Addition:
2022 case Operator.Subtraction:
2025 case Operator.LeftShift:
2028 case Operator.RightShift:
2031 case Operator.LessThan:
2034 case Operator.GreaterThan:
2037 case Operator.LessThanOrEqual:
2040 case Operator.GreaterThanOrEqual:
2043 case Operator.Equality:
2046 case Operator.Inequality:
2049 case Operator.BitwiseAnd:
2052 case Operator.BitwiseOr:
2055 case Operator.ExclusiveOr:
2058 case Operator.LogicalOr:
2061 case Operator.LogicalAnd:
2065 s = oper.ToString ();
2075 public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, Operator oper, Location loc)
2077 new Binary (oper, left, right, loc).Error_OperatorCannotBeApplied (ec, left, right);
2080 public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, string oper, Location loc)
2083 l = TypeManager.CSharpName (left.Type);
2084 r = TypeManager.CSharpName (right.Type);
2086 ec.Report.Error (19, loc, "Operator `{0}' cannot be applied to operands of type `{1}' and `{2}'",
2090 protected void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right)
2092 Error_OperatorCannotBeApplied (ec, left, right, OperName (oper), loc);
2096 // Converts operator to System.Linq.Expressions.ExpressionType enum name
2098 string GetOperatorExpressionTypeName ()
2101 case Operator.Addition:
2102 return is_compound ? "AddAssign" : "Add";
2103 case Operator.BitwiseAnd:
2104 return is_compound ? "AndAssign" : "And";
2105 case Operator.BitwiseOr:
2106 return is_compound ? "OrAssign" : "Or";
2107 case Operator.Division:
2108 return is_compound ? "DivideAssign" : "Divide";
2109 case Operator.ExclusiveOr:
2110 return is_compound ? "ExclusiveOrAssign" : "ExclusiveOr";
2111 case Operator.Equality:
2113 case Operator.GreaterThan:
2114 return "GreaterThan";
2115 case Operator.GreaterThanOrEqual:
2116 return "GreaterThanOrEqual";
2117 case Operator.Inequality:
2119 case Operator.LeftShift:
2120 return is_compound ? "LeftShiftAssign" : "LeftShift";
2121 case Operator.LessThan:
2123 case Operator.LessThanOrEqual:
2124 return "LessThanOrEqual";
2125 case Operator.LogicalAnd:
2127 case Operator.LogicalOr:
2129 case Operator.Modulus:
2130 return is_compound ? "ModuloAssign" : "Modulo";
2131 case Operator.Multiply:
2132 return is_compound ? "MultiplyAssign" : "Multiply";
2133 case Operator.RightShift:
2134 return is_compound ? "RightShiftAssign" : "RightShift";
2135 case Operator.Subtraction:
2136 return is_compound ? "SubtractAssign" : "Subtract";
2138 throw new NotImplementedException ("Unknown expression type operator " + oper.ToString ());
2142 static CSharp.Operator.OpType ConvertBinaryToUserOperator (Operator op)
2145 case Operator.Addition:
2146 return CSharp.Operator.OpType.Addition;
2147 case Operator.BitwiseAnd:
2148 case Operator.LogicalAnd:
2149 return CSharp.Operator.OpType.BitwiseAnd;
2150 case Operator.BitwiseOr:
2151 case Operator.LogicalOr:
2152 return CSharp.Operator.OpType.BitwiseOr;
2153 case Operator.Division:
2154 return CSharp.Operator.OpType.Division;
2155 case Operator.Equality:
2156 return CSharp.Operator.OpType.Equality;
2157 case Operator.ExclusiveOr:
2158 return CSharp.Operator.OpType.ExclusiveOr;
2159 case Operator.GreaterThan:
2160 return CSharp.Operator.OpType.GreaterThan;
2161 case Operator.GreaterThanOrEqual:
2162 return CSharp.Operator.OpType.GreaterThanOrEqual;
2163 case Operator.Inequality:
2164 return CSharp.Operator.OpType.Inequality;
2165 case Operator.LeftShift:
2166 return CSharp.Operator.OpType.LeftShift;
2167 case Operator.LessThan:
2168 return CSharp.Operator.OpType.LessThan;
2169 case Operator.LessThanOrEqual:
2170 return CSharp.Operator.OpType.LessThanOrEqual;
2171 case Operator.Modulus:
2172 return CSharp.Operator.OpType.Modulus;
2173 case Operator.Multiply:
2174 return CSharp.Operator.OpType.Multiply;
2175 case Operator.RightShift:
2176 return CSharp.Operator.OpType.RightShift;
2177 case Operator.Subtraction:
2178 return CSharp.Operator.OpType.Subtraction;
2180 throw new InternalErrorException (op.ToString ());
2184 public static void EmitOperatorOpcode (EmitContext ec, Operator oper, TypeSpec l)
2189 case Operator.Multiply:
2190 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2191 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2192 opcode = OpCodes.Mul_Ovf;
2193 else if (!IsFloat (l))
2194 opcode = OpCodes.Mul_Ovf_Un;
2196 opcode = OpCodes.Mul;
2198 opcode = OpCodes.Mul;
2202 case Operator.Division:
2204 opcode = OpCodes.Div_Un;
2206 opcode = OpCodes.Div;
2209 case Operator.Modulus:
2211 opcode = OpCodes.Rem_Un;
2213 opcode = OpCodes.Rem;
2216 case Operator.Addition:
2217 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2218 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2219 opcode = OpCodes.Add_Ovf;
2220 else if (!IsFloat (l))
2221 opcode = OpCodes.Add_Ovf_Un;
2223 opcode = OpCodes.Add;
2225 opcode = OpCodes.Add;
2228 case Operator.Subtraction:
2229 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2230 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2231 opcode = OpCodes.Sub_Ovf;
2232 else if (!IsFloat (l))
2233 opcode = OpCodes.Sub_Ovf_Un;
2235 opcode = OpCodes.Sub;
2237 opcode = OpCodes.Sub;
2240 case Operator.RightShift:
2242 opcode = OpCodes.Shr_Un;
2244 opcode = OpCodes.Shr;
2247 case Operator.LeftShift:
2248 opcode = OpCodes.Shl;
2251 case Operator.Equality:
2252 opcode = OpCodes.Ceq;
2255 case Operator.Inequality:
2256 ec.Emit (OpCodes.Ceq);
2257 ec.Emit (OpCodes.Ldc_I4_0);
2259 opcode = OpCodes.Ceq;
2262 case Operator.LessThan:
2264 opcode = OpCodes.Clt_Un;
2266 opcode = OpCodes.Clt;
2269 case Operator.GreaterThan:
2271 opcode = OpCodes.Cgt_Un;
2273 opcode = OpCodes.Cgt;
2276 case Operator.LessThanOrEqual:
2277 if (IsUnsigned (l) || IsFloat (l))
2278 ec.Emit (OpCodes.Cgt_Un);
2280 ec.Emit (OpCodes.Cgt);
2281 ec.Emit (OpCodes.Ldc_I4_0);
2283 opcode = OpCodes.Ceq;
2286 case Operator.GreaterThanOrEqual:
2287 if (IsUnsigned (l) || IsFloat (l))
2288 ec.Emit (OpCodes.Clt_Un);
2290 ec.Emit (OpCodes.Clt);
2292 ec.Emit (OpCodes.Ldc_I4_0);
2294 opcode = OpCodes.Ceq;
2297 case Operator.BitwiseOr:
2298 opcode = OpCodes.Or;
2301 case Operator.BitwiseAnd:
2302 opcode = OpCodes.And;
2305 case Operator.ExclusiveOr:
2306 opcode = OpCodes.Xor;
2310 throw new InternalErrorException (oper.ToString ());
2316 static bool IsUnsigned (TypeSpec t)
2321 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2322 t == TypeManager.ushort_type || t == TypeManager.byte_type);
2325 static bool IsFloat (TypeSpec t)
2327 return t == TypeManager.float_type || t == TypeManager.double_type;
2330 public static void Reset ()
2332 equality_operators = pointer_operators = standard_operators = null;
2335 Expression ResolveOperator (ResolveContext ec)
2337 TypeSpec l = left.Type;
2338 TypeSpec r = right.Type;
2340 bool primitives_only = false;
2342 if (standard_operators == null)
2343 CreateStandardOperatorsTable ();
2346 // Handles predefined primitive types
2348 if (TypeManager.IsPrimitiveType (l) && TypeManager.IsPrimitiveType (r)) {
2349 if ((oper & Operator.ShiftMask) == 0) {
2350 if (l != TypeManager.bool_type && !DoBinaryOperatorPromotion (ec))
2353 primitives_only = true;
2357 if (l.IsPointer || r.IsPointer)
2358 return ResolveOperatorPointer (ec, l, r);
2361 bool lenum = TypeManager.IsEnumType (l);
2362 bool renum = TypeManager.IsEnumType (r);
2363 if (lenum || renum) {
2364 expr = ResolveOperatorEnum (ec, lenum, renum, l, r);
2366 // TODO: Can this be ambiguous
2372 if ((oper == Operator.Addition || oper == Operator.Subtraction) && (l.IsDelegate || r.IsDelegate)) {
2374 expr = ResolveOperatorDelegate (ec, l, r);
2376 // TODO: Can this be ambiguous
2382 expr = ResolveUserOperator (ec, l, r);
2386 // Predefined reference types equality
2387 if ((oper & Operator.EqualityMask) != 0) {
2388 expr = ResolveOperatorEquality (ec, l, r);
2394 return ResolveOperatorPredefined (ec, standard_operators, primitives_only, null);
2397 // at least one of 'left' or 'right' is an enumeration constant (EnumConstant or SideEffectConstant or ...)
2398 // if 'left' is not an enumeration constant, create one from the type of 'right'
2399 Constant EnumLiftUp (ResolveContext ec, Constant left, Constant right, Location loc)
2402 case Operator.BitwiseOr:
2403 case Operator.BitwiseAnd:
2404 case Operator.ExclusiveOr:
2405 case Operator.Equality:
2406 case Operator.Inequality:
2407 case Operator.LessThan:
2408 case Operator.LessThanOrEqual:
2409 case Operator.GreaterThan:
2410 case Operator.GreaterThanOrEqual:
2411 if (TypeManager.IsEnumType (left.Type))
2414 if (left.IsZeroInteger)
2415 return left.TryReduce (ec, right.Type, loc);
2419 case Operator.Addition:
2420 case Operator.Subtraction:
2423 case Operator.Multiply:
2424 case Operator.Division:
2425 case Operator.Modulus:
2426 case Operator.LeftShift:
2427 case Operator.RightShift:
2428 if (TypeManager.IsEnumType (right.Type) || TypeManager.IsEnumType (left.Type))
2432 Error_OperatorCannotBeApplied (ec, this.left, this.right);
2437 // The `|' operator used on types which were extended is dangerous
2439 void CheckBitwiseOrOnSignExtended (ResolveContext ec)
2441 OpcodeCast lcast = left as OpcodeCast;
2442 if (lcast != null) {
2443 if (IsUnsigned (lcast.UnderlyingType))
2447 OpcodeCast rcast = right as OpcodeCast;
2448 if (rcast != null) {
2449 if (IsUnsigned (rcast.UnderlyingType))
2453 if (lcast == null && rcast == null)
2456 // FIXME: consider constants
2458 ec.Report.Warning (675, 3, loc,
2459 "The operator `|' used on the sign-extended type `{0}'. Consider casting to a smaller unsigned type first",
2460 TypeManager.CSharpName (lcast != null ? lcast.UnderlyingType : rcast.UnderlyingType));
2463 static void CreatePointerOperatorsTable ()
2465 var temp = new List<PredefinedPointerOperator> ();
2468 // Pointer arithmetic:
2470 // T* operator + (T* x, int y); T* operator - (T* x, int y);
2471 // T* operator + (T* x, uint y); T* operator - (T* x, uint y);
2472 // T* operator + (T* x, long y); T* operator - (T* x, long y);
2473 // T* operator + (T* x, ulong y); T* operator - (T* x, ulong y);
2475 temp.Add (new PredefinedPointerOperator (null, TypeManager.int32_type, Operator.AdditionMask | Operator.SubtractionMask));
2476 temp.Add (new PredefinedPointerOperator (null, TypeManager.uint32_type, Operator.AdditionMask | Operator.SubtractionMask));
2477 temp.Add (new PredefinedPointerOperator (null, TypeManager.int64_type, Operator.AdditionMask | Operator.SubtractionMask));
2478 temp.Add (new PredefinedPointerOperator (null, TypeManager.uint64_type, Operator.AdditionMask | Operator.SubtractionMask));
2481 // T* operator + (int y, T* x);
2482 // T* operator + (uint y, T *x);
2483 // T* operator + (long y, T *x);
2484 // T* operator + (ulong y, T *x);
2486 temp.Add (new PredefinedPointerOperator (TypeManager.int32_type, null, Operator.AdditionMask, null));
2487 temp.Add (new PredefinedPointerOperator (TypeManager.uint32_type, null, Operator.AdditionMask, null));
2488 temp.Add (new PredefinedPointerOperator (TypeManager.int64_type, null, Operator.AdditionMask, null));
2489 temp.Add (new PredefinedPointerOperator (TypeManager.uint64_type, null, Operator.AdditionMask, null));
2492 // long operator - (T* x, T *y)
2494 temp.Add (new PredefinedPointerOperator (null, Operator.SubtractionMask, TypeManager.int64_type));
2496 pointer_operators = temp.ToArray ();
2499 static void CreateStandardOperatorsTable ()
2501 var temp = new List<PredefinedOperator> ();
2502 TypeSpec bool_type = TypeManager.bool_type;
2504 temp.Add (new PredefinedOperator (TypeManager.int32_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2505 temp.Add (new PredefinedOperator (TypeManager.uint32_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2506 temp.Add (new PredefinedOperator (TypeManager.int64_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2507 temp.Add (new PredefinedOperator (TypeManager.uint64_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2508 temp.Add (new PredefinedOperator (TypeManager.float_type, Operator.ArithmeticMask));
2509 temp.Add (new PredefinedOperator (TypeManager.double_type, Operator.ArithmeticMask));
2510 temp.Add (new PredefinedOperator (TypeManager.decimal_type, Operator.ArithmeticMask));
2512 temp.Add (new PredefinedOperator (TypeManager.int32_type, Operator.ComparisonMask, bool_type));
2513 temp.Add (new PredefinedOperator (TypeManager.uint32_type, Operator.ComparisonMask, bool_type));
2514 temp.Add (new PredefinedOperator (TypeManager.int64_type, Operator.ComparisonMask, bool_type));
2515 temp.Add (new PredefinedOperator (TypeManager.uint64_type, Operator.ComparisonMask, bool_type));
2516 temp.Add (new PredefinedOperator (TypeManager.float_type, Operator.ComparisonMask, bool_type));
2517 temp.Add (new PredefinedOperator (TypeManager.double_type, Operator.ComparisonMask, bool_type));
2518 temp.Add (new PredefinedOperator (TypeManager.decimal_type, Operator.ComparisonMask, bool_type));
2520 temp.Add (new PredefinedStringOperator (TypeManager.string_type, Operator.AdditionMask));
2521 temp.Add (new PredefinedStringOperator (TypeManager.string_type, TypeManager.object_type, Operator.AdditionMask));
2522 temp.Add (new PredefinedStringOperator (TypeManager.object_type, TypeManager.string_type, Operator.AdditionMask));
2524 temp.Add (new PredefinedOperator (bool_type,
2525 Operator.BitwiseMask | Operator.LogicalMask | Operator.EqualityMask, bool_type));
2527 temp.Add (new PredefinedShiftOperator (TypeManager.int32_type, Operator.ShiftMask));
2528 temp.Add (new PredefinedShiftOperator (TypeManager.uint32_type, Operator.ShiftMask));
2529 temp.Add (new PredefinedShiftOperator (TypeManager.int64_type, Operator.ShiftMask));
2530 temp.Add (new PredefinedShiftOperator (TypeManager.uint64_type, Operator.ShiftMask));
2532 standard_operators = temp.ToArray ();
2534 var equality = new List<PredefinedOperator> () {
2535 new PredefinedEqualityOperator (TypeManager.string_type, bool_type),
2536 new PredefinedEqualityOperator (TypeManager.delegate_type, bool_type),
2537 new PredefinedOperator (bool_type, Operator.EqualityMask, bool_type)
2540 equality_operators = equality.ToArray ();
2544 // Rules used during binary numeric promotion
2546 static bool DoNumericPromotion (ResolveContext rc, ref Expression prim_expr, ref Expression second_expr, TypeSpec type)
2551 Constant c = prim_expr as Constant;
2553 temp = c.ConvertImplicitly (rc, type);
2560 if (type == TypeManager.uint32_type) {
2561 etype = prim_expr.Type;
2562 if (etype == TypeManager.int32_type || etype == TypeManager.short_type || etype == TypeManager.sbyte_type) {
2563 type = TypeManager.int64_type;
2565 if (type != second_expr.Type) {
2566 c = second_expr as Constant;
2568 temp = c.ConvertImplicitly (rc, type);
2570 temp = Convert.ImplicitNumericConversion (second_expr, type);
2576 } else if (type == TypeManager.uint64_type) {
2578 // A compile-time error occurs if the other operand is of type sbyte, short, int, or long
2580 if (type == TypeManager.int32_type || type == TypeManager.int64_type ||
2581 type == TypeManager.short_type || type == TypeManager.sbyte_type)
2585 temp = Convert.ImplicitNumericConversion (prim_expr, type);
2594 // 7.2.6.2 Binary numeric promotions
2596 public bool DoBinaryOperatorPromotion (ResolveContext ec)
2598 TypeSpec ltype = left.Type;
2599 TypeSpec rtype = right.Type;
2602 foreach (TypeSpec t in ConstantFold.BinaryPromotionsTypes) {
2604 return t == rtype || DoNumericPromotion (ec, ref right, ref left, t);
2607 return t == ltype || DoNumericPromotion (ec, ref left, ref right, t);
2610 TypeSpec int32 = TypeManager.int32_type;
2611 if (ltype != int32) {
2612 Constant c = left as Constant;
2614 temp = c.ConvertImplicitly (ec, int32);
2616 temp = Convert.ImplicitNumericConversion (left, int32);
2623 if (rtype != int32) {
2624 Constant c = right as Constant;
2626 temp = c.ConvertImplicitly (ec, int32);
2628 temp = Convert.ImplicitNumericConversion (right, int32);
2638 protected override Expression DoResolve (ResolveContext ec)
2643 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2644 left = ((ParenthesizedExpression) left).Expr;
2645 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2649 if (left.eclass == ExprClass.Type) {
2650 ec.Report.Error (75, loc, "To cast a negative value, you must enclose the value in parentheses");
2654 left = left.Resolve (ec);
2659 Constant lc = left as Constant;
2661 if (lc != null && lc.Type == TypeManager.bool_type &&
2662 ((oper == Operator.LogicalAnd && lc.IsDefaultValue) ||
2663 (oper == Operator.LogicalOr && !lc.IsDefaultValue))) {
2665 // FIXME: resolve right expression as unreachable
2666 // right.Resolve (ec);
2668 ec.Report.Warning (429, 4, loc, "Unreachable expression code detected");
2672 right = right.Resolve (ec);
2676 eclass = ExprClass.Value;
2677 Constant rc = right as Constant;
2679 // The conversion rules are ignored in enum context but why
2680 if (!ec.HasSet (ResolveContext.Options.EnumScope) && lc != null && rc != null && (TypeManager.IsEnumType (left.Type) || TypeManager.IsEnumType (right.Type))) {
2681 lc = EnumLiftUp (ec, lc, rc, loc);
2683 rc = EnumLiftUp (ec, rc, lc, loc);
2686 if (rc != null && lc != null) {
2687 int prev_e = ec.Report.Errors;
2688 Expression e = ConstantFold.BinaryFold (ec, oper, lc, rc, loc);
2692 if (e != null || ec.Report.Errors != prev_e)
2696 // Comparison warnings
2697 if ((oper & Operator.ComparisonMask) != 0) {
2698 if (left.Equals (right)) {
2699 ec.Report.Warning (1718, 3, loc, "A comparison made to same variable. Did you mean to compare something else?");
2701 CheckUselessComparison (ec, lc, right.Type);
2702 CheckUselessComparison (ec, rc, left.Type);
2705 if (left.Type == InternalType.Dynamic || right.Type == InternalType.Dynamic) {
2706 Arguments args = new Arguments (2);
2707 args.Add (new Argument (left));
2708 args.Add (new Argument (right));
2709 return new DynamicExpressionStatement (this, args, loc).Resolve (ec);
2712 if (RootContext.Version >= LanguageVersion.ISO_2 &&
2713 ((TypeManager.IsNullableType (left.Type) && (right is NullLiteral || TypeManager.IsNullableType (right.Type) || TypeManager.IsValueType (right.Type))) ||
2714 (TypeManager.IsValueType (left.Type) && right is NullLiteral) ||
2715 (TypeManager.IsNullableType (right.Type) && (left is NullLiteral || TypeManager.IsNullableType (left.Type) || TypeManager.IsValueType (left.Type))) ||
2716 (TypeManager.IsValueType (right.Type) && left is NullLiteral)))
2717 return new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
2719 return DoResolveCore (ec, left, right);
2722 protected Expression DoResolveCore (ResolveContext ec, Expression left_orig, Expression right_orig)
2724 Expression expr = ResolveOperator (ec);
2726 Error_OperatorCannotBeApplied (ec, left_orig, right_orig);
2728 if (left == null || right == null)
2729 throw new InternalErrorException ("Invalid conversion");
2731 if (oper == Operator.BitwiseOr)
2732 CheckBitwiseOrOnSignExtended (ec);
2737 public override SLE.Expression MakeExpression (BuilderContext ctx)
2739 var le = left.MakeExpression (ctx);
2740 var re = right.MakeExpression (ctx);
2741 bool is_checked = ctx.HasSet (BuilderContext.Options.CheckedScope);
2744 case Operator.Addition:
2745 return is_checked ? SLE.Expression.AddChecked (le, re) : SLE.Expression.Add (le, re);
2746 case Operator.BitwiseAnd:
2747 return SLE.Expression.And (le, re);
2748 case Operator.BitwiseOr:
2749 return SLE.Expression.Or (le, re);
2750 case Operator.Division:
2751 return SLE.Expression.Divide (le, re);
2752 case Operator.Equality:
2753 return SLE.Expression.Equal (le, re);
2754 case Operator.ExclusiveOr:
2755 return SLE.Expression.ExclusiveOr (le, re);
2756 case Operator.GreaterThan:
2757 return SLE.Expression.GreaterThan (le, re);
2758 case Operator.GreaterThanOrEqual:
2759 return SLE.Expression.GreaterThanOrEqual (le, re);
2760 case Operator.Inequality:
2761 return SLE.Expression.NotEqual (le, re);
2762 case Operator.LeftShift:
2763 return SLE.Expression.LeftShift (le, re);
2764 case Operator.LessThan:
2765 return SLE.Expression.LessThan (le, re);
2766 case Operator.LessThanOrEqual:
2767 return SLE.Expression.LessThanOrEqual (le, re);
2768 case Operator.LogicalAnd:
2769 return SLE.Expression.AndAlso (le, re);
2770 case Operator.LogicalOr:
2771 return SLE.Expression.OrElse (le, re);
2772 case Operator.Modulus:
2773 return SLE.Expression.Modulo (le, re);
2774 case Operator.Multiply:
2775 return is_checked ? SLE.Expression.MultiplyChecked (le, re) : SLE.Expression.Multiply (le, re);
2776 case Operator.RightShift:
2777 return SLE.Expression.RightShift (le, re);
2778 case Operator.Subtraction:
2779 return is_checked ? SLE.Expression.SubtractChecked (le, re) : SLE.Expression.Subtract (le, re);
2781 throw new NotImplementedException (oper.ToString ());
2786 // D operator + (D x, D y)
2787 // D operator - (D x, D y)
2789 Expression ResolveOperatorDelegate (ResolveContext ec, TypeSpec l, TypeSpec r)
2791 if (!TypeManager.IsEqual (l, r) && !TypeSpecComparer.Variant.IsEqual (r, l)) {
2793 if (right.eclass == ExprClass.MethodGroup || (r == InternalType.AnonymousMethod)) {
2794 tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2799 } else if (left.eclass == ExprClass.MethodGroup || (l == InternalType.AnonymousMethod)) {
2800 tmp = Convert.ImplicitConversionRequired (ec, left, r, loc);
2811 Arguments args = new Arguments (2);
2812 args.Add (new Argument (left));
2813 args.Add (new Argument (right));
2815 if (oper == Operator.Addition) {
2816 if (TypeManager.delegate_combine_delegate_delegate == null) {
2817 TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
2818 TypeManager.delegate_type, "Combine", loc, TypeManager.delegate_type, TypeManager.delegate_type);
2821 method = TypeManager.delegate_combine_delegate_delegate;
2822 } else if (oper == Operator.Subtraction) {
2823 if (TypeManager.delegate_remove_delegate_delegate == null) {
2824 TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
2825 TypeManager.delegate_type, "Remove", loc, TypeManager.delegate_type, TypeManager.delegate_type);
2828 method = TypeManager.delegate_remove_delegate_delegate;
2830 return new EmptyExpression (TypeManager.decimal_type);
2833 MethodGroupExpr mg = MethodGroupExpr.CreatePredefined (method, TypeManager.delegate_type, loc);
2834 Expression expr = new UserOperatorCall (mg.BestCandidate, args, CreateExpressionTree, loc);
2835 return new ClassCast (expr, l);
2839 // Enumeration operators
2841 Expression ResolveOperatorEnum (ResolveContext ec, bool lenum, bool renum, TypeSpec ltype, TypeSpec rtype)
2844 // bool operator == (E x, E y);
2845 // bool operator != (E x, E y);
2846 // bool operator < (E x, E y);
2847 // bool operator > (E x, E y);
2848 // bool operator <= (E x, E y);
2849 // bool operator >= (E x, E y);
2851 // E operator & (E x, E y);
2852 // E operator | (E x, E y);
2853 // E operator ^ (E x, E y);
2855 // U operator - (E e, E f)
2856 // E operator - (E e, U x)
2858 // E operator + (U x, E e)
2859 // E operator + (E e, U x)
2861 if (!((oper & (Operator.ComparisonMask | Operator.BitwiseMask)) != 0 ||
2862 (oper == Operator.Subtraction && lenum) ||
2863 (oper == Operator.Addition && (lenum != renum || type != null)))) // type != null for lifted null
2866 Expression ltemp = left;
2867 Expression rtemp = right;
2868 TypeSpec underlying_type;
2871 if ((oper & (Operator.ComparisonMask | Operator.BitwiseMask)) != 0) {
2873 expr = Convert.ImplicitConversion (ec, left, rtype, loc);
2879 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
2887 if (TypeManager.IsEqual (ltype, rtype)) {
2888 underlying_type = EnumSpec.GetUnderlyingType (ltype);
2890 if (left is Constant)
2891 left = ((Constant) left).ConvertExplicitly (false, underlying_type).Resolve (ec);
2893 left = EmptyCast.Create (left, underlying_type);
2895 if (right is Constant)
2896 right = ((Constant) right).ConvertExplicitly (false, underlying_type).Resolve (ec);
2898 right = EmptyCast.Create (right, underlying_type);
2900 underlying_type = EnumSpec.GetUnderlyingType (ltype);
2902 if (oper != Operator.Subtraction && oper != Operator.Addition) {
2903 Constant c = right as Constant;
2904 if (c == null || !c.IsDefaultValue)
2907 if (!Convert.ImplicitStandardConversionExists (right, underlying_type))
2910 right = Convert.ImplicitConversionStandard (ec, right, underlying_type, right.Location);
2913 if (left is Constant)
2914 left = ((Constant) left).ConvertExplicitly (false, underlying_type).Resolve (ec);
2916 left = EmptyCast.Create (left, underlying_type);
2919 underlying_type = EnumSpec.GetUnderlyingType (rtype);
2921 if (oper != Operator.Addition) {
2922 Constant c = left as Constant;
2923 if (c == null || !c.IsDefaultValue)
2926 if (!Convert.ImplicitStandardConversionExists (left, underlying_type))
2929 left = Convert.ImplicitConversionStandard (ec, left, underlying_type, left.Location);
2932 if (right is Constant)
2933 right = ((Constant) right).ConvertExplicitly (false, underlying_type).Resolve (ec);
2935 right = EmptyCast.Create (right, underlying_type);
2942 // C# specification uses explicit cast syntax which means binary promotion
2943 // should happen, however it seems that csc does not do that
2945 if (!DoBinaryOperatorPromotion (ec)) {
2951 TypeSpec res_type = null;
2952 if ((oper & Operator.BitwiseMask) != 0 || oper == Operator.Subtraction || oper == Operator.Addition) {
2953 TypeSpec promoted_type = lenum ? left.Type : right.Type;
2954 enum_conversion = Convert.ExplicitNumericConversion (
2955 new EmptyExpression (promoted_type), underlying_type);
2957 if (oper == Operator.Subtraction && renum && lenum)
2958 res_type = underlying_type;
2959 else if (oper == Operator.Addition && renum)
2965 expr = ResolveOperatorPredefined (ec, standard_operators, true, res_type);
2966 if (!is_compound || expr == null)
2974 // If the return type of the selected operator is implicitly convertible to the type of x
2976 if (Convert.ImplicitConversionExists (ec, expr, ltype))
2980 // Otherwise, if the selected operator is a predefined operator, if the return type of the
2981 // selected operator is explicitly convertible to the type of x, and if y is implicitly
2982 // convertible to the type of x or the operator is a shift operator, then the operation
2983 // is evaluated as x = (T)(x op y), where T is the type of x
2985 expr = Convert.ExplicitConversion (ec, expr, ltype, loc);
2989 if (Convert.ImplicitConversionExists (ec, ltemp, ltype))
2996 // 7.9.6 Reference type equality operators
2998 Expression ResolveOperatorEquality (ResolveContext ec, TypeSpec l, TypeSpec r)
3001 type = TypeManager.bool_type;
3004 // a, Both operands are reference-type values or the value null
3005 // b, One operand is a value of type T where T is a type-parameter and
3006 // the other operand is the value null. Furthermore T does not have the
3007 // value type constraint
3009 // LAMESPEC: Very confusing details in the specification, basically any
3010 // reference like type-parameter is allowed
3012 var tparam_l = l as TypeParameterSpec;
3013 var tparam_r = r as TypeParameterSpec;
3014 if (tparam_l != null) {
3015 if (right is NullLiteral && !tparam_l.HasSpecialStruct) {
3016 left = new BoxedCast (left, TypeManager.object_type);
3020 if (!tparam_l.IsReferenceType)
3023 l = tparam_l.GetEffectiveBase ();
3024 left = new BoxedCast (left, l);
3025 } else if (left is NullLiteral && tparam_r == null) {
3026 if (!TypeManager.IsReferenceType (r) || r.Kind == MemberKind.InternalCompilerType)
3032 if (tparam_r != null) {
3033 if (left is NullLiteral && !tparam_r.HasSpecialStruct) {
3034 right = new BoxedCast (right, TypeManager.object_type);
3038 if (!tparam_r.IsReferenceType)
3041 r = tparam_r.GetEffectiveBase ();
3042 right = new BoxedCast (right, r);
3043 } else if (right is NullLiteral) {
3044 if (!TypeManager.IsReferenceType (l) || l.Kind == MemberKind.InternalCompilerType)
3051 // LAMESPEC: method groups can be compared when they convert to other side delegate
3054 if (right.eclass == ExprClass.MethodGroup) {
3055 result = Convert.ImplicitConversion (ec, right, l, loc);
3061 } else if (r.IsDelegate && l != r) {
3064 } else if (left.eclass == ExprClass.MethodGroup && r.IsDelegate) {
3065 result = Convert.ImplicitConversionRequired (ec, left, r, loc);
3074 // bool operator != (string a, string b)
3075 // bool operator == (string a, string b)
3077 // bool operator != (Delegate a, Delegate b)
3078 // bool operator == (Delegate a, Delegate b)
3080 // bool operator != (bool a, bool b)
3081 // bool operator == (bool a, bool b)
3083 // LAMESPEC: Reference equality comparison can apply to value types when
3084 // they implement an implicit conversion to any of types above.
3086 if (r != TypeManager.object_type && l != TypeManager.object_type) {
3087 result = ResolveOperatorPredefined (ec, equality_operators, false, null);
3093 // bool operator != (object a, object b)
3094 // bool operator == (object a, object b)
3096 // An explicit reference conversion exists from the
3097 // type of either operand to the type of the other operand.
3100 // Optimize common path
3102 return l.Kind == MemberKind.InternalCompilerType || l.Kind == MemberKind.Struct ? null : this;
3105 if (!Convert.ExplicitReferenceConversionExists (l, r) &&
3106 !Convert.ExplicitReferenceConversionExists (r, l))
3109 // Reject allowed explicit conversions like int->object
3110 if (!TypeManager.IsReferenceType (l) || !TypeManager.IsReferenceType (r))
3113 if (l == TypeManager.string_type || l == TypeManager.delegate_type || MemberCache.GetUserOperator (l, CSharp.Operator.OpType.Equality, false) != null)
3114 ec.Report.Warning (253, 2, loc,
3115 "Possible unintended reference comparison. Consider casting the right side expression to type `{0}' to get value comparison",
3116 l.GetSignatureForError ());
3118 if (r == TypeManager.string_type || r == TypeManager.delegate_type || MemberCache.GetUserOperator (r, CSharp.Operator.OpType.Equality, false) != null)
3119 ec.Report.Warning (252, 2, loc,
3120 "Possible unintended reference comparison. Consider casting the left side expression to type `{0}' to get value comparison",
3121 r.GetSignatureForError ());
3127 Expression ResolveOperatorPointer (ResolveContext ec, TypeSpec l, TypeSpec r)
3130 // bool operator == (void* x, void* y);
3131 // bool operator != (void* x, void* y);
3132 // bool operator < (void* x, void* y);
3133 // bool operator > (void* x, void* y);
3134 // bool operator <= (void* x, void* y);
3135 // bool operator >= (void* x, void* y);
3137 if ((oper & Operator.ComparisonMask) != 0) {
3140 temp = Convert.ImplicitConversion (ec, left, r, left.Location);
3147 temp = Convert.ImplicitConversion (ec, right, l, right.Location);
3153 type = TypeManager.bool_type;
3157 if (pointer_operators == null)
3158 CreatePointerOperatorsTable ();
3160 return ResolveOperatorPredefined (ec, pointer_operators, false, null);
3164 // Build-in operators method overloading
3166 protected virtual Expression ResolveOperatorPredefined (ResolveContext ec, PredefinedOperator [] operators, bool primitives_only, TypeSpec enum_type)
3168 PredefinedOperator best_operator = null;
3169 TypeSpec l = left.Type;
3170 TypeSpec r = right.Type;
3171 Operator oper_mask = oper & ~Operator.ValuesOnlyMask;
3173 foreach (PredefinedOperator po in operators) {
3174 if ((po.OperatorsMask & oper_mask) == 0)
3177 if (primitives_only) {
3178 if (!po.IsPrimitiveApplicable (l, r))
3181 if (!po.IsApplicable (ec, left, right))
3185 if (best_operator == null) {
3187 if (primitives_only)
3193 best_operator = po.ResolveBetterOperator (ec, best_operator);
3195 if (best_operator == null) {
3196 ec.Report.Error (34, loc, "Operator `{0}' is ambiguous on operands of type `{1}' and `{2}'",
3197 OperName (oper), TypeManager.CSharpName (l), TypeManager.CSharpName (r));
3204 if (best_operator == null)
3207 Expression expr = best_operator.ConvertResult (ec, this);
3210 // Optimize &/&& constant expressions with 0 value
3212 if (oper == Operator.BitwiseAnd || oper == Operator.LogicalAnd) {
3213 Constant rc = right as Constant;
3214 Constant lc = left as Constant;
3215 if ((lc != null && lc.IsDefaultValue) || (rc != null && rc.IsDefaultValue)) {
3217 // The result is a constant with side-effect
3219 Constant side_effect = rc == null ?
3220 new SideEffectConstant (lc, right, loc) :
3221 new SideEffectConstant (rc, left, loc);
3223 return ReducedExpression.Create (side_effect.Resolve (ec), expr);
3227 if (enum_type == null)
3231 // HACK: required by enum_conversion
3233 expr.Type = enum_type;
3234 return EmptyCast.Create (expr, enum_type);
3238 // Performs user-operator overloading
3240 protected virtual Expression ResolveUserOperator (ResolveContext ec, TypeSpec l, TypeSpec r)
3242 var op = ConvertBinaryToUserOperator (oper);
3243 IList<MemberSpec> left_operators = MemberCache.GetUserOperator (l, op, false);
3244 IList<MemberSpec> right_operators = null;
3247 right_operators = MemberCache.GetUserOperator (r, op, false);
3248 if (right_operators == null && left_operators == null)
3250 } else if (left_operators == null) {
3254 Arguments args = new Arguments (2);
3255 Argument larg = new Argument (left);
3257 Argument rarg = new Argument (right);
3261 // User-defined operator implementations always take precedence
3262 // over predefined operator implementations
3264 if (left_operators != null && right_operators != null) {
3265 left_operators = CombineUserOperators (left_operators, right_operators);
3266 } else if (right_operators != null) {
3267 left_operators = right_operators;
3270 var mg = new MethodGroupExpr (left_operators, l, loc);
3271 mg = mg.OverloadResolve (ec, ref args, true, loc);
3275 Expression oper_expr;
3277 // TODO: CreateExpressionTree is allocated every time
3278 if ((oper & Operator.LogicalMask) != 0) {
3279 oper_expr = new ConditionalLogicalOperator (mg.BestCandidate, args, CreateExpressionTree,
3280 oper == Operator.LogicalAnd, loc).Resolve (ec);
3282 oper_expr = new UserOperatorCall (mg.BestCandidate, args, CreateExpressionTree, loc);
3291 // Merge two sets of user operators into one, they are mostly distinguish
3292 // expect when they share base type and it contains an operator
3294 static IList<MemberSpec> CombineUserOperators (IList<MemberSpec> left, IList<MemberSpec> right)
3296 var combined = new List<MemberSpec> (left.Count + right.Count);
3297 combined.AddRange (left);
3298 foreach (var r in right) {
3300 foreach (var l in left) {
3301 if (l.DeclaringType == r.DeclaringType) {
3314 public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
3319 private void CheckUselessComparison (ResolveContext ec, Constant c, TypeSpec type)
3321 if (c == null || !IsTypeIntegral (type)
3322 || c is StringConstant
3323 || c is BoolConstant
3324 || c is FloatConstant
3325 || c is DoubleConstant
3326 || c is DecimalConstant
3332 if (c is ULongConstant) {
3333 ulong uvalue = ((ULongConstant) c).Value;
3334 if (uvalue > long.MaxValue) {
3335 if (type == TypeManager.byte_type ||
3336 type == TypeManager.sbyte_type ||
3337 type == TypeManager.short_type ||
3338 type == TypeManager.ushort_type ||
3339 type == TypeManager.int32_type ||
3340 type == TypeManager.uint32_type ||
3341 type == TypeManager.int64_type ||
3342 type == TypeManager.char_type)
3343 WarnUselessComparison (ec, type);
3346 value = (long) uvalue;
3348 else if (c is ByteConstant)
3349 value = ((ByteConstant) c).Value;
3350 else if (c is SByteConstant)
3351 value = ((SByteConstant) c).Value;
3352 else if (c is ShortConstant)
3353 value = ((ShortConstant) c).Value;
3354 else if (c is UShortConstant)
3355 value = ((UShortConstant) c).Value;
3356 else if (c is IntConstant)
3357 value = ((IntConstant) c).Value;
3358 else if (c is UIntConstant)
3359 value = ((UIntConstant) c).Value;
3360 else if (c is LongConstant)
3361 value = ((LongConstant) c).Value;
3362 else if (c is CharConstant)
3363 value = ((CharConstant)c).Value;
3368 if (IsValueOutOfRange (value, type))
3369 WarnUselessComparison (ec, type);
3372 static bool IsValueOutOfRange (long value, TypeSpec type)
3374 if (IsTypeUnsigned (type) && value < 0)
3376 return type == TypeManager.sbyte_type && (value >= 0x80 || value < -0x80) ||
3377 type == TypeManager.byte_type && value >= 0x100 ||
3378 type == TypeManager.short_type && (value >= 0x8000 || value < -0x8000) ||
3379 type == TypeManager.ushort_type && value >= 0x10000 ||
3380 type == TypeManager.int32_type && (value >= 0x80000000 || value < -0x80000000) ||
3381 type == TypeManager.uint32_type && value >= 0x100000000;
3384 private static bool IsTypeIntegral (TypeSpec type)
3386 return type == TypeManager.uint64_type ||
3387 type == TypeManager.int64_type ||
3388 type == TypeManager.uint32_type ||
3389 type == TypeManager.int32_type ||
3390 type == TypeManager.ushort_type ||
3391 type == TypeManager.short_type ||
3392 type == TypeManager.sbyte_type ||
3393 type == TypeManager.byte_type ||
3394 type == TypeManager.char_type;
3397 private static bool IsTypeUnsigned (TypeSpec type)
3399 return type == TypeManager.uint64_type ||
3400 type == TypeManager.uint32_type ||
3401 type == TypeManager.ushort_type ||
3402 type == TypeManager.byte_type ||
3403 type == TypeManager.char_type;
3406 private void WarnUselessComparison (ResolveContext ec, TypeSpec type)
3408 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}'",
3409 TypeManager.CSharpName (type));
3413 /// EmitBranchable is called from Statement.EmitBoolExpression in the
3414 /// context of a conditional bool expression. This function will return
3415 /// false if it is was possible to use EmitBranchable, or true if it was.
3417 /// The expression's code is generated, and we will generate a branch to `target'
3418 /// if the resulting expression value is equal to isTrue
3420 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
3423 // This is more complicated than it looks, but its just to avoid
3424 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
3425 // but on top of that we want for == and != to use a special path
3426 // if we are comparing against null
3428 if ((oper & Operator.EqualityMask) != 0 && (left is Constant || right is Constant)) {
3429 bool my_on_true = oper == Operator.Inequality ? on_true : !on_true;
3432 // put the constant on the rhs, for simplicity
3434 if (left is Constant) {
3435 Expression swap = right;
3441 // brtrue/brfalse works with native int only
3443 if (((Constant) right).IsZeroInteger && right.Type != TypeManager.int64_type && right.Type != TypeManager.uint64_type) {
3444 left.EmitBranchable (ec, target, my_on_true);
3447 if (right.Type == TypeManager.bool_type) {
3448 // right is a boolean, and it's not 'false' => it is 'true'
3449 left.EmitBranchable (ec, target, !my_on_true);
3453 } else if (oper == Operator.LogicalAnd) {
3456 Label tests_end = ec.DefineLabel ();
3458 left.EmitBranchable (ec, tests_end, false);
3459 right.EmitBranchable (ec, target, true);
3460 ec.MarkLabel (tests_end);
3463 // This optimizes code like this
3464 // if (true && i > 4)
3466 if (!(left is Constant))
3467 left.EmitBranchable (ec, target, false);
3469 if (!(right is Constant))
3470 right.EmitBranchable (ec, target, false);
3475 } else if (oper == Operator.LogicalOr){
3477 left.EmitBranchable (ec, target, true);
3478 right.EmitBranchable (ec, target, true);
3481 Label tests_end = ec.DefineLabel ();
3482 left.EmitBranchable (ec, tests_end, true);
3483 right.EmitBranchable (ec, target, false);
3484 ec.MarkLabel (tests_end);
3489 } else if ((oper & Operator.ComparisonMask) == 0) {
3490 base.EmitBranchable (ec, target, on_true);
3497 TypeSpec t = left.Type;
3498 bool is_float = IsFloat (t);
3499 bool is_unsigned = is_float || IsUnsigned (t);
3502 case Operator.Equality:
3504 ec.Emit (OpCodes.Beq, target);
3506 ec.Emit (OpCodes.Bne_Un, target);
3509 case Operator.Inequality:
3511 ec.Emit (OpCodes.Bne_Un, target);
3513 ec.Emit (OpCodes.Beq, target);
3516 case Operator.LessThan:
3518 if (is_unsigned && !is_float)
3519 ec.Emit (OpCodes.Blt_Un, target);
3521 ec.Emit (OpCodes.Blt, target);
3524 ec.Emit (OpCodes.Bge_Un, target);
3526 ec.Emit (OpCodes.Bge, target);
3529 case Operator.GreaterThan:
3531 if (is_unsigned && !is_float)
3532 ec.Emit (OpCodes.Bgt_Un, target);
3534 ec.Emit (OpCodes.Bgt, target);
3537 ec.Emit (OpCodes.Ble_Un, target);
3539 ec.Emit (OpCodes.Ble, target);
3542 case Operator.LessThanOrEqual:
3544 if (is_unsigned && !is_float)
3545 ec.Emit (OpCodes.Ble_Un, target);
3547 ec.Emit (OpCodes.Ble, target);
3550 ec.Emit (OpCodes.Bgt_Un, target);
3552 ec.Emit (OpCodes.Bgt, target);
3556 case Operator.GreaterThanOrEqual:
3558 if (is_unsigned && !is_float)
3559 ec.Emit (OpCodes.Bge_Un, target);
3561 ec.Emit (OpCodes.Bge, target);
3564 ec.Emit (OpCodes.Blt_Un, target);
3566 ec.Emit (OpCodes.Blt, target);
3569 throw new InternalErrorException (oper.ToString ());
3573 public override void Emit (EmitContext ec)
3575 EmitOperator (ec, left.Type);
3578 protected virtual void EmitOperator (EmitContext ec, TypeSpec l)
3581 // Handle short-circuit operators differently
3584 if ((oper & Operator.LogicalMask) != 0) {
3585 Label load_result = ec.DefineLabel ();
3586 Label end = ec.DefineLabel ();
3588 bool is_or = oper == Operator.LogicalOr;
3589 left.EmitBranchable (ec, load_result, is_or);
3591 ec.Emit (OpCodes.Br_S, end);
3593 ec.MarkLabel (load_result);
3594 ec.Emit (is_or ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
3600 // Optimize zero-based operations which cannot be optimized at expression level
3602 if (oper == Operator.Subtraction) {
3603 var lc = left as IntegralConstant;
3604 if (lc != null && lc.IsDefaultValue) {
3606 ec.Emit (OpCodes.Neg);
3613 EmitOperatorOpcode (ec, oper, l);
3616 // Nullable enum could require underlying type cast and we cannot simply wrap binary
3617 // expression because that would wrap lifted binary operation
3619 if (enum_conversion != null)
3620 enum_conversion.Emit (ec);
3623 public override void EmitSideEffect (EmitContext ec)
3625 if ((oper & Operator.LogicalMask) != 0 ||
3626 (ec.HasSet (EmitContext.Options.CheckedScope) && (oper == Operator.Multiply || oper == Operator.Addition || oper == Operator.Subtraction))) {
3627 base.EmitSideEffect (ec);
3629 left.EmitSideEffect (ec);
3630 right.EmitSideEffect (ec);
3634 protected override void CloneTo (CloneContext clonectx, Expression t)
3636 Binary target = (Binary) t;
3638 target.left = left.Clone (clonectx);
3639 target.right = right.Clone (clonectx);
3642 public Expression CreateCallSiteBinder (ResolveContext ec, Arguments args)
3644 Arguments binder_args = new Arguments (4);
3646 MemberAccess sle = new MemberAccess (new MemberAccess (
3647 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Linq", loc), "Expressions", loc);
3649 CSharpBinderFlags flags = 0;
3650 if (ec.HasSet (ResolveContext.Options.CheckedScope))
3651 flags = CSharpBinderFlags.CheckedContext;
3653 if ((oper & Operator.LogicalMask) != 0)
3654 flags |= CSharpBinderFlags.BinaryOperationLogical;
3656 binder_args.Add (new Argument (new EnumConstant (new IntLiteral ((int) flags, loc), TypeManager.binder_flags)));
3657 binder_args.Add (new Argument (new MemberAccess (new MemberAccess (sle, "ExpressionType", loc), GetOperatorExpressionTypeName (), loc)));
3658 binder_args.Add (new Argument (new TypeOf (new TypeExpression (ec.CurrentType, loc), loc)));
3659 binder_args.Add (new Argument (new ImplicitlyTypedArrayCreation (args.CreateDynamicBinderArguments (ec), loc)));
3661 return new Invocation (DynamicExpressionStatement.GetBinder ("BinaryOperation", loc), binder_args);
3664 public override Expression CreateExpressionTree (ResolveContext ec)
3666 return CreateExpressionTree (ec, null);
3669 Expression CreateExpressionTree (ResolveContext ec, Expression method)
3672 bool lift_arg = false;
3675 case Operator.Addition:
3676 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
3677 method_name = "AddChecked";
3679 method_name = "Add";
3681 case Operator.BitwiseAnd:
3682 method_name = "And";
3684 case Operator.BitwiseOr:
3687 case Operator.Division:
3688 method_name = "Divide";
3690 case Operator.Equality:
3691 method_name = "Equal";
3694 case Operator.ExclusiveOr:
3695 method_name = "ExclusiveOr";
3697 case Operator.GreaterThan:
3698 method_name = "GreaterThan";
3701 case Operator.GreaterThanOrEqual:
3702 method_name = "GreaterThanOrEqual";
3705 case Operator.Inequality:
3706 method_name = "NotEqual";
3709 case Operator.LeftShift:
3710 method_name = "LeftShift";
3712 case Operator.LessThan:
3713 method_name = "LessThan";
3716 case Operator.LessThanOrEqual:
3717 method_name = "LessThanOrEqual";
3720 case Operator.LogicalAnd:
3721 method_name = "AndAlso";
3723 case Operator.LogicalOr:
3724 method_name = "OrElse";
3726 case Operator.Modulus:
3727 method_name = "Modulo";
3729 case Operator.Multiply:
3730 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
3731 method_name = "MultiplyChecked";
3733 method_name = "Multiply";
3735 case Operator.RightShift:
3736 method_name = "RightShift";
3738 case Operator.Subtraction:
3739 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
3740 method_name = "SubtractChecked";
3742 method_name = "Subtract";
3746 throw new InternalErrorException ("Unknown expression tree binary operator " + oper);
3749 Arguments args = new Arguments (2);
3750 args.Add (new Argument (left.CreateExpressionTree (ec)));
3751 args.Add (new Argument (right.CreateExpressionTree (ec)));
3752 if (method != null) {
3754 args.Add (new Argument (new BoolConstant (false, loc)));
3756 args.Add (new Argument (method));
3759 return CreateExpressionFactoryCall (ec, method_name, args);
3764 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3765 // b, c, d... may be strings or objects.
3767 public class StringConcat : Expression {
3768 Arguments arguments;
3769 static IList<MemberSpec> concat_members;
3771 public StringConcat (Expression left, Expression right, Location loc)
3774 type = TypeManager.string_type;
3775 eclass = ExprClass.Value;
3777 arguments = new Arguments (2);
3780 public static StringConcat Create (ResolveContext rc, Expression left, Expression right, Location loc)
3782 if (left.eclass == ExprClass.Unresolved || right.eclass == ExprClass.Unresolved)
3783 throw new ArgumentException ();
3785 var s = new StringConcat (left, right, loc);
3786 s.Append (rc, left);
3787 s.Append (rc, right);
3791 public override Expression CreateExpressionTree (ResolveContext ec)
3793 Argument arg = arguments [0];
3794 return CreateExpressionAddCall (ec, arg, arg.CreateExpressionTree (ec), 1);
3798 // Creates nested calls tree from an array of arguments used for IL emit
3800 Expression CreateExpressionAddCall (ResolveContext ec, Argument left, Expression left_etree, int pos)
3802 Arguments concat_args = new Arguments (2);
3803 Arguments add_args = new Arguments (3);
3805 concat_args.Add (left);
3806 add_args.Add (new Argument (left_etree));
3808 concat_args.Add (arguments [pos]);
3809 add_args.Add (new Argument (arguments [pos].CreateExpressionTree (ec)));
3811 MethodGroupExpr method = CreateConcatMethodGroup ();
3815 method = method.OverloadResolve (ec, ref concat_args, false, loc);
3819 add_args.Add (new Argument (method.CreateExpressionTree (ec)));
3821 Expression expr = CreateExpressionFactoryCall (ec, "Add", add_args);
3822 if (++pos == arguments.Count)
3825 left = new Argument (new EmptyExpression (method.BestCandidate.ReturnType));
3826 return CreateExpressionAddCall (ec, left, expr, pos);
3829 protected override Expression DoResolve (ResolveContext ec)
3834 void Append (ResolveContext rc, Expression operand)
3839 StringConstant sc = operand as StringConstant;
3841 if (arguments.Count != 0) {
3842 Argument last_argument = arguments [arguments.Count - 1];
3843 StringConstant last_expr_constant = last_argument.Expr as StringConstant;
3844 if (last_expr_constant != null) {
3845 last_argument.Expr = new StringConstant (
3846 last_expr_constant.Value + sc.Value, sc.Location).Resolve (rc);
3852 // Multiple (3+) concatenation are resolved as multiple StringConcat instances
3854 StringConcat concat_oper = operand as StringConcat;
3855 if (concat_oper != null) {
3856 arguments.AddRange (concat_oper.arguments);
3861 arguments.Add (new Argument (operand));
3864 MethodGroupExpr CreateConcatMethodGroup ()
3866 if (concat_members == null) {
3867 concat_members = MemberCache.FindMembers (type,
3868 MemberFilter.Method ("Concat", -1, null, type), BindingRestriction.DeclaredOnly);
3871 return new MethodGroupExpr (concat_members, type, loc);
3874 public override void Emit (EmitContext ec)
3876 var mg = CreateConcatMethodGroup ();
3877 mg = mg.OverloadResolve (new ResolveContext (ec.MemberContext), ref arguments, false, loc);
3879 mg.EmitCall (ec, arguments);
3882 public override SLE.Expression MakeExpression (BuilderContext ctx)
3884 if (arguments.Count != 2)
3885 throw new NotImplementedException ("arguments.Count != 2");
3887 var concat = typeof (string).GetMethod ("Concat", new[] { typeof (object), typeof (object) });
3888 return SLE.Expression.Add (arguments[0].Expr.MakeExpression (ctx), arguments[1].Expr.MakeExpression (ctx), concat);
3891 public static void Reset ()
3893 concat_members = null;
3898 // User-defined conditional logical operator
3900 public class ConditionalLogicalOperator : UserOperatorCall {
3901 readonly bool is_and;
3902 Expression oper_expr;
3904 public ConditionalLogicalOperator (MethodSpec oper, Arguments arguments, Func<ResolveContext, Expression, Expression> expr_tree, bool is_and, Location loc)
3905 : base (oper, arguments, expr_tree, loc)
3907 this.is_and = is_and;
3908 eclass = ExprClass.Unresolved;
3911 protected override Expression DoResolve (ResolveContext ec)
3913 AParametersCollection pd = oper.Parameters;
3914 if (!TypeManager.IsEqual (type, type) || !TypeManager.IsEqual (type, pd.Types [0]) || !TypeManager.IsEqual (type, pd.Types [1])) {
3915 ec.Report.Error (217, loc,
3916 "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",
3917 oper.GetSignatureForError ());
3921 Expression left_dup = new EmptyExpression (type);
3922 Expression op_true = GetOperatorTrue (ec, left_dup, loc);
3923 Expression op_false = GetOperatorFalse (ec, left_dup, loc);
3924 if (op_true == null || op_false == null) {
3925 ec.Report.Error (218, loc,
3926 "The type `{0}' must have operator `true' and operator `false' defined when `{1}' is used as a short circuit operator",
3927 TypeManager.CSharpName (type), oper.GetSignatureForError ());
3931 oper_expr = is_and ? op_false : op_true;
3932 eclass = ExprClass.Value;
3936 public override void Emit (EmitContext ec)
3938 Label end_target = ec.DefineLabel ();
3941 // Emit and duplicate left argument
3943 arguments [0].Expr.Emit (ec);
3944 ec.Emit (OpCodes.Dup);
3945 arguments.RemoveAt (0);
3947 oper_expr.EmitBranchable (ec, end_target, true);
3949 ec.MarkLabel (end_target);
3953 public class PointerArithmetic : Expression {
3954 Expression left, right;
3958 // We assume that `l' is always a pointer
3960 public PointerArithmetic (Binary.Operator op, Expression l, Expression r, TypeSpec t, Location loc)
3969 public override Expression CreateExpressionTree (ResolveContext ec)
3971 Error_PointerInsideExpressionTree (ec);
3975 protected override Expression DoResolve (ResolveContext ec)
3977 eclass = ExprClass.Variable;
3979 if (left.Type == TypeManager.void_ptr_type) {
3980 ec.Report.Error (242, loc, "The operation in question is undefined on void pointers");
3987 public override void Emit (EmitContext ec)
3989 TypeSpec op_type = left.Type;
3991 // It must be either array or fixed buffer
3993 if (TypeManager.HasElementType (op_type)) {
3994 element = TypeManager.GetElementType (op_type);
3996 FieldExpr fe = left as FieldExpr;
3998 element = ((FixedFieldSpec) (fe.Spec)).ElementType;
4003 int size = GetTypeSize (element);
4004 TypeSpec rtype = right.Type;
4006 if ((op & Binary.Operator.SubtractionMask) != 0 && rtype.IsPointer){
4008 // handle (pointer - pointer)
4012 ec.Emit (OpCodes.Sub);
4016 ec.Emit (OpCodes.Sizeof, element);
4019 ec.Emit (OpCodes.Div);
4021 ec.Emit (OpCodes.Conv_I8);
4024 // handle + and - on (pointer op int)
4026 Constant left_const = left as Constant;
4027 if (left_const != null) {
4029 // Optimize ((T*)null) pointer operations
4031 if (left_const.IsDefaultValue) {
4032 left = EmptyExpression.Null;
4040 var right_const = right as Constant;
4041 if (right_const != null) {
4043 // Optimize 0-based arithmetic
4045 if (right_const.IsDefaultValue)
4049 right = new IntConstant (size, right.Location);
4051 right = new SizeOf (new TypeExpression (element, right.Location), right.Location);
4053 // TODO: Should be the checks resolve context sensitive?
4054 ResolveContext rc = new ResolveContext (ec.MemberContext, ResolveContext.Options.UnsafeScope);
4055 right = new Binary (Binary.Operator.Multiply, right, right_const, loc).Resolve (rc);
4061 if (rtype == TypeManager.sbyte_type || rtype == TypeManager.byte_type ||
4062 rtype == TypeManager.short_type || rtype == TypeManager.ushort_type) {
4063 ec.Emit (OpCodes.Conv_I);
4064 } else if (rtype == TypeManager.uint32_type) {
4065 ec.Emit (OpCodes.Conv_U);
4068 if (right_const == null && size != 1){
4070 ec.Emit (OpCodes.Sizeof, element);
4073 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
4074 ec.Emit (OpCodes.Conv_I8);
4076 Binary.EmitOperatorOpcode (ec, Binary.Operator.Multiply, rtype);
4079 if (left_const == null) {
4080 if (rtype == TypeManager.int64_type)
4081 ec.Emit (OpCodes.Conv_I);
4082 else if (rtype == TypeManager.uint64_type)
4083 ec.Emit (OpCodes.Conv_U);
4085 Binary.EmitOperatorOpcode (ec, op, op_type);
4092 // A boolean-expression is an expression that yields a result
4095 public class BooleanExpression : ShimExpression
4097 public BooleanExpression (Expression expr)
4100 this.loc = expr.Location;
4103 public override Expression CreateExpressionTree (ResolveContext ec)
4105 // TODO: We should emit IsTrue (v4) instead of direct user operator
4106 // call but that would break csc compatibility
4107 return base.CreateExpressionTree (ec);
4110 protected override Expression DoResolve (ResolveContext ec)
4112 // A boolean-expression is required to be of a type
4113 // that can be implicitly converted to bool or of
4114 // a type that implements operator true
4116 expr = expr.Resolve (ec);
4120 Assign ass = expr as Assign;
4121 if (ass != null && ass.Source is Constant) {
4122 ec.Report.Warning (665, 3, loc,
4123 "Assignment in conditional expression is always constant. Did you mean to use `==' instead ?");
4126 if (expr.Type == TypeManager.bool_type)
4129 if (expr.Type == InternalType.Dynamic) {
4130 Arguments args = new Arguments (1);
4131 args.Add (new Argument (expr));
4132 return new DynamicUnaryConversion ("IsTrue", args, loc).Resolve (ec);
4135 type = TypeManager.bool_type;
4136 Expression converted = Convert.ImplicitConversion (ec, expr, type, loc);
4137 if (converted != null)
4141 // If no implicit conversion to bool exists, try using `operator true'
4143 converted = GetOperatorTrue (ec, expr, loc);
4144 if (converted == null) {
4145 expr.Error_ValueCannotBeConverted (ec, loc, type, false);
4154 /// Implements the ternary conditional operator (?:)
4156 public class Conditional : Expression {
4157 Expression expr, true_expr, false_expr;
4159 public Conditional (BooleanExpression expr, Expression true_expr, Expression false_expr, Location loc)
4162 this.true_expr = true_expr;
4163 this.false_expr = false_expr;
4167 public Expression Expr {
4173 public Expression TrueExpr {
4179 public Expression FalseExpr {
4185 public override Expression CreateExpressionTree (ResolveContext ec)
4187 Arguments args = new Arguments (3);
4188 args.Add (new Argument (expr.CreateExpressionTree (ec)));
4189 args.Add (new Argument (true_expr.CreateExpressionTree (ec)));
4190 args.Add (new Argument (false_expr.CreateExpressionTree (ec)));
4191 return CreateExpressionFactoryCall (ec, "Condition", args);
4194 protected override Expression DoResolve (ResolveContext ec)
4196 expr = expr.Resolve (ec);
4197 true_expr = true_expr.Resolve (ec);
4198 false_expr = false_expr.Resolve (ec);
4200 if (true_expr == null || false_expr == null || expr == null)
4203 eclass = ExprClass.Value;
4204 TypeSpec true_type = true_expr.Type;
4205 TypeSpec false_type = false_expr.Type;
4209 // First, if an implicit conversion exists from true_expr
4210 // to false_expr, then the result type is of type false_expr.Type
4212 if (!TypeManager.IsEqual (true_type, false_type)) {
4213 Expression conv = Convert.ImplicitConversion (ec, true_expr, false_type, loc);
4216 // Check if both can convert implicitly to each other's type
4218 if (Convert.ImplicitConversion (ec, false_expr, true_type, loc) != null) {
4219 ec.Report.Error (172, true_expr.Location,
4220 "Type of conditional expression cannot be determined as `{0}' and `{1}' convert implicitly to each other",
4221 TypeManager.CSharpName (true_type), TypeManager.CSharpName (false_type));
4226 } else if ((conv = Convert.ImplicitConversion (ec, false_expr, true_type, loc)) != null) {
4229 ec.Report.Error (173, true_expr.Location,
4230 "Type of conditional expression cannot be determined because there is no implicit conversion between `{0}' and `{1}'",
4231 TypeManager.CSharpName (true_type), TypeManager.CSharpName (false_type));
4236 // Dead code optimalization
4237 Constant c = expr as Constant;
4239 bool is_false = c.IsDefaultValue;
4240 ec.Report.Warning (429, 4, is_false ? true_expr.Location : false_expr.Location, "Unreachable expression code detected");
4241 return ReducedExpression.Create (is_false ? false_expr : true_expr, this).Resolve (ec);
4247 public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
4252 public override void Emit (EmitContext ec)
4254 Label false_target = ec.DefineLabel ();
4255 Label end_target = ec.DefineLabel ();
4257 expr.EmitBranchable (ec, false_target, false);
4258 true_expr.Emit (ec);
4260 if (type.IsInterface) {
4261 LocalBuilder temp = ec.GetTemporaryLocal (type);
4262 ec.Emit (OpCodes.Stloc, temp);
4263 ec.Emit (OpCodes.Ldloc, temp);
4264 ec.FreeTemporaryLocal (temp, type);
4267 ec.Emit (OpCodes.Br, end_target);
4268 ec.MarkLabel (false_target);
4269 false_expr.Emit (ec);
4270 ec.MarkLabel (end_target);
4273 protected override void CloneTo (CloneContext clonectx, Expression t)
4275 Conditional target = (Conditional) t;
4277 target.expr = expr.Clone (clonectx);
4278 target.true_expr = true_expr.Clone (clonectx);
4279 target.false_expr = false_expr.Clone (clonectx);
4283 public abstract class VariableReference : Expression, IAssignMethod, IMemoryLocation, IVariableReference {
4284 LocalTemporary temp;
4287 public abstract HoistedVariable GetHoistedVariable (AnonymousExpression ae);
4288 public abstract bool IsFixed { get; }
4289 public abstract bool IsRef { get; }
4290 public abstract string Name { get; }
4291 public abstract void SetHasAddressTaken ();
4294 // Variable IL data, it has to be protected to encapsulate hoisted variables
4296 protected abstract ILocalVariable Variable { get; }
4299 // Variable flow-analysis data
4301 public abstract VariableInfo VariableInfo { get; }
4304 public virtual void AddressOf (EmitContext ec, AddressOp mode)
4306 HoistedVariable hv = GetHoistedVariable (ec);
4308 hv.AddressOf (ec, mode);
4312 Variable.EmitAddressOf (ec);
4315 public HoistedVariable GetHoistedVariable (ResolveContext rc)
4317 return GetHoistedVariable (rc.CurrentAnonymousMethod);
4320 public HoistedVariable GetHoistedVariable (EmitContext ec)
4322 return GetHoistedVariable (ec.CurrentAnonymousMethod);
4325 public override string GetSignatureForError ()
4330 public override void Emit (EmitContext ec)
4335 public override void EmitSideEffect (EmitContext ec)
4341 // This method is used by parameters that are references, that are
4342 // being passed as references: we only want to pass the pointer (that
4343 // is already stored in the parameter, not the address of the pointer,
4344 // and not the value of the variable).
4346 public void EmitLoad (EmitContext ec)
4351 public void Emit (EmitContext ec, bool leave_copy)
4353 Report.Debug (64, "VARIABLE EMIT", this, Variable, type, IsRef, loc);
4355 HoistedVariable hv = GetHoistedVariable (ec);
4357 hv.Emit (ec, leave_copy);
4365 // If we are a reference, we loaded on the stack a pointer
4366 // Now lets load the real value
4368 ec.EmitLoadFromPtr (type);
4372 ec.Emit (OpCodes.Dup);
4375 temp = new LocalTemporary (Type);
4381 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy,
4382 bool prepare_for_load)
4384 HoistedVariable hv = GetHoistedVariable (ec);
4386 hv.EmitAssign (ec, source, leave_copy, prepare_for_load);
4390 New n_source = source as New;
4391 if (n_source != null) {
4392 if (!n_source.Emit (ec, this)) {
4405 ec.Emit (OpCodes.Dup);
4407 temp = new LocalTemporary (Type);
4413 ec.EmitStoreFromPtr (type);
4415 Variable.EmitAssign (ec);
4423 public bool IsHoisted {
4424 get { return GetHoistedVariable ((AnonymousExpression) null) != null; }
4431 public class LocalVariableReference : VariableReference {
4432 readonly string name;
4434 public LocalInfo local_info;
4437 public LocalVariableReference (Block block, string name, Location l)
4445 // Setting `is_readonly' to false will allow you to create a writable
4446 // reference to a read-only variable. This is used by foreach and using.
4448 public LocalVariableReference (Block block, string name, Location l,
4449 LocalInfo local_info, bool is_readonly)
4450 : this (block, name, l)
4452 this.local_info = local_info;
4453 this.is_readonly = is_readonly;
4456 public override VariableInfo VariableInfo {
4457 get { return local_info.VariableInfo; }
4460 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
4462 return local_info.HoistedVariant;
4466 // A local variable is always fixed
4468 public override bool IsFixed {
4469 get { return true; }
4472 public override bool IsRef {
4473 get { return false; }
4476 public bool IsReadOnly {
4477 get { return is_readonly; }
4480 public override string Name {
4481 get { return name; }
4484 public bool VerifyAssigned (ResolveContext ec)
4486 VariableInfo variable_info = local_info.VariableInfo;
4487 return variable_info == null || variable_info.IsAssigned (ec, loc);
4490 void ResolveLocalInfo ()
4492 if (local_info == null) {
4493 local_info = Block.GetLocalInfo (Name);
4494 type = local_info.VariableType;
4495 is_readonly = local_info.ReadOnly;
4499 public override void SetHasAddressTaken ()
4501 local_info.AddressTaken = true;
4504 public override Expression CreateExpressionTree (ResolveContext ec)
4506 HoistedVariable hv = GetHoistedVariable (ec);
4508 return hv.CreateExpressionTree ();
4510 Arguments arg = new Arguments (1);
4511 arg.Add (new Argument (this));
4512 return CreateExpressionFactoryCall (ec, "Constant", arg);
4515 Expression DoResolveBase (ResolveContext ec)
4517 Expression e = Block.GetConstantExpression (Name);
4519 return e.Resolve (ec);
4521 VerifyAssigned (ec);
4524 // If we are referencing a variable from the external block
4525 // flag it for capturing
4527 if (ec.MustCaptureVariable (local_info)) {
4528 if (local_info.AddressTaken)
4529 AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, this, loc);
4531 if (ec.IsVariableCapturingRequired) {
4532 AnonymousMethodStorey storey = local_info.Block.Explicit.CreateAnonymousMethodStorey (ec);
4533 storey.CaptureLocalVariable (ec, local_info);
4537 eclass = ExprClass.Variable;
4538 type = local_info.VariableType;
4542 protected override Expression DoResolve (ResolveContext ec)
4544 ResolveLocalInfo ();
4545 local_info.Used = true;
4547 if (type == null && local_info.Type is VarExpr) {
4548 local_info.VariableType = TypeManager.object_type;
4549 Error_VariableIsUsedBeforeItIsDeclared (ec.Report, Name);
4553 return DoResolveBase (ec);
4556 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
4558 ResolveLocalInfo ();
4561 if (right_side == EmptyExpression.OutAccess.Instance)
4562 local_info.Used = true;
4564 // Infer implicitly typed local variable
4566 VarExpr ve = local_info.Type as VarExpr;
4568 if (!ve.InferType (ec, right_side))
4570 type = local_info.VariableType = ve.Type;
4577 if (right_side == EmptyExpression.OutAccess.Instance) {
4578 code = 1657; msg = "Cannot pass `{0}' as a ref or out argument because it is a `{1}'";
4579 } else if (right_side == EmptyExpression.LValueMemberAccess) {
4580 code = 1654; msg = "Cannot assign to members of `{0}' because it is a `{1}'";
4581 } else if (right_side == EmptyExpression.LValueMemberOutAccess) {
4582 code = 1655; msg = "Cannot pass members of `{0}' as ref or out arguments because it is a `{1}'";
4583 } else if (right_side == EmptyExpression.UnaryAddress) {
4584 code = 459; msg = "Cannot take the address of {1} `{0}'";
4586 code = 1656; msg = "Cannot assign to `{0}' because it is a `{1}'";
4588 ec.Report.Error (code, loc, msg, Name, local_info.GetReadOnlyContext ());
4589 } else if (VariableInfo != null) {
4590 VariableInfo.SetAssigned (ec);
4593 return DoResolveBase (ec);
4596 public override int GetHashCode ()
4598 return Name.GetHashCode ();
4601 public override bool Equals (object obj)
4603 LocalVariableReference lvr = obj as LocalVariableReference;
4607 return Name == lvr.Name && Block == lvr.Block;
4610 protected override ILocalVariable Variable {
4611 get { return local_info; }
4614 public override string ToString ()
4616 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
4619 protected override void CloneTo (CloneContext clonectx, Expression t)
4621 LocalVariableReference target = (LocalVariableReference) t;
4623 target.Block = clonectx.LookupBlock (Block);
4624 if (local_info != null)
4625 target.local_info = clonectx.LookupVariable (local_info);
4630 /// This represents a reference to a parameter in the intermediate
4633 public class ParameterReference : VariableReference {
4634 readonly ToplevelParameterInfo pi;
4636 public ParameterReference (ToplevelParameterInfo pi, Location loc)
4642 public override bool IsRef {
4643 get { return (pi.Parameter.ModFlags & Parameter.Modifier.ISBYREF) != 0; }
4646 bool HasOutModifier {
4647 get { return pi.Parameter.ModFlags == Parameter.Modifier.OUT; }
4650 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
4652 return pi.Parameter.HoistedVariant;
4656 // A ref or out parameter is classified as a moveable variable, even
4657 // if the argument given for the parameter is a fixed variable
4659 public override bool IsFixed {
4660 get { return !IsRef; }
4663 public override string Name {
4664 get { return Parameter.Name; }
4667 public Parameter Parameter {
4668 get { return pi.Parameter; }
4671 public override VariableInfo VariableInfo {
4672 get { return pi.VariableInfo; }
4675 protected override ILocalVariable Variable {
4676 get { return Parameter; }
4679 public bool IsAssigned (ResolveContext ec, Location loc)
4681 // HACK: Variables are not captured in probing mode
4682 if (ec.IsInProbingMode)
4685 if (!ec.DoFlowAnalysis || !HasOutModifier || ec.CurrentBranching.IsAssigned (VariableInfo))
4688 ec.Report.Error (269, loc, "Use of unassigned out parameter `{0}'", Name);
4692 public override void SetHasAddressTaken ()
4694 Parameter.HasAddressTaken = true;
4697 void SetAssigned (ResolveContext ec)
4699 if (HasOutModifier && ec.DoFlowAnalysis)
4700 ec.CurrentBranching.SetAssigned (VariableInfo);
4703 bool DoResolveBase (ResolveContext ec)
4705 type = pi.ParameterType;
4706 eclass = ExprClass.Variable;
4708 AnonymousExpression am = ec.CurrentAnonymousMethod;
4712 Block b = ec.CurrentBlock;
4715 IParameterData[] p = b.Toplevel.Parameters.FixedParameters;
4716 for (int i = 0; i < p.Length; ++i) {
4717 if (p [i] != Parameter)
4721 // Don't capture local parameters
4723 if (b == ec.CurrentBlock.Toplevel && !am.IsIterator)
4727 ec.Report.Error (1628, loc,
4728 "Parameter `{0}' cannot be used inside `{1}' when using `ref' or `out' modifier",
4729 Name, am.ContainerType);
4732 if (pi.Parameter.HasAddressTaken)
4733 AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, this, loc);
4735 if (ec.IsVariableCapturingRequired && !b.Toplevel.IsExpressionTree) {
4736 AnonymousMethodStorey storey = pi.Block.CreateAnonymousMethodStorey (ec);
4737 storey.CaptureParameter (ec, this);
4749 public override int GetHashCode ()
4751 return Name.GetHashCode ();
4754 public override bool Equals (object obj)
4756 ParameterReference pr = obj as ParameterReference;
4760 return Name == pr.Name;
4763 public override void AddressOf (EmitContext ec, AddressOp mode)
4766 // ParameterReferences might already be a reference
4773 base.AddressOf (ec, mode);
4776 protected override void CloneTo (CloneContext clonectx, Expression target)
4781 public override Expression CreateExpressionTree (ResolveContext ec)
4783 HoistedVariable hv = GetHoistedVariable (ec);
4785 return hv.CreateExpressionTree ();
4787 return Parameter.ExpressionTreeVariableReference ();
4791 // Notice that for ref/out parameters, the type exposed is not the
4792 // same type exposed externally.
4795 // externally we expose "int&"
4796 // here we expose "int".
4798 // We record this in "is_ref". This means that the type system can treat
4799 // the type as it is expected, but when we generate the code, we generate
4800 // the alternate kind of code.
4802 protected override Expression DoResolve (ResolveContext ec)
4804 if (!DoResolveBase (ec))
4807 // HACK: Variables are not captured in probing mode
4808 if (ec.IsInProbingMode)
4811 if (HasOutModifier && ec.DoFlowAnalysis &&
4812 (!ec.OmitStructFlowAnalysis || !VariableInfo.TypeInfo.IsStruct) && !IsAssigned (ec, loc))
4818 override public Expression DoResolveLValue (ResolveContext ec, Expression right_side)
4820 if (!DoResolveBase (ec))
4827 static public void EmitLdArg (EmitContext ec, int x)
4830 case 0: ec.Emit (OpCodes.Ldarg_0); break;
4831 case 1: ec.Emit (OpCodes.Ldarg_1); break;
4832 case 2: ec.Emit (OpCodes.Ldarg_2); break;
4833 case 3: ec.Emit (OpCodes.Ldarg_3); break;
4835 if (x > byte.MaxValue)
4836 ec.Emit (OpCodes.Ldarg, x);
4838 ec.Emit (OpCodes.Ldarg_S, (byte) x);
4845 /// Invocation of methods or delegates.
4847 public class Invocation : ExpressionStatement
4849 protected Arguments arguments;
4850 protected Expression expr;
4851 protected MethodGroupExpr mg;
4853 public Invocation (Expression expr, Arguments arguments)
4856 this.arguments = arguments;
4858 loc = expr.Location;
4862 public Arguments Arguments {
4868 public Expression Expression {
4875 public override Expression CreateExpressionTree (ResolveContext ec)
4877 Expression instance = mg.IsInstance ?
4878 mg.InstanceExpression.CreateExpressionTree (ec) :
4879 new NullLiteral (loc);
4881 var args = Arguments.CreateForExpressionTree (ec, arguments,
4883 mg.CreateExpressionTree (ec));
4885 return CreateExpressionFactoryCall (ec, "Call", args);
4888 protected override Expression DoResolve (ResolveContext ec)
4890 Expression member_expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4891 if (member_expr == null)
4895 // Next, evaluate all the expressions in the argument list
4897 bool dynamic_arg = false;
4898 if (arguments != null)
4899 arguments.Resolve (ec, out dynamic_arg);
4901 TypeSpec expr_type = member_expr.Type;
4902 mg = member_expr as MethodGroupExpr;
4904 bool dynamic_member = expr_type == InternalType.Dynamic;
4906 if (!dynamic_member) {
4907 Expression invoke = null;
4910 if (expr_type != null && TypeManager.IsDelegateType (expr_type)) {
4911 invoke = new DelegateInvocation (member_expr, arguments, loc);
4912 invoke = invoke.Resolve (ec);
4913 if (invoke == null || !dynamic_arg)
4916 MemberExpr me = member_expr as MemberExpr;
4918 member_expr.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup, loc);
4922 mg = ec.LookupExtensionMethod (me.Type, me.Name, -1, loc);
4924 ec.Report.Error (1955, loc, "The member `{0}' cannot be used as method or delegate",
4925 member_expr.GetSignatureForError ());
4929 ((ExtensionMethodGroupExpr) mg).ExtensionExpression = me.InstanceExpression;
4933 if (invoke == null) {
4934 mg = DoResolveOverload (ec);
4940 if (dynamic_arg || dynamic_member)
4941 return DoResolveDynamic (ec, member_expr);
4943 var method = mg.BestCandidate;
4944 if (method != null) {
4945 type = method.ReturnType;
4949 // Only base will allow this invocation to happen.
4951 if (mg.IsBase && method.IsAbstract){
4952 Error_CannotCallAbstractBase (ec, TypeManager.CSharpSignature (method));
4956 if (arguments == null && method.DeclaringType == TypeManager.object_type && method.Name == Destructor.MetadataName) {
4958 ec.Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
4960 ec.Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
4964 IsSpecialMethodInvocation (ec, method, loc);
4966 if (mg.InstanceExpression != null)
4967 mg.InstanceExpression.CheckMarshalByRefAccess (ec);
4969 eclass = ExprClass.Value;
4973 Expression DoResolveDynamic (ResolveContext ec, Expression memberExpr)
4976 DynamicMemberBinder dmb = memberExpr as DynamicMemberBinder;
4978 args = dmb.Arguments;
4979 if (arguments != null)
4980 args.AddRange (arguments);
4981 } else if (mg == null) {
4982 if (arguments == null)
4983 args = new Arguments (1);
4987 args.Insert (0, new Argument (memberExpr));
4991 ec.Report.Error (1971, loc,
4992 "The base call to method `{0}' cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access",
4997 if (arguments == null)
4998 args = new Arguments (1);
5002 MemberAccess ma = expr as MemberAccess;
5004 var left_type = ma.Left as TypeExpr;
5005 if (left_type != null) {
5006 args.Insert (0, new Argument (new TypeOf (left_type, loc).Resolve (ec), Argument.AType.DynamicTypeName));
5008 args.Insert (0, new Argument (ma.Left));
5010 } else { // is SimpleName
5012 args.Insert (0, new Argument (new TypeOf (new TypeExpression (ec.CurrentType, loc), loc).Resolve (ec), Argument.AType.DynamicTypeName));
5014 args.Insert (0, new Argument (new This (loc).Resolve (ec)));
5019 return new DynamicInvocation (expr as ATypeNameExpression, args, loc).Resolve (ec);
5022 protected virtual MethodGroupExpr DoResolveOverload (ResolveContext ec)
5024 return mg.OverloadResolve (ec, ref arguments, false, loc);
5027 public static bool IsSpecialMethodInvocation (ResolveContext ec, MethodSpec method, Location loc)
5029 if (!method.IsReservedMethod)
5032 if (ec.HasSet (ResolveContext.Options.InvokeSpecialName))
5035 ec.Report.SymbolRelatedToPreviousError (method);
5036 ec.Report.Error (571, loc, "`{0}': cannot explicitly call operator or accessor",
5037 method.GetSignatureForError ());
5042 static Type[] GetVarargsTypes (MethodSpec mb, Arguments arguments)
5044 AParametersCollection pd = mb.Parameters;
5046 Argument a = arguments [pd.Count - 1];
5047 Arglist list = (Arglist) a.Expr;
5049 return list.ArgumentTypes;
5053 /// is_base tells whether we want to force the use of the `call'
5054 /// opcode instead of using callvirt. Call is required to call
5055 /// a specific method, while callvirt will always use the most
5056 /// recent method in the vtable.
5058 /// is_static tells whether this is an invocation on a static method
5060 /// instance_expr is an expression that represents the instance
5061 /// it must be non-null if is_static is false.
5063 /// method is the method to invoke.
5065 /// Arguments is the list of arguments to pass to the method or constructor.
5067 public static void EmitCall (EmitContext ec, Expression instance_expr,
5068 MethodSpec method, Arguments Arguments, Location loc)
5070 EmitCall (ec, instance_expr, method, Arguments, loc, false, false);
5073 // `dup_args' leaves an extra copy of the arguments on the stack
5074 // `omit_args' does not leave any arguments at all.
5075 // So, basically, you could make one call with `dup_args' set to true,
5076 // and then another with `omit_args' set to true, and the two calls
5077 // would have the same set of arguments. However, each argument would
5078 // only have been evaluated once.
5079 public static void EmitCall (EmitContext ec, Expression instance_expr,
5080 MethodSpec method, Arguments Arguments, Location loc,
5081 bool dup_args, bool omit_args)
5083 LocalTemporary this_arg = null;
5085 TypeSpec decl_type = method.DeclaringType;
5087 // Speed up the check by not doing it on not allowed targets
5088 if (method.ReturnType == TypeManager.void_type && method.IsConditionallyExcluded (loc))
5092 TypeSpec iexpr_type;
5094 if (method.IsStatic) {
5096 call_op = OpCodes.Call;
5098 iexpr_type = instance_expr.Type;
5100 if (decl_type.IsStruct || decl_type.IsEnum || (instance_expr is This && !method.IsVirtual) || (instance_expr is BaseThis)) {
5101 call_op = OpCodes.Call;
5103 call_op = OpCodes.Callvirt;
5107 // If this is ourselves, push "this"
5110 TypeSpec t = iexpr_type;
5113 // Push the instance expression
5115 if ((iexpr_type.IsStruct && (call_op == OpCodes.Callvirt || (call_op == OpCodes.Call && decl_type == iexpr_type))) ||
5116 iexpr_type.IsGenericParameter || TypeManager.IsNullableType (decl_type)) {
5118 // If the expression implements IMemoryLocation, then
5119 // we can optimize and use AddressOf on the
5122 // If not we have to use some temporary storage for
5124 var iml = instance_expr as IMemoryLocation;
5126 iml.AddressOf (ec, AddressOp.LoadStore);
5128 LocalTemporary temp = new LocalTemporary (iexpr_type);
5129 instance_expr.Emit (ec);
5131 temp.AddressOf (ec, AddressOp.Load);
5134 // avoid the overhead of doing this all the time.
5136 t = ReferenceContainer.MakeType (iexpr_type);
5137 } else if (iexpr_type.IsEnum || iexpr_type.IsStruct) {
5138 instance_expr.Emit (ec);
5139 ec.Emit (OpCodes.Box, iexpr_type);
5140 t = iexpr_type = TypeManager.object_type;
5142 instance_expr.Emit (ec);
5146 ec.Emit (OpCodes.Dup);
5147 if (Arguments != null && Arguments.Count != 0) {
5148 this_arg = new LocalTemporary (t);
5149 this_arg.Store (ec);
5155 if (!omit_args && Arguments != null)
5156 Arguments.Emit (ec, dup_args, this_arg);
5158 if (call_op == OpCodes.Callvirt && (iexpr_type.IsGenericParameter || iexpr_type.IsStruct)) {
5159 ec.Emit (OpCodes.Constrained, iexpr_type);
5162 if (method.Parameters.HasArglist) {
5163 Type[] varargs_types = GetVarargsTypes (method, Arguments);
5164 ec.Emit (call_op, method, varargs_types);
5171 // and DoFoo is not virtual, you can omit the callvirt,
5172 // because you don't need the null checking behavior.
5174 ec.Emit (call_op, method);
5177 public override void Emit (EmitContext ec)
5179 mg.EmitCall (ec, arguments);
5182 public override void EmitStatement (EmitContext ec)
5187 // Pop the return value if there is one
5189 if (type != TypeManager.void_type)
5190 ec.Emit (OpCodes.Pop);
5193 protected override void CloneTo (CloneContext clonectx, Expression t)
5195 Invocation target = (Invocation) t;
5197 if (arguments != null)
5198 target.arguments = arguments.Clone (clonectx);
5200 target.expr = expr.Clone (clonectx);
5203 public override SLE.Expression MakeExpression (BuilderContext ctx)
5205 return MakeExpression (ctx, mg.InstanceExpression, mg.BestCandidate, arguments);
5208 public static SLE.Expression MakeExpression (BuilderContext ctx, Expression instance, MethodSpec mi, Arguments args)
5210 var instance_expr = instance == null ? null : instance.MakeExpression (ctx);
5211 return SLE.Expression.Call (instance_expr, (MethodInfo) mi.GetMetaInfo (), Arguments.MakeExpression (args, ctx));
5216 /// Implements the new expression
5218 public class New : ExpressionStatement, IMemoryLocation {
5219 protected Arguments Arguments;
5222 // During bootstrap, it contains the RequestedType,
5223 // but if `type' is not null, it *might* contain a NewDelegate
5224 // (because of field multi-initialization)
5226 protected Expression RequestedType;
5228 protected MethodGroupExpr method;
5230 public New (Expression requested_type, Arguments arguments, Location l)
5232 RequestedType = requested_type;
5233 Arguments = arguments;
5238 /// Converts complex core type syntax like 'new int ()' to simple constant
5240 public static Constant Constantify (TypeSpec t)
5242 if (t == TypeManager.int32_type)
5243 return new IntConstant (0, Location.Null);
5244 if (t == TypeManager.uint32_type)
5245 return new UIntConstant (0, Location.Null);
5246 if (t == TypeManager.int64_type)
5247 return new LongConstant (0, Location.Null);
5248 if (t == TypeManager.uint64_type)
5249 return new ULongConstant (0, Location.Null);
5250 if (t == TypeManager.float_type)
5251 return new FloatConstant (0, Location.Null);
5252 if (t == TypeManager.double_type)
5253 return new DoubleConstant (0, Location.Null);
5254 if (t == TypeManager.short_type)
5255 return new ShortConstant (0, Location.Null);
5256 if (t == TypeManager.ushort_type)
5257 return new UShortConstant (0, Location.Null);
5258 if (t == TypeManager.sbyte_type)
5259 return new SByteConstant (0, Location.Null);
5260 if (t == TypeManager.byte_type)
5261 return new ByteConstant (0, Location.Null);
5262 if (t == TypeManager.char_type)
5263 return new CharConstant ('\0', Location.Null);
5264 if (t == TypeManager.bool_type)
5265 return new BoolConstant (false, Location.Null);
5266 if (t == TypeManager.decimal_type)
5267 return new DecimalConstant (0, Location.Null);
5268 if (TypeManager.IsEnumType (t))
5269 return new EnumConstant (Constantify (EnumSpec.GetUnderlyingType (t)), t);
5270 if (TypeManager.IsNullableType (t))
5271 return Nullable.LiftedNull.Create (t, Location.Null);
5277 // Checks whether the type is an interface that has the
5278 // [ComImport, CoClass] attributes and must be treated
5281 public Expression CheckComImport (ResolveContext ec)
5283 if (!type.IsInterface)
5287 // Turn the call into:
5288 // (the-interface-stated) (new class-referenced-in-coclassattribute ())
5290 var real_class = type.MemberDefinition.GetAttributeCoClass ();
5291 if (real_class == null)
5294 New proxy = new New (new TypeExpression (real_class, loc), Arguments, loc);
5295 Cast cast = new Cast (new TypeExpression (type, loc), proxy, loc);
5296 return cast.Resolve (ec);
5299 public override Expression CreateExpressionTree (ResolveContext ec)
5302 if (method == null) {
5303 args = new Arguments (1);
5304 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
5306 args = Arguments.CreateForExpressionTree (ec,
5308 method.CreateExpressionTree (ec));
5311 return CreateExpressionFactoryCall (ec, "New", args);
5314 protected override Expression DoResolve (ResolveContext ec)
5316 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec, false);
5322 if (type.IsPointer) {
5323 ec.Report.Error (1919, loc, "Unsafe type `{0}' cannot be used in an object creation expression",
5324 TypeManager.CSharpName (type));
5328 if (Arguments == null) {
5329 Constant c = Constantify (type);
5331 return ReducedExpression.Create (c.Resolve (ec), this);
5334 if (TypeManager.IsDelegateType (type)) {
5335 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5338 var tparam = type as TypeParameterSpec;
5339 if (tparam != null) {
5340 if (!tparam.HasSpecialConstructor && !tparam.HasSpecialStruct) {
5341 ec.Report.Error (304, loc,
5342 "Cannot create an instance of the variable type `{0}' because it does not have the new() constraint",
5343 TypeManager.CSharpName (type));
5346 if ((Arguments != null) && (Arguments.Count != 0)) {
5347 ec.Report.Error (417, loc,
5348 "`{0}': cannot provide arguments when creating an instance of a variable type",
5349 TypeManager.CSharpName (type));
5352 if (TypeManager.activator_create_instance == null) {
5353 TypeSpec activator_type = TypeManager.CoreLookupType (ec.Compiler, "System", "Activator", MemberKind.Class, true);
5354 if (activator_type != null) {
5355 TypeManager.activator_create_instance = TypeManager.GetPredefinedMethod (
5356 activator_type, MemberFilter.Method ("CreateInstance", 1, ParametersCompiled.EmptyReadOnlyParameters, null), loc);
5360 eclass = ExprClass.Value;
5364 if (type.IsStatic) {
5365 ec.Report.SymbolRelatedToPreviousError (type);
5366 ec.Report.Error (712, loc, "Cannot create an instance of the static class `{0}'", TypeManager.CSharpName (type));
5370 if (type.IsInterface || type.IsAbstract){
5371 if (!TypeManager.IsGenericType (type)) {
5372 RequestedType = CheckComImport (ec);
5373 if (RequestedType != null)
5374 return RequestedType;
5377 ec.Report.SymbolRelatedToPreviousError (type);
5378 ec.Report.Error (144, loc, "Cannot create an instance of the abstract class or interface `{0}'", TypeManager.CSharpName (type));
5382 bool is_struct = TypeManager.IsStruct (type);
5383 eclass = ExprClass.Value;
5386 // SRE returns a match for .ctor () on structs (the object constructor),
5387 // so we have to manually ignore it.
5389 if (is_struct && Arguments == null)
5392 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
5393 Expression ml = MemberLookupFinal (ec, type, type, ConstructorInfo.ConstructorName, 0,
5394 MemberKind.Constructor, BindingRestriction.AccessibleOnly | BindingRestriction.DeclaredOnly, loc);
5397 if (Arguments != null) {
5398 Arguments.Resolve (ec, out dynamic);
5406 method = ml as MethodGroupExpr;
5407 if (method == null) {
5408 ml.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup, loc);
5412 method = method.OverloadResolve (ec, ref Arguments, false, loc);
5417 Arguments.Insert (0, new Argument (new TypeOf (texpr, loc).Resolve (ec), Argument.AType.DynamicTypeName));
5418 return new DynamicConstructorBinder (type, Arguments, loc).Resolve (ec);
5424 bool DoEmitTypeParameter (EmitContext ec)
5426 var ctor_factory = TypeManager.activator_create_instance.MakeGenericMethod (type);
5427 var tparam = (TypeParameterSpec) type;
5429 if (tparam.IsReferenceType) {
5430 ec.Emit (OpCodes.Call, ctor_factory);
5434 // Allow DoEmit() to be called multiple times.
5435 // We need to create a new LocalTemporary each time since
5436 // you can't share LocalBuilders among ILGeneators.
5437 LocalTemporary temp = new LocalTemporary (type);
5439 Label label_activator = ec.DefineLabel ();
5440 Label label_end = ec.DefineLabel ();
5442 temp.AddressOf (ec, AddressOp.Store);
5443 ec.Emit (OpCodes.Initobj, type);
5446 ec.Emit (OpCodes.Box, type);
5447 ec.Emit (OpCodes.Brfalse, label_activator);
5449 temp.AddressOf (ec, AddressOp.Store);
5450 ec.Emit (OpCodes.Initobj, type);
5452 ec.Emit (OpCodes.Br_S, label_end);
5454 ec.MarkLabel (label_activator);
5456 ec.Emit (OpCodes.Call, ctor_factory);
5457 ec.MarkLabel (label_end);
5462 // This Emit can be invoked in two contexts:
5463 // * As a mechanism that will leave a value on the stack (new object)
5464 // * As one that wont (init struct)
5466 // If we are dealing with a ValueType, we have a few
5467 // situations to deal with:
5469 // * The target is a ValueType, and we have been provided
5470 // the instance (this is easy, we are being assigned).
5472 // * The target of New is being passed as an argument,
5473 // to a boxing operation or a function that takes a
5476 // In this case, we need to create a temporary variable
5477 // that is the argument of New.
5479 // Returns whether a value is left on the stack
5481 // *** Implementation note ***
5483 // To benefit from this optimization, each assignable expression
5484 // has to manually cast to New and call this Emit.
5486 // TODO: It's worth to implement it for arrays and fields
5488 public virtual bool Emit (EmitContext ec, IMemoryLocation target)
5490 bool is_value_type = TypeManager.IsValueType (type);
5491 VariableReference vr = target as VariableReference;
5493 if (target != null && is_value_type && (vr != null || method == null)) {
5494 target.AddressOf (ec, AddressOp.Store);
5495 } else if (vr != null && vr.IsRef) {
5499 if (Arguments != null)
5500 Arguments.Emit (ec);
5502 if (is_value_type) {
5503 if (method == null) {
5504 ec.Emit (OpCodes.Initobj, type);
5509 ec.Emit (OpCodes.Call, method.BestCandidate);
5514 if (type is TypeParameterSpec)
5515 return DoEmitTypeParameter (ec);
5517 ec.Emit (OpCodes.Newobj, method.BestCandidate);
5521 public override void Emit (EmitContext ec)
5523 LocalTemporary v = null;
5524 if (method == null && TypeManager.IsValueType (type)) {
5525 // TODO: Use temporary variable from pool
5526 v = new LocalTemporary (type);
5533 public override void EmitStatement (EmitContext ec)
5535 LocalTemporary v = null;
5536 if (method == null && TypeManager.IsValueType (type)) {
5537 // TODO: Use temporary variable from pool
5538 v = new LocalTemporary (type);
5542 ec.Emit (OpCodes.Pop);
5545 public virtual bool HasInitializer {
5551 public void AddressOf (EmitContext ec, AddressOp mode)
5553 EmitAddressOf (ec, mode);
5556 protected virtual IMemoryLocation EmitAddressOf (EmitContext ec, AddressOp mode)
5558 LocalTemporary value_target = new LocalTemporary (type);
5560 if (type is TypeParameterSpec) {
5561 DoEmitTypeParameter (ec);
5562 value_target.Store (ec);
5563 value_target.AddressOf (ec, mode);
5564 return value_target;
5567 if (!TypeManager.IsStruct (type)){
5569 // We throw an exception. So far, I believe we only need to support
5571 // foreach (int j in new StructType ())
5574 throw new Exception ("AddressOf should not be used for classes");
5577 value_target.AddressOf (ec, AddressOp.Store);
5579 if (method == null) {
5580 ec.Emit (OpCodes.Initobj, type);
5582 if (Arguments != null)
5583 Arguments.Emit (ec);
5585 ec.Emit (OpCodes.Call, method.BestCandidate);
5588 value_target.AddressOf (ec, mode);
5589 return value_target;
5592 protected override void CloneTo (CloneContext clonectx, Expression t)
5594 New target = (New) t;
5596 target.RequestedType = RequestedType.Clone (clonectx);
5597 if (Arguments != null){
5598 target.Arguments = Arguments.Clone (clonectx);
5602 public override SLE.Expression MakeExpression (BuilderContext ctx)
5604 return SLE.Expression.New ((ConstructorInfo) method.BestCandidate.GetMetaInfo (), Arguments.MakeExpression (Arguments, ctx));
5608 public class ArrayInitializer : Expression
5610 List<Expression> elements;
5612 public ArrayInitializer (List<Expression> init, Location loc)
5618 public ArrayInitializer (int count, Location loc)
5620 elements = new List<Expression> (count);
5624 public ArrayInitializer (Location loc)
5629 public void Add (Expression expr)
5631 elements.Add (expr);
5634 public override Expression CreateExpressionTree (ResolveContext ec)
5636 throw new NotSupportedException ("ET");
5639 protected override void CloneTo (CloneContext clonectx, Expression t)
5641 var target = (ArrayInitializer) t;
5643 target.elements = new List<Expression> (elements.Count);
5644 foreach (var element in elements)
5645 target.elements.Add (element.Clone (clonectx));
5649 get { return elements.Count; }
5652 protected override Expression DoResolve (ResolveContext rc)
5654 var current_field = rc.CurrentMemberDefinition as FieldBase;
5655 return new ArrayCreation (new TypeExpression (current_field.MemberType, current_field.Location), this).Resolve (rc);
5658 public override void Emit (EmitContext ec)
5660 throw new InternalErrorException ("Missing Resolve call");
5663 public Expression this [int index] {
5664 get { return elements [index]; }
5669 /// 14.5.10.2: Represents an array creation expression.
5673 /// There are two possible scenarios here: one is an array creation
5674 /// expression that specifies the dimensions and optionally the
5675 /// initialization data and the other which does not need dimensions
5676 /// specified but where initialization data is mandatory.
5678 public class ArrayCreation : Expression
5680 FullNamedExpression requested_base_type;
5681 ArrayInitializer initializers;
5684 // The list of Argument types.
5685 // This is used to construct the `newarray' or constructor signature
5687 protected List<Expression> arguments;
5689 protected TypeSpec array_element_type;
5690 int num_arguments = 0;
5691 protected int dimensions;
5692 protected readonly ComposedTypeSpecifier rank;
5693 Expression first_emit;
5694 LocalTemporary first_emit_temp;
5696 protected List<Expression> array_data;
5698 Dictionary<int, int> bounds;
5700 // The number of constants in array initializers
5701 int const_initializers_count;
5702 bool only_constant_initializers;
5704 public ArrayCreation (FullNamedExpression requested_base_type, List<Expression> exprs, ComposedTypeSpecifier rank, ArrayInitializer initializers, Location l)
5705 : this (requested_base_type, rank, initializers, l)
5707 arguments = new List<Expression> (exprs);
5708 num_arguments = arguments.Count;
5712 // For expressions like int[] foo = new int[] { 1, 2, 3 };
5714 public ArrayCreation (FullNamedExpression requested_base_type, ComposedTypeSpecifier rank, ArrayInitializer initializers, Location loc)
5716 this.requested_base_type = requested_base_type;
5718 this.initializers = initializers;
5722 num_arguments = rank.Dimension;
5726 // For compiler generated single dimensional arrays only
5728 public ArrayCreation (FullNamedExpression requested_base_type, ArrayInitializer initializers, Location loc)
5729 : this (requested_base_type, ComposedTypeSpecifier.SingleDimension, initializers, loc)
5734 // For expressions like int[] foo = { 1, 2, 3 };
5736 public ArrayCreation (FullNamedExpression requested_base_type, ArrayInitializer initializers)
5737 : this (requested_base_type, null, initializers, initializers.Location)
5741 protected override void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
5743 ec.Report.Error (248, loc, "Cannot create an array with a negative size");
5746 bool CheckIndices (ResolveContext ec, ArrayInitializer probe, int idx, bool specified_dims, int child_bounds)
5748 if (initializers != null && bounds == null) {
5750 // We use this to store all the date values in the order in which we
5751 // will need to store them in the byte blob later
5753 array_data = new List<Expression> ();
5754 bounds = new Dictionary<int, int> ();
5757 if (specified_dims) {
5758 Expression a = arguments [idx];
5763 a = ConvertExpressionToArrayIndex (ec, a);
5769 if (initializers != null) {
5770 Constant c = a as Constant;
5771 if (c == null && a is ArrayIndexCast)
5772 c = ((ArrayIndexCast) a).Child as Constant;
5775 ec.Report.Error (150, a.Location, "A constant value is expected");
5781 value = System.Convert.ToInt32 (c.GetValue ());
5783 ec.Report.Error (150, a.Location, "A constant value is expected");
5787 // TODO: probe.Count does not fit ulong in
5788 if (value != probe.Count) {
5789 ec.Report.Error (847, loc, "An array initializer of length `{0}' was expected", value.ToString ());
5793 bounds[idx] = value;
5797 if (initializers == null)
5800 only_constant_initializers = true;
5801 for (int i = 0; i < probe.Count; ++i) {
5803 if (o is ArrayInitializer) {
5804 var sub_probe = o as ArrayInitializer;
5805 if (idx + 1 >= dimensions){
5806 ec.Report.Error (623, loc, "Array initializers can only be used in a variable or field initializer. Try using a new expression instead");
5810 bool ret = CheckIndices (ec, sub_probe, idx + 1, specified_dims, child_bounds - 1);
5813 } else if (child_bounds > 1) {
5814 ec.Report.Error (846, o.Location, "A nested array initializer was expected");
5816 Expression element = ResolveArrayElement (ec, o);
5817 if (element == null)
5820 // Initializers with the default values can be ignored
5821 Constant c = element as Constant;
5823 if (!c.IsDefaultInitializer (array_element_type)) {
5824 ++const_initializers_count;
5827 only_constant_initializers = false;
5830 array_data.Add (element);
5837 public override Expression CreateExpressionTree (ResolveContext ec)
5841 if (array_data == null) {
5842 args = new Arguments (arguments.Count + 1);
5843 args.Add (new Argument (new TypeOf (new TypeExpression (array_element_type, loc), loc)));
5844 foreach (Expression a in arguments)
5845 args.Add (new Argument (a.CreateExpressionTree (ec)));
5847 return CreateExpressionFactoryCall (ec, "NewArrayBounds", args);
5850 if (dimensions > 1) {
5851 ec.Report.Error (838, loc, "An expression tree cannot contain a multidimensional array initializer");
5855 args = new Arguments (array_data == null ? 1 : array_data.Count + 1);
5856 args.Add (new Argument (new TypeOf (new TypeExpression (array_element_type, loc), loc)));
5857 if (array_data != null) {
5858 for (int i = 0; i < array_data.Count; ++i) {
5859 Expression e = array_data [i];
5860 args.Add (new Argument (e.CreateExpressionTree (ec)));
5864 return CreateExpressionFactoryCall (ec, "NewArrayInit", args);
5867 public void UpdateIndices ()
5870 for (var probe = initializers; probe != null;) {
5871 if (probe.Count > 0 && probe [0] is ArrayInitializer) {
5872 Expression e = new IntConstant (probe.Count, Location.Null);
5875 bounds [i++] = probe.Count;
5877 probe = (ArrayInitializer) probe[0];
5880 Expression e = new IntConstant (probe.Count, Location.Null);
5883 bounds [i++] = probe.Count;
5889 protected virtual Expression ResolveArrayElement (ResolveContext ec, Expression element)
5891 element = element.Resolve (ec);
5892 if (element == null)
5895 if (element is CompoundAssign.TargetExpression) {
5896 if (first_emit != null)
5897 throw new InternalErrorException ("Can only handle one mutator at a time");
5898 first_emit = element;
5899 element = first_emit_temp = new LocalTemporary (element.Type);
5902 return Convert.ImplicitConversionRequired (
5903 ec, element, array_element_type, loc);
5906 protected bool ResolveInitializers (ResolveContext ec)
5908 if (arguments != null) {
5910 for (int i = 0; i < arguments.Count; ++i) {
5911 res &= CheckIndices (ec, initializers, i, true, dimensions);
5912 if (initializers != null)
5919 arguments = new List<Expression> ();
5921 if (!CheckIndices (ec, initializers, 0, false, dimensions))
5930 // Resolved the type of the array
5932 bool ResolveArrayType (ResolveContext ec)
5934 if (requested_base_type is VarExpr) {
5935 ec.Report.Error (820, loc, "An implicitly typed local variable declarator cannot use an array initializer");
5942 FullNamedExpression array_type_expr;
5943 if (num_arguments > 0) {
5944 array_type_expr = new ComposedCast (requested_base_type, rank);
5946 array_type_expr = requested_base_type;
5949 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec, false);
5950 if (array_type_expr == null)
5953 type = array_type_expr.Type;
5954 var ac = type as ArrayContainer;
5956 ec.Report.Error (622, loc, "Can only use array initializer expressions to assign to array types. Try using a new expression instead");
5960 array_element_type = ac.Element;
5961 dimensions = ac.Rank;
5966 protected override Expression DoResolve (ResolveContext ec)
5971 if (!ResolveArrayType (ec))
5975 // validate the initializers and fill in any missing bits
5977 if (!ResolveInitializers (ec))
5980 eclass = ExprClass.Value;
5984 byte [] MakeByteBlob ()
5989 int count = array_data.Count;
5991 TypeSpec element_type = array_element_type;
5992 if (TypeManager.IsEnumType (element_type))
5993 element_type = EnumSpec.GetUnderlyingType (element_type);
5995 factor = GetTypeSize (element_type);
5997 throw new Exception ("unrecognized type in MakeByteBlob: " + element_type);
5999 data = new byte [(count * factor + 3) & ~3];
6002 for (int i = 0; i < count; ++i) {
6003 object v = array_data [i];
6005 if (v is EnumConstant)
6006 v = ((EnumConstant) v).Child;
6008 if (v is Constant && !(v is StringConstant))
6009 v = ((Constant) v).GetValue ();
6015 if (element_type == TypeManager.int64_type){
6016 if (!(v is Expression)){
6017 long val = (long) v;
6019 for (int j = 0; j < factor; ++j) {
6020 data [idx + j] = (byte) (val & 0xFF);
6024 } else if (element_type == TypeManager.uint64_type){
6025 if (!(v is Expression)){
6026 ulong val = (ulong) v;
6028 for (int j = 0; j < factor; ++j) {
6029 data [idx + j] = (byte) (val & 0xFF);
6033 } else if (element_type == TypeManager.float_type) {
6034 if (!(v is Expression)){
6035 element = BitConverter.GetBytes ((float) v);
6037 for (int j = 0; j < factor; ++j)
6038 data [idx + j] = element [j];
6039 if (!BitConverter.IsLittleEndian)
6040 System.Array.Reverse (data, idx, 4);
6042 } else if (element_type == TypeManager.double_type) {
6043 if (!(v is Expression)){
6044 element = BitConverter.GetBytes ((double) v);
6046 for (int j = 0; j < factor; ++j)
6047 data [idx + j] = element [j];
6049 // FIXME: Handle the ARM float format.
6050 if (!BitConverter.IsLittleEndian)
6051 System.Array.Reverse (data, idx, 8);
6053 } else if (element_type == TypeManager.char_type){
6054 if (!(v is Expression)){
6055 int val = (int) ((char) v);
6057 data [idx] = (byte) (val & 0xff);
6058 data [idx+1] = (byte) (val >> 8);
6060 } else if (element_type == TypeManager.short_type){
6061 if (!(v is Expression)){
6062 int val = (int) ((short) v);
6064 data [idx] = (byte) (val & 0xff);
6065 data [idx+1] = (byte) (val >> 8);
6067 } else if (element_type == TypeManager.ushort_type){
6068 if (!(v is Expression)){
6069 int val = (int) ((ushort) v);
6071 data [idx] = (byte) (val & 0xff);
6072 data [idx+1] = (byte) (val >> 8);
6074 } else if (element_type == TypeManager.int32_type) {
6075 if (!(v is Expression)){
6078 data [idx] = (byte) (val & 0xff);
6079 data [idx+1] = (byte) ((val >> 8) & 0xff);
6080 data [idx+2] = (byte) ((val >> 16) & 0xff);
6081 data [idx+3] = (byte) (val >> 24);
6083 } else if (element_type == TypeManager.uint32_type) {
6084 if (!(v is Expression)){
6085 uint val = (uint) v;
6087 data [idx] = (byte) (val & 0xff);
6088 data [idx+1] = (byte) ((val >> 8) & 0xff);
6089 data [idx+2] = (byte) ((val >> 16) & 0xff);
6090 data [idx+3] = (byte) (val >> 24);
6092 } else if (element_type == TypeManager.sbyte_type) {
6093 if (!(v is Expression)){
6094 sbyte val = (sbyte) v;
6095 data [idx] = (byte) val;
6097 } else if (element_type == TypeManager.byte_type) {
6098 if (!(v is Expression)){
6099 byte val = (byte) v;
6100 data [idx] = (byte) val;
6102 } else if (element_type == TypeManager.bool_type) {
6103 if (!(v is Expression)){
6104 bool val = (bool) v;
6105 data [idx] = (byte) (val ? 1 : 0);
6107 } else if (element_type == TypeManager.decimal_type){
6108 if (!(v is Expression)){
6109 int [] bits = Decimal.GetBits ((decimal) v);
6112 // FIXME: For some reason, this doesn't work on the MS runtime.
6113 int [] nbits = new int [4];
6114 nbits [0] = bits [3];
6115 nbits [1] = bits [2];
6116 nbits [2] = bits [0];
6117 nbits [3] = bits [1];
6119 for (int j = 0; j < 4; j++){
6120 data [p++] = (byte) (nbits [j] & 0xff);
6121 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6122 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6123 data [p++] = (byte) (nbits [j] >> 24);
6127 throw new Exception ("Unrecognized type in MakeByteBlob: " + element_type);
6137 public override SLE.Expression MakeExpression (BuilderContext ctx)
6139 var initializers = new SLE.Expression [array_data.Count];
6140 for (var i = 0; i < initializers.Length; i++) {
6141 if (array_data [i] == null)
6142 initializers [i] = SLE.Expression.Default (array_element_type.GetMetaInfo ());
6144 initializers [i] = array_data [i].MakeExpression (ctx);
6147 return SLE.Expression.NewArrayInit (array_element_type.GetMetaInfo (), initializers);
6151 // Emits the initializers for the array
6153 void EmitStaticInitializers (EmitContext ec)
6155 // FIXME: This should go to Resolve !
6156 if (TypeManager.void_initializearray_array_fieldhandle == null) {
6157 TypeManager.void_initializearray_array_fieldhandle = TypeManager.GetPredefinedMethod (
6158 TypeManager.runtime_helpers_type, "InitializeArray", loc,
6159 TypeManager.array_type, TypeManager.runtime_field_handle_type);
6160 if (TypeManager.void_initializearray_array_fieldhandle == null)
6165 // First, the static data
6169 byte [] data = MakeByteBlob ();
6171 fb = RootContext.MakeStaticData (data);
6173 ec.Emit (OpCodes.Dup);
6174 ec.Emit (OpCodes.Ldtoken, fb);
6175 ec.Emit (OpCodes.Call, TypeManager.void_initializearray_array_fieldhandle);
6179 // Emits pieces of the array that can not be computed at compile
6180 // time (variables and string locations).
6182 // This always expect the top value on the stack to be the array
6184 void EmitDynamicInitializers (EmitContext ec, bool emitConstants)
6186 int dims = bounds.Count;
6187 var current_pos = new int [dims];
6189 for (int i = 0; i < array_data.Count; i++){
6191 Expression e = array_data [i];
6192 var c = e as Constant;
6194 // Constant can be initialized via StaticInitializer
6195 if (c == null || (c != null && emitConstants && !c.IsDefaultInitializer (array_element_type))) {
6196 TypeSpec etype = e.Type;
6198 ec.Emit (OpCodes.Dup);
6200 for (int idx = 0; idx < dims; idx++)
6201 ec.EmitInt (current_pos [idx]);
6204 // If we are dealing with a struct, get the
6205 // address of it, so we can store it.
6207 if ((dims == 1) && TypeManager.IsStruct (etype) &&
6208 (!TypeManager.IsBuiltinOrEnum (etype) ||
6209 etype == TypeManager.decimal_type)) {
6211 ec.Emit (OpCodes.Ldelema, etype);
6216 ec.EmitArrayStore ((ArrayContainer) type);
6222 for (int j = dims - 1; j >= 0; j--){
6224 if (current_pos [j] < bounds [j])
6226 current_pos [j] = 0;
6231 public override void Emit (EmitContext ec)
6233 if (first_emit != null) {
6234 first_emit.Emit (ec);
6235 first_emit_temp.Store (ec);
6238 foreach (Expression e in arguments)
6241 ec.EmitArrayNew ((ArrayContainer) type);
6243 if (initializers == null)
6246 // Emit static initializer for arrays which have contain more than 2 items and
6247 // the static initializer will initialize at least 25% of array values.
6248 // NOTE: const_initializers_count does not contain default constant values.
6249 if (const_initializers_count > 2 && const_initializers_count * 4 > (array_data.Count) &&
6250 (TypeManager.IsPrimitiveType (array_element_type) || TypeManager.IsEnumType (array_element_type))) {
6251 EmitStaticInitializers (ec);
6253 if (!only_constant_initializers)
6254 EmitDynamicInitializers (ec, false);
6256 EmitDynamicInitializers (ec, true);
6259 if (first_emit_temp != null)
6260 first_emit_temp.Release (ec);
6263 public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
6265 // no multi dimensional or jagged arrays
6266 if (arguments.Count != 1 || array_element_type.IsArray) {
6267 base.EncodeAttributeValue (rc, enc, targetType);
6271 // No array covariance, except for array -> object
6272 if (type != targetType) {
6273 if (targetType != TypeManager.object_type) {
6274 base.EncodeAttributeValue (rc, enc, targetType);
6281 // Single dimensional array of 0 size
6282 if (array_data == null) {
6283 IntConstant ic = arguments[0] as IntConstant;
6284 if (ic == null || !ic.IsDefaultValue) {
6285 base.EncodeAttributeValue (rc, enc, targetType);
6287 enc.Stream.Write (0);
6293 enc.Stream.Write ((int) array_data.Count);
6294 foreach (var element in array_data) {
6295 element.EncodeAttributeValue (rc, enc, array_element_type);
6299 protected override void CloneTo (CloneContext clonectx, Expression t)
6301 ArrayCreation target = (ArrayCreation) t;
6303 if (requested_base_type != null)
6304 target.requested_base_type = (FullNamedExpression)requested_base_type.Clone (clonectx);
6306 if (arguments != null){
6307 target.arguments = new List<Expression> (arguments.Count);
6308 foreach (Expression e in arguments)
6309 target.arguments.Add (e.Clone (clonectx));
6312 if (initializers != null)
6313 target.initializers = (ArrayInitializer) initializers.Clone (clonectx);
6318 // Represents an implicitly typed array epxression
6320 class ImplicitlyTypedArrayCreation : ArrayCreation
6322 public ImplicitlyTypedArrayCreation (ComposedTypeSpecifier rank, ArrayInitializer initializers, Location loc)
6323 : base (null, rank, initializers, loc)
6327 public ImplicitlyTypedArrayCreation (ArrayInitializer initializers, Location loc)
6328 : base (null, initializers, loc)
6332 protected override Expression DoResolve (ResolveContext ec)
6337 dimensions = rank.Dimension;
6339 if (!ResolveInitializers (ec))
6342 if (array_element_type == null || array_element_type == TypeManager.null_type ||
6343 array_element_type == TypeManager.void_type || array_element_type == InternalType.AnonymousMethod ||
6344 array_element_type == InternalType.MethodGroup ||
6345 arguments.Count != rank.Dimension) {
6346 Error_NoBestType (ec);
6351 // At this point we found common base type for all initializer elements
6352 // but we have to be sure that all static initializer elements are of
6355 UnifyInitializerElement (ec);
6357 type = ArrayContainer.MakeType (array_element_type, dimensions);
6358 eclass = ExprClass.Value;
6362 void Error_NoBestType (ResolveContext ec)
6364 ec.Report.Error (826, loc,
6365 "The type of an implicitly typed array cannot be inferred from the initializer. Try specifying array type explicitly");
6369 // Converts static initializer only
6371 void UnifyInitializerElement (ResolveContext ec)
6373 for (int i = 0; i < array_data.Count; ++i) {
6374 Expression e = (Expression)array_data[i];
6376 array_data [i] = Convert.ImplicitConversion (ec, e, array_element_type, Location.Null);
6380 protected override Expression ResolveArrayElement (ResolveContext ec, Expression element)
6382 element = element.Resolve (ec);
6383 if (element == null)
6386 if (array_element_type == null) {
6387 if (element.Type != TypeManager.null_type)
6388 array_element_type = element.Type;
6393 if (Convert.ImplicitConversionExists (ec, element, array_element_type)) {
6397 if (Convert.ImplicitConversionExists (ec, new TypeExpression (array_element_type, loc), element.Type)) {
6398 array_element_type = element.Type;
6402 Error_NoBestType (ec);
6407 public sealed class CompilerGeneratedThis : This
6409 public static This Instance = new CompilerGeneratedThis ();
6411 private CompilerGeneratedThis ()
6412 : base (Location.Null)
6416 public CompilerGeneratedThis (TypeSpec type, Location loc)
6422 protected override Expression DoResolve (ResolveContext ec)
6424 eclass = ExprClass.Variable;
6426 type = ec.CurrentType;
6431 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
6438 /// Represents the `this' construct
6441 public class This : VariableReference
6443 sealed class ThisVariable : ILocalVariable
6445 public static readonly ILocalVariable Instance = new ThisVariable ();
6447 public void Emit (EmitContext ec)
6449 ec.Emit (OpCodes.Ldarg_0);
6452 public void EmitAssign (EmitContext ec)
6454 throw new InvalidOperationException ();
6457 public void EmitAddressOf (EmitContext ec)
6459 ec.Emit (OpCodes.Ldarg_0);
6463 VariableInfo variable_info;
6465 public This (Location loc)
6472 public override string Name {
6473 get { return "this"; }
6476 public override bool IsRef {
6477 get { return type.IsStruct; }
6480 protected override ILocalVariable Variable {
6481 get { return ThisVariable.Instance; }
6484 public override VariableInfo VariableInfo {
6485 get { return variable_info; }
6488 public override bool IsFixed {
6489 get { return false; }
6494 protected virtual void Error_ThisNotAvailable (ResolveContext ec)
6496 if (ec.IsStatic && !ec.HasSet (ResolveContext.Options.ConstantScope)) {
6497 ec.Report.Error (26, loc, "Keyword `this' is not valid in a static property, static method, or static field initializer");
6498 } else if (ec.CurrentAnonymousMethod != null) {
6499 ec.Report.Error (1673, loc,
6500 "Anonymous methods inside structs cannot access instance members of `this'. " +
6501 "Consider copying `this' to a local variable outside the anonymous method and using the local instead");
6503 ec.Report.Error (27, loc, "Keyword `this' is not available in the current context");
6507 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
6512 AnonymousMethodStorey storey = ae.Storey;
6513 while (storey != null) {
6514 AnonymousMethodStorey temp = storey.Parent as AnonymousMethodStorey;
6516 return storey.HoistedThis;
6524 public static bool IsThisAvailable (ResolveContext ec, bool ignoreAnonymous)
6526 if (ec.IsStatic || ec.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.BaseInitializer | ResolveContext.Options.ConstantScope))
6529 if (ignoreAnonymous || ec.CurrentAnonymousMethod == null)
6532 if (TypeManager.IsStruct (ec.CurrentType) && ec.CurrentIterator == null)
6538 public virtual void ResolveBase (ResolveContext ec)
6540 if (!IsThisAvailable (ec, false)) {
6541 Error_ThisNotAvailable (ec);
6544 var block = ec.CurrentBlock;
6545 if (block != null) {
6546 if (block.Toplevel.ThisVariable != null)
6547 variable_info = block.Toplevel.ThisVariable.VariableInfo;
6549 AnonymousExpression am = ec.CurrentAnonymousMethod;
6550 if (am != null && ec.IsVariableCapturingRequired) {
6551 am.SetHasThisAccess ();
6555 eclass = ExprClass.Variable;
6556 type = ec.CurrentType;
6560 // Called from Invocation to check if the invocation is correct
6562 public override void CheckMarshalByRefAccess (ResolveContext ec)
6564 if ((variable_info != null) && !(TypeManager.IsStruct (type) && ec.OmitStructFlowAnalysis) &&
6565 !variable_info.IsAssigned (ec)) {
6566 ec.Report.Error (188, loc,
6567 "The `this' object cannot be used before all of its fields are assigned to");
6568 variable_info.SetAssigned (ec);
6572 public override Expression CreateExpressionTree (ResolveContext ec)
6574 Arguments args = new Arguments (1);
6575 args.Add (new Argument (this));
6577 // Use typeless constant for ldarg.0 to save some
6578 // space and avoid problems with anonymous stories
6579 return CreateExpressionFactoryCall (ec, "Constant", args);
6582 protected override Expression DoResolve (ResolveContext ec)
6588 override public Expression DoResolveLValue (ResolveContext ec, Expression right_side)
6592 if (variable_info != null)
6593 variable_info.SetAssigned (ec);
6595 if (ec.CurrentType.IsClass){
6596 if (right_side == EmptyExpression.UnaryAddress)
6597 ec.Report.Error (459, loc, "Cannot take the address of `this' because it is read-only");
6598 else if (right_side == EmptyExpression.OutAccess.Instance)
6599 ec.Report.Error (1605, loc, "Cannot pass `this' as a ref or out argument because it is read-only");
6601 ec.Report.Error (1604, loc, "Cannot assign to `this' because it is read-only");
6607 public override int GetHashCode()
6609 throw new NotImplementedException ();
6612 public override bool Equals (object obj)
6614 This t = obj as This;
6621 protected override void CloneTo (CloneContext clonectx, Expression t)
6626 public override void SetHasAddressTaken ()
6633 /// Represents the `__arglist' construct
6635 public class ArglistAccess : Expression
6637 public ArglistAccess (Location loc)
6642 public override Expression CreateExpressionTree (ResolveContext ec)
6644 throw new NotSupportedException ("ET");
6647 protected override Expression DoResolve (ResolveContext ec)
6649 eclass = ExprClass.Variable;
6650 type = TypeManager.runtime_argument_handle_type;
6652 if (ec.HasSet (ResolveContext.Options.FieldInitializerScope) || !ec.CurrentBlock.Toplevel.Parameters.HasArglist) {
6653 ec.Report.Error (190, loc,
6654 "The __arglist construct is valid only within a variable argument method");
6660 public override void Emit (EmitContext ec)
6662 ec.Emit (OpCodes.Arglist);
6665 protected override void CloneTo (CloneContext clonectx, Expression target)
6672 /// Represents the `__arglist (....)' construct
6674 public class Arglist : Expression
6676 Arguments Arguments;
6678 public Arglist (Location loc)
6683 public Arglist (Arguments args, Location l)
6689 public Type[] ArgumentTypes {
6691 if (Arguments == null)
6692 return System.Type.EmptyTypes;
6694 var retval = new Type [Arguments.Count];
6695 for (int i = 0; i < retval.Length; i++)
6696 retval[i] = Arguments[i].Expr.Type.GetMetaInfo ();
6702 public override Expression CreateExpressionTree (ResolveContext ec)
6704 ec.Report.Error (1952, loc, "An expression tree cannot contain a method with variable arguments");
6708 protected override Expression DoResolve (ResolveContext ec)
6710 eclass = ExprClass.Variable;
6711 type = InternalType.Arglist;
6712 if (Arguments != null) {
6713 bool dynamic; // Can be ignored as there is always only 1 overload
6714 Arguments.Resolve (ec, out dynamic);
6720 public override void Emit (EmitContext ec)
6722 if (Arguments != null)
6723 Arguments.Emit (ec);
6726 protected override void CloneTo (CloneContext clonectx, Expression t)
6728 Arglist target = (Arglist) t;
6730 if (Arguments != null)
6731 target.Arguments = Arguments.Clone (clonectx);
6736 /// Implements the typeof operator
6738 public class TypeOf : Expression {
6739 FullNamedExpression QueriedType;
6742 public TypeOf (FullNamedExpression queried_type, Location l)
6744 QueriedType = queried_type;
6749 public TypeSpec TypeArgument {
6755 public FullNamedExpression TypeExpression {
6763 public override Expression CreateExpressionTree (ResolveContext ec)
6765 Arguments args = new Arguments (2);
6766 args.Add (new Argument (this));
6767 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
6768 return CreateExpressionFactoryCall (ec, "Constant", args);
6771 protected override Expression DoResolve (ResolveContext ec)
6773 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
6777 typearg = texpr.Type;
6779 if (typearg == TypeManager.void_type && !(QueriedType is TypeExpression)) {
6780 ec.Report.Error (673, loc, "System.Void cannot be used from C#. Use typeof (void) to get the void type object");
6781 } else if (typearg.IsPointer && !ec.IsUnsafe){
6782 UnsafeError (ec, loc);
6783 } else if (texpr is DynamicTypeExpr) {
6784 ec.Report.Error (1962, QueriedType.Location,
6785 "The typeof operator cannot be used on the dynamic type");
6788 type = TypeManager.type_type;
6790 return DoResolveBase ();
6793 protected Expression DoResolveBase ()
6795 if (TypeManager.system_type_get_type_from_handle == null) {
6796 TypeManager.system_type_get_type_from_handle = TypeManager.GetPredefinedMethod (
6797 TypeManager.type_type, "GetTypeFromHandle", loc, TypeManager.runtime_handle_type);
6800 // Even though what is returned is a type object, it's treated as a value by the compiler.
6801 // In particular, 'typeof (Foo).X' is something totally different from 'Foo.X'.
6802 eclass = ExprClass.Value;
6806 static bool ContainsTypeParameter (TypeSpec type)
6808 if (type.Kind == MemberKind.TypeParameter)
6811 var element_container = type as ElementTypeSpec;
6812 if (element_container != null)
6813 return ContainsTypeParameter (element_container.Element);
6815 foreach (var t in type.TypeArguments) {
6816 if (ContainsTypeParameter (t)) {
6824 public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
6826 // Target type is not System.Type therefore must be object
6827 // and we need to use different encoding sequence
6828 if (targetType != type)
6831 if (ContainsTypeParameter (typearg)) {
6832 rc.Compiler.Report.Error (416, loc, "`{0}': an attribute argument cannot use type parameters",
6833 TypeManager.CSharpName (typearg));
6837 enc.EncodeTypeName (typearg);
6840 public override void Emit (EmitContext ec)
6842 ec.Emit (OpCodes.Ldtoken, typearg);
6843 ec.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6846 protected override void CloneTo (CloneContext clonectx, Expression t)
6848 TypeOf target = (TypeOf) t;
6849 if (QueriedType != null)
6850 target.QueriedType = (FullNamedExpression) QueriedType.Clone (clonectx);
6854 class TypeOfMethod : TypeOfMember<MethodSpec>
6856 public TypeOfMethod (MethodSpec method, Location loc)
6857 : base (method, loc)
6861 protected override Expression DoResolve (ResolveContext ec)
6863 if (member.IsConstructor) {
6864 type = TypeManager.ctorinfo_type;
6866 type = TypeManager.ctorinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", "ConstructorInfo", MemberKind.Class, true);
6868 type = TypeManager.methodinfo_type;
6870 type = TypeManager.methodinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", "MethodInfo", MemberKind.Class, true);
6873 return base.DoResolve (ec);
6876 public override void Emit (EmitContext ec)
6878 ec.Emit (OpCodes.Ldtoken, member);
6881 ec.Emit (OpCodes.Castclass, type);
6884 protected override string GetMethodName {
6885 get { return "GetMethodFromHandle"; }
6888 protected override string RuntimeHandleName {
6889 get { return "RuntimeMethodHandle"; }
6892 protected override MethodSpec TypeFromHandle {
6894 return TypeManager.methodbase_get_type_from_handle;
6897 TypeManager.methodbase_get_type_from_handle = value;
6901 protected override MethodSpec TypeFromHandleGeneric {
6903 return TypeManager.methodbase_get_type_from_handle_generic;
6906 TypeManager.methodbase_get_type_from_handle_generic = value;
6910 protected override string TypeName {
6911 get { return "MethodBase"; }
6915 abstract class TypeOfMember<T> : Expression where T : MemberSpec
6917 protected readonly T member;
6919 protected TypeOfMember (T member, Location loc)
6921 this.member = member;
6925 public override Expression CreateExpressionTree (ResolveContext ec)
6927 Arguments args = new Arguments (2);
6928 args.Add (new Argument (this));
6929 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
6930 return CreateExpressionFactoryCall (ec, "Constant", args);
6933 protected override Expression DoResolve (ResolveContext ec)
6935 bool is_generic = member.DeclaringType.IsGenericOrParentIsGeneric;
6936 var mi = is_generic ? TypeFromHandleGeneric : TypeFromHandle;
6939 TypeSpec t = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", TypeName, MemberKind.Class, true);
6940 TypeSpec handle_type = TypeManager.CoreLookupType (ec.Compiler, "System", RuntimeHandleName, MemberKind.Struct, true);
6942 if (t == null || handle_type == null)
6945 mi = TypeManager.GetPredefinedMethod (t, GetMethodName, loc,
6947 new TypeSpec[] { handle_type, TypeManager.runtime_handle_type } :
6948 new TypeSpec[] { handle_type } );
6951 TypeFromHandleGeneric = mi;
6953 TypeFromHandle = mi;
6956 eclass = ExprClass.Value;
6960 public override void Emit (EmitContext ec)
6962 bool is_generic = member.DeclaringType.IsGenericOrParentIsGeneric;
6965 mi = TypeFromHandleGeneric;
6966 ec.Emit (OpCodes.Ldtoken, member.DeclaringType);
6968 mi = TypeFromHandle;
6971 ec.Emit (OpCodes.Call, mi);
6974 protected abstract string GetMethodName { get; }
6975 protected abstract string RuntimeHandleName { get; }
6976 protected abstract MethodSpec TypeFromHandle { get; set; }
6977 protected abstract MethodSpec TypeFromHandleGeneric { get; set; }
6978 protected abstract string TypeName { get; }
6981 class TypeOfField : TypeOfMember<FieldSpec>
6983 public TypeOfField (FieldSpec field, Location loc)
6988 protected override Expression DoResolve (ResolveContext ec)
6990 if (TypeManager.fieldinfo_type == null)
6991 TypeManager.fieldinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", TypeName, MemberKind.Class, true);
6993 type = TypeManager.fieldinfo_type;
6994 return base.DoResolve (ec);
6997 public override void Emit (EmitContext ec)
6999 ec.Emit (OpCodes.Ldtoken, member);
7003 protected override string GetMethodName {
7004 get { return "GetFieldFromHandle"; }
7007 protected override string RuntimeHandleName {
7008 get { return "RuntimeFieldHandle"; }
7011 protected override MethodSpec TypeFromHandle {
7013 return TypeManager.fieldinfo_get_field_from_handle;
7016 TypeManager.fieldinfo_get_field_from_handle = value;
7020 protected override MethodSpec TypeFromHandleGeneric {
7022 return TypeManager.fieldinfo_get_field_from_handle_generic;
7025 TypeManager.fieldinfo_get_field_from_handle_generic = value;
7029 protected override string TypeName {
7030 get { return "FieldInfo"; }
7035 /// Implements the sizeof expression
7037 public class SizeOf : Expression {
7038 readonly Expression QueriedType;
7039 TypeSpec type_queried;
7041 public SizeOf (Expression queried_type, Location l)
7043 this.QueriedType = queried_type;
7047 public override Expression CreateExpressionTree (ResolveContext ec)
7049 Error_PointerInsideExpressionTree (ec);
7053 protected override Expression DoResolve (ResolveContext ec)
7055 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
7059 type_queried = texpr.Type;
7060 if (TypeManager.IsEnumType (type_queried))
7061 type_queried = EnumSpec.GetUnderlyingType (type_queried);
7063 int size_of = GetTypeSize (type_queried);
7065 return new IntConstant (size_of, loc).Resolve (ec);
7068 if (!TypeManager.VerifyUnmanaged (ec.Compiler, type_queried, loc)){
7073 ec.Report.Error (233, loc,
7074 "`{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)",
7075 TypeManager.CSharpName (type_queried));
7078 type = TypeManager.int32_type;
7079 eclass = ExprClass.Value;
7083 public override void Emit (EmitContext ec)
7085 ec.Emit (OpCodes.Sizeof, type_queried);
7088 protected override void CloneTo (CloneContext clonectx, Expression t)
7094 /// Implements the qualified-alias-member (::) expression.
7096 public class QualifiedAliasMember : MemberAccess
7098 readonly string alias;
7099 public static readonly string GlobalAlias = "global";
7101 public QualifiedAliasMember (string alias, string identifier, Location l)
7102 : base (null, identifier, l)
7107 public QualifiedAliasMember (string alias, string identifier, TypeArguments targs, Location l)
7108 : base (null, identifier, targs, l)
7113 public QualifiedAliasMember (string alias, string identifier, int arity, Location l)
7114 : base (null, identifier, arity, l)
7119 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
7121 if (alias == GlobalAlias) {
7122 expr = GlobalRootNamespace.Instance;
7123 return base.ResolveAsTypeStep (ec, silent);
7126 int errors = ec.Compiler.Report.Errors;
7127 expr = ec.LookupNamespaceAlias (alias);
7129 if (errors == ec.Compiler.Report.Errors)
7130 ec.Compiler.Report.Error (432, loc, "Alias `{0}' not found", alias);
7134 FullNamedExpression fne = base.ResolveAsTypeStep (ec, silent);
7138 if (expr.eclass == ExprClass.Type) {
7140 ec.Compiler.Report.Error (431, loc,
7141 "Alias `{0}' cannot be used with '::' since it denotes a type. Consider replacing '::' with '.'", alias);
7149 protected override Expression DoResolve (ResolveContext ec)
7151 return ResolveAsTypeStep (ec, false);
7154 protected override void Error_IdentifierNotFound (IMemberContext rc, TypeSpec expr_type, string identifier)
7156 rc.Compiler.Report.Error (687, loc,
7157 "A namespace alias qualifier `{0}' did not resolve to a namespace or a type",
7158 GetSignatureForError ());
7161 public override string GetSignatureForError ()
7164 if (targs != null) {
7165 name = Name + "<" + targs.GetSignatureForError () + ">";
7168 return alias + "::" + name;
7171 protected override void CloneTo (CloneContext clonectx, Expression t)
7178 /// Implements the member access expression
7180 public class MemberAccess : ATypeNameExpression {
7181 protected Expression expr;
7183 public MemberAccess (Expression expr, string id)
7184 : base (id, expr.Location)
7189 public MemberAccess (Expression expr, string identifier, Location loc)
7190 : base (identifier, loc)
7195 public MemberAccess (Expression expr, string identifier, TypeArguments args, Location loc)
7196 : base (identifier, args, loc)
7201 public MemberAccess (Expression expr, string identifier, int arity, Location loc)
7202 : base (identifier, arity, loc)
7207 Expression DoResolve (ResolveContext ec, Expression right_side)
7210 throw new Exception ();
7213 // Resolve the expression with flow analysis turned off, we'll do the definite
7214 // assignment checks later. This is because we don't know yet what the expression
7215 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7216 // definite assignment check on the actual field and not on the whole struct.
7219 SimpleName original = expr as SimpleName;
7220 Expression expr_resolved;
7221 const ResolveFlags flags = ResolveFlags.VariableOrValue | ResolveFlags.Type;
7223 using (ec.Set (ResolveContext.Options.OmitStructFlowAnalysis)) {
7224 if (original != null) {
7225 expr_resolved = original.DoResolve (ec, true);
7226 if (expr_resolved != null) {
7227 // Ugly, simulate skipped Resolve
7228 if (expr_resolved is ConstantExpr) {
7229 expr_resolved = expr_resolved.Resolve (ec);
7230 } else if (expr_resolved is FieldExpr || expr_resolved is PropertyExpr) {
7232 } else if ((flags & expr_resolved.ExprClassToResolveFlags) == 0) {
7233 expr_resolved.Error_UnexpectedKind (ec, flags, expr.Location);
7234 expr_resolved = null;
7238 expr_resolved = expr.Resolve (ec, flags);
7242 if (expr_resolved == null)
7245 Namespace ns = expr_resolved as Namespace;
7247 FullNamedExpression retval = ns.Lookup (ec.Compiler, Name, Arity, loc);
7250 ns.Error_NamespaceDoesNotExist (loc, Name, Arity, ec);
7251 else if (HasTypeArguments)
7252 retval = new GenericTypeExpr (retval.Type, targs, loc).ResolveAsTypeStep (ec, false);
7254 expr = expr_resolved;
7258 TypeSpec expr_type = expr_resolved.Type;
7259 if (expr_type == InternalType.Dynamic) {
7260 Arguments args = new Arguments (1);
7261 args.Add (new Argument (expr_resolved.Resolve (ec)));
7262 expr = new DynamicMemberBinder (Name, args, loc);
7263 if (right_side != null)
7264 return expr.DoResolveLValue (ec, right_side);
7266 return expr.Resolve (ec);
7270 const MemberKind dot_kinds = MemberKind.Class | MemberKind.Struct | MemberKind.Delegate | MemberKind.Enum |
7271 MemberKind.Interface | MemberKind.TypeParameter | MemberKind.ArrayType;
7273 if ((expr_type.Kind & dot_kinds) == 0 || expr_type == TypeManager.void_type) {
7274 Unary.Error_OperatorCannotBeApplied (ec, loc, ".", expr_type);
7278 var arity = HasTypeArguments ? targs.Count : -1;
7280 var member_lookup = MemberLookup (ec.Compiler,
7281 ec.CurrentType, expr_type, expr_type, Name, arity, BindingRestriction.DefaultMemberLookup, loc);
7283 if (member_lookup == null) {
7284 expr = expr_resolved.Resolve (ec);
7286 ExprClass expr_eclass = expr.eclass;
7289 // Extension methods are not allowed on all expression types
7291 if (expr_eclass == ExprClass.Value || expr_eclass == ExprClass.Variable ||
7292 expr_eclass == ExprClass.IndexerAccess || expr_eclass == ExprClass.PropertyAccess ||
7293 expr_eclass == ExprClass.EventAccess) {
7294 ExtensionMethodGroupExpr ex_method_lookup = ec.LookupExtensionMethod (expr_type, Name, arity, loc);
7295 if (ex_method_lookup != null) {
7296 ex_method_lookup.ExtensionExpression = expr;
7298 if (HasTypeArguments) {
7299 if (!targs.Resolve (ec))
7302 ex_method_lookup.SetTypeArguments (ec, targs);
7305 return ex_method_lookup.Resolve (ec);
7309 member_lookup = Error_MemberLookupFailed (ec,
7310 ec.CurrentType, expr_type, expr_type, Name, arity, null,
7311 MemberKind.All, BindingRestriction.AccessibleOnly);
7312 if (member_lookup == null)
7316 expr = expr_resolved;
7319 TypeExpr texpr = member_lookup as TypeExpr;
7320 if (texpr != null) {
7321 if (!(expr_resolved is TypeExpr)) {
7322 me = expr_resolved as MemberExpr;
7323 if (me == null || me.ProbeIdenticalTypeName (ec, expr_resolved, original) == expr_resolved) {
7324 ec.Report.Error (572, loc, "`{0}': cannot reference a type through an expression; try `{1}' instead",
7325 Name, member_lookup.GetSignatureForError ());
7330 if (!texpr.CheckAccessLevel (ec.MemberContext)) {
7331 ec.Report.SymbolRelatedToPreviousError (member_lookup.Type);
7332 ErrorIsInaccesible (loc, TypeManager.CSharpName (member_lookup.Type), ec.Report);
7336 if (HasTypeArguments) {
7337 var ct = new GenericTypeExpr (member_lookup.Type, targs, loc);
7338 return ct.ResolveAsTypeStep (ec, false);
7341 return member_lookup;
7344 me = (MemberExpr) member_lookup;
7346 if (original != null && me.IsStatic)
7347 expr_resolved = me.ProbeIdenticalTypeName (ec, expr_resolved, original);
7349 me = me.ResolveMemberAccess (ec, expr_resolved, original);
7351 if (HasTypeArguments) {
7352 if (!targs.Resolve (ec))
7355 me.SetTypeArguments (ec, targs);
7358 if (original != null && (!TypeManager.IsValueType (expr_type) || me is PropertyExpr)) {
7359 if (me.IsInstance) {
7360 LocalVariableReference var = expr_resolved as LocalVariableReference;
7361 if (var != null && !var.VerifyAssigned (ec))
7366 // The following DoResolve/DoResolveLValue will do the definite assignment
7369 if (right_side != null)
7370 return me.DoResolveLValue (ec, right_side);
7372 return me.Resolve (ec);
7375 protected override Expression DoResolve (ResolveContext ec)
7377 return DoResolve (ec, null);
7380 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
7382 return DoResolve (ec, right_side);
7385 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
7387 return ResolveNamespaceOrType (ec, silent);
7390 public FullNamedExpression ResolveNamespaceOrType (IMemberContext rc, bool silent)
7392 FullNamedExpression expr_resolved = expr.ResolveAsTypeStep (rc, silent);
7394 if (expr_resolved == null)
7397 Namespace ns = expr_resolved as Namespace;
7399 FullNamedExpression retval = ns.Lookup (rc.Compiler, Name, Arity, loc);
7401 if (retval == null) {
7403 ns.Error_NamespaceDoesNotExist (loc, Name, Arity, rc);
7404 } else if (HasTypeArguments) {
7405 retval = new GenericTypeExpr (retval.Type, targs, loc).ResolveAsTypeStep (rc, silent);
7411 TypeExpr tnew_expr = expr_resolved.ResolveAsTypeTerminal (rc, false);
7412 if (tnew_expr == null)
7415 TypeSpec expr_type = tnew_expr.Type;
7416 if (TypeManager.IsGenericParameter (expr_type)) {
7417 rc.Compiler.Report.Error (704, loc, "A nested type cannot be specified through a type parameter `{0}'",
7418 tnew_expr.GetSignatureForError ());
7422 var nested = MemberCache.FindNestedType (expr_type, Name, Arity);
7423 if (nested == null) {
7427 Error_IdentifierNotFound (rc, expr_type, Name);
7432 if (!IsMemberAccessible (rc.CurrentType ?? InternalType.FakeInternalType, nested, out extra_check)) {
7433 ErrorIsInaccesible (loc, nested.GetSignatureForError (), rc.Compiler.Report);
7437 if (HasTypeArguments) {
7438 texpr = new GenericTypeExpr (nested, targs, loc);
7440 texpr = new TypeExpression (nested, loc);
7443 return texpr.ResolveAsTypeStep (rc, false);
7446 protected virtual void Error_IdentifierNotFound (IMemberContext rc, TypeSpec expr_type, string identifier)
7448 var nested = MemberCache.FindNestedType (expr_type, Name, -System.Math.Max (1, Arity));
7450 if (nested != null) {
7451 Error_TypeArgumentsCannotBeUsed (rc.Compiler.Report, expr.Location, nested, Arity);
7455 var member_lookup = MemberLookup (rc.Compiler,
7456 rc.CurrentType, expr_type, expr_type, identifier, -1,
7457 MemberKind.All, BindingRestriction.None, loc);
7459 if (member_lookup == null) {
7460 rc.Compiler.Report.Error (426, loc, "The nested type `{0}' does not exist in the type `{1}'",
7461 Name, expr_type.GetSignatureForError ());
7463 // TODO: Report.SymbolRelatedToPreviousError
7464 member_lookup.Error_UnexpectedKind (rc.Compiler.Report, null, "type", loc);
7468 protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
7470 if (RootContext.Version > LanguageVersion.ISO_2 && !ec.Compiler.IsRuntimeBinder && !(expr is BaseThis) &&
7471 ((expr.eclass & (ExprClass.Value | ExprClass.Variable)) != 0)) {
7472 ec.Report.Error (1061, loc, "Type `{0}' does not contain a definition for `{1}' and no " +
7473 "extension method `{1}' of type `{0}' could be found " +
7474 "(are you missing a using directive or an assembly reference?)",
7475 TypeManager.CSharpName (type), name);
7479 base.Error_TypeDoesNotContainDefinition (ec, type, name);
7482 public override string GetSignatureForError ()
7484 return expr.GetSignatureForError () + "." + base.GetSignatureForError ();
7487 public Expression Left {
7493 protected override void CloneTo (CloneContext clonectx, Expression t)
7495 MemberAccess target = (MemberAccess) t;
7497 target.expr = expr.Clone (clonectx);
7502 /// Implements checked expressions
7504 public class CheckedExpr : Expression {
7506 public Expression Expr;
7508 public CheckedExpr (Expression e, Location l)
7514 public override Expression CreateExpressionTree (ResolveContext ec)
7516 using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
7517 return Expr.CreateExpressionTree (ec);
7520 protected override Expression DoResolve (ResolveContext ec)
7522 using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
7523 Expr = Expr.Resolve (ec);
7528 if (Expr is Constant || Expr is MethodGroupExpr || Expr is AnonymousMethodExpression || Expr is DefaultValueExpression)
7531 eclass = Expr.eclass;
7536 public override void Emit (EmitContext ec)
7538 using (ec.With (EmitContext.Options.AllCheckStateFlags, true))
7542 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
7544 using (ec.With (EmitContext.Options.AllCheckStateFlags, true))
7545 Expr.EmitBranchable (ec, target, on_true);
7548 public override SLE.Expression MakeExpression (BuilderContext ctx)
7550 using (ctx.With (BuilderContext.Options.AllCheckStateFlags, true)) {
7551 return Expr.MakeExpression (ctx);
7555 protected override void CloneTo (CloneContext clonectx, Expression t)
7557 CheckedExpr target = (CheckedExpr) t;
7559 target.Expr = Expr.Clone (clonectx);
7564 /// Implements the unchecked expression
7566 public class UnCheckedExpr : Expression {
7568 public Expression Expr;
7570 public UnCheckedExpr (Expression e, Location l)
7576 public override Expression CreateExpressionTree (ResolveContext ec)
7578 using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
7579 return Expr.CreateExpressionTree (ec);
7582 protected override Expression DoResolve (ResolveContext ec)
7584 using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
7585 Expr = Expr.Resolve (ec);
7590 if (Expr is Constant || Expr is MethodGroupExpr || Expr is AnonymousMethodExpression || Expr is DefaultValueExpression)
7593 eclass = Expr.eclass;
7598 public override void Emit (EmitContext ec)
7600 using (ec.With (EmitContext.Options.AllCheckStateFlags, false))
7604 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
7606 using (ec.With (EmitContext.Options.AllCheckStateFlags, false))
7607 Expr.EmitBranchable (ec, target, on_true);
7610 protected override void CloneTo (CloneContext clonectx, Expression t)
7612 UnCheckedExpr target = (UnCheckedExpr) t;
7614 target.Expr = Expr.Clone (clonectx);
7619 /// An Element Access expression.
7621 /// During semantic analysis these are transformed into
7622 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7624 public class ElementAccess : Expression {
7625 public Arguments Arguments;
7626 public Expression Expr;
7628 public ElementAccess (Expression e, Arguments args, Location loc)
7632 this.Arguments = args;
7635 public override Expression CreateExpressionTree (ResolveContext ec)
7637 Arguments args = Arguments.CreateForExpressionTree (ec, Arguments,
7638 Expr.CreateExpressionTree (ec));
7640 return CreateExpressionFactoryCall (ec, "ArrayIndex", args);
7643 Expression MakePointerAccess (ResolveContext ec, TypeSpec t)
7645 if (Arguments.Count != 1){
7646 ec.Report.Error (196, loc, "A pointer must be indexed by only one value");
7650 if (Arguments [0] is NamedArgument)
7651 Error_NamedArgument ((NamedArgument) Arguments[0], ec.Report);
7653 Expression p = new PointerArithmetic (Binary.Operator.Addition, Expr, Arguments [0].Expr.Resolve (ec), t, loc);
7654 return new Indirection (p, loc).Resolve (ec);
7657 protected override Expression DoResolve (ResolveContext ec)
7659 Expr = Expr.Resolve (ec);
7664 // We perform some simple tests, and then to "split" the emit and store
7665 // code we create an instance of a different class, and return that.
7667 TypeSpec t = Expr.Type;
7670 return (new ArrayAccess (this, loc)).Resolve (ec);
7672 return MakePointerAccess (ec, t);
7674 FieldExpr fe = Expr as FieldExpr;
7676 var ff = fe.Spec as FixedFieldSpec;
7678 return MakePointerAccess (ec, ff.ElementType);
7681 return (new IndexerAccess (this, loc)).Resolve (ec);
7684 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
7686 Expr = Expr.Resolve (ec);
7692 return (new ArrayAccess (this, loc)).DoResolveLValue (ec, right_side);
7695 return MakePointerAccess (ec, type);
7697 if (Expr.eclass != ExprClass.Variable && TypeManager.IsStruct (type))
7698 Error_CannotModifyIntermediateExpressionValue (ec);
7700 return (new IndexerAccess (this, loc)).DoResolveLValue (ec, right_side);
7703 public override void Emit (EmitContext ec)
7705 throw new Exception ("Should never be reached");
7708 public static void Error_NamedArgument (NamedArgument na, Report Report)
7710 Report.Error (1742, na.Location, "An element access expression cannot use named argument");
7713 public override string GetSignatureForError ()
7715 return Expr.GetSignatureForError ();
7718 protected override void CloneTo (CloneContext clonectx, Expression t)
7720 ElementAccess target = (ElementAccess) t;
7722 target.Expr = Expr.Clone (clonectx);
7723 if (Arguments != null)
7724 target.Arguments = Arguments.Clone (clonectx);
7729 /// Implements array access
7731 public class ArrayAccess : Expression, IDynamicAssign, IMemoryLocation {
7733 // Points to our "data" repository
7737 LocalTemporary temp;
7741 public ArrayAccess (ElementAccess ea_data, Location l)
7747 public override Expression CreateExpressionTree (ResolveContext ec)
7749 return ea.CreateExpressionTree (ec);
7752 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
7754 return DoResolve (ec);
7757 protected override Expression DoResolve (ResolveContext ec)
7759 // dynamic is used per argument in ConvertExpressionToArrayIndex case
7761 ea.Arguments.Resolve (ec, out dynamic);
7763 var ac = ea.Expr.Type as ArrayContainer;
7764 int rank = ea.Arguments.Count;
7765 if (ac.Rank != rank) {
7766 ec.Report.Error (22, ea.Location, "Wrong number of indexes `{0}' inside [], expected `{1}'",
7767 rank.ToString (), ac.Rank.ToString ());
7772 if (type.IsPointer && !ec.IsUnsafe) {
7773 UnsafeError (ec, ea.Location);
7776 foreach (Argument a in ea.Arguments) {
7777 if (a is NamedArgument)
7778 ElementAccess.Error_NamedArgument ((NamedArgument) a, ec.Report);
7780 a.Expr = ConvertExpressionToArrayIndex (ec, a.Expr);
7783 eclass = ExprClass.Variable;
7788 protected override void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
7790 ec.Report.Warning (251, 2, loc, "Indexing an array with a negative index (array indices always start at zero)");
7794 // Load the array arguments into the stack.
7796 void LoadArrayAndArguments (EmitContext ec)
7800 for (int i = 0; i < ea.Arguments.Count; ++i) {
7801 ea.Arguments [i].Emit (ec);
7805 public void Emit (EmitContext ec, bool leave_copy)
7807 var ac = ea.Expr.Type as ArrayContainer;
7810 ec.EmitLoadFromPtr (type);
7812 LoadArrayAndArguments (ec);
7813 ec.EmitArrayLoad (ac);
7817 ec.Emit (OpCodes.Dup);
7818 temp = new LocalTemporary (this.type);
7823 public override void Emit (EmitContext ec)
7828 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
7830 var ac = (ArrayContainer) ea.Expr.Type;
7831 TypeSpec t = source.Type;
7832 prepared = prepare_for_load;
7835 AddressOf (ec, AddressOp.LoadStore);
7836 ec.Emit (OpCodes.Dup);
7838 LoadArrayAndArguments (ec);
7841 // If we are dealing with a struct, get the
7842 // address of it, so we can store it.
7844 // The stobj opcode used by value types will need
7845 // an address on the stack, not really an array/array
7848 if (ac.Rank == 1 && TypeManager.IsStruct (t) &&
7849 (!TypeManager.IsBuiltinOrEnum (t) ||
7850 t == TypeManager.decimal_type)) {
7852 ec.Emit (OpCodes.Ldelema, t);
7858 ec.Emit (OpCodes.Dup);
7859 temp = new LocalTemporary (this.type);
7864 ec.EmitStoreFromPtr (t);
7866 ec.EmitArrayStore (ac);
7875 public void EmitNew (EmitContext ec, New source, bool leave_copy)
7877 if (!source.Emit (ec, this)) {
7879 throw new NotImplementedException ();
7884 throw new NotImplementedException ();
7887 public void AddressOf (EmitContext ec, AddressOp mode)
7889 var ac = (ArrayContainer) ea.Expr.Type;
7891 LoadArrayAndArguments (ec);
7892 ec.EmitArrayAddress (ac);
7896 public SLE.Expression MakeAssignExpression (BuilderContext ctx)
7898 return SLE.Expression.ArrayAccess (
7899 ea.Expr.MakeExpression (ctx),
7900 Arguments.MakeExpression (ea.Arguments, ctx));
7904 public override SLE.Expression MakeExpression (BuilderContext ctx)
7906 return SLE.Expression.ArrayIndex (
7907 ea.Expr.MakeExpression (ctx),
7908 Arguments.MakeExpression (ea.Arguments, ctx));
7913 /// Expressions that represent an indexer call.
7915 class IndexerAccess : Expression, IDynamicAssign
7917 class IndexerMethodGroupExpr : MethodGroupExpr
7919 IEnumerable<IndexerSpec> candidates;
7921 public IndexerMethodGroupExpr (IEnumerable<IndexerSpec> indexers, Location loc)
7922 : base (FilterAccessors (indexers).ToList (), null, loc)
7924 candidates = indexers;
7927 public IndexerSpec BestIndexer ()
7929 return MemberCache.FindIndexers (BestCandidate.DeclaringType, BindingRestriction.None).
7931 (l.HasGet && l.Get.MemberDefinition == BestCandidate.MemberDefinition) ||
7932 (l.HasSet && l.Set.MemberDefinition == BestCandidate.MemberDefinition)).First ();
7935 static IEnumerable<MemberSpec> FilterAccessors (IEnumerable<IndexerSpec> indexers)
7937 foreach (IndexerSpec i in indexers) {
7945 protected override IList<MemberSpec> GetBaseTypeMethods (ResolveContext rc, TypeSpec type)
7947 candidates = GetIndexersForType (type);
7948 if (candidates == null)
7951 return FilterAccessors (candidates).ToList ();
7954 public override string Name {
7960 protected override int GetApplicableParametersCount (MethodSpec method, AParametersCollection parameters)
7963 // Here is the trick, decrease number of arguments by 1 when only
7964 // available property method is setter. This makes overload resolution
7965 // work correctly for indexers.
7968 if (method.Name [0] == 'g')
7969 return parameters.Count;
7971 return parameters.Count - 1;
7976 // Points to our "data" repository
7980 LocalTemporary temp;
7981 LocalTemporary prepared_value;
7982 Expression set_expr;
7984 protected TypeSpec indexer_type;
7985 protected Expression instance_expr;
7986 protected Arguments arguments;
7988 public IndexerAccess (ElementAccess ea, Location loc)
7990 this.instance_expr = ea.Expr;
7991 this.arguments = ea.Arguments;
7995 static string GetAccessorName (bool isSet)
7997 return isSet ? "set" : "get";
8000 public override Expression CreateExpressionTree (ResolveContext ec)
8002 Arguments args = Arguments.CreateForExpressionTree (ec, arguments,
8003 instance_expr.CreateExpressionTree (ec),
8004 new TypeOfMethod (spec.Get, loc));
8006 return CreateExpressionFactoryCall (ec, "Call", args);
8009 static IEnumerable<IndexerSpec> GetIndexersForType (TypeSpec lookup_type)
8011 return MemberCache.FindIndexers (lookup_type, BindingRestriction.AccessibleOnly | BindingRestriction.DefaultMemberLookup);
8014 protected override Expression DoResolve (ResolveContext ec)
8016 return ResolveAccessor (ec, null);
8019 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
8021 if (right_side == EmptyExpression.OutAccess.Instance) {
8022 right_side.DoResolveLValue (ec, this);
8026 // if the indexer returns a value type, and we try to set a field in it
8027 if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess) {
8028 Error_CannotModifyIntermediateExpressionValue (ec);
8031 return ResolveAccessor (ec, right_side);
8034 Expression ResolveAccessor (ResolveContext ec, Expression right_side)
8036 indexer_type = instance_expr.Type;
8039 arguments.Resolve (ec, out dynamic);
8041 if (indexer_type == InternalType.Dynamic) {
8044 var ilist = GetIndexersForType (indexer_type);
8045 if (ilist == null) {
8046 ec.Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
8047 TypeManager.CSharpName (indexer_type));
8051 var mg = new IndexerMethodGroupExpr (ilist, loc) {
8052 InstanceExpression = instance_expr
8055 mg = mg.OverloadResolve (ec, ref arguments, false, loc) as IndexerMethodGroupExpr;
8060 spec = mg.BestIndexer ();
8064 Arguments args = new Arguments (arguments.Count + 1);
8065 if (instance_expr is BaseThis) {
8066 ec.Report.Error (1972, loc, "The indexer base access cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access");
8068 args.Add (new Argument (instance_expr));
8070 args.AddRange (arguments);
8072 var expr = new DynamicIndexBinder (args, loc);
8073 if (right_side != null)
8074 return expr.ResolveLValue (ec, right_side);
8076 return expr.Resolve (ec);
8079 type = spec.MemberType;
8080 if (type.IsPointer && !ec.IsUnsafe)
8081 UnsafeError (ec, loc);
8083 MethodSpec accessor;
8084 if (right_side == null) {
8085 accessor = spec.Get;
8087 accessor = spec.Set;
8088 if (!spec.HasSet && spec.HasGet) {
8089 ec.Report.SymbolRelatedToPreviousError (spec);
8090 ec.Report.Error (200, loc, "The read only property or indexer `{0}' cannot be assigned to",
8091 spec.GetSignatureForError ());
8095 set_expr = Convert.ImplicitConversion (ec, right_side, type, loc);
8098 if (accessor == null) {
8099 ec.Report.SymbolRelatedToPreviousError (spec);
8100 ec.Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks a `{1}' accessor",
8101 spec.GetSignatureForError (), GetAccessorName (right_side != null));
8106 // Only base will allow this invocation to happen.
8108 if (spec.IsAbstract && instance_expr is BaseThis) {
8109 Error_CannotCallAbstractBase (ec, spec.GetSignatureForError ());
8112 bool must_do_cs1540_check;
8113 if (!IsMemberAccessible (ec.CurrentType, accessor, out must_do_cs1540_check)) {
8114 if (spec.HasDifferentAccessibility) {
8115 ec.Report.SymbolRelatedToPreviousError (accessor);
8116 ec.Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because a `{1}' accessor is inaccessible",
8117 TypeManager.GetFullNameSignature (spec), GetAccessorName (right_side != null));
8119 ec.Report.SymbolRelatedToPreviousError (spec);
8120 ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (spec), ec.Report);
8124 instance_expr.CheckMarshalByRefAccess (ec);
8126 if (must_do_cs1540_check && (instance_expr != EmptyExpression.Null) &&
8127 !(instance_expr is BaseThis) &&
8128 !TypeManager.IsInstantiationOfSameGenericType (instance_expr.Type, ec.CurrentType) &&
8129 !TypeManager.IsNestedChildOf (ec.CurrentType, instance_expr.Type) &&
8130 !TypeManager.IsSubclassOf (instance_expr.Type, ec.CurrentType)) {
8131 ec.Report.SymbolRelatedToPreviousError (accessor);
8132 Error_CannotAccessProtected (ec, loc, spec, instance_expr.Type, ec.CurrentType);
8136 eclass = ExprClass.IndexerAccess;
8140 public override void Emit (EmitContext ec)
8145 public void Emit (EmitContext ec, bool leave_copy)
8148 prepared_value.Emit (ec);
8150 Invocation.EmitCall (ec, instance_expr, spec.Get,
8151 arguments, loc, false, false);
8155 ec.Emit (OpCodes.Dup);
8156 temp = new LocalTemporary (Type);
8162 // source is ignored, because we already have a copy of it from the
8163 // LValue resolution and we have already constructed a pre-cached
8164 // version of the arguments (ea.set_arguments);
8166 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8168 prepared = prepare_for_load;
8169 Expression value = set_expr;
8172 Invocation.EmitCall (ec, instance_expr, spec.Get,
8173 arguments, loc, true, false);
8175 prepared_value = new LocalTemporary (type);
8176 prepared_value.Store (ec);
8178 prepared_value.Release (ec);
8181 ec.Emit (OpCodes.Dup);
8182 temp = new LocalTemporary (Type);
8185 } else if (leave_copy) {
8186 temp = new LocalTemporary (Type);
8193 arguments.Add (new Argument (value));
8195 Invocation.EmitCall (ec, instance_expr, spec.Set, arguments, loc, false, prepared);
8203 public override string GetSignatureForError ()
8205 return spec.GetSignatureForError ();
8209 public SLE.Expression MakeAssignExpression (BuilderContext ctx)
8211 var value = new[] { set_expr.MakeExpression (ctx) };
8212 var args = Arguments.MakeExpression (arguments, ctx).Concat (value);
8214 return SLE.Expression.Block (
8215 SLE.Expression.Call (instance_expr.MakeExpression (ctx), (MethodInfo) spec.Set.GetMetaInfo (), args),
8220 public override SLE.Expression MakeExpression (BuilderContext ctx)
8222 var args = Arguments.MakeExpression (arguments, ctx);
8223 return SLE.Expression.Call (instance_expr.MakeExpression (ctx), (MethodInfo) spec.Get.GetMetaInfo (), args);
8226 protected override void CloneTo (CloneContext clonectx, Expression t)
8228 IndexerAccess target = (IndexerAccess) t;
8230 if (arguments != null)
8231 target.arguments = arguments.Clone (clonectx);
8233 if (instance_expr != null)
8234 target.instance_expr = instance_expr.Clone (clonectx);
8239 // A base access expression
8241 public class BaseThis : This
8243 public BaseThis (Location loc)
8248 public BaseThis (TypeSpec type, Location loc)
8252 eclass = ExprClass.Variable;
8255 public override Expression CreateExpressionTree (ResolveContext ec)
8257 ec.Report.Error (831, loc, "An expression tree may not contain a base access");
8258 return base.CreateExpressionTree (ec);
8261 public override void ResolveBase (ResolveContext ec)
8263 base.ResolveBase (ec);
8264 type = ec.CurrentType.BaseType;
8267 public override void Emit (EmitContext ec)
8271 if (ec.CurrentType.IsStruct) {
8272 ec.Emit (OpCodes.Ldobj, ec.CurrentType);
8273 ec.Emit (OpCodes.Box, ec.CurrentType);
8277 protected override void Error_ThisNotAvailable (ResolveContext ec)
8280 ec.Report.Error (1511, loc, "Keyword `base' is not available in a static method");
8282 ec.Report.Error (1512, loc, "Keyword `base' is not available in the current context");
8288 /// This class exists solely to pass the Type around and to be a dummy
8289 /// that can be passed to the conversion functions (this is used by
8290 /// foreach implementation to typecast the object return value from
8291 /// get_Current into the proper type. All code has been generated and
8292 /// we only care about the side effect conversions to be performed
8294 /// This is also now used as a placeholder where a no-action expression
8295 /// is needed (the `New' class).
8297 public class EmptyExpression : Expression {
8298 public static readonly Expression Null = new EmptyExpression ();
8300 public class OutAccess : EmptyExpression
8302 public static readonly OutAccess Instance = new OutAccess ();
8304 public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
8306 rc.Report.Error (206, right_side.Location,
8307 "A property, indexer or dynamic member access may not be passed as `ref' or `out' parameter");
8313 public static readonly EmptyExpression LValueMemberAccess = new EmptyExpression ();
8314 public static readonly EmptyExpression LValueMemberOutAccess = new EmptyExpression ();
8315 public static readonly EmptyExpression UnaryAddress = new EmptyExpression ();
8317 static EmptyExpression temp = new EmptyExpression ();
8318 public static EmptyExpression Grab ()
8320 EmptyExpression retval = temp == null ? new EmptyExpression () : temp;
8325 public static void Release (EmptyExpression e)
8332 // FIXME: Don't set to object
8333 type = TypeManager.object_type;
8334 eclass = ExprClass.Value;
8335 loc = Location.Null;
8338 public EmptyExpression (TypeSpec t)
8341 eclass = ExprClass.Value;
8342 loc = Location.Null;
8345 public override Expression CreateExpressionTree (ResolveContext ec)
8347 throw new NotSupportedException ("ET");
8350 protected override Expression DoResolve (ResolveContext ec)
8355 public override void Emit (EmitContext ec)
8357 // nothing, as we only exist to not do anything.
8360 public override void EmitSideEffect (EmitContext ec)
8365 // This is just because we might want to reuse this bad boy
8366 // instead of creating gazillions of EmptyExpressions.
8367 // (CanImplicitConversion uses it)
8369 public void SetType (TypeSpec t)
8376 // Empty statement expression
8378 public sealed class EmptyExpressionStatement : ExpressionStatement
8380 public static readonly EmptyExpressionStatement Instance = new EmptyExpressionStatement ();
8382 private EmptyExpressionStatement ()
8384 loc = Location.Null;
8387 public override Expression CreateExpressionTree (ResolveContext ec)
8392 public override void EmitStatement (EmitContext ec)
8397 protected override Expression DoResolve (ResolveContext ec)
8399 eclass = ExprClass.Value;
8400 type = TypeManager.object_type;
8404 public override void Emit (EmitContext ec)
8410 public class UserCast : Expression {
8414 public UserCast (MethodSpec method, Expression source, Location l)
8416 this.method = method;
8417 this.source = source;
8418 type = method.ReturnType;
8422 public Expression Source {
8428 public override Expression CreateExpressionTree (ResolveContext ec)
8430 Arguments args = new Arguments (3);
8431 args.Add (new Argument (source.CreateExpressionTree (ec)));
8432 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
8433 args.Add (new Argument (new TypeOfMethod (method, loc)));
8434 return CreateExpressionFactoryCall (ec, "Convert", args);
8437 protected override Expression DoResolve (ResolveContext ec)
8439 ObsoleteAttribute oa = method.GetAttributeObsolete ();
8441 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
8443 eclass = ExprClass.Value;
8447 public override void Emit (EmitContext ec)
8450 ec.Emit (OpCodes.Call, method);
8453 public override string GetSignatureForError ()
8455 return TypeManager.CSharpSignature (method);
8458 public override SLE.Expression MakeExpression (BuilderContext ctx)
8460 return SLE.Expression.Convert (source.MakeExpression (ctx), type.GetMetaInfo (), (MethodInfo) method.GetMetaInfo ());
8465 // Holds additional type specifiers like ?, *, []
8467 public class ComposedTypeSpecifier
8469 public static readonly ComposedTypeSpecifier SingleDimension = new ComposedTypeSpecifier (1, Location.Null);
8471 public readonly int Dimension;
8472 public readonly Location Location;
8474 public ComposedTypeSpecifier (int specifier, Location loc)
8476 this.Dimension = specifier;
8477 this.Location = loc;
8481 public bool IsNullable {
8483 return Dimension == -1;
8487 public bool IsPointer {
8489 return Dimension == -2;
8493 public ComposedTypeSpecifier Next { get; set; }
8497 public static ComposedTypeSpecifier CreateArrayDimension (int dimension, Location loc)
8499 return new ComposedTypeSpecifier (dimension, loc);
8502 public static ComposedTypeSpecifier CreateNullable (Location loc)
8504 return new ComposedTypeSpecifier (-1, loc);
8507 public static ComposedTypeSpecifier CreatePointer (Location loc)
8509 return new ComposedTypeSpecifier (-2, loc);
8512 public string GetSignatureForError ()
8517 ArrayContainer.GetPostfixSignature (Dimension);
8519 return Next != null ? s + Next.GetSignatureForError () : s;
8524 // This class is used to "construct" the type during a typecast
8525 // operation. Since the Type.GetType class in .NET can parse
8526 // the type specification, we just use this to construct the type
8527 // one bit at a time.
8529 public class ComposedCast : TypeExpr {
8530 FullNamedExpression left;
8531 ComposedTypeSpecifier spec;
8533 public ComposedCast (FullNamedExpression left, ComposedTypeSpecifier spec)
8536 throw new ArgumentNullException ("spec");
8540 this.loc = spec.Location;
8543 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
8545 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec, false);
8550 eclass = ExprClass.Type;
8552 var single_spec = spec;
8554 if (single_spec.IsNullable) {
8555 lexpr = new Nullable.NullableType (lexpr, loc);
8556 lexpr = lexpr.ResolveAsTypeTerminal (ec, false);
8560 single_spec = single_spec.Next;
8561 } else if (single_spec.IsPointer) {
8562 if (!TypeManager.VerifyUnmanaged (ec.Compiler, type, loc))
8566 UnsafeError (ec.Compiler.Report, loc);
8569 type = PointerContainer.MakeType (type);
8570 single_spec = single_spec.Next;
8573 if (single_spec != null && single_spec.Dimension > 0) {
8574 if (TypeManager.IsSpecialType (type)) {
8575 ec.Compiler.Report.Error (611, loc, "Array elements cannot be of type `{0}'", type.GetSignatureForError ());
8576 } else if (type.IsStatic) {
8577 ec.Compiler.Report.SymbolRelatedToPreviousError (type);
8578 ec.Compiler.Report.Error (719, loc, "Array elements cannot be of static type `{0}'",
8579 type.GetSignatureForError ());
8581 MakeArray (single_spec);
8588 void MakeArray (ComposedTypeSpecifier spec)
8590 if (spec.Next != null)
8591 MakeArray (spec.Next);
8593 type = ArrayContainer.MakeType (type, spec.Dimension);
8596 public override string GetSignatureForError ()
8598 return left.GetSignatureForError () + spec.GetSignatureForError ();
8602 public class FixedBufferPtr : Expression {
8605 public FixedBufferPtr (Expression array, TypeSpec array_type, Location l)
8610 type = PointerContainer.MakeType (array_type);
8611 eclass = ExprClass.Value;
8614 public override Expression CreateExpressionTree (ResolveContext ec)
8616 Error_PointerInsideExpressionTree (ec);
8620 public override void Emit(EmitContext ec)
8625 protected override Expression DoResolve (ResolveContext ec)
8628 // We are born fully resolved
8636 // This class is used to represent the address of an array, used
8637 // only by the Fixed statement, this generates "&a [0]" construct
8638 // for fixed (char *pa = a)
8640 public class ArrayPtr : FixedBufferPtr {
8641 TypeSpec array_type;
8643 public ArrayPtr (Expression array, TypeSpec array_type, Location l):
8644 base (array, array_type, l)
8646 this.array_type = array_type;
8649 public override void Emit (EmitContext ec)
8654 ec.Emit (OpCodes.Ldelema, array_type);
8659 // Encapsulates a conversion rules required for array indexes
8661 public class ArrayIndexCast : TypeCast
8663 public ArrayIndexCast (Expression expr)
8664 : base (expr, TypeManager.int32_type)
8666 if (expr.Type == TypeManager.int32_type)
8667 throw new ArgumentException ("unnecessary array index conversion");
8670 public override Expression CreateExpressionTree (ResolveContext ec)
8672 using (ec.Set (ResolveContext.Options.CheckedScope)) {
8673 return base.CreateExpressionTree (ec);
8677 public override void Emit (EmitContext ec)
8681 var expr_type = child.Type;
8683 if (expr_type == TypeManager.uint32_type)
8684 ec.Emit (OpCodes.Conv_U);
8685 else if (expr_type == TypeManager.int64_type)
8686 ec.Emit (OpCodes.Conv_Ovf_I);
8687 else if (expr_type == TypeManager.uint64_type)
8688 ec.Emit (OpCodes.Conv_Ovf_I_Un);
8690 throw new InternalErrorException ("Cannot emit cast to unknown array element type", type);
8695 // Implements the `stackalloc' keyword
8697 public class StackAlloc : Expression {
8702 public StackAlloc (Expression type, Expression count, Location l)
8709 public override Expression CreateExpressionTree (ResolveContext ec)
8711 throw new NotSupportedException ("ET");
8714 protected override Expression DoResolve (ResolveContext ec)
8716 count = count.Resolve (ec);
8720 if (count.Type != TypeManager.uint32_type){
8721 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8726 Constant c = count as Constant;
8727 if (c != null && c.IsNegative) {
8728 ec.Report.Error (247, loc, "Cannot use a negative size with stackalloc");
8731 if (ec.HasAny (ResolveContext.Options.CatchScope | ResolveContext.Options.FinallyScope)) {
8732 ec.Report.Error (255, loc, "Cannot use stackalloc in finally or catch");
8735 TypeExpr texpr = t.ResolveAsTypeTerminal (ec, false);
8741 if (!TypeManager.VerifyUnmanaged (ec.Compiler, otype, loc))
8744 type = PointerContainer.MakeType (otype);
8745 eclass = ExprClass.Value;
8750 public override void Emit (EmitContext ec)
8752 int size = GetTypeSize (otype);
8757 ec.Emit (OpCodes.Sizeof, otype);
8761 ec.Emit (OpCodes.Mul_Ovf_Un);
8762 ec.Emit (OpCodes.Localloc);
8765 protected override void CloneTo (CloneContext clonectx, Expression t)
8767 StackAlloc target = (StackAlloc) t;
8768 target.count = count.Clone (clonectx);
8769 target.t = t.Clone (clonectx);
8774 // An object initializer expression
8776 public class ElementInitializer : Assign
8778 public readonly string Name;
8780 public ElementInitializer (string name, Expression initializer, Location loc)
8781 : base (null, initializer, loc)
8786 protected override void CloneTo (CloneContext clonectx, Expression t)
8788 ElementInitializer target = (ElementInitializer) t;
8789 target.source = source.Clone (clonectx);
8792 public override Expression CreateExpressionTree (ResolveContext ec)
8794 Arguments args = new Arguments (2);
8795 FieldExpr fe = target as FieldExpr;
8797 args.Add (new Argument (fe.CreateTypeOfExpression ()));
8799 args.Add (new Argument (((PropertyExpr)target).CreateSetterTypeOfExpression ()));
8801 args.Add (new Argument (source.CreateExpressionTree (ec)));
8802 return CreateExpressionFactoryCall (ec,
8803 source is CollectionOrObjectInitializers ? "ListBind" : "Bind",
8807 protected override Expression DoResolve (ResolveContext ec)
8810 return EmptyExpressionStatement.Instance;
8812 MemberExpr me = MemberLookupFinal (ec, ec.CurrentInitializerVariable.Type, ec.CurrentInitializerVariable.Type,
8813 Name, 0, MemberKind.Field | MemberKind.Property, BindingRestriction.AccessibleOnly | BindingRestriction.InstanceOnly | BindingRestriction.DefaultMemberLookup, loc) as MemberExpr;
8819 me.InstanceExpression = ec.CurrentInitializerVariable;
8821 if (source is CollectionOrObjectInitializers) {
8822 Expression previous = ec.CurrentInitializerVariable;
8823 ec.CurrentInitializerVariable = target;
8824 source = source.Resolve (ec);
8825 ec.CurrentInitializerVariable = previous;
8829 eclass = source.eclass;
8834 return base.DoResolve (ec);
8837 protected override MemberExpr Error_MemberLookupFailed (ResolveContext ec, TypeSpec type, IList<MemberSpec> members)
8839 var member = members.First ();
8840 if (member.Kind != MemberKind.Property && member.Kind != MemberKind.Field)
8841 ec.Report.Error (1913, loc, "Member `{0}' cannot be initialized. An object " +
8842 "initializer may only be used for fields, or properties", TypeManager.GetFullNameSignature (member));
8844 ec.Report.Error (1914, loc, " Static field or property `{0}' cannot be assigned in an object initializer",
8845 TypeManager.GetFullNameSignature (member));
8850 public override void EmitStatement (EmitContext ec)
8852 if (source is CollectionOrObjectInitializers)
8855 base.EmitStatement (ec);
8860 // A collection initializer expression
8862 class CollectionElementInitializer : Invocation
8864 public class ElementInitializerArgument : Argument
8866 public ElementInitializerArgument (Expression e)
8872 sealed class AddMemberAccess : MemberAccess
8874 public AddMemberAccess (Expression expr, Location loc)
8875 : base (expr, "Add", loc)
8879 protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
8881 if (TypeManager.HasElementType (type))
8884 base.Error_TypeDoesNotContainDefinition (ec, type, name);
8888 public CollectionElementInitializer (Expression argument)
8889 : base (null, new Arguments (1))
8891 base.arguments.Add (new ElementInitializerArgument (argument));
8892 this.loc = argument.Location;
8895 public CollectionElementInitializer (List<Expression> arguments, Location loc)
8896 : base (null, new Arguments (arguments.Count))
8898 foreach (Expression e in arguments)
8899 base.arguments.Add (new ElementInitializerArgument (e));
8904 public override Expression CreateExpressionTree (ResolveContext ec)
8906 Arguments args = new Arguments (2);
8907 args.Add (new Argument (mg.CreateExpressionTree (ec)));
8909 var expr_initializers = new ArrayInitializer (arguments.Count, loc);
8910 foreach (Argument a in arguments)
8911 expr_initializers.Add (a.CreateExpressionTree (ec));
8913 args.Add (new Argument (new ArrayCreation (
8914 CreateExpressionTypeExpression (ec, loc), expr_initializers, loc)));
8915 return CreateExpressionFactoryCall (ec, "ElementInit", args);
8918 protected override void CloneTo (CloneContext clonectx, Expression t)
8920 CollectionElementInitializer target = (CollectionElementInitializer) t;
8921 if (arguments != null)
8922 target.arguments = arguments.Clone (clonectx);
8925 protected override Expression DoResolve (ResolveContext ec)
8927 base.expr = new AddMemberAccess (ec.CurrentInitializerVariable, loc);
8929 return base.DoResolve (ec);
8934 // A block of object or collection initializers
8936 public class CollectionOrObjectInitializers : ExpressionStatement
8938 IList<Expression> initializers;
8939 bool is_collection_initialization;
8941 public static readonly CollectionOrObjectInitializers Empty =
8942 new CollectionOrObjectInitializers (Array.AsReadOnly (new Expression [0]), Location.Null);
8944 public CollectionOrObjectInitializers (IList<Expression> initializers, Location loc)
8946 this.initializers = initializers;
8950 public bool IsEmpty {
8952 return initializers.Count == 0;
8956 public bool IsCollectionInitializer {
8958 return is_collection_initialization;
8962 protected override void CloneTo (CloneContext clonectx, Expression target)
8964 CollectionOrObjectInitializers t = (CollectionOrObjectInitializers) target;
8966 t.initializers = new List<Expression> (initializers.Count);
8967 foreach (var e in initializers)
8968 t.initializers.Add (e.Clone (clonectx));
8971 public override Expression CreateExpressionTree (ResolveContext ec)
8973 var expr_initializers = new ArrayInitializer (initializers.Count, loc);
8974 foreach (Expression e in initializers) {
8975 Expression expr = e.CreateExpressionTree (ec);
8977 expr_initializers.Add (expr);
8980 return new ImplicitlyTypedArrayCreation (expr_initializers, loc);
8983 protected override Expression DoResolve (ResolveContext ec)
8985 List<string> element_names = null;
8986 for (int i = 0; i < initializers.Count; ++i) {
8987 Expression initializer = initializers [i];
8988 ElementInitializer element_initializer = initializer as ElementInitializer;
8991 if (element_initializer != null) {
8992 element_names = new List<string> (initializers.Count);
8993 element_names.Add (element_initializer.Name);
8994 } else if (initializer is CompletingExpression){
8995 initializer.Resolve (ec);
8996 throw new InternalErrorException ("This line should never be reached");
8998 if (!ec.CurrentInitializerVariable.Type.ImplementsInterface (TypeManager.ienumerable_type)) {
8999 ec.Report.Error (1922, loc, "A field or property `{0}' cannot be initialized with a collection " +
9000 "object initializer because type `{1}' does not implement `{2}' interface",
9001 ec.CurrentInitializerVariable.GetSignatureForError (),
9002 TypeManager.CSharpName (ec.CurrentInitializerVariable.Type),
9003 TypeManager.CSharpName (TypeManager.ienumerable_type));
9006 is_collection_initialization = true;
9009 if (is_collection_initialization != (element_initializer == null)) {
9010 ec.Report.Error (747, initializer.Location, "Inconsistent `{0}' member declaration",
9011 is_collection_initialization ? "collection initializer" : "object initializer");
9015 if (!is_collection_initialization) {
9016 if (element_names.Contains (element_initializer.Name)) {
9017 ec.Report.Error (1912, element_initializer.Location,
9018 "An object initializer includes more than one member `{0}' initialization",
9019 element_initializer.Name);
9021 element_names.Add (element_initializer.Name);
9026 Expression e = initializer.Resolve (ec);
9027 if (e == EmptyExpressionStatement.Instance)
9028 initializers.RemoveAt (i--);
9030 initializers [i] = e;
9033 type = ec.CurrentInitializerVariable.Type;
9034 if (is_collection_initialization) {
9035 if (TypeManager.HasElementType (type)) {
9036 ec.Report.Error (1925, loc, "Cannot initialize object of type `{0}' with a collection initializer",
9037 TypeManager.CSharpName (type));
9041 eclass = ExprClass.Variable;
9045 public override void Emit (EmitContext ec)
9050 public override void EmitStatement (EmitContext ec)
9052 foreach (ExpressionStatement e in initializers)
9053 e.EmitStatement (ec);
9058 // New expression with element/object initializers
9060 public class NewInitialize : New
9063 // This class serves as a proxy for variable initializer target instances.
9064 // A real variable is assigned later when we resolve left side of an
9067 sealed class InitializerTargetExpression : Expression, IMemoryLocation
9069 NewInitialize new_instance;
9071 public InitializerTargetExpression (NewInitialize newInstance)
9073 this.type = newInstance.type;
9074 this.loc = newInstance.loc;
9075 this.eclass = newInstance.eclass;
9076 this.new_instance = newInstance;
9079 public override Expression CreateExpressionTree (ResolveContext ec)
9081 // Should not be reached
9082 throw new NotSupportedException ("ET");
9085 protected override Expression DoResolve (ResolveContext ec)
9090 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
9095 public override void Emit (EmitContext ec)
9097 Expression e = (Expression) new_instance.instance;
9101 #region IMemoryLocation Members
9103 public void AddressOf (EmitContext ec, AddressOp mode)
9105 new_instance.instance.AddressOf (ec, mode);
9111 CollectionOrObjectInitializers initializers;
9112 IMemoryLocation instance;
9114 public NewInitialize (FullNamedExpression requested_type, Arguments arguments, CollectionOrObjectInitializers initializers, Location l)
9115 : base (requested_type, arguments, l)
9117 this.initializers = initializers;
9120 protected override IMemoryLocation EmitAddressOf (EmitContext ec, AddressOp Mode)
9122 instance = base.EmitAddressOf (ec, Mode);
9124 if (!initializers.IsEmpty)
9125 initializers.Emit (ec);
9130 protected override void CloneTo (CloneContext clonectx, Expression t)
9132 base.CloneTo (clonectx, t);
9134 NewInitialize target = (NewInitialize) t;
9135 target.initializers = (CollectionOrObjectInitializers) initializers.Clone (clonectx);
9138 public override Expression CreateExpressionTree (ResolveContext ec)
9140 Arguments args = new Arguments (2);
9141 args.Add (new Argument (base.CreateExpressionTree (ec)));
9142 if (!initializers.IsEmpty)
9143 args.Add (new Argument (initializers.CreateExpressionTree (ec)));
9145 return CreateExpressionFactoryCall (ec,
9146 initializers.IsCollectionInitializer ? "ListInit" : "MemberInit",
9150 protected override Expression DoResolve (ResolveContext ec)
9152 Expression e = base.DoResolve (ec);
9156 Expression previous = ec.CurrentInitializerVariable;
9157 ec.CurrentInitializerVariable = new InitializerTargetExpression (this);
9158 initializers.Resolve (ec);
9159 ec.CurrentInitializerVariable = previous;
9163 public override bool Emit (EmitContext ec, IMemoryLocation target)
9165 bool left_on_stack = base.Emit (ec, target);
9167 if (initializers.IsEmpty)
9168 return left_on_stack;
9170 LocalTemporary temp = target as LocalTemporary;
9172 if (!left_on_stack) {
9173 VariableReference vr = target as VariableReference;
9175 // FIXME: This still does not work correctly for pre-set variables
9176 if (vr != null && vr.IsRef)
9177 target.AddressOf (ec, AddressOp.Load);
9179 ((Expression) target).Emit (ec);
9180 left_on_stack = true;
9183 temp = new LocalTemporary (type);
9190 initializers.Emit (ec);
9192 if (left_on_stack) {
9197 return left_on_stack;
9200 public override bool HasInitializer {
9202 return !initializers.IsEmpty;
9207 public class NewAnonymousType : New
9209 static readonly AnonymousTypeParameter[] EmptyParameters = new AnonymousTypeParameter[0];
9211 List<AnonymousTypeParameter> parameters;
9212 readonly TypeContainer parent;
9213 AnonymousTypeClass anonymous_type;
9215 public NewAnonymousType (List<AnonymousTypeParameter> parameters, TypeContainer parent, Location loc)
9216 : base (null, null, loc)
9218 this.parameters = parameters;
9219 this.parent = parent;
9222 protected override void CloneTo (CloneContext clonectx, Expression target)
9224 if (parameters == null)
9227 NewAnonymousType t = (NewAnonymousType) target;
9228 t.parameters = new List<AnonymousTypeParameter> (parameters.Count);
9229 foreach (AnonymousTypeParameter atp in parameters)
9230 t.parameters.Add ((AnonymousTypeParameter) atp.Clone (clonectx));
9233 AnonymousTypeClass CreateAnonymousType (ResolveContext ec, IList<AnonymousTypeParameter> parameters)
9235 AnonymousTypeClass type = parent.Module.Compiled.GetAnonymousType (parameters);
9239 type = AnonymousTypeClass.Create (ec.Compiler, parent, parameters, loc);
9245 type.ResolveTypeParameters ();
9248 if (ec.Report.Errors == 0)
9251 parent.Module.Compiled.AddAnonymousType (type);
9255 public override Expression CreateExpressionTree (ResolveContext ec)
9257 if (parameters == null)
9258 return base.CreateExpressionTree (ec);
9260 var init = new ArrayInitializer (parameters.Count, loc);
9261 foreach (Property p in anonymous_type.Properties)
9262 init.Add (new TypeOfMethod (MemberCache.GetMember (type, p.Get.Spec), loc));
9264 var ctor_args = new ArrayInitializer (Arguments.Count, loc);
9265 foreach (Argument a in Arguments)
9266 ctor_args.Add (a.CreateExpressionTree (ec));
9268 Arguments args = new Arguments (3);
9269 args.Add (new Argument (method.CreateExpressionTree (ec)));
9270 args.Add (new Argument (new ArrayCreation (TypeManager.expression_type_expr, ctor_args, loc)));
9271 args.Add (new Argument (new ImplicitlyTypedArrayCreation (init, loc)));
9273 return CreateExpressionFactoryCall (ec, "New", args);
9276 protected override Expression DoResolve (ResolveContext ec)
9278 if (ec.HasSet (ResolveContext.Options.ConstantScope)) {
9279 ec.Report.Error (836, loc, "Anonymous types cannot be used in this expression");
9283 if (parameters == null) {
9284 anonymous_type = CreateAnonymousType (ec, EmptyParameters);
9285 RequestedType = new TypeExpression (anonymous_type.Definition, loc);
9286 return base.DoResolve (ec);
9290 Arguments = new Arguments (parameters.Count);
9291 TypeExpression [] t_args = new TypeExpression [parameters.Count];
9292 for (int i = 0; i < parameters.Count; ++i) {
9293 Expression e = ((AnonymousTypeParameter) parameters [i]).Resolve (ec);
9299 Arguments.Add (new Argument (e));
9300 t_args [i] = new TypeExpression (e.Type, e.Location);
9306 anonymous_type = CreateAnonymousType (ec, parameters);
9307 if (anonymous_type == null)
9310 RequestedType = new GenericTypeExpr (anonymous_type.Definition, new TypeArguments (t_args), loc);
9311 return base.DoResolve (ec);
9315 public class AnonymousTypeParameter : ShimExpression
9317 public readonly string Name;
9319 public AnonymousTypeParameter (Expression initializer, string name, Location loc)
9320 : base (initializer)
9326 public AnonymousTypeParameter (Parameter parameter)
9327 : base (new SimpleName (parameter.Name, parameter.Location))
9329 this.Name = parameter.Name;
9330 this.loc = parameter.Location;
9333 public override bool Equals (object o)
9335 AnonymousTypeParameter other = o as AnonymousTypeParameter;
9336 return other != null && Name == other.Name;
9339 public override int GetHashCode ()
9341 return Name.GetHashCode ();
9344 protected override Expression DoResolve (ResolveContext ec)
9346 Expression e = expr.Resolve (ec);
9350 if (e.eclass == ExprClass.MethodGroup) {
9351 Error_InvalidInitializer (ec, e.ExprClassName);
9356 if (type == TypeManager.void_type || type == TypeManager.null_type ||
9357 type == InternalType.AnonymousMethod || type.IsPointer) {
9358 Error_InvalidInitializer (ec, e.GetSignatureForError ());
9365 protected virtual void Error_InvalidInitializer (ResolveContext ec, string initializer)
9367 ec.Report.Error (828, loc, "An anonymous type property `{0}' cannot be initialized with `{1}'",