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 public delegate Expression ExpressionTreeExpression (ResolveContext ec, MethodGroupExpr mg);
29 protected readonly Arguments arguments;
30 protected readonly MethodGroupExpr mg;
31 readonly ExpressionTreeExpression expr_tree;
33 public UserOperatorCall (MethodGroupExpr mg, Arguments args, ExpressionTreeExpression expr_tree, Location loc)
36 this.arguments = args;
37 this.expr_tree = expr_tree;
39 type = mg.BestCandidate.ReturnType;
40 eclass = ExprClass.Value;
44 public override Expression CreateExpressionTree (ResolveContext ec)
46 if (expr_tree != null)
47 return expr_tree (ec, mg);
49 Arguments args = Arguments.CreateForExpressionTree (ec, arguments,
50 new NullLiteral (loc),
51 mg.CreateExpressionTree (ec));
53 return CreateExpressionFactoryCall (ec, "Call", args);
56 protected override void CloneTo (CloneContext context, Expression target)
61 protected override Expression DoResolve (ResolveContext ec)
64 // We are born fully resolved
69 public override void Emit (EmitContext ec)
71 mg.EmitCall (ec, arguments);
74 public override SLE.Expression MakeExpression (BuilderContext ctx)
76 var method = mg.BestCandidate.GetMetaInfo () as MethodInfo;
77 return SLE.Expression.Call (method, Arguments.MakeExpression (arguments, ctx));
80 public MethodGroupExpr Method {
85 public class ParenthesizedExpression : ShimExpression
87 public ParenthesizedExpression (Expression expr)
93 protected override Expression DoResolve (ResolveContext ec)
95 return expr.Resolve (ec);
98 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
100 return expr.DoResolveLValue (ec, right_side);
105 // Unary implements unary expressions.
107 public class Unary : Expression
109 public enum Operator : byte {
110 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
114 static TypeSpec[][] predefined_operators;
116 public readonly Operator Oper;
117 public Expression Expr;
118 Expression enum_conversion;
120 public Unary (Operator op, Expression expr, Location loc)
128 // This routine will attempt to simplify the unary expression when the
129 // argument is a constant.
131 Constant TryReduceConstant (ResolveContext ec, Constant e)
133 if (e is EmptyConstantCast)
134 return TryReduceConstant (ec, ((EmptyConstantCast) e).child);
136 if (e is SideEffectConstant) {
137 Constant r = TryReduceConstant (ec, ((SideEffectConstant) e).value);
138 return r == null ? null : new SideEffectConstant (r, e, r.Location);
141 TypeSpec expr_type = e.Type;
144 case Operator.UnaryPlus:
145 // Unary numeric promotions
146 if (expr_type == TypeManager.byte_type)
147 return new IntConstant (((ByteConstant)e).Value, e.Location);
148 if (expr_type == TypeManager.sbyte_type)
149 return new IntConstant (((SByteConstant)e).Value, e.Location);
150 if (expr_type == TypeManager.short_type)
151 return new IntConstant (((ShortConstant)e).Value, e.Location);
152 if (expr_type == TypeManager.ushort_type)
153 return new IntConstant (((UShortConstant)e).Value, e.Location);
154 if (expr_type == TypeManager.char_type)
155 return new IntConstant (((CharConstant)e).Value, e.Location);
157 // Predefined operators
158 if (expr_type == TypeManager.int32_type || expr_type == TypeManager.uint32_type ||
159 expr_type == TypeManager.int64_type || expr_type == TypeManager.uint64_type ||
160 expr_type == TypeManager.float_type || expr_type == TypeManager.double_type ||
161 expr_type == TypeManager.decimal_type) {
167 case Operator.UnaryNegation:
168 // Unary numeric promotions
169 if (expr_type == TypeManager.byte_type)
170 return new IntConstant (-((ByteConstant)e).Value, e.Location);
171 if (expr_type == TypeManager.sbyte_type)
172 return new IntConstant (-((SByteConstant)e).Value, e.Location);
173 if (expr_type == TypeManager.short_type)
174 return new IntConstant (-((ShortConstant)e).Value, e.Location);
175 if (expr_type == TypeManager.ushort_type)
176 return new IntConstant (-((UShortConstant)e).Value, e.Location);
177 if (expr_type == TypeManager.char_type)
178 return new IntConstant (-((CharConstant)e).Value, e.Location);
180 // Predefined operators
181 if (expr_type == TypeManager.int32_type) {
182 int value = ((IntConstant)e).Value;
183 if (value == int.MinValue) {
184 if (ec.ConstantCheckState) {
185 ConstantFold.Error_CompileTimeOverflow (ec, loc);
190 return new IntConstant (-value, e.Location);
192 if (expr_type == TypeManager.int64_type) {
193 long value = ((LongConstant)e).Value;
194 if (value == long.MinValue) {
195 if (ec.ConstantCheckState) {
196 ConstantFold.Error_CompileTimeOverflow (ec, loc);
201 return new LongConstant (-value, e.Location);
204 if (expr_type == TypeManager.uint32_type) {
205 UIntLiteral uil = e as UIntLiteral;
207 if (uil.Value == int.MaxValue + (uint) 1)
208 return new IntLiteral (int.MinValue, e.Location);
209 return new LongLiteral (-uil.Value, e.Location);
211 return new LongConstant (-((UIntConstant)e).Value, e.Location);
214 if (expr_type == TypeManager.uint64_type) {
215 ULongLiteral ull = e as ULongLiteral;
216 if (ull != null && ull.Value == 9223372036854775808)
217 return new LongLiteral (long.MinValue, e.Location);
221 if (expr_type == TypeManager.float_type) {
222 FloatLiteral fl = e as FloatLiteral;
223 // For better error reporting
225 return new FloatLiteral (-fl.Value, e.Location);
227 return new FloatConstant (-((FloatConstant)e).Value, e.Location);
229 if (expr_type == TypeManager.double_type) {
230 DoubleLiteral dl = e as DoubleLiteral;
231 // For better error reporting
233 return new DoubleLiteral (-dl.Value, e.Location);
235 return new DoubleConstant (-((DoubleConstant)e).Value, e.Location);
237 if (expr_type == TypeManager.decimal_type)
238 return new DecimalConstant (-((DecimalConstant)e).Value, e.Location);
242 case Operator.LogicalNot:
243 if (expr_type != TypeManager.bool_type)
246 bool b = (bool)e.GetValue ();
247 return new BoolConstant (!b, e.Location);
249 case Operator.OnesComplement:
250 // Unary numeric promotions
251 if (expr_type == TypeManager.byte_type)
252 return new IntConstant (~((ByteConstant)e).Value, e.Location);
253 if (expr_type == TypeManager.sbyte_type)
254 return new IntConstant (~((SByteConstant)e).Value, e.Location);
255 if (expr_type == TypeManager.short_type)
256 return new IntConstant (~((ShortConstant)e).Value, e.Location);
257 if (expr_type == TypeManager.ushort_type)
258 return new IntConstant (~((UShortConstant)e).Value, e.Location);
259 if (expr_type == TypeManager.char_type)
260 return new IntConstant (~((CharConstant)e).Value, e.Location);
262 // Predefined operators
263 if (expr_type == TypeManager.int32_type)
264 return new IntConstant (~((IntConstant)e).Value, e.Location);
265 if (expr_type == TypeManager.uint32_type)
266 return new UIntConstant (~((UIntConstant)e).Value, e.Location);
267 if (expr_type == TypeManager.int64_type)
268 return new LongConstant (~((LongConstant)e).Value, e.Location);
269 if (expr_type == TypeManager.uint64_type){
270 return new ULongConstant (~((ULongConstant)e).Value, e.Location);
272 if (e is EnumConstant) {
273 e = TryReduceConstant (ec, ((EnumConstant)e).Child);
275 e = new EnumConstant (e, expr_type);
280 throw new Exception ("Can not constant fold: " + Oper.ToString());
283 protected Expression ResolveOperator (ResolveContext ec, Expression expr)
285 eclass = ExprClass.Value;
287 if (predefined_operators == null)
288 CreatePredefinedOperatorsTable ();
290 TypeSpec expr_type = expr.Type;
291 Expression best_expr;
294 // Primitive types first
296 if (TypeManager.IsPrimitiveType (expr_type)) {
297 best_expr = ResolvePrimitivePredefinedType (expr);
298 if (best_expr == null)
301 type = best_expr.Type;
307 // E operator ~(E x);
309 if (Oper == Operator.OnesComplement && TypeManager.IsEnumType (expr_type))
310 return ResolveEnumOperator (ec, expr);
312 return ResolveUserType (ec, expr);
315 protected virtual Expression ResolveEnumOperator (ResolveContext ec, Expression expr)
317 TypeSpec underlying_type = EnumSpec.GetUnderlyingType (expr.Type);
318 Expression best_expr = ResolvePrimitivePredefinedType (EmptyCast.Create (expr, underlying_type));
319 if (best_expr == null)
323 enum_conversion = Convert.ExplicitNumericConversion (new EmptyExpression (best_expr.Type), underlying_type);
325 return EmptyCast.Create (this, type);
328 public override Expression CreateExpressionTree (ResolveContext ec)
330 return CreateExpressionTree (ec, null);
333 Expression CreateExpressionTree (ResolveContext ec, MethodGroupExpr user_op)
337 case Operator.AddressOf:
338 Error_PointerInsideExpressionTree (ec);
340 case Operator.UnaryNegation:
341 if (ec.HasSet (ResolveContext.Options.CheckedScope) && user_op == null && !IsFloat (type))
342 method_name = "NegateChecked";
344 method_name = "Negate";
346 case Operator.OnesComplement:
347 case Operator.LogicalNot:
350 case Operator.UnaryPlus:
351 method_name = "UnaryPlus";
354 throw new InternalErrorException ("Unknown unary operator " + Oper.ToString ());
357 Arguments args = new Arguments (2);
358 args.Add (new Argument (Expr.CreateExpressionTree (ec)));
360 args.Add (new Argument (user_op.CreateExpressionTree (ec)));
361 return CreateExpressionFactoryCall (ec, method_name, args);
364 static void CreatePredefinedOperatorsTable ()
366 predefined_operators = new TypeSpec [(int) Operator.TOP] [];
369 // 7.6.1 Unary plus operator
371 predefined_operators [(int) Operator.UnaryPlus] = new TypeSpec [] {
372 TypeManager.int32_type, TypeManager.uint32_type,
373 TypeManager.int64_type, TypeManager.uint64_type,
374 TypeManager.float_type, TypeManager.double_type,
375 TypeManager.decimal_type
379 // 7.6.2 Unary minus operator
381 predefined_operators [(int) Operator.UnaryNegation] = new TypeSpec [] {
382 TypeManager.int32_type,
383 TypeManager.int64_type,
384 TypeManager.float_type, TypeManager.double_type,
385 TypeManager.decimal_type
389 // 7.6.3 Logical negation operator
391 predefined_operators [(int) Operator.LogicalNot] = new TypeSpec [] {
392 TypeManager.bool_type
396 // 7.6.4 Bitwise complement operator
398 predefined_operators [(int) Operator.OnesComplement] = new TypeSpec [] {
399 TypeManager.int32_type, TypeManager.uint32_type,
400 TypeManager.int64_type, TypeManager.uint64_type
405 // Unary numeric promotions
407 static Expression DoNumericPromotion (Operator op, Expression expr)
409 TypeSpec expr_type = expr.Type;
410 if ((op == Operator.UnaryPlus || op == Operator.UnaryNegation || op == Operator.OnesComplement) &&
411 expr_type == TypeManager.byte_type || expr_type == TypeManager.sbyte_type ||
412 expr_type == TypeManager.short_type || expr_type == TypeManager.ushort_type ||
413 expr_type == TypeManager.char_type)
414 return Convert.ImplicitNumericConversion (expr, TypeManager.int32_type);
416 if (op == Operator.UnaryNegation && expr_type == TypeManager.uint32_type)
417 return Convert.ImplicitNumericConversion (expr, TypeManager.int64_type);
422 protected override Expression DoResolve (ResolveContext ec)
424 if (Oper == Operator.AddressOf) {
425 return ResolveAddressOf (ec);
428 Expr = Expr.Resolve (ec);
432 if (Expr.Type == InternalType.Dynamic) {
433 Arguments args = new Arguments (1);
434 args.Add (new Argument (Expr));
435 return new DynamicUnaryConversion (GetOperatorExpressionTypeName (), args, loc).Resolve (ec);
438 if (TypeManager.IsNullableType (Expr.Type))
439 return new Nullable.LiftedUnaryOperator (Oper, Expr, loc).Resolve (ec);
442 // Attempt to use a constant folding operation.
444 Constant cexpr = Expr as Constant;
446 cexpr = TryReduceConstant (ec, cexpr);
448 return cexpr.Resolve (ec);
451 Expression expr = ResolveOperator (ec, Expr);
453 Error_OperatorCannotBeApplied (ec, loc, OperName (Oper), Expr.Type);
456 // Reduce unary operator on predefined types
458 if (expr == this && Oper == Operator.UnaryPlus)
464 public override Expression DoResolveLValue (ResolveContext ec, Expression right)
469 public override void Emit (EmitContext ec)
471 EmitOperator (ec, type);
474 protected void EmitOperator (EmitContext ec, TypeSpec type)
477 case Operator.UnaryPlus:
481 case Operator.UnaryNegation:
482 if (ec.HasSet (EmitContext.Options.CheckedScope) && !IsFloat (type)) {
483 ec.Emit (OpCodes.Ldc_I4_0);
484 if (type == TypeManager.int64_type)
485 ec.Emit (OpCodes.Conv_U8);
487 ec.Emit (OpCodes.Sub_Ovf);
490 ec.Emit (OpCodes.Neg);
495 case Operator.LogicalNot:
497 ec.Emit (OpCodes.Ldc_I4_0);
498 ec.Emit (OpCodes.Ceq);
501 case Operator.OnesComplement:
503 ec.Emit (OpCodes.Not);
506 case Operator.AddressOf:
507 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
511 throw new Exception ("This should not happen: Operator = "
516 // Same trick as in Binary expression
518 if (enum_conversion != null)
519 enum_conversion.Emit (ec);
522 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
524 if (Oper == Operator.LogicalNot)
525 Expr.EmitBranchable (ec, target, !on_true);
527 base.EmitBranchable (ec, target, on_true);
530 public override void EmitSideEffect (EmitContext ec)
532 Expr.EmitSideEffect (ec);
535 public static void Error_OperatorCannotBeApplied (ResolveContext ec, Location loc, string oper, TypeSpec t)
537 ec.Report.Error (23, loc, "The `{0}' operator cannot be applied to operand of type `{1}'",
538 oper, TypeManager.CSharpName (t));
542 // Converts operator to System.Linq.Expressions.ExpressionType enum name
544 string GetOperatorExpressionTypeName ()
547 case Operator.OnesComplement:
548 return "OnesComplement";
549 case Operator.LogicalNot:
551 case Operator.UnaryNegation:
553 case Operator.UnaryPlus:
556 throw new NotImplementedException ("Unknown express type operator " + Oper.ToString ());
560 static bool IsFloat (TypeSpec t)
562 return t == TypeManager.float_type || t == TypeManager.double_type;
566 // Returns a stringified representation of the Operator
568 public static string OperName (Operator oper)
571 case Operator.UnaryPlus:
573 case Operator.UnaryNegation:
575 case Operator.LogicalNot:
577 case Operator.OnesComplement:
579 case Operator.AddressOf:
583 throw new NotImplementedException (oper.ToString ());
586 public override SLE.Expression MakeExpression (BuilderContext ctx)
588 var expr = Expr.MakeExpression (ctx);
589 bool is_checked = ctx.HasSet (BuilderContext.Options.CheckedScope);
592 case Operator.UnaryNegation:
593 return is_checked ? SLE.Expression.NegateChecked (expr) : SLE.Expression.Negate (expr);
594 case Operator.LogicalNot:
595 return SLE.Expression.Not (expr);
597 case Operator.OnesComplement:
598 return SLE.Expression.OnesComplement (expr);
601 throw new NotImplementedException (Oper.ToString ());
605 public static void Reset ()
607 predefined_operators = null;
610 Expression ResolveAddressOf (ResolveContext ec)
613 UnsafeError (ec, loc);
615 Expr = Expr.DoResolveLValue (ec, EmptyExpression.UnaryAddress);
616 if (Expr == null || Expr.eclass != ExprClass.Variable) {
617 ec.Report.Error (211, loc, "Cannot take the address of the given expression");
621 if (!TypeManager.VerifyUnmanaged (ec.Compiler, Expr.Type, loc)) {
625 IVariableReference vr = Expr as IVariableReference;
628 VariableInfo vi = vr.VariableInfo;
630 if (vi.LocalInfo != null)
631 vi.LocalInfo.Used = true;
634 // A variable is considered definitely assigned if you take its address.
639 is_fixed = vr.IsFixed;
640 vr.SetHasAddressTaken ();
643 AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, vr, loc);
646 IFixedExpression fe = Expr as IFixedExpression;
647 is_fixed = fe != null && fe.IsFixed;
650 if (!is_fixed && !ec.HasSet (ResolveContext.Options.FixedInitializerScope)) {
651 ec.Report.Error (212, loc, "You can only take the address of unfixed expression inside of a fixed statement initializer");
654 type = PointerContainer.MakeType (Expr.Type);
655 eclass = ExprClass.Value;
659 Expression ResolvePrimitivePredefinedType (Expression expr)
661 expr = DoNumericPromotion (Oper, expr);
662 TypeSpec expr_type = expr.Type;
663 TypeSpec[] predefined = predefined_operators [(int) Oper];
664 foreach (TypeSpec t in predefined) {
672 // Perform user-operator overload resolution
674 protected virtual Expression ResolveUserOperator (ResolveContext ec, Expression expr)
676 CSharp.Operator.OpType op_type;
678 case Operator.LogicalNot:
679 op_type = CSharp.Operator.OpType.LogicalNot; break;
680 case Operator.OnesComplement:
681 op_type = CSharp.Operator.OpType.OnesComplement; break;
682 case Operator.UnaryNegation:
683 op_type = CSharp.Operator.OpType.UnaryNegation; break;
684 case Operator.UnaryPlus:
685 op_type = CSharp.Operator.OpType.UnaryPlus; break;
687 throw new InternalErrorException (Oper.ToString ());
690 var methods = MemberCache.GetUserOperator (expr.Type, op_type, false);
694 var user_op = new MethodGroupExpr (methods, expr.Type, loc);
696 Arguments args = new Arguments (1);
697 args.Add (new Argument (expr));
698 user_op = user_op.OverloadResolve (ec, ref args, false, expr.Location);
703 Expr = args [0].Expr;
704 return new UserOperatorCall (user_op, args, CreateExpressionTree, expr.Location);
708 // Unary user type overload resolution
710 Expression ResolveUserType (ResolveContext ec, Expression expr)
712 Expression best_expr = ResolveUserOperator (ec, expr);
713 if (best_expr != null)
716 TypeSpec[] predefined = predefined_operators [(int) Oper];
717 foreach (TypeSpec t in predefined) {
718 Expression oper_expr = Convert.ImplicitUserConversion (ec, expr, t, expr.Location);
719 if (oper_expr == null)
723 // decimal type is predefined but has user-operators
725 if (oper_expr.Type == TypeManager.decimal_type)
726 oper_expr = ResolveUserType (ec, oper_expr);
728 oper_expr = ResolvePrimitivePredefinedType (oper_expr);
730 if (oper_expr == null)
733 if (best_expr == null) {
734 best_expr = oper_expr;
738 int result = MethodGroupExpr.BetterTypeConversion (ec, best_expr.Type, t);
740 ec.Report.Error (35, loc, "Operator `{0}' is ambiguous on an operand of type `{1}'",
741 OperName (Oper), TypeManager.CSharpName (expr.Type));
746 best_expr = oper_expr;
749 if (best_expr == null)
753 // HACK: Decimal user-operator is included in standard operators
755 if (best_expr.Type == TypeManager.decimal_type)
759 type = best_expr.Type;
763 protected override void CloneTo (CloneContext clonectx, Expression t)
765 Unary target = (Unary) t;
767 target.Expr = Expr.Clone (clonectx);
772 // Unary operators are turned into Indirection expressions
773 // after semantic analysis (this is so we can take the address
774 // of an indirection).
776 public class Indirection : Expression, IMemoryLocation, IAssignMethod, IFixedExpression {
778 LocalTemporary temporary;
781 public Indirection (Expression expr, Location l)
787 public override Expression CreateExpressionTree (ResolveContext ec)
789 Error_PointerInsideExpressionTree (ec);
793 protected override void CloneTo (CloneContext clonectx, Expression t)
795 Indirection target = (Indirection) t;
796 target.expr = expr.Clone (clonectx);
799 public override void Emit (EmitContext ec)
804 ec.EmitLoadFromPtr (Type);
807 public void Emit (EmitContext ec, bool leave_copy)
811 ec.Emit (OpCodes.Dup);
812 temporary = new LocalTemporary (expr.Type);
813 temporary.Store (ec);
817 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
819 prepared = prepare_for_load;
823 if (prepare_for_load)
824 ec.Emit (OpCodes.Dup);
828 ec.Emit (OpCodes.Dup);
829 temporary = new LocalTemporary (expr.Type);
830 temporary.Store (ec);
833 ec.EmitStoreFromPtr (type);
835 if (temporary != null) {
837 temporary.Release (ec);
841 public void AddressOf (EmitContext ec, AddressOp Mode)
846 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
848 return DoResolve (ec);
851 protected override Expression DoResolve (ResolveContext ec)
853 expr = expr.Resolve (ec);
858 UnsafeError (ec, loc);
860 if (!expr.Type.IsPointer) {
861 ec.Report.Error (193, loc, "The * or -> operator must be applied to a pointer");
865 if (expr.Type == TypeManager.void_ptr_type) {
866 ec.Report.Error (242, loc, "The operation in question is undefined on void pointers");
870 type = TypeManager.GetElementType (expr.Type);
871 eclass = ExprClass.Variable;
875 public bool IsFixed {
879 public override string ToString ()
881 return "*(" + expr + ")";
886 /// Unary Mutator expressions (pre and post ++ and --)
890 /// UnaryMutator implements ++ and -- expressions. It derives from
891 /// ExpressionStatement becuase the pre/post increment/decrement
892 /// operators can be used in a statement context.
894 /// FIXME: Idea, we could split this up in two classes, one simpler
895 /// for the common case, and one with the extra fields for more complex
896 /// classes (indexers require temporary access; overloaded require method)
899 public class UnaryMutator : ExpressionStatement
901 class DynamicPostMutator : Expression, IAssignMethod
906 public DynamicPostMutator (Expression expr)
909 this.type = expr.Type;
910 this.loc = expr.Location;
913 public override Expression CreateExpressionTree (ResolveContext ec)
915 throw new NotImplementedException ("ET");
918 protected override Expression DoResolve (ResolveContext rc)
920 eclass = expr.eclass;
924 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
926 expr.DoResolveLValue (ec, right_side);
927 return DoResolve (ec);
930 public override void Emit (EmitContext ec)
935 public void Emit (EmitContext ec, bool leave_copy)
937 throw new NotImplementedException ();
941 // Emits target assignment using unmodified source value
943 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
946 // Allocate temporary variable to keep original value before it's modified
948 temp = new LocalTemporary (type);
952 ((IAssignMethod) expr).EmitAssign (ec, source, false, prepare_for_load);
963 public enum Mode : byte {
970 PreDecrement = IsDecrement,
971 PostIncrement = IsPost,
972 PostDecrement = IsPost | IsDecrement
976 bool is_expr, recurse;
980 // Holds the real operation
981 Expression operation;
983 public UnaryMutator (Mode m, Expression e, Location loc)
990 public override Expression CreateExpressionTree (ResolveContext ec)
992 return new SimpleAssign (this, this).CreateExpressionTree (ec);
995 protected override Expression DoResolve (ResolveContext ec)
997 expr = expr.Resolve (ec);
1002 if (expr.Type == InternalType.Dynamic) {
1004 // Handle postfix unary operators using local
1005 // temporary variable
1007 if ((mode & Mode.IsPost) != 0)
1008 expr = new DynamicPostMutator (expr);
1010 Arguments args = new Arguments (1);
1011 args.Add (new Argument (expr));
1012 return new SimpleAssign (expr, new DynamicUnaryConversion (GetOperatorExpressionTypeName (), args, loc)).Resolve (ec);
1015 if (TypeManager.IsNullableType (expr.Type))
1016 return new Nullable.LiftedUnaryMutator (mode, expr, loc).Resolve (ec);
1018 eclass = ExprClass.Value;
1020 return ResolveOperator (ec);
1023 void EmitCode (EmitContext ec, bool is_expr)
1026 this.is_expr = is_expr;
1027 ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
1030 public override void Emit (EmitContext ec)
1033 // We use recurse to allow ourselfs to be the source
1034 // of an assignment. This little hack prevents us from
1035 // having to allocate another expression
1038 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
1040 operation.Emit (ec);
1046 EmitCode (ec, true);
1049 public override void EmitStatement (EmitContext ec)
1051 EmitCode (ec, false);
1055 // Converts operator to System.Linq.Expressions.ExpressionType enum name
1057 string GetOperatorExpressionTypeName ()
1059 return IsDecrement ? "Decrement" : "Increment";
1063 get { return (mode & Mode.IsDecrement) != 0; }
1067 // Returns whether an object of type `t' can be incremented
1068 // or decremented with add/sub (ie, basically whether we can
1069 // use pre-post incr-decr operations on it, but it is not a
1070 // System.Decimal, which we require operator overloading to catch)
1072 static bool IsPredefinedOperator (TypeSpec t)
1074 return (TypeManager.IsPrimitiveType (t) && t != TypeManager.bool_type) ||
1075 TypeManager.IsEnumType (t) ||
1076 t.IsPointer && t != TypeManager.void_ptr_type;
1080 public override SLE.Expression MakeExpression (BuilderContext ctx)
1082 var target = ((RuntimeValueExpression) expr).MetaObject.Expression;
1083 var source = SLE.Expression.Convert (operation.MakeExpression (ctx), target.Type);
1084 return SLE.Expression.Assign (target, source);
1088 protected override void CloneTo (CloneContext clonectx, Expression t)
1090 UnaryMutator target = (UnaryMutator) t;
1092 target.expr = expr.Clone (clonectx);
1095 Expression ResolveOperator (ResolveContext ec)
1097 if (expr is RuntimeValueExpression) {
1100 // Use itself at the top of the stack
1101 operation = new EmptyExpression (type);
1105 // The operand of the prefix/postfix increment decrement operators
1106 // should be an expression that is classified as a variable,
1107 // a property access or an indexer access
1109 if (expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.IndexerAccess || expr.eclass == ExprClass.PropertyAccess) {
1110 expr = expr.ResolveLValue (ec, expr);
1112 ec.Report.Error (1059, loc, "The operand of an increment or decrement operator must be a variable, property or indexer");
1116 // 1. Check predefined types
1118 if (IsPredefinedOperator (type)) {
1119 // TODO: Move to IntConstant once I get rid of int32_type
1120 var one = new IntConstant (1, loc);
1122 // TODO: Cache this based on type when using EmptyExpression in
1124 Binary.Operator op = IsDecrement ? Binary.Operator.Subtraction : Binary.Operator.Addition;
1125 operation = new Binary (op, operation, one, loc);
1126 operation = operation.Resolve (ec);
1127 if (operation != null && operation.Type != type)
1128 operation = Convert.ExplicitNumericConversion (operation, type);
1134 // Step 2: Perform Operator Overload location
1136 var user_op = IsDecrement ? Operator.OpType.Decrement : Operator.OpType.Increment;
1137 var methods = MemberCache.GetUserOperator (type, user_op, false);
1139 if (methods != null) {
1140 Arguments args = new Arguments (1);
1141 args.Add (new Argument (expr));
1143 var mg = new MethodGroupExpr (methods, type, loc);
1144 mg = mg.OverloadResolve (ec, ref args, false, loc);
1148 args[0].Expr = operation;
1149 operation = new UserOperatorCall (mg, args, null, loc);
1150 operation = Convert.ImplicitConversionRequired (ec, operation, type, loc);
1154 string name = IsDecrement ?
1155 Operator.GetName (Operator.OpType.Decrement) :
1156 Operator.GetName (Operator.OpType.Increment);
1158 Unary.Error_OperatorCannotBeApplied (ec, loc, name, type);
1164 /// Base class for the `Is' and `As' classes.
1168 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1171 public abstract class Probe : Expression {
1172 public Expression ProbeType;
1173 protected Expression expr;
1174 protected TypeExpr probe_type_expr;
1176 public Probe (Expression expr, Expression probe_type, Location l)
1178 ProbeType = probe_type;
1183 public Expression Expr {
1189 protected override Expression DoResolve (ResolveContext ec)
1191 probe_type_expr = ProbeType.ResolveAsTypeTerminal (ec, false);
1192 if (probe_type_expr == null)
1195 expr = expr.Resolve (ec);
1199 if (probe_type_expr.Type.IsStatic) {
1200 ec.Report.Error (-244, loc, "The `{0}' operator cannot be applied to an operand of a static type",
1204 if (expr.Type.IsPointer || probe_type_expr.Type.IsPointer) {
1205 ec.Report.Error (244, loc, "The `{0}' operator cannot be applied to an operand of pointer type",
1210 if (expr.Type == InternalType.AnonymousMethod) {
1211 ec.Report.Error (837, loc, "The `{0}' operator cannot be applied to a lambda expression or anonymous method",
1219 protected abstract string OperatorName { get; }
1221 protected override void CloneTo (CloneContext clonectx, Expression t)
1223 Probe target = (Probe) t;
1225 target.expr = expr.Clone (clonectx);
1226 target.ProbeType = ProbeType.Clone (clonectx);
1232 /// Implementation of the `is' operator.
1234 public class Is : Probe {
1235 Nullable.Unwrap expr_unwrap;
1237 public Is (Expression expr, Expression probe_type, Location l)
1238 : base (expr, probe_type, l)
1242 public override Expression CreateExpressionTree (ResolveContext ec)
1244 Arguments args = Arguments.CreateForExpressionTree (ec, null,
1245 expr.CreateExpressionTree (ec),
1246 new TypeOf (probe_type_expr, loc));
1248 return CreateExpressionFactoryCall (ec, "TypeIs", args);
1251 public override void Emit (EmitContext ec)
1253 if (expr_unwrap != null) {
1254 expr_unwrap.EmitCheck (ec);
1259 ec.Emit (OpCodes.Isinst, probe_type_expr.Type);
1260 ec.Emit (OpCodes.Ldnull);
1261 ec.Emit (OpCodes.Cgt_Un);
1264 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
1266 if (expr_unwrap != null) {
1267 expr_unwrap.EmitCheck (ec);
1270 ec.Emit (OpCodes.Isinst, probe_type_expr.Type);
1272 ec.Emit (on_true ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1275 Expression CreateConstantResult (ResolveContext ec, bool result)
1278 ec.Report.Warning (183, 1, loc, "The given expression is always of the provided (`{0}') type",
1279 TypeManager.CSharpName (probe_type_expr.Type));
1281 ec.Report.Warning (184, 1, loc, "The given expression is never of the provided (`{0}') type",
1282 TypeManager.CSharpName (probe_type_expr.Type));
1284 return ReducedExpression.Create (new BoolConstant (result, loc).Resolve (ec), this);
1287 protected override Expression DoResolve (ResolveContext ec)
1289 if (base.DoResolve (ec) == null)
1292 TypeSpec d = expr.Type;
1293 bool d_is_nullable = false;
1296 // If E is a method group or the null literal, or if the type of E is a reference
1297 // type or a nullable type and the value of E is null, the result is false
1299 if (expr.IsNull || expr.eclass == ExprClass.MethodGroup)
1300 return CreateConstantResult (ec, false);
1302 if (TypeManager.IsNullableType (d)) {
1303 var ut = Nullable.NullableInfo.GetUnderlyingType (d);
1304 if (!ut.IsGenericParameter) {
1306 d_is_nullable = true;
1310 type = TypeManager.bool_type;
1311 eclass = ExprClass.Value;
1312 TypeSpec t = probe_type_expr.Type;
1313 bool t_is_nullable = false;
1314 if (TypeManager.IsNullableType (t)) {
1315 var ut = Nullable.NullableInfo.GetUnderlyingType (t);
1316 if (!ut.IsGenericParameter) {
1318 t_is_nullable = true;
1322 if (TypeManager.IsStruct (t)) {
1325 // D and T are the same value types but D can be null
1327 if (d_is_nullable && !t_is_nullable) {
1328 expr_unwrap = Nullable.Unwrap.Create (expr, false);
1333 // The result is true if D and T are the same value types
1335 return CreateConstantResult (ec, true);
1338 var tp = d as TypeParameterSpec;
1340 return ResolveGenericParameter (ec, t, tp);
1343 // An unboxing conversion exists
1345 if (Convert.ExplicitReferenceConversionExists (d, t))
1348 if (TypeManager.IsGenericParameter (t))
1349 return ResolveGenericParameter (ec, d, (TypeParameterSpec) t);
1351 if (TypeManager.IsStruct (d)) {
1352 if (Convert.ImplicitBoxingConversion (null, d, t) != null)
1353 return CreateConstantResult (ec, true);
1355 if (TypeManager.IsGenericParameter (d))
1356 return ResolveGenericParameter (ec, t, (TypeParameterSpec) d);
1358 if (TypeManager.ContainsGenericParameters (d))
1361 if (Convert.ImplicitReferenceConversionExists (expr, t) ||
1362 Convert.ExplicitReferenceConversionExists (d, t)) {
1368 return CreateConstantResult (ec, false);
1371 Expression ResolveGenericParameter (ResolveContext ec, TypeSpec d, TypeParameterSpec t)
1373 if (t.IsReferenceType) {
1374 if (TypeManager.IsStruct (d))
1375 return CreateConstantResult (ec, false);
1378 if (TypeManager.IsGenericParameter (expr.Type)) {
1379 if (t.IsValueType && expr.Type == t)
1380 return CreateConstantResult (ec, true);
1382 expr = new BoxedCast (expr, d);
1388 protected override string OperatorName {
1389 get { return "is"; }
1394 /// Implementation of the `as' operator.
1396 public class As : Probe {
1398 Expression resolved_type;
1400 public As (Expression expr, Expression probe_type, Location l)
1401 : base (expr, probe_type, l)
1405 public override Expression CreateExpressionTree (ResolveContext ec)
1407 Arguments args = Arguments.CreateForExpressionTree (ec, null,
1408 expr.CreateExpressionTree (ec),
1409 new TypeOf (probe_type_expr, loc));
1411 return CreateExpressionFactoryCall (ec, "TypeAs", args);
1414 public override void Emit (EmitContext ec)
1419 ec.Emit (OpCodes.Isinst, type);
1421 if (TypeManager.IsGenericParameter (type) || TypeManager.IsNullableType (type))
1422 ec.Emit (OpCodes.Unbox_Any, type);
1425 protected override Expression DoResolve (ResolveContext ec)
1427 if (resolved_type == null) {
1428 resolved_type = base.DoResolve (ec);
1430 if (resolved_type == null)
1434 type = probe_type_expr.Type;
1435 eclass = ExprClass.Value;
1436 TypeSpec etype = expr.Type;
1438 if (!TypeManager.IsReferenceType (type) && !TypeManager.IsNullableType (type)) {
1439 if (TypeManager.IsGenericParameter (type)) {
1440 ec.Report.Error (413, loc,
1441 "The `as' operator cannot be used with a non-reference type parameter `{0}'. Consider adding `class' or a reference type constraint",
1442 probe_type_expr.GetSignatureForError ());
1444 ec.Report.Error (77, loc,
1445 "The `as' operator cannot be used with a non-nullable value type `{0}'",
1446 TypeManager.CSharpName (type));
1451 if (expr.IsNull && TypeManager.IsNullableType (type)) {
1452 return Nullable.LiftedNull.CreateFromExpression (ec, this);
1455 Expression e = Convert.ImplicitConversion (ec, expr, type, loc);
1462 if (Convert.ExplicitReferenceConversionExists (etype, type)){
1463 if (TypeManager.IsGenericParameter (etype))
1464 expr = new BoxedCast (expr, etype);
1470 if (TypeManager.ContainsGenericParameters (etype) ||
1471 TypeManager.ContainsGenericParameters (type)) {
1472 expr = new BoxedCast (expr, etype);
1477 ec.Report.Error (39, loc, "Cannot convert type `{0}' to `{1}' via a built-in conversion",
1478 TypeManager.CSharpName (etype), TypeManager.CSharpName (type));
1483 protected override string OperatorName {
1484 get { return "as"; }
1489 // This represents a typecast in the source language.
1491 public class Cast : ShimExpression {
1492 Expression target_type;
1494 public Cast (Expression cast_type, Expression expr, Location loc)
1497 this.target_type = cast_type;
1501 public Expression TargetType {
1502 get { return target_type; }
1505 protected override Expression DoResolve (ResolveContext ec)
1507 expr = expr.Resolve (ec);
1511 TypeExpr target = target_type.ResolveAsTypeTerminal (ec, false);
1517 if (type.IsStatic) {
1518 ec.Report.Error (716, loc, "Cannot convert to static type `{0}'", TypeManager.CSharpName (type));
1522 eclass = ExprClass.Value;
1524 Constant c = expr as Constant;
1526 c = c.TryReduce (ec, type, loc);
1531 if (type.IsPointer && !ec.IsUnsafe) {
1532 UnsafeError (ec, loc);
1533 } else if (expr.Type == InternalType.Dynamic) {
1534 Arguments arg = new Arguments (1);
1535 arg.Add (new Argument (expr));
1536 return new DynamicConversion (type, CSharpBinderFlags.ConvertExplicit, arg, loc).Resolve (ec);
1539 var res = Convert.ExplicitConversion (ec, expr, type, loc);
1541 return EmptyCast.Create (res, type);
1546 protected override void CloneTo (CloneContext clonectx, Expression t)
1548 Cast target = (Cast) t;
1550 target.target_type = target_type.Clone (clonectx);
1551 target.expr = expr.Clone (clonectx);
1555 public class ImplicitCast : ShimExpression
1559 public ImplicitCast (Expression expr, TypeSpec target, bool arrayAccess)
1562 this.loc = expr.Location;
1564 this.arrayAccess = arrayAccess;
1567 protected override Expression DoResolve (ResolveContext ec)
1569 expr = expr.Resolve (ec);
1574 expr = ConvertExpressionToArrayIndex (ec, expr);
1576 expr = Convert.ImplicitConversionRequired (ec, expr, type, loc);
1583 // C# 2.0 Default value expression
1585 public class DefaultValueExpression : Expression
1589 public DefaultValueExpression (Expression expr, Location loc)
1595 public override Expression CreateExpressionTree (ResolveContext ec)
1597 Arguments args = new Arguments (2);
1598 args.Add (new Argument (this));
1599 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
1600 return CreateExpressionFactoryCall (ec, "Constant", args);
1603 protected override Expression DoResolve (ResolveContext ec)
1605 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
1611 if (type.IsStatic) {
1612 ec.Report.Error (-244, loc, "The `default value' operator cannot be applied to an operand of a static type");
1616 return new NullLiteral (Location).ConvertImplicitly (ec, type);
1618 if (TypeManager.IsReferenceType (type))
1619 return new NullConstant (type, loc);
1621 Constant c = New.Constantify (type);
1623 return c.Resolve (ec);
1625 eclass = ExprClass.Variable;
1629 public override void Emit (EmitContext ec)
1631 LocalTemporary temp_storage = new LocalTemporary(type);
1633 temp_storage.AddressOf(ec, AddressOp.LoadStore);
1634 ec.Emit(OpCodes.Initobj, type);
1635 temp_storage.Emit(ec);
1638 protected override void CloneTo (CloneContext clonectx, Expression t)
1640 DefaultValueExpression target = (DefaultValueExpression) t;
1642 target.expr = expr.Clone (clonectx);
1647 /// Binary operators
1649 public class Binary : Expression, IDynamicBinder
1651 protected class PredefinedOperator {
1652 protected readonly TypeSpec left;
1653 protected readonly TypeSpec right;
1654 public readonly Operator OperatorsMask;
1655 public TypeSpec ReturnType;
1657 public PredefinedOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
1658 : this (ltype, rtype, op_mask, ltype)
1662 public PredefinedOperator (TypeSpec type, Operator op_mask, TypeSpec return_type)
1663 : this (type, type, op_mask, return_type)
1667 public PredefinedOperator (TypeSpec type, Operator op_mask)
1668 : this (type, type, op_mask, type)
1672 public PredefinedOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask, TypeSpec return_type)
1674 if ((op_mask & Operator.ValuesOnlyMask) != 0)
1675 throw new InternalErrorException ("Only masked values can be used");
1679 this.OperatorsMask = op_mask;
1680 this.ReturnType = return_type;
1683 public virtual Expression ConvertResult (ResolveContext ec, Binary b)
1685 b.type = ReturnType;
1687 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1688 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
1691 // A user operators does not support multiple user conversions, but decimal type
1692 // is considered to be predefined type therefore we apply predefined operators rules
1693 // and then look for decimal user-operator implementation
1695 if (left == TypeManager.decimal_type)
1696 return b.ResolveUserOperator (ec, b.left.Type, b.right.Type);
1698 var c = b.right as Constant;
1700 if (c.IsDefaultValue && (b.oper == Operator.Addition || b.oper == Operator.BitwiseOr || b.oper == Operator.Subtraction))
1701 return ReducedExpression.Create (b.left, b).Resolve (ec);
1702 if ((b.oper == Operator.Multiply || b.oper == Operator.Division) && c.IsOneInteger)
1703 return ReducedExpression.Create (b.left, b).Resolve (ec);
1707 c = b.left as Constant;
1709 if (c.IsDefaultValue && (b.oper == Operator.Addition || b.oper == Operator.BitwiseOr))
1710 return ReducedExpression.Create (b.right, b).Resolve (ec);
1711 if (b.oper == Operator.Multiply && c.IsOneInteger)
1712 return ReducedExpression.Create (b.right, b).Resolve (ec);
1719 public bool IsPrimitiveApplicable (TypeSpec ltype, TypeSpec rtype)
1722 // We are dealing with primitive types only
1724 return left == ltype && ltype == rtype;
1727 public virtual bool IsApplicable (ResolveContext ec, Expression lexpr, Expression rexpr)
1729 if (TypeManager.IsEqual (left, lexpr.Type) &&
1730 TypeManager.IsEqual (right, rexpr.Type))
1733 return Convert.ImplicitConversionExists (ec, lexpr, left) &&
1734 Convert.ImplicitConversionExists (ec, rexpr, right);
1737 public PredefinedOperator ResolveBetterOperator (ResolveContext ec, PredefinedOperator best_operator)
1740 if (left != null && best_operator.left != null) {
1741 result = MethodGroupExpr.BetterTypeConversion (ec, best_operator.left, left);
1745 // When second arguments are same as the first one, the result is same
1747 if (right != null && (left != right || best_operator.left != best_operator.right)) {
1748 result |= MethodGroupExpr.BetterTypeConversion (ec, best_operator.right, right);
1751 if (result == 0 || result > 2)
1754 return result == 1 ? best_operator : this;
1758 class PredefinedStringOperator : PredefinedOperator {
1759 public PredefinedStringOperator (TypeSpec type, Operator op_mask)
1760 : base (type, op_mask, type)
1762 ReturnType = TypeManager.string_type;
1765 public PredefinedStringOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
1766 : base (ltype, rtype, op_mask)
1768 ReturnType = TypeManager.string_type;
1771 public override Expression ConvertResult (ResolveContext ec, Binary b)
1774 // Use original expression for nullable arguments
1776 Nullable.Unwrap unwrap = b.left as Nullable.Unwrap;
1778 b.left = unwrap.Original;
1780 unwrap = b.right as Nullable.Unwrap;
1782 b.right = unwrap.Original;
1784 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1785 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
1788 // Start a new concat expression using converted expression
1790 return StringConcat.Create (ec, b.left, b.right, b.loc);
1794 class PredefinedShiftOperator : PredefinedOperator {
1795 public PredefinedShiftOperator (TypeSpec ltype, Operator op_mask) :
1796 base (ltype, TypeManager.int32_type, op_mask)
1800 public override Expression ConvertResult (ResolveContext ec, Binary b)
1802 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1804 Expression expr_tree_expr = Convert.ImplicitConversion (ec, b.right, TypeManager.int32_type, b.right.Location);
1806 int right_mask = left == TypeManager.int32_type || left == TypeManager.uint32_type ? 0x1f : 0x3f;
1809 // b = b.left >> b.right & (0x1f|0x3f)
1811 b.right = new Binary (Operator.BitwiseAnd,
1812 b.right, new IntConstant (right_mask, b.right.Location), b.loc).Resolve (ec);
1815 // Expression tree representation does not use & mask
1817 b.right = ReducedExpression.Create (b.right, expr_tree_expr).Resolve (ec);
1818 b.type = ReturnType;
1821 // Optimize shift by 0
1823 var c = b.right as Constant;
1824 if (c != null && c.IsDefaultValue)
1825 return ReducedExpression.Create (b.left, b).Resolve (ec);
1831 class PredefinedPointerOperator : PredefinedOperator {
1832 public PredefinedPointerOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
1833 : base (ltype, rtype, op_mask)
1837 public PredefinedPointerOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask, TypeSpec retType)
1838 : base (ltype, rtype, op_mask, retType)
1842 public PredefinedPointerOperator (TypeSpec type, Operator op_mask, TypeSpec return_type)
1843 : base (type, op_mask, return_type)
1847 public override bool IsApplicable (ResolveContext ec, Expression lexpr, Expression rexpr)
1850 if (!lexpr.Type.IsPointer)
1853 if (!Convert.ImplicitConversionExists (ec, lexpr, left))
1857 if (right == null) {
1858 if (!rexpr.Type.IsPointer)
1861 if (!Convert.ImplicitConversionExists (ec, rexpr, right))
1868 public override Expression ConvertResult (ResolveContext ec, Binary b)
1871 b.left = EmptyCast.Create (b.left, left);
1872 } else if (right != null) {
1873 b.right = EmptyCast.Create (b.right, right);
1876 TypeSpec r_type = ReturnType;
1877 Expression left_arg, right_arg;
1878 if (r_type == null) {
1881 right_arg = b.right;
1882 r_type = b.left.Type;
1886 r_type = b.right.Type;
1890 right_arg = b.right;
1893 return new PointerArithmetic (b.oper, left_arg, right_arg, r_type, b.loc).Resolve (ec);
1898 public enum Operator {
1899 Multiply = 0 | ArithmeticMask,
1900 Division = 1 | ArithmeticMask,
1901 Modulus = 2 | ArithmeticMask,
1902 Addition = 3 | ArithmeticMask | AdditionMask,
1903 Subtraction = 4 | ArithmeticMask | SubtractionMask,
1905 LeftShift = 5 | ShiftMask,
1906 RightShift = 6 | ShiftMask,
1908 LessThan = 7 | ComparisonMask | RelationalMask,
1909 GreaterThan = 8 | ComparisonMask | RelationalMask,
1910 LessThanOrEqual = 9 | ComparisonMask | RelationalMask,
1911 GreaterThanOrEqual = 10 | ComparisonMask | RelationalMask,
1912 Equality = 11 | ComparisonMask | EqualityMask,
1913 Inequality = 12 | ComparisonMask | EqualityMask,
1915 BitwiseAnd = 13 | BitwiseMask,
1916 ExclusiveOr = 14 | BitwiseMask,
1917 BitwiseOr = 15 | BitwiseMask,
1919 LogicalAnd = 16 | LogicalMask,
1920 LogicalOr = 17 | LogicalMask,
1925 ValuesOnlyMask = ArithmeticMask - 1,
1926 ArithmeticMask = 1 << 5,
1928 ComparisonMask = 1 << 7,
1929 EqualityMask = 1 << 8,
1930 BitwiseMask = 1 << 9,
1931 LogicalMask = 1 << 10,
1932 AdditionMask = 1 << 11,
1933 SubtractionMask = 1 << 12,
1934 RelationalMask = 1 << 13
1937 readonly Operator oper;
1938 protected Expression left, right;
1939 readonly bool is_compound;
1940 Expression enum_conversion;
1942 static PredefinedOperator[] standard_operators;
1943 static PredefinedOperator[] pointer_operators;
1945 public Binary (Operator oper, Expression left, Expression right, bool isCompound, Location loc)
1946 : this (oper, left, right, loc)
1948 this.is_compound = isCompound;
1951 public Binary (Operator oper, Expression left, Expression right, Location loc)
1959 public Operator Oper {
1966 /// Returns a stringified representation of the Operator
1968 string OperName (Operator oper)
1972 case Operator.Multiply:
1975 case Operator.Division:
1978 case Operator.Modulus:
1981 case Operator.Addition:
1984 case Operator.Subtraction:
1987 case Operator.LeftShift:
1990 case Operator.RightShift:
1993 case Operator.LessThan:
1996 case Operator.GreaterThan:
1999 case Operator.LessThanOrEqual:
2002 case Operator.GreaterThanOrEqual:
2005 case Operator.Equality:
2008 case Operator.Inequality:
2011 case Operator.BitwiseAnd:
2014 case Operator.BitwiseOr:
2017 case Operator.ExclusiveOr:
2020 case Operator.LogicalOr:
2023 case Operator.LogicalAnd:
2027 s = oper.ToString ();
2037 public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, Operator oper, Location loc)
2039 new Binary (oper, left, right, loc).Error_OperatorCannotBeApplied (ec, left, right);
2042 public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, string oper, Location loc)
2045 l = TypeManager.CSharpName (left.Type);
2046 r = TypeManager.CSharpName (right.Type);
2048 ec.Report.Error (19, loc, "Operator `{0}' cannot be applied to operands of type `{1}' and `{2}'",
2052 protected void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right)
2054 Error_OperatorCannotBeApplied (ec, left, right, OperName (oper), loc);
2058 // Converts operator to System.Linq.Expressions.ExpressionType enum name
2060 string GetOperatorExpressionTypeName ()
2063 case Operator.Addition:
2064 return is_compound ? "AddAssign" : "Add";
2065 case Operator.BitwiseAnd:
2066 return is_compound ? "AndAssign" : "And";
2067 case Operator.BitwiseOr:
2068 return is_compound ? "OrAssign" : "Or";
2069 case Operator.Division:
2070 return is_compound ? "DivideAssign" : "Divide";
2071 case Operator.ExclusiveOr:
2072 return is_compound ? "ExclusiveOrAssign" : "ExclusiveOr";
2073 case Operator.Equality:
2075 case Operator.GreaterThan:
2076 return "GreaterThan";
2077 case Operator.GreaterThanOrEqual:
2078 return "GreaterThanOrEqual";
2079 case Operator.Inequality:
2081 case Operator.LeftShift:
2082 return is_compound ? "LeftShiftAssign" : "LeftShift";
2083 case Operator.LessThan:
2085 case Operator.LessThanOrEqual:
2086 return "LessThanOrEqual";
2087 case Operator.LogicalAnd:
2089 case Operator.LogicalOr:
2091 case Operator.Modulus:
2092 return is_compound ? "ModuloAssign" : "Modulo";
2093 case Operator.Multiply:
2094 return is_compound ? "MultiplyAssign" : "Multiply";
2095 case Operator.RightShift:
2096 return is_compound ? "RightShiftAssign" : "RightShift";
2097 case Operator.Subtraction:
2098 return is_compound ? "SubtractAssign" : "Subtract";
2100 throw new NotImplementedException ("Unknown expression type operator " + oper.ToString ());
2104 static CSharp.Operator.OpType ConvertBinaryToUserOperator (Operator op)
2107 case Operator.Addition:
2108 return CSharp.Operator.OpType.Addition;
2109 case Operator.BitwiseAnd:
2110 case Operator.LogicalAnd:
2111 return CSharp.Operator.OpType.BitwiseAnd;
2112 case Operator.BitwiseOr:
2113 case Operator.LogicalOr:
2114 return CSharp.Operator.OpType.BitwiseOr;
2115 case Operator.Division:
2116 return CSharp.Operator.OpType.Division;
2117 case Operator.Equality:
2118 return CSharp.Operator.OpType.Equality;
2119 case Operator.ExclusiveOr:
2120 return CSharp.Operator.OpType.ExclusiveOr;
2121 case Operator.GreaterThan:
2122 return CSharp.Operator.OpType.GreaterThan;
2123 case Operator.GreaterThanOrEqual:
2124 return CSharp.Operator.OpType.GreaterThanOrEqual;
2125 case Operator.Inequality:
2126 return CSharp.Operator.OpType.Inequality;
2127 case Operator.LeftShift:
2128 return CSharp.Operator.OpType.LeftShift;
2129 case Operator.LessThan:
2130 return CSharp.Operator.OpType.LessThan;
2131 case Operator.LessThanOrEqual:
2132 return CSharp.Operator.OpType.LessThanOrEqual;
2133 case Operator.Modulus:
2134 return CSharp.Operator.OpType.Modulus;
2135 case Operator.Multiply:
2136 return CSharp.Operator.OpType.Multiply;
2137 case Operator.RightShift:
2138 return CSharp.Operator.OpType.RightShift;
2139 case Operator.Subtraction:
2140 return CSharp.Operator.OpType.Subtraction;
2142 throw new InternalErrorException (op.ToString ());
2146 public static void EmitOperatorOpcode (EmitContext ec, Operator oper, TypeSpec l)
2151 case Operator.Multiply:
2152 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2153 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2154 opcode = OpCodes.Mul_Ovf;
2155 else if (!IsFloat (l))
2156 opcode = OpCodes.Mul_Ovf_Un;
2158 opcode = OpCodes.Mul;
2160 opcode = OpCodes.Mul;
2164 case Operator.Division:
2166 opcode = OpCodes.Div_Un;
2168 opcode = OpCodes.Div;
2171 case Operator.Modulus:
2173 opcode = OpCodes.Rem_Un;
2175 opcode = OpCodes.Rem;
2178 case Operator.Addition:
2179 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2180 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2181 opcode = OpCodes.Add_Ovf;
2182 else if (!IsFloat (l))
2183 opcode = OpCodes.Add_Ovf_Un;
2185 opcode = OpCodes.Add;
2187 opcode = OpCodes.Add;
2190 case Operator.Subtraction:
2191 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2192 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2193 opcode = OpCodes.Sub_Ovf;
2194 else if (!IsFloat (l))
2195 opcode = OpCodes.Sub_Ovf_Un;
2197 opcode = OpCodes.Sub;
2199 opcode = OpCodes.Sub;
2202 case Operator.RightShift:
2204 opcode = OpCodes.Shr_Un;
2206 opcode = OpCodes.Shr;
2209 case Operator.LeftShift:
2210 opcode = OpCodes.Shl;
2213 case Operator.Equality:
2214 opcode = OpCodes.Ceq;
2217 case Operator.Inequality:
2218 ec.Emit (OpCodes.Ceq);
2219 ec.Emit (OpCodes.Ldc_I4_0);
2221 opcode = OpCodes.Ceq;
2224 case Operator.LessThan:
2226 opcode = OpCodes.Clt_Un;
2228 opcode = OpCodes.Clt;
2231 case Operator.GreaterThan:
2233 opcode = OpCodes.Cgt_Un;
2235 opcode = OpCodes.Cgt;
2238 case Operator.LessThanOrEqual:
2239 if (IsUnsigned (l) || IsFloat (l))
2240 ec.Emit (OpCodes.Cgt_Un);
2242 ec.Emit (OpCodes.Cgt);
2243 ec.Emit (OpCodes.Ldc_I4_0);
2245 opcode = OpCodes.Ceq;
2248 case Operator.GreaterThanOrEqual:
2249 if (IsUnsigned (l) || IsFloat (l))
2250 ec.Emit (OpCodes.Clt_Un);
2252 ec.Emit (OpCodes.Clt);
2254 ec.Emit (OpCodes.Ldc_I4_0);
2256 opcode = OpCodes.Ceq;
2259 case Operator.BitwiseOr:
2260 opcode = OpCodes.Or;
2263 case Operator.BitwiseAnd:
2264 opcode = OpCodes.And;
2267 case Operator.ExclusiveOr:
2268 opcode = OpCodes.Xor;
2272 throw new InternalErrorException (oper.ToString ());
2278 static bool IsUnsigned (TypeSpec t)
2283 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2284 t == TypeManager.ushort_type || t == TypeManager.byte_type);
2287 static bool IsFloat (TypeSpec t)
2289 return t == TypeManager.float_type || t == TypeManager.double_type;
2292 public static void Reset ()
2294 pointer_operators = standard_operators = null;
2297 Expression ResolveOperator (ResolveContext ec)
2299 TypeSpec l = left.Type;
2300 TypeSpec r = right.Type;
2302 bool primitives_only = false;
2304 if (standard_operators == null)
2305 CreateStandardOperatorsTable ();
2308 // Handles predefined primitive types
2310 if (TypeManager.IsPrimitiveType (l) && TypeManager.IsPrimitiveType (r)) {
2311 if ((oper & Operator.ShiftMask) == 0) {
2312 if (l != TypeManager.bool_type && !DoBinaryOperatorPromotion (ec))
2315 primitives_only = true;
2319 if (l.IsPointer || r.IsPointer)
2320 return ResolveOperatorPointer (ec, l, r);
2323 bool lenum = TypeManager.IsEnumType (l);
2324 bool renum = TypeManager.IsEnumType (r);
2325 if (lenum || renum) {
2326 expr = ResolveOperatorEnum (ec, lenum, renum, l, r);
2328 // TODO: Can this be ambiguous
2334 if ((oper == Operator.Addition || oper == Operator.Subtraction || (oper & Operator.EqualityMask) != 0) &&
2335 (TypeManager.IsDelegateType (l) || TypeManager.IsDelegateType (r))) {
2337 expr = ResolveOperatorDelegate (ec, l, r);
2339 // TODO: Can this be ambiguous
2345 expr = ResolveUserOperator (ec, l, r);
2349 // Predefined reference types equality
2350 if ((oper & Operator.EqualityMask) != 0) {
2351 expr = ResolveOperatorEqualityRerefence (ec, l, r);
2357 return ResolveOperatorPredefined (ec, standard_operators, primitives_only, null);
2360 // at least one of 'left' or 'right' is an enumeration constant (EnumConstant or SideEffectConstant or ...)
2361 // if 'left' is not an enumeration constant, create one from the type of 'right'
2362 Constant EnumLiftUp (ResolveContext ec, Constant left, Constant right, Location loc)
2365 case Operator.BitwiseOr:
2366 case Operator.BitwiseAnd:
2367 case Operator.ExclusiveOr:
2368 case Operator.Equality:
2369 case Operator.Inequality:
2370 case Operator.LessThan:
2371 case Operator.LessThanOrEqual:
2372 case Operator.GreaterThan:
2373 case Operator.GreaterThanOrEqual:
2374 if (TypeManager.IsEnumType (left.Type))
2377 if (left.IsZeroInteger)
2378 return left.TryReduce (ec, right.Type, loc);
2382 case Operator.Addition:
2383 case Operator.Subtraction:
2386 case Operator.Multiply:
2387 case Operator.Division:
2388 case Operator.Modulus:
2389 case Operator.LeftShift:
2390 case Operator.RightShift:
2391 if (TypeManager.IsEnumType (right.Type) || TypeManager.IsEnumType (left.Type))
2395 Error_OperatorCannotBeApplied (ec, this.left, this.right);
2400 // The `|' operator used on types which were extended is dangerous
2402 void CheckBitwiseOrOnSignExtended (ResolveContext ec)
2404 OpcodeCast lcast = left as OpcodeCast;
2405 if (lcast != null) {
2406 if (IsUnsigned (lcast.UnderlyingType))
2410 OpcodeCast rcast = right as OpcodeCast;
2411 if (rcast != null) {
2412 if (IsUnsigned (rcast.UnderlyingType))
2416 if (lcast == null && rcast == null)
2419 // FIXME: consider constants
2421 ec.Report.Warning (675, 3, loc,
2422 "The operator `|' used on the sign-extended type `{0}'. Consider casting to a smaller unsigned type first",
2423 TypeManager.CSharpName (lcast != null ? lcast.UnderlyingType : rcast.UnderlyingType));
2426 static void CreatePointerOperatorsTable ()
2428 var temp = new List<PredefinedPointerOperator> ();
2431 // Pointer arithmetic:
2433 // T* operator + (T* x, int y); T* operator - (T* x, int y);
2434 // T* operator + (T* x, uint y); T* operator - (T* x, uint y);
2435 // T* operator + (T* x, long y); T* operator - (T* x, long y);
2436 // T* operator + (T* x, ulong y); T* operator - (T* x, ulong y);
2438 temp.Add (new PredefinedPointerOperator (null, TypeManager.int32_type, Operator.AdditionMask | Operator.SubtractionMask));
2439 temp.Add (new PredefinedPointerOperator (null, TypeManager.uint32_type, Operator.AdditionMask | Operator.SubtractionMask));
2440 temp.Add (new PredefinedPointerOperator (null, TypeManager.int64_type, Operator.AdditionMask | Operator.SubtractionMask));
2441 temp.Add (new PredefinedPointerOperator (null, TypeManager.uint64_type, Operator.AdditionMask | Operator.SubtractionMask));
2444 // T* operator + (int y, T* x);
2445 // T* operator + (uint y, T *x);
2446 // T* operator + (long y, T *x);
2447 // T* operator + (ulong y, T *x);
2449 temp.Add (new PredefinedPointerOperator (TypeManager.int32_type, null, Operator.AdditionMask, null));
2450 temp.Add (new PredefinedPointerOperator (TypeManager.uint32_type, null, Operator.AdditionMask, null));
2451 temp.Add (new PredefinedPointerOperator (TypeManager.int64_type, null, Operator.AdditionMask, null));
2452 temp.Add (new PredefinedPointerOperator (TypeManager.uint64_type, null, Operator.AdditionMask, null));
2455 // long operator - (T* x, T *y)
2457 temp.Add (new PredefinedPointerOperator (null, Operator.SubtractionMask, TypeManager.int64_type));
2459 pointer_operators = temp.ToArray ();
2462 static void CreateStandardOperatorsTable ()
2464 var temp = new List<PredefinedOperator> ();
2465 TypeSpec bool_type = TypeManager.bool_type;
2467 temp.Add (new PredefinedOperator (TypeManager.int32_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2468 temp.Add (new PredefinedOperator (TypeManager.uint32_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2469 temp.Add (new PredefinedOperator (TypeManager.int64_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2470 temp.Add (new PredefinedOperator (TypeManager.uint64_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2471 temp.Add (new PredefinedOperator (TypeManager.float_type, Operator.ArithmeticMask));
2472 temp.Add (new PredefinedOperator (TypeManager.double_type, Operator.ArithmeticMask));
2473 temp.Add (new PredefinedOperator (TypeManager.decimal_type, Operator.ArithmeticMask));
2475 temp.Add (new PredefinedOperator (TypeManager.int32_type, Operator.ComparisonMask, bool_type));
2476 temp.Add (new PredefinedOperator (TypeManager.uint32_type, Operator.ComparisonMask, bool_type));
2477 temp.Add (new PredefinedOperator (TypeManager.int64_type, Operator.ComparisonMask, bool_type));
2478 temp.Add (new PredefinedOperator (TypeManager.uint64_type, Operator.ComparisonMask, bool_type));
2479 temp.Add (new PredefinedOperator (TypeManager.float_type, Operator.ComparisonMask, bool_type));
2480 temp.Add (new PredefinedOperator (TypeManager.double_type, Operator.ComparisonMask, bool_type));
2481 temp.Add (new PredefinedOperator (TypeManager.decimal_type, Operator.ComparisonMask, bool_type));
2483 temp.Add (new PredefinedStringOperator (TypeManager.string_type, Operator.AdditionMask));
2484 temp.Add (new PredefinedStringOperator (TypeManager.string_type, TypeManager.object_type, Operator.AdditionMask));
2485 temp.Add (new PredefinedStringOperator (TypeManager.object_type, TypeManager.string_type, Operator.AdditionMask));
2487 temp.Add (new PredefinedOperator (bool_type,
2488 Operator.BitwiseMask | Operator.LogicalMask | Operator.EqualityMask, bool_type));
2490 temp.Add (new PredefinedShiftOperator (TypeManager.int32_type, Operator.ShiftMask));
2491 temp.Add (new PredefinedShiftOperator (TypeManager.uint32_type, Operator.ShiftMask));
2492 temp.Add (new PredefinedShiftOperator (TypeManager.int64_type, Operator.ShiftMask));
2493 temp.Add (new PredefinedShiftOperator (TypeManager.uint64_type, Operator.ShiftMask));
2495 standard_operators = temp.ToArray ();
2499 // Rules used during binary numeric promotion
2501 static bool DoNumericPromotion (ResolveContext rc, ref Expression prim_expr, ref Expression second_expr, TypeSpec type)
2506 Constant c = prim_expr as Constant;
2508 temp = c.ConvertImplicitly (rc, type);
2515 if (type == TypeManager.uint32_type) {
2516 etype = prim_expr.Type;
2517 if (etype == TypeManager.int32_type || etype == TypeManager.short_type || etype == TypeManager.sbyte_type) {
2518 type = TypeManager.int64_type;
2520 if (type != second_expr.Type) {
2521 c = second_expr as Constant;
2523 temp = c.ConvertImplicitly (rc, type);
2525 temp = Convert.ImplicitNumericConversion (second_expr, type);
2531 } else if (type == TypeManager.uint64_type) {
2533 // A compile-time error occurs if the other operand is of type sbyte, short, int, or long
2535 if (type == TypeManager.int32_type || type == TypeManager.int64_type ||
2536 type == TypeManager.short_type || type == TypeManager.sbyte_type)
2540 temp = Convert.ImplicitNumericConversion (prim_expr, type);
2549 // 7.2.6.2 Binary numeric promotions
2551 public bool DoBinaryOperatorPromotion (ResolveContext ec)
2553 TypeSpec ltype = left.Type;
2554 TypeSpec rtype = right.Type;
2557 foreach (TypeSpec t in ConstantFold.BinaryPromotionsTypes) {
2559 return t == rtype || DoNumericPromotion (ec, ref right, ref left, t);
2562 return t == ltype || DoNumericPromotion (ec, ref left, ref right, t);
2565 TypeSpec int32 = TypeManager.int32_type;
2566 if (ltype != int32) {
2567 Constant c = left as Constant;
2569 temp = c.ConvertImplicitly (ec, int32);
2571 temp = Convert.ImplicitNumericConversion (left, int32);
2578 if (rtype != int32) {
2579 Constant c = right as Constant;
2581 temp = c.ConvertImplicitly (ec, int32);
2583 temp = Convert.ImplicitNumericConversion (right, int32);
2593 protected override Expression DoResolve (ResolveContext ec)
2598 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2599 left = ((ParenthesizedExpression) left).Expr;
2600 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2604 if (left.eclass == ExprClass.Type) {
2605 ec.Report.Error (75, loc, "To cast a negative value, you must enclose the value in parentheses");
2609 left = left.Resolve (ec);
2614 Constant lc = left as Constant;
2616 if (lc != null && lc.Type == TypeManager.bool_type &&
2617 ((oper == Operator.LogicalAnd && lc.IsDefaultValue) ||
2618 (oper == Operator.LogicalOr && !lc.IsDefaultValue))) {
2620 // FIXME: resolve right expression as unreachable
2621 // right.Resolve (ec);
2623 ec.Report.Warning (429, 4, loc, "Unreachable expression code detected");
2627 right = right.Resolve (ec);
2631 eclass = ExprClass.Value;
2632 Constant rc = right as Constant;
2634 // The conversion rules are ignored in enum context but why
2635 if (!ec.HasSet (ResolveContext.Options.EnumScope) && lc != null && rc != null && (TypeManager.IsEnumType (left.Type) || TypeManager.IsEnumType (right.Type))) {
2636 lc = EnumLiftUp (ec, lc, rc, loc);
2638 rc = EnumLiftUp (ec, rc, lc, loc);
2641 if (rc != null && lc != null) {
2642 int prev_e = ec.Report.Errors;
2643 Expression e = ConstantFold.BinaryFold (ec, oper, lc, rc, loc);
2647 if (e != null || ec.Report.Errors != prev_e)
2651 // Comparison warnings
2652 if ((oper & Operator.ComparisonMask) != 0) {
2653 if (left.Equals (right)) {
2654 ec.Report.Warning (1718, 3, loc, "A comparison made to same variable. Did you mean to compare something else?");
2656 CheckUselessComparison (ec, lc, right.Type);
2657 CheckUselessComparison (ec, rc, left.Type);
2660 if (left.Type == InternalType.Dynamic || right.Type == InternalType.Dynamic) {
2661 Arguments args = new Arguments (2);
2662 args.Add (new Argument (left));
2663 args.Add (new Argument (right));
2664 return new DynamicExpressionStatement (this, args, loc).Resolve (ec);
2667 if (RootContext.Version >= LanguageVersion.ISO_2 &&
2668 ((TypeManager.IsNullableType (left.Type) && (right is NullLiteral || TypeManager.IsNullableType (right.Type) || TypeManager.IsValueType (right.Type))) ||
2669 (TypeManager.IsValueType (left.Type) && right is NullLiteral) ||
2670 (TypeManager.IsNullableType (right.Type) && (left is NullLiteral || TypeManager.IsNullableType (left.Type) || TypeManager.IsValueType (left.Type))) ||
2671 (TypeManager.IsValueType (right.Type) && left is NullLiteral)))
2672 return new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
2674 return DoResolveCore (ec, left, right);
2677 protected Expression DoResolveCore (ResolveContext ec, Expression left_orig, Expression right_orig)
2679 Expression expr = ResolveOperator (ec);
2681 Error_OperatorCannotBeApplied (ec, left_orig, right_orig);
2683 if (left == null || right == null)
2684 throw new InternalErrorException ("Invalid conversion");
2686 if (oper == Operator.BitwiseOr)
2687 CheckBitwiseOrOnSignExtended (ec);
2692 public override SLE.Expression MakeExpression (BuilderContext ctx)
2694 var le = left.MakeExpression (ctx);
2695 var re = right.MakeExpression (ctx);
2696 bool is_checked = ctx.HasSet (BuilderContext.Options.CheckedScope);
2699 case Operator.Addition:
2700 return is_checked ? SLE.Expression.AddChecked (le, re) : SLE.Expression.Add (le, re);
2701 case Operator.BitwiseAnd:
2702 return SLE.Expression.And (le, re);
2703 case Operator.BitwiseOr:
2704 return SLE.Expression.Or (le, re);
2705 case Operator.Division:
2706 return SLE.Expression.Divide (le, re);
2707 case Operator.Equality:
2708 return SLE.Expression.Equal (le, re);
2709 case Operator.ExclusiveOr:
2710 return SLE.Expression.ExclusiveOr (le, re);
2711 case Operator.GreaterThan:
2712 return SLE.Expression.GreaterThan (le, re);
2713 case Operator.GreaterThanOrEqual:
2714 return SLE.Expression.GreaterThanOrEqual (le, re);
2715 case Operator.Inequality:
2716 return SLE.Expression.NotEqual (le, re);
2717 case Operator.LeftShift:
2718 return SLE.Expression.LeftShift (le, re);
2719 case Operator.LessThan:
2720 return SLE.Expression.LessThan (le, re);
2721 case Operator.LessThanOrEqual:
2722 return SLE.Expression.LessThanOrEqual (le, re);
2723 case Operator.LogicalAnd:
2724 return SLE.Expression.AndAlso (le, re);
2725 case Operator.LogicalOr:
2726 return SLE.Expression.OrElse (le, re);
2727 case Operator.Modulus:
2728 return SLE.Expression.Modulo (le, re);
2729 case Operator.Multiply:
2730 return is_checked ? SLE.Expression.MultiplyChecked (le, re) : SLE.Expression.Multiply (le, re);
2731 case Operator.RightShift:
2732 return SLE.Expression.RightShift (le, re);
2733 case Operator.Subtraction:
2734 return is_checked ? SLE.Expression.SubtractChecked (le, re) : SLE.Expression.Subtract (le, re);
2736 throw new NotImplementedException (oper.ToString ());
2741 // D operator + (D x, D y)
2742 // D operator - (D x, D y)
2743 // bool operator == (D x, D y)
2744 // bool operator != (D x, D y)
2746 Expression ResolveOperatorDelegate (ResolveContext ec, TypeSpec l, TypeSpec r)
2748 bool is_equality = (oper & Operator.EqualityMask) != 0;
2749 if (!TypeManager.IsEqual (l, r) && !TypeSpecComparer.Variant.IsEqual (r, l)) {
2751 if (right.eclass == ExprClass.MethodGroup || (r == InternalType.AnonymousMethod && !is_equality)) {
2752 tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2757 } else if (left.eclass == ExprClass.MethodGroup || (l == InternalType.AnonymousMethod && !is_equality)) {
2758 tmp = Convert.ImplicitConversionRequired (ec, left, r, loc);
2769 Arguments args = new Arguments (2);
2770 args.Add (new Argument (left));
2771 args.Add (new Argument (right));
2773 if (oper == Operator.Addition) {
2774 if (TypeManager.delegate_combine_delegate_delegate == null) {
2775 TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
2776 TypeManager.delegate_type, "Combine", loc, TypeManager.delegate_type, TypeManager.delegate_type);
2779 method = TypeManager.delegate_combine_delegate_delegate;
2780 } else if (oper == Operator.Subtraction) {
2781 if (TypeManager.delegate_remove_delegate_delegate == null) {
2782 TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
2783 TypeManager.delegate_type, "Remove", loc, TypeManager.delegate_type, TypeManager.delegate_type);
2786 method = TypeManager.delegate_remove_delegate_delegate;
2787 } else if (oper == Operator.Equality) {
2788 if (TypeManager.delegate_equal == null) {
2789 TypeManager.delegate_equal = TypeManager.GetPredefinedMethod (
2790 TypeManager.delegate_type,
2791 new MemberFilter (CSharp.Operator.GetMetadataName (CSharp.Operator.OpType.Equality), 0, MemberKind.Operator,
2792 ParametersCompiled.CreateFullyResolved (new [] { TypeManager.delegate_type, TypeManager.delegate_type }), TypeManager.bool_type), loc);
2795 method = TypeManager.delegate_equal;
2797 if (TypeManager.delegate_inequal == null) {
2798 TypeManager.delegate_inequal = TypeManager.GetPredefinedMethod (
2799 TypeManager.delegate_type,
2800 new MemberFilter (CSharp.Operator.GetMetadataName (CSharp.Operator.OpType.Inequality), 0, MemberKind.Operator,
2801 ParametersCompiled.CreateFullyResolved (new [] { TypeManager.delegate_type, TypeManager.delegate_type }), TypeManager.bool_type), loc);
2804 method = TypeManager.delegate_inequal;
2808 return new EmptyExpression (TypeManager.decimal_type);
2810 MethodGroupExpr mg = MethodGroupExpr.CreatePredefined (method, TypeManager.delegate_type, loc);
2811 Expression expr = new UserOperatorCall (mg, args, CreateExpressionTree, loc);
2812 if (expr.Type != TypeManager.bool_type) {
2813 expr = new ClassCast (expr, l);
2820 // Enumeration operators
2822 Expression ResolveOperatorEnum (ResolveContext ec, bool lenum, bool renum, TypeSpec ltype, TypeSpec rtype)
2825 // bool operator == (E x, E y);
2826 // bool operator != (E x, E y);
2827 // bool operator < (E x, E y);
2828 // bool operator > (E x, E y);
2829 // bool operator <= (E x, E y);
2830 // bool operator >= (E x, E y);
2832 // E operator & (E x, E y);
2833 // E operator | (E x, E y);
2834 // E operator ^ (E x, E y);
2836 // U operator - (E e, E f)
2837 // E operator - (E e, U x)
2839 // E operator + (U x, E e)
2840 // E operator + (E e, U x)
2842 if (!((oper & (Operator.ComparisonMask | Operator.BitwiseMask)) != 0 ||
2843 (oper == Operator.Subtraction && lenum) ||
2844 (oper == Operator.Addition && (lenum != renum || type != null)))) // type != null for lifted null
2847 Expression ltemp = left;
2848 Expression rtemp = right;
2849 TypeSpec underlying_type;
2852 if ((oper & (Operator.ComparisonMask | Operator.BitwiseMask)) != 0) {
2854 expr = Convert.ImplicitConversion (ec, left, rtype, loc);
2860 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
2868 if (TypeManager.IsEqual (ltype, rtype)) {
2869 underlying_type = EnumSpec.GetUnderlyingType (ltype);
2871 if (left is Constant)
2872 left = ((Constant) left).ConvertExplicitly (false, underlying_type).Resolve (ec);
2874 left = EmptyCast.Create (left, underlying_type);
2876 if (right is Constant)
2877 right = ((Constant) right).ConvertExplicitly (false, underlying_type).Resolve (ec);
2879 right = EmptyCast.Create (right, underlying_type);
2881 underlying_type = EnumSpec.GetUnderlyingType (ltype);
2883 if (oper != Operator.Subtraction && oper != Operator.Addition) {
2884 Constant c = right as Constant;
2885 if (c == null || !c.IsDefaultValue)
2888 if (!Convert.ImplicitStandardConversionExists (right, underlying_type))
2891 right = Convert.ImplicitConversionStandard (ec, right, underlying_type, right.Location);
2894 if (left is Constant)
2895 left = ((Constant) left).ConvertExplicitly (false, underlying_type).Resolve (ec);
2897 left = EmptyCast.Create (left, underlying_type);
2900 underlying_type = EnumSpec.GetUnderlyingType (rtype);
2902 if (oper != Operator.Addition) {
2903 Constant c = left as Constant;
2904 if (c == null || !c.IsDefaultValue)
2907 if (!Convert.ImplicitStandardConversionExists (left, underlying_type))
2910 left = Convert.ImplicitConversionStandard (ec, left, underlying_type, left.Location);
2913 if (right is Constant)
2914 right = ((Constant) right).ConvertExplicitly (false, underlying_type).Resolve (ec);
2916 right = EmptyCast.Create (right, underlying_type);
2923 // C# specification uses explicit cast syntax which means binary promotion
2924 // should happen, however it seems that csc does not do that
2926 if (!DoBinaryOperatorPromotion (ec)) {
2932 TypeSpec res_type = null;
2933 if ((oper & Operator.BitwiseMask) != 0 || oper == Operator.Subtraction || oper == Operator.Addition) {
2934 TypeSpec promoted_type = lenum ? left.Type : right.Type;
2935 enum_conversion = Convert.ExplicitNumericConversion (
2936 new EmptyExpression (promoted_type), underlying_type);
2938 if (oper == Operator.Subtraction && renum && lenum)
2939 res_type = underlying_type;
2940 else if (oper == Operator.Addition && renum)
2946 expr = ResolveOperatorPredefined (ec, standard_operators, true, res_type);
2947 if (!is_compound || expr == null)
2955 // If the return type of the selected operator is implicitly convertible to the type of x
2957 if (Convert.ImplicitConversionExists (ec, expr, ltype))
2961 // Otherwise, if the selected operator is a predefined operator, if the return type of the
2962 // selected operator is explicitly convertible to the type of x, and if y is implicitly
2963 // convertible to the type of x or the operator is a shift operator, then the operation
2964 // is evaluated as x = (T)(x op y), where T is the type of x
2966 expr = Convert.ExplicitConversion (ec, expr, ltype, loc);
2970 if (Convert.ImplicitConversionExists (ec, ltemp, ltype))
2977 // 7.9.6 Reference type equality operators
2979 Expression ResolveOperatorEqualityRerefence (ResolveContext ec, TypeSpec l, TypeSpec r)
2982 // bool operator != (object a, object b)
2983 // bool operator == (object a, object b)
2985 // bool operator != (string a, string b)
2986 // bool operator == (string a, string b)
2989 // TODO: this method is almost equivalent to Convert.ImplicitReferenceConversion
2991 if (left.eclass == ExprClass.MethodGroup || right.eclass == ExprClass.MethodGroup)
2994 type = TypeManager.bool_type;
2996 var lgen = l as TypeParameterSpec;
2999 if (l is InternalType)
3004 // Only allow to compare same reference type parameter
3006 if (TypeManager.IsReferenceType (l)) {
3007 left = new BoxedCast (left, TypeManager.object_type);
3008 right = new BoxedCast (right, TypeManager.object_type);
3015 if (TypeManager.IsValueType (l))
3018 if (l == TypeManager.string_type) {
3019 Arguments args = new Arguments (2);
3020 args.Add (new Argument (left));
3021 args.Add (new Argument (right));
3024 if (oper == Operator.Equality) {
3025 if (TypeManager.string_equal == null) {
3026 TypeManager.string_equal = TypeManager.GetPredefinedMethod (TypeManager.string_type,
3027 new MemberFilter (CSharp.Operator.GetMetadataName (CSharp.Operator.OpType.Equality), 0, MemberKind.Operator, null, type), loc);
3030 method = TypeManager.string_equal;
3032 if (TypeManager.string_inequal == null) {
3033 TypeManager.string_inequal = TypeManager.GetPredefinedMethod (TypeManager.string_type,
3034 new MemberFilter (CSharp.Operator.GetMetadataName (CSharp.Operator.OpType.Inequality), 0, MemberKind.Operator, null, type), loc);
3037 method = TypeManager.string_inequal;
3041 return new EmptyExpression (type);
3043 var mg = MethodGroupExpr.CreatePredefined (method, TypeManager.string_type, loc);
3044 return new UserOperatorCall (mg, args, CreateExpressionTree, loc);
3047 if (l == TypeManager.delegate_type || l == TypeManager.multicast_delegate_type) {
3048 Arguments args = new Arguments (2);
3049 args.Add (new Argument (left));
3050 args.Add (new Argument (right));
3053 if (oper == Operator.Equality) {
3054 if (TypeManager.delegate_equal == null) {
3055 TypeManager.delegate_equal = TypeManager.GetPredefinedMethod (TypeManager.delegate_type,
3056 new MemberFilter (CSharp.Operator.GetMetadataName (CSharp.Operator.OpType.Equality), 0, MemberKind.Operator, null, type), loc);
3059 method = TypeManager.delegate_equal;
3061 if (TypeManager.delegate_inequal == null) {
3062 TypeManager.delegate_inequal = TypeManager.GetPredefinedMethod (TypeManager.delegate_type,
3063 new MemberFilter (CSharp.Operator.GetMetadataName (CSharp.Operator.OpType.Inequality), 0, MemberKind.Operator, null, type), loc);
3066 method = TypeManager.delegate_inequal;
3070 return new EmptyExpression (type);
3072 var mg = MethodGroupExpr.CreatePredefined (method, TypeManager.delegate_type, loc);
3073 return new UserOperatorCall (mg, args, CreateExpressionTree, loc);
3079 var rgen = r as TypeParameterSpec;
3082 // a, Both operands are reference-type values or the value null
3083 // b, One operand is a value of type T where T is a type-parameter and
3084 // the other operand is the value null. Furthermore T does not have the
3085 // value type constrain
3087 if (left is NullLiteral || right is NullLiteral) {
3089 if (lgen.HasSpecialStruct)
3092 left = new BoxedCast (left, TypeManager.object_type);
3097 if (rgen.HasSpecialStruct)
3100 right = new BoxedCast (right, TypeManager.object_type);
3106 // An interface is converted to the object before the
3107 // standard conversion is applied. It's not clear from the
3108 // standard but it looks like it works like that.
3111 if (!TypeManager.IsReferenceType (l))
3114 l = TypeManager.object_type;
3115 left = new BoxedCast (left, l);
3116 } else if (l.IsInterface) {
3117 l = TypeManager.object_type;
3118 } else if (TypeManager.IsStruct (l)) {
3123 if (!TypeManager.IsReferenceType (r))
3126 r = TypeManager.object_type;
3127 right = new BoxedCast (right, r);
3128 } else if (r.IsInterface) {
3129 r = TypeManager.object_type;
3130 } else if (TypeManager.IsStruct (r)) {
3135 const string ref_comparison = "Possible unintended reference comparison. " +
3136 "Consider casting the {0} side of the expression to `string' to compare the values";
3139 // A standard implicit conversion exists from the type of either
3140 // operand to the type of the other operand
3142 if (Convert.ImplicitReferenceConversionExists (left, r)) {
3143 if (l == TypeManager.string_type)
3144 ec.Report.Warning (253, 2, loc, ref_comparison, "right");
3149 if (Convert.ImplicitReferenceConversionExists (right, l)) {
3150 if (r == TypeManager.string_type)
3151 ec.Report.Warning (252, 2, loc, ref_comparison, "left");
3160 Expression ResolveOperatorPointer (ResolveContext ec, TypeSpec l, TypeSpec r)
3163 // bool operator == (void* x, void* y);
3164 // bool operator != (void* x, void* y);
3165 // bool operator < (void* x, void* y);
3166 // bool operator > (void* x, void* y);
3167 // bool operator <= (void* x, void* y);
3168 // bool operator >= (void* x, void* y);
3170 if ((oper & Operator.ComparisonMask) != 0) {
3173 temp = Convert.ImplicitConversion (ec, left, r, left.Location);
3180 temp = Convert.ImplicitConversion (ec, right, l, right.Location);
3186 type = TypeManager.bool_type;
3190 if (pointer_operators == null)
3191 CreatePointerOperatorsTable ();
3193 return ResolveOperatorPredefined (ec, pointer_operators, false, null);
3197 // Build-in operators method overloading
3199 protected virtual Expression ResolveOperatorPredefined (ResolveContext ec, PredefinedOperator [] operators, bool primitives_only, TypeSpec enum_type)
3201 PredefinedOperator best_operator = null;
3202 TypeSpec l = left.Type;
3203 TypeSpec r = right.Type;
3204 Operator oper_mask = oper & ~Operator.ValuesOnlyMask;
3206 foreach (PredefinedOperator po in operators) {
3207 if ((po.OperatorsMask & oper_mask) == 0)
3210 if (primitives_only) {
3211 if (!po.IsPrimitiveApplicable (l, r))
3214 if (!po.IsApplicable (ec, left, right))
3218 if (best_operator == null) {
3220 if (primitives_only)
3226 best_operator = po.ResolveBetterOperator (ec, best_operator);
3228 if (best_operator == null) {
3229 ec.Report.Error (34, loc, "Operator `{0}' is ambiguous on operands of type `{1}' and `{2}'",
3230 OperName (oper), TypeManager.CSharpName (l), TypeManager.CSharpName (r));
3237 if (best_operator == null)
3240 Expression expr = best_operator.ConvertResult (ec, this);
3243 // Optimize &/&& constant expressions with 0 value
3245 if (oper == Operator.BitwiseAnd || oper == Operator.LogicalAnd) {
3246 Constant rc = right as Constant;
3247 Constant lc = left as Constant;
3248 if ((lc != null && lc.IsDefaultValue) || (rc != null && rc.IsDefaultValue)) {
3250 // The result is a constant with side-effect
3252 Constant side_effect = rc == null ?
3253 new SideEffectConstant (lc, right, loc) :
3254 new SideEffectConstant (rc, left, loc);
3256 return ReducedExpression.Create (side_effect.Resolve (ec), expr);
3260 if (enum_type == null)
3264 // HACK: required by enum_conversion
3266 expr.Type = enum_type;
3267 return EmptyCast.Create (expr, enum_type);
3271 // Performs user-operator overloading
3273 protected virtual Expression ResolveUserOperator (ResolveContext ec, TypeSpec l, TypeSpec r)
3275 var op = ConvertBinaryToUserOperator (oper);
3276 IList<MemberSpec> left_operators = MemberCache.GetUserOperator (l, op, false);
3277 IList<MemberSpec> right_operators = null;
3280 right_operators = MemberCache.GetUserOperator (r, op, false);
3281 if (right_operators == null && left_operators == null)
3283 } else if (left_operators == null) {
3287 Arguments args = new Arguments (2);
3288 Argument larg = new Argument (left);
3290 Argument rarg = new Argument (right);
3294 // User-defined operator implementations always take precedence
3295 // over predefined operator implementations
3297 if (left_operators != null && right_operators != null) {
3298 left_operators = CombineUserOperators (left_operators, right_operators);
3299 } else if (right_operators != null) {
3300 left_operators = right_operators;
3303 var mg = new MethodGroupExpr (left_operators, l, loc);
3304 mg = mg.OverloadResolve (ec, ref args, true, loc);
3308 Expression oper_expr;
3310 // TODO: CreateExpressionTree is allocated every time
3311 if ((oper & Operator.LogicalMask) != 0) {
3312 oper_expr = new ConditionalLogicalOperator (mg, args, CreateExpressionTree,
3313 oper == Operator.LogicalAnd, loc).Resolve (ec);
3315 oper_expr = new UserOperatorCall (mg, args, CreateExpressionTree, loc);
3324 // Merge two sets of user operators into one, they are mostly distinguish
3325 // expect when they share base type and it contains an operator
3327 static IList<MemberSpec> CombineUserOperators (IList<MemberSpec> left, IList<MemberSpec> right)
3329 var combined = new List<MemberSpec> (left.Count + right.Count);
3330 combined.AddRange (left);
3331 foreach (var r in right) {
3333 foreach (var l in left) {
3334 if (l.DeclaringType == r.DeclaringType) {
3347 public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
3352 private void CheckUselessComparison (ResolveContext ec, Constant c, TypeSpec type)
3354 if (c == null || !IsTypeIntegral (type)
3355 || c is StringConstant
3356 || c is BoolConstant
3357 || c is FloatConstant
3358 || c is DoubleConstant
3359 || c is DecimalConstant
3365 if (c is ULongConstant) {
3366 ulong uvalue = ((ULongConstant) c).Value;
3367 if (uvalue > long.MaxValue) {
3368 if (type == TypeManager.byte_type ||
3369 type == TypeManager.sbyte_type ||
3370 type == TypeManager.short_type ||
3371 type == TypeManager.ushort_type ||
3372 type == TypeManager.int32_type ||
3373 type == TypeManager.uint32_type ||
3374 type == TypeManager.int64_type ||
3375 type == TypeManager.char_type)
3376 WarnUselessComparison (ec, type);
3379 value = (long) uvalue;
3381 else if (c is ByteConstant)
3382 value = ((ByteConstant) c).Value;
3383 else if (c is SByteConstant)
3384 value = ((SByteConstant) c).Value;
3385 else if (c is ShortConstant)
3386 value = ((ShortConstant) c).Value;
3387 else if (c is UShortConstant)
3388 value = ((UShortConstant) c).Value;
3389 else if (c is IntConstant)
3390 value = ((IntConstant) c).Value;
3391 else if (c is UIntConstant)
3392 value = ((UIntConstant) c).Value;
3393 else if (c is LongConstant)
3394 value = ((LongConstant) c).Value;
3395 else if (c is CharConstant)
3396 value = ((CharConstant)c).Value;
3401 if (IsValueOutOfRange (value, type))
3402 WarnUselessComparison (ec, type);
3405 static bool IsValueOutOfRange (long value, TypeSpec type)
3407 if (IsTypeUnsigned (type) && value < 0)
3409 return type == TypeManager.sbyte_type && (value >= 0x80 || value < -0x80) ||
3410 type == TypeManager.byte_type && value >= 0x100 ||
3411 type == TypeManager.short_type && (value >= 0x8000 || value < -0x8000) ||
3412 type == TypeManager.ushort_type && value >= 0x10000 ||
3413 type == TypeManager.int32_type && (value >= 0x80000000 || value < -0x80000000) ||
3414 type == TypeManager.uint32_type && value >= 0x100000000;
3417 private static bool IsTypeIntegral (TypeSpec type)
3419 return type == TypeManager.uint64_type ||
3420 type == TypeManager.int64_type ||
3421 type == TypeManager.uint32_type ||
3422 type == TypeManager.int32_type ||
3423 type == TypeManager.ushort_type ||
3424 type == TypeManager.short_type ||
3425 type == TypeManager.sbyte_type ||
3426 type == TypeManager.byte_type ||
3427 type == TypeManager.char_type;
3430 private static bool IsTypeUnsigned (TypeSpec type)
3432 return type == TypeManager.uint64_type ||
3433 type == TypeManager.uint32_type ||
3434 type == TypeManager.ushort_type ||
3435 type == TypeManager.byte_type ||
3436 type == TypeManager.char_type;
3439 private void WarnUselessComparison (ResolveContext ec, TypeSpec type)
3441 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}'",
3442 TypeManager.CSharpName (type));
3446 /// EmitBranchable is called from Statement.EmitBoolExpression in the
3447 /// context of a conditional bool expression. This function will return
3448 /// false if it is was possible to use EmitBranchable, or true if it was.
3450 /// The expression's code is generated, and we will generate a branch to `target'
3451 /// if the resulting expression value is equal to isTrue
3453 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
3456 // This is more complicated than it looks, but its just to avoid
3457 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
3458 // but on top of that we want for == and != to use a special path
3459 // if we are comparing against null
3461 if ((oper & Operator.EqualityMask) != 0 && (left is Constant || right is Constant)) {
3462 bool my_on_true = oper == Operator.Inequality ? on_true : !on_true;
3465 // put the constant on the rhs, for simplicity
3467 if (left is Constant) {
3468 Expression swap = right;
3474 // brtrue/brfalse works with native int only
3476 if (((Constant) right).IsZeroInteger && right.Type != TypeManager.int64_type && right.Type != TypeManager.uint64_type) {
3477 left.EmitBranchable (ec, target, my_on_true);
3480 if (right.Type == TypeManager.bool_type) {
3481 // right is a boolean, and it's not 'false' => it is 'true'
3482 left.EmitBranchable (ec, target, !my_on_true);
3486 } else if (oper == Operator.LogicalAnd) {
3489 Label tests_end = ec.DefineLabel ();
3491 left.EmitBranchable (ec, tests_end, false);
3492 right.EmitBranchable (ec, target, true);
3493 ec.MarkLabel (tests_end);
3496 // This optimizes code like this
3497 // if (true && i > 4)
3499 if (!(left is Constant))
3500 left.EmitBranchable (ec, target, false);
3502 if (!(right is Constant))
3503 right.EmitBranchable (ec, target, false);
3508 } else if (oper == Operator.LogicalOr){
3510 left.EmitBranchable (ec, target, true);
3511 right.EmitBranchable (ec, target, true);
3514 Label tests_end = ec.DefineLabel ();
3515 left.EmitBranchable (ec, tests_end, true);
3516 right.EmitBranchable (ec, target, false);
3517 ec.MarkLabel (tests_end);
3522 } else if ((oper & Operator.ComparisonMask) == 0) {
3523 base.EmitBranchable (ec, target, on_true);
3530 TypeSpec t = left.Type;
3531 bool is_float = IsFloat (t);
3532 bool is_unsigned = is_float || IsUnsigned (t);
3535 case Operator.Equality:
3537 ec.Emit (OpCodes.Beq, target);
3539 ec.Emit (OpCodes.Bne_Un, target);
3542 case Operator.Inequality:
3544 ec.Emit (OpCodes.Bne_Un, target);
3546 ec.Emit (OpCodes.Beq, target);
3549 case Operator.LessThan:
3551 if (is_unsigned && !is_float)
3552 ec.Emit (OpCodes.Blt_Un, target);
3554 ec.Emit (OpCodes.Blt, target);
3557 ec.Emit (OpCodes.Bge_Un, target);
3559 ec.Emit (OpCodes.Bge, target);
3562 case Operator.GreaterThan:
3564 if (is_unsigned && !is_float)
3565 ec.Emit (OpCodes.Bgt_Un, target);
3567 ec.Emit (OpCodes.Bgt, target);
3570 ec.Emit (OpCodes.Ble_Un, target);
3572 ec.Emit (OpCodes.Ble, target);
3575 case Operator.LessThanOrEqual:
3577 if (is_unsigned && !is_float)
3578 ec.Emit (OpCodes.Ble_Un, target);
3580 ec.Emit (OpCodes.Ble, target);
3583 ec.Emit (OpCodes.Bgt_Un, target);
3585 ec.Emit (OpCodes.Bgt, target);
3589 case Operator.GreaterThanOrEqual:
3591 if (is_unsigned && !is_float)
3592 ec.Emit (OpCodes.Bge_Un, target);
3594 ec.Emit (OpCodes.Bge, target);
3597 ec.Emit (OpCodes.Blt_Un, target);
3599 ec.Emit (OpCodes.Blt, target);
3602 throw new InternalErrorException (oper.ToString ());
3606 public override void Emit (EmitContext ec)
3608 EmitOperator (ec, left.Type);
3611 protected virtual void EmitOperator (EmitContext ec, TypeSpec l)
3614 // Handle short-circuit operators differently
3617 if ((oper & Operator.LogicalMask) != 0) {
3618 Label load_result = ec.DefineLabel ();
3619 Label end = ec.DefineLabel ();
3621 bool is_or = oper == Operator.LogicalOr;
3622 left.EmitBranchable (ec, load_result, is_or);
3624 ec.Emit (OpCodes.Br_S, end);
3626 ec.MarkLabel (load_result);
3627 ec.Emit (is_or ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
3633 // Optimize zero-based operations which cannot be optimized at expression level
3635 if (oper == Operator.Subtraction) {
3636 var lc = left as IntegralConstant;
3637 if (lc != null && lc.IsDefaultValue) {
3639 ec.Emit (OpCodes.Neg);
3646 EmitOperatorOpcode (ec, oper, l);
3649 // Nullable enum could require underlying type cast and we cannot simply wrap binary
3650 // expression because that would wrap lifted binary operation
3652 if (enum_conversion != null)
3653 enum_conversion.Emit (ec);
3656 public override void EmitSideEffect (EmitContext ec)
3658 if ((oper & Operator.LogicalMask) != 0 ||
3659 (ec.HasSet (EmitContext.Options.CheckedScope) && (oper == Operator.Multiply || oper == Operator.Addition || oper == Operator.Subtraction))) {
3660 base.EmitSideEffect (ec);
3662 left.EmitSideEffect (ec);
3663 right.EmitSideEffect (ec);
3667 protected override void CloneTo (CloneContext clonectx, Expression t)
3669 Binary target = (Binary) t;
3671 target.left = left.Clone (clonectx);
3672 target.right = right.Clone (clonectx);
3675 public Expression CreateCallSiteBinder (ResolveContext ec, Arguments args)
3677 Arguments binder_args = new Arguments (4);
3679 MemberAccess sle = new MemberAccess (new MemberAccess (
3680 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Linq", loc), "Expressions", loc);
3682 CSharpBinderFlags flags = 0;
3683 if (ec.HasSet (ResolveContext.Options.CheckedScope))
3684 flags = CSharpBinderFlags.CheckedContext;
3686 if ((oper & Operator.LogicalMask) != 0)
3687 flags |= CSharpBinderFlags.BinaryOperationLogical;
3689 binder_args.Add (new Argument (new EnumConstant (new IntLiteral ((int) flags, loc), TypeManager.binder_flags)));
3690 binder_args.Add (new Argument (new MemberAccess (new MemberAccess (sle, "ExpressionType", loc), GetOperatorExpressionTypeName (), loc)));
3691 binder_args.Add (new Argument (new TypeOf (new TypeExpression (ec.CurrentType, loc), loc)));
3692 binder_args.Add (new Argument (new ImplicitlyTypedArrayCreation (args.CreateDynamicBinderArguments (ec), loc)));
3694 return new Invocation (DynamicExpressionStatement.GetBinder ("BinaryOperation", loc), binder_args);
3697 public override Expression CreateExpressionTree (ResolveContext ec)
3699 return CreateExpressionTree (ec, null);
3702 Expression CreateExpressionTree (ResolveContext ec, MethodGroupExpr method)
3705 bool lift_arg = false;
3708 case Operator.Addition:
3709 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
3710 method_name = "AddChecked";
3712 method_name = "Add";
3714 case Operator.BitwiseAnd:
3715 method_name = "And";
3717 case Operator.BitwiseOr:
3720 case Operator.Division:
3721 method_name = "Divide";
3723 case Operator.Equality:
3724 method_name = "Equal";
3727 case Operator.ExclusiveOr:
3728 method_name = "ExclusiveOr";
3730 case Operator.GreaterThan:
3731 method_name = "GreaterThan";
3734 case Operator.GreaterThanOrEqual:
3735 method_name = "GreaterThanOrEqual";
3738 case Operator.Inequality:
3739 method_name = "NotEqual";
3742 case Operator.LeftShift:
3743 method_name = "LeftShift";
3745 case Operator.LessThan:
3746 method_name = "LessThan";
3749 case Operator.LessThanOrEqual:
3750 method_name = "LessThanOrEqual";
3753 case Operator.LogicalAnd:
3754 method_name = "AndAlso";
3756 case Operator.LogicalOr:
3757 method_name = "OrElse";
3759 case Operator.Modulus:
3760 method_name = "Modulo";
3762 case Operator.Multiply:
3763 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
3764 method_name = "MultiplyChecked";
3766 method_name = "Multiply";
3768 case Operator.RightShift:
3769 method_name = "RightShift";
3771 case Operator.Subtraction:
3772 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
3773 method_name = "SubtractChecked";
3775 method_name = "Subtract";
3779 throw new InternalErrorException ("Unknown expression tree binary operator " + oper);
3782 Arguments args = new Arguments (2);
3783 args.Add (new Argument (left.CreateExpressionTree (ec)));
3784 args.Add (new Argument (right.CreateExpressionTree (ec)));
3785 if (method != null) {
3787 args.Add (new Argument (new BoolConstant (false, loc)));
3789 args.Add (new Argument (method.CreateExpressionTree (ec)));
3792 return CreateExpressionFactoryCall (ec, method_name, args);
3797 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3798 // b, c, d... may be strings or objects.
3800 public class StringConcat : Expression {
3801 Arguments arguments;
3802 static IList<MemberSpec> concat_members;
3804 public StringConcat (Expression left, Expression right, Location loc)
3807 type = TypeManager.string_type;
3808 eclass = ExprClass.Value;
3810 arguments = new Arguments (2);
3813 public static StringConcat Create (ResolveContext rc, Expression left, Expression right, Location loc)
3815 if (left.eclass == ExprClass.Unresolved || right.eclass == ExprClass.Unresolved)
3816 throw new ArgumentException ();
3818 var s = new StringConcat (left, right, loc);
3819 s.Append (rc, left);
3820 s.Append (rc, right);
3824 public override Expression CreateExpressionTree (ResolveContext ec)
3826 Argument arg = arguments [0];
3827 return CreateExpressionAddCall (ec, arg, arg.CreateExpressionTree (ec), 1);
3831 // Creates nested calls tree from an array of arguments used for IL emit
3833 Expression CreateExpressionAddCall (ResolveContext ec, Argument left, Expression left_etree, int pos)
3835 Arguments concat_args = new Arguments (2);
3836 Arguments add_args = new Arguments (3);
3838 concat_args.Add (left);
3839 add_args.Add (new Argument (left_etree));
3841 concat_args.Add (arguments [pos]);
3842 add_args.Add (new Argument (arguments [pos].CreateExpressionTree (ec)));
3844 MethodGroupExpr method = CreateConcatMethodGroup ();
3848 method = method.OverloadResolve (ec, ref concat_args, false, loc);
3852 add_args.Add (new Argument (method.CreateExpressionTree (ec)));
3854 Expression expr = CreateExpressionFactoryCall (ec, "Add", add_args);
3855 if (++pos == arguments.Count)
3858 left = new Argument (new EmptyExpression (method.BestCandidate.ReturnType));
3859 return CreateExpressionAddCall (ec, left, expr, pos);
3862 protected override Expression DoResolve (ResolveContext ec)
3867 void Append (ResolveContext rc, Expression operand)
3872 StringConstant sc = operand as StringConstant;
3874 if (arguments.Count != 0) {
3875 Argument last_argument = arguments [arguments.Count - 1];
3876 StringConstant last_expr_constant = last_argument.Expr as StringConstant;
3877 if (last_expr_constant != null) {
3878 last_argument.Expr = new StringConstant (
3879 last_expr_constant.Value + sc.Value, sc.Location).Resolve (rc);
3885 // Multiple (3+) concatenation are resolved as multiple StringConcat instances
3887 StringConcat concat_oper = operand as StringConcat;
3888 if (concat_oper != null) {
3889 arguments.AddRange (concat_oper.arguments);
3894 arguments.Add (new Argument (operand));
3897 MethodGroupExpr CreateConcatMethodGroup ()
3899 if (concat_members == null) {
3900 concat_members = MemberCache.FindMembers (type,
3901 MemberFilter.Method ("Concat", -1, null, type), BindingRestriction.DeclaredOnly);
3904 return new MethodGroupExpr (concat_members, type, loc);
3907 public override void Emit (EmitContext ec)
3909 var mg = CreateConcatMethodGroup ();
3910 mg = mg.OverloadResolve (new ResolveContext (ec.MemberContext), ref arguments, false, loc);
3912 mg.EmitCall (ec, arguments);
3915 public override SLE.Expression MakeExpression (BuilderContext ctx)
3917 if (arguments.Count != 2)
3918 throw new NotImplementedException ("arguments.Count != 2");
3920 var concat = typeof (string).GetMethod ("Concat", new[] { typeof (object), typeof (object) });
3921 return SLE.Expression.Add (arguments[0].Expr.MakeExpression (ctx), arguments[1].Expr.MakeExpression (ctx), concat);
3924 public static void Reset ()
3926 concat_members = null;
3931 // User-defined conditional logical operator
3933 public class ConditionalLogicalOperator : UserOperatorCall {
3934 readonly bool is_and;
3937 public ConditionalLogicalOperator (MethodGroupExpr oper_method, Arguments arguments,
3938 ExpressionTreeExpression expr_tree, bool is_and, Location loc)
3939 : base (oper_method, arguments, expr_tree, loc)
3941 this.is_and = is_and;
3942 eclass = ExprClass.Unresolved;
3945 protected override Expression DoResolve (ResolveContext ec)
3947 var method = mg.BestCandidate;
3948 type = method.ReturnType;
3949 AParametersCollection pd = method.Parameters;
3950 if (!TypeManager.IsEqual (type, type) || !TypeManager.IsEqual (type, pd.Types [0]) || !TypeManager.IsEqual (type, pd.Types [1])) {
3951 ec.Report.Error (217, loc,
3952 "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",
3953 TypeManager.CSharpSignature (method));
3957 Expression left_dup = new EmptyExpression (type);
3958 Expression op_true = GetOperatorTrue (ec, left_dup, loc);
3959 Expression op_false = GetOperatorFalse (ec, left_dup, loc);
3960 if (op_true == null || op_false == null) {
3961 ec.Report.Error (218, loc,
3962 "The type `{0}' must have operator `true' and operator `false' defined when `{1}' is used as a short circuit operator",
3963 TypeManager.CSharpName (type), TypeManager.CSharpSignature (method));
3967 oper = is_and ? op_false : op_true;
3968 eclass = ExprClass.Value;
3972 public override void Emit (EmitContext ec)
3974 Label end_target = ec.DefineLabel ();
3977 // Emit and duplicate left argument
3979 arguments [0].Expr.Emit (ec);
3980 ec.Emit (OpCodes.Dup);
3981 arguments.RemoveAt (0);
3983 oper.EmitBranchable (ec, end_target, true);
3985 ec.MarkLabel (end_target);
3989 public class PointerArithmetic : Expression {
3990 Expression left, right;
3994 // We assume that `l' is always a pointer
3996 public PointerArithmetic (Binary.Operator op, Expression l, Expression r, TypeSpec t, Location loc)
4005 public override Expression CreateExpressionTree (ResolveContext ec)
4007 Error_PointerInsideExpressionTree (ec);
4011 protected override Expression DoResolve (ResolveContext ec)
4013 eclass = ExprClass.Variable;
4015 if (left.Type == TypeManager.void_ptr_type) {
4016 ec.Report.Error (242, loc, "The operation in question is undefined on void pointers");
4023 public override void Emit (EmitContext ec)
4025 TypeSpec op_type = left.Type;
4027 // It must be either array or fixed buffer
4029 if (TypeManager.HasElementType (op_type)) {
4030 element = TypeManager.GetElementType (op_type);
4032 FieldExpr fe = left as FieldExpr;
4034 element = ((FixedFieldSpec) (fe.Spec)).ElementType;
4039 int size = GetTypeSize (element);
4040 TypeSpec rtype = right.Type;
4042 if ((op & Binary.Operator.SubtractionMask) != 0 && rtype.IsPointer){
4044 // handle (pointer - pointer)
4048 ec.Emit (OpCodes.Sub);
4052 ec.Emit (OpCodes.Sizeof, element);
4055 ec.Emit (OpCodes.Div);
4057 ec.Emit (OpCodes.Conv_I8);
4060 // handle + and - on (pointer op int)
4062 Constant left_const = left as Constant;
4063 if (left_const != null) {
4065 // Optimize ((T*)null) pointer operations
4067 if (left_const.IsDefaultValue) {
4068 left = EmptyExpression.Null;
4076 var right_const = right as Constant;
4077 if (right_const != null) {
4079 // Optimize 0-based arithmetic
4081 if (right_const.IsDefaultValue)
4085 right = new IntConstant (size, right.Location);
4087 right = new SizeOf (new TypeExpression (element, right.Location), right.Location);
4089 // TODO: Should be the checks resolve context sensitive?
4090 ResolveContext rc = new ResolveContext (ec.MemberContext, ResolveContext.Options.UnsafeScope);
4091 right = new Binary (Binary.Operator.Multiply, right, right_const, loc).Resolve (rc);
4097 if (rtype == TypeManager.sbyte_type || rtype == TypeManager.byte_type ||
4098 rtype == TypeManager.short_type || rtype == TypeManager.ushort_type) {
4099 ec.Emit (OpCodes.Conv_I);
4100 } else if (rtype == TypeManager.uint32_type) {
4101 ec.Emit (OpCodes.Conv_U);
4104 if (right_const == null && size != 1){
4106 ec.Emit (OpCodes.Sizeof, element);
4109 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
4110 ec.Emit (OpCodes.Conv_I8);
4112 Binary.EmitOperatorOpcode (ec, Binary.Operator.Multiply, rtype);
4115 if (left_const == null) {
4116 if (rtype == TypeManager.int64_type)
4117 ec.Emit (OpCodes.Conv_I);
4118 else if (rtype == TypeManager.uint64_type)
4119 ec.Emit (OpCodes.Conv_U);
4121 Binary.EmitOperatorOpcode (ec, op, op_type);
4128 // A boolean-expression is an expression that yields a result
4131 public class BooleanExpression : ShimExpression
4133 public BooleanExpression (Expression expr)
4136 this.loc = expr.Location;
4139 public override Expression CreateExpressionTree (ResolveContext ec)
4141 // TODO: We should emit IsTrue (v4) instead of direct user operator
4142 // call but that would break csc compatibility
4143 return base.CreateExpressionTree (ec);
4146 protected override Expression DoResolve (ResolveContext ec)
4148 // A boolean-expression is required to be of a type
4149 // that can be implicitly converted to bool or of
4150 // a type that implements operator true
4152 expr = expr.Resolve (ec);
4156 Assign ass = expr as Assign;
4157 if (ass != null && ass.Source is Constant) {
4158 ec.Report.Warning (665, 3, loc,
4159 "Assignment in conditional expression is always constant. Did you mean to use `==' instead ?");
4162 if (expr.Type == TypeManager.bool_type)
4165 if (expr.Type == InternalType.Dynamic) {
4166 Arguments args = new Arguments (1);
4167 args.Add (new Argument (expr));
4168 return new DynamicUnaryConversion ("IsTrue", args, loc).Resolve (ec);
4171 type = TypeManager.bool_type;
4172 Expression converted = Convert.ImplicitConversion (ec, expr, type, loc);
4173 if (converted != null)
4177 // If no implicit conversion to bool exists, try using `operator true'
4179 converted = GetOperatorTrue (ec, expr, loc);
4180 if (converted == null) {
4181 expr.Error_ValueCannotBeConverted (ec, loc, type, false);
4190 /// Implements the ternary conditional operator (?:)
4192 public class Conditional : Expression {
4193 Expression expr, true_expr, false_expr;
4195 public Conditional (BooleanExpression expr, Expression true_expr, Expression false_expr, Location loc)
4198 this.true_expr = true_expr;
4199 this.false_expr = false_expr;
4203 public Expression Expr {
4209 public Expression TrueExpr {
4215 public Expression FalseExpr {
4221 public override Expression CreateExpressionTree (ResolveContext ec)
4223 Arguments args = new Arguments (3);
4224 args.Add (new Argument (expr.CreateExpressionTree (ec)));
4225 args.Add (new Argument (true_expr.CreateExpressionTree (ec)));
4226 args.Add (new Argument (false_expr.CreateExpressionTree (ec)));
4227 return CreateExpressionFactoryCall (ec, "Condition", args);
4230 protected override Expression DoResolve (ResolveContext ec)
4232 expr = expr.Resolve (ec);
4233 true_expr = true_expr.Resolve (ec);
4234 false_expr = false_expr.Resolve (ec);
4236 if (true_expr == null || false_expr == null || expr == null)
4239 eclass = ExprClass.Value;
4240 TypeSpec true_type = true_expr.Type;
4241 TypeSpec false_type = false_expr.Type;
4245 // First, if an implicit conversion exists from true_expr
4246 // to false_expr, then the result type is of type false_expr.Type
4248 if (!TypeManager.IsEqual (true_type, false_type)) {
4249 Expression conv = Convert.ImplicitConversion (ec, true_expr, false_type, loc);
4252 // Check if both can convert implicitly to each other's type
4254 if (Convert.ImplicitConversion (ec, false_expr, true_type, loc) != null) {
4255 ec.Report.Error (172, true_expr.Location,
4256 "Type of conditional expression cannot be determined as `{0}' and `{1}' convert implicitly to each other",
4257 TypeManager.CSharpName (true_type), TypeManager.CSharpName (false_type));
4262 } else if ((conv = Convert.ImplicitConversion (ec, false_expr, true_type, loc)) != null) {
4265 ec.Report.Error (173, true_expr.Location,
4266 "Type of conditional expression cannot be determined because there is no implicit conversion between `{0}' and `{1}'",
4267 TypeManager.CSharpName (true_type), TypeManager.CSharpName (false_type));
4272 // Dead code optimalization
4273 Constant c = expr as Constant;
4275 bool is_false = c.IsDefaultValue;
4276 ec.Report.Warning (429, 4, is_false ? true_expr.Location : false_expr.Location, "Unreachable expression code detected");
4277 return ReducedExpression.Create (is_false ? false_expr : true_expr, this).Resolve (ec);
4283 public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
4288 public override void Emit (EmitContext ec)
4290 Label false_target = ec.DefineLabel ();
4291 Label end_target = ec.DefineLabel ();
4293 expr.EmitBranchable (ec, false_target, false);
4294 true_expr.Emit (ec);
4296 if (type.IsInterface) {
4297 LocalBuilder temp = ec.GetTemporaryLocal (type);
4298 ec.Emit (OpCodes.Stloc, temp);
4299 ec.Emit (OpCodes.Ldloc, temp);
4300 ec.FreeTemporaryLocal (temp, type);
4303 ec.Emit (OpCodes.Br, end_target);
4304 ec.MarkLabel (false_target);
4305 false_expr.Emit (ec);
4306 ec.MarkLabel (end_target);
4309 protected override void CloneTo (CloneContext clonectx, Expression t)
4311 Conditional target = (Conditional) t;
4313 target.expr = expr.Clone (clonectx);
4314 target.true_expr = true_expr.Clone (clonectx);
4315 target.false_expr = false_expr.Clone (clonectx);
4319 public abstract class VariableReference : Expression, IAssignMethod, IMemoryLocation, IVariableReference {
4320 LocalTemporary temp;
4323 public abstract HoistedVariable GetHoistedVariable (AnonymousExpression ae);
4324 public abstract bool IsFixed { get; }
4325 public abstract bool IsRef { get; }
4326 public abstract string Name { get; }
4327 public abstract void SetHasAddressTaken ();
4330 // Variable IL data, it has to be protected to encapsulate hoisted variables
4332 protected abstract ILocalVariable Variable { get; }
4335 // Variable flow-analysis data
4337 public abstract VariableInfo VariableInfo { get; }
4340 public virtual void AddressOf (EmitContext ec, AddressOp mode)
4342 HoistedVariable hv = GetHoistedVariable (ec);
4344 hv.AddressOf (ec, mode);
4348 Variable.EmitAddressOf (ec);
4351 public HoistedVariable GetHoistedVariable (ResolveContext rc)
4353 return GetHoistedVariable (rc.CurrentAnonymousMethod);
4356 public HoistedVariable GetHoistedVariable (EmitContext ec)
4358 return GetHoistedVariable (ec.CurrentAnonymousMethod);
4361 public override string GetSignatureForError ()
4366 public override void Emit (EmitContext ec)
4371 public override void EmitSideEffect (EmitContext ec)
4377 // This method is used by parameters that are references, that are
4378 // being passed as references: we only want to pass the pointer (that
4379 // is already stored in the parameter, not the address of the pointer,
4380 // and not the value of the variable).
4382 public void EmitLoad (EmitContext ec)
4387 public void Emit (EmitContext ec, bool leave_copy)
4389 Report.Debug (64, "VARIABLE EMIT", this, Variable, type, IsRef, loc);
4391 HoistedVariable hv = GetHoistedVariable (ec);
4393 hv.Emit (ec, leave_copy);
4401 // If we are a reference, we loaded on the stack a pointer
4402 // Now lets load the real value
4404 ec.EmitLoadFromPtr (type);
4408 ec.Emit (OpCodes.Dup);
4411 temp = new LocalTemporary (Type);
4417 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy,
4418 bool prepare_for_load)
4420 HoistedVariable hv = GetHoistedVariable (ec);
4422 hv.EmitAssign (ec, source, leave_copy, prepare_for_load);
4426 New n_source = source as New;
4427 if (n_source != null) {
4428 if (!n_source.Emit (ec, this)) {
4441 ec.Emit (OpCodes.Dup);
4443 temp = new LocalTemporary (Type);
4449 ec.EmitStoreFromPtr (type);
4451 Variable.EmitAssign (ec);
4459 public bool IsHoisted {
4460 get { return GetHoistedVariable ((AnonymousExpression) null) != null; }
4467 public class LocalVariableReference : VariableReference {
4468 readonly string name;
4470 public LocalInfo local_info;
4473 public LocalVariableReference (Block block, string name, Location l)
4481 // Setting `is_readonly' to false will allow you to create a writable
4482 // reference to a read-only variable. This is used by foreach and using.
4484 public LocalVariableReference (Block block, string name, Location l,
4485 LocalInfo local_info, bool is_readonly)
4486 : this (block, name, l)
4488 this.local_info = local_info;
4489 this.is_readonly = is_readonly;
4492 public override VariableInfo VariableInfo {
4493 get { return local_info.VariableInfo; }
4496 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
4498 return local_info.HoistedVariant;
4502 // A local variable is always fixed
4504 public override bool IsFixed {
4505 get { return true; }
4508 public override bool IsRef {
4509 get { return false; }
4512 public bool IsReadOnly {
4513 get { return is_readonly; }
4516 public override string Name {
4517 get { return name; }
4520 public bool VerifyAssigned (ResolveContext ec)
4522 VariableInfo variable_info = local_info.VariableInfo;
4523 return variable_info == null || variable_info.IsAssigned (ec, loc);
4526 void ResolveLocalInfo ()
4528 if (local_info == null) {
4529 local_info = Block.GetLocalInfo (Name);
4530 type = local_info.VariableType;
4531 is_readonly = local_info.ReadOnly;
4535 public override void SetHasAddressTaken ()
4537 local_info.AddressTaken = true;
4540 public override Expression CreateExpressionTree (ResolveContext ec)
4542 HoistedVariable hv = GetHoistedVariable (ec);
4544 return hv.CreateExpressionTree ();
4546 Arguments arg = new Arguments (1);
4547 arg.Add (new Argument (this));
4548 return CreateExpressionFactoryCall (ec, "Constant", arg);
4551 Expression DoResolveBase (ResolveContext ec)
4553 Expression e = Block.GetConstantExpression (Name);
4555 return e.Resolve (ec);
4557 VerifyAssigned (ec);
4560 // If we are referencing a variable from the external block
4561 // flag it for capturing
4563 if (ec.MustCaptureVariable (local_info)) {
4564 if (local_info.AddressTaken)
4565 AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, this, loc);
4567 if (ec.IsVariableCapturingRequired) {
4568 AnonymousMethodStorey storey = local_info.Block.Explicit.CreateAnonymousMethodStorey (ec);
4569 storey.CaptureLocalVariable (ec, local_info);
4573 eclass = ExprClass.Variable;
4574 type = local_info.VariableType;
4578 protected override Expression DoResolve (ResolveContext ec)
4580 ResolveLocalInfo ();
4581 local_info.Used = true;
4583 if (type == null && local_info.Type is VarExpr) {
4584 local_info.VariableType = TypeManager.object_type;
4585 Error_VariableIsUsedBeforeItIsDeclared (ec.Report, Name);
4589 return DoResolveBase (ec);
4592 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
4594 ResolveLocalInfo ();
4597 if (right_side == EmptyExpression.OutAccess.Instance)
4598 local_info.Used = true;
4600 // Infer implicitly typed local variable
4602 VarExpr ve = local_info.Type as VarExpr;
4604 if (!ve.InferType (ec, right_side))
4606 type = local_info.VariableType = ve.Type;
4613 if (right_side == EmptyExpression.OutAccess.Instance) {
4614 code = 1657; msg = "Cannot pass `{0}' as a ref or out argument because it is a `{1}'";
4615 } else if (right_side == EmptyExpression.LValueMemberAccess) {
4616 code = 1654; msg = "Cannot assign to members of `{0}' because it is a `{1}'";
4617 } else if (right_side == EmptyExpression.LValueMemberOutAccess) {
4618 code = 1655; msg = "Cannot pass members of `{0}' as ref or out arguments because it is a `{1}'";
4619 } else if (right_side == EmptyExpression.UnaryAddress) {
4620 code = 459; msg = "Cannot take the address of {1} `{0}'";
4622 code = 1656; msg = "Cannot assign to `{0}' because it is a `{1}'";
4624 ec.Report.Error (code, loc, msg, Name, local_info.GetReadOnlyContext ());
4625 } else if (VariableInfo != null) {
4626 VariableInfo.SetAssigned (ec);
4629 return DoResolveBase (ec);
4632 public override int GetHashCode ()
4634 return Name.GetHashCode ();
4637 public override bool Equals (object obj)
4639 LocalVariableReference lvr = obj as LocalVariableReference;
4643 return Name == lvr.Name && Block == lvr.Block;
4646 protected override ILocalVariable Variable {
4647 get { return local_info; }
4650 public override string ToString ()
4652 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
4655 protected override void CloneTo (CloneContext clonectx, Expression t)
4657 LocalVariableReference target = (LocalVariableReference) t;
4659 target.Block = clonectx.LookupBlock (Block);
4660 if (local_info != null)
4661 target.local_info = clonectx.LookupVariable (local_info);
4666 /// This represents a reference to a parameter in the intermediate
4669 public class ParameterReference : VariableReference {
4670 readonly ToplevelParameterInfo pi;
4672 public ParameterReference (ToplevelParameterInfo pi, Location loc)
4678 public override bool IsRef {
4679 get { return (pi.Parameter.ModFlags & Parameter.Modifier.ISBYREF) != 0; }
4682 bool HasOutModifier {
4683 get { return pi.Parameter.ModFlags == Parameter.Modifier.OUT; }
4686 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
4688 return pi.Parameter.HoistedVariant;
4692 // A ref or out parameter is classified as a moveable variable, even
4693 // if the argument given for the parameter is a fixed variable
4695 public override bool IsFixed {
4696 get { return !IsRef; }
4699 public override string Name {
4700 get { return Parameter.Name; }
4703 public Parameter Parameter {
4704 get { return pi.Parameter; }
4707 public override VariableInfo VariableInfo {
4708 get { return pi.VariableInfo; }
4711 protected override ILocalVariable Variable {
4712 get { return Parameter; }
4715 public bool IsAssigned (ResolveContext ec, Location loc)
4717 // HACK: Variables are not captured in probing mode
4718 if (ec.IsInProbingMode)
4721 if (!ec.DoFlowAnalysis || !HasOutModifier || ec.CurrentBranching.IsAssigned (VariableInfo))
4724 ec.Report.Error (269, loc, "Use of unassigned out parameter `{0}'", Name);
4728 public override void SetHasAddressTaken ()
4730 Parameter.HasAddressTaken = true;
4733 void SetAssigned (ResolveContext ec)
4735 if (HasOutModifier && ec.DoFlowAnalysis)
4736 ec.CurrentBranching.SetAssigned (VariableInfo);
4739 bool DoResolveBase (ResolveContext ec)
4741 type = pi.ParameterType;
4742 eclass = ExprClass.Variable;
4744 AnonymousExpression am = ec.CurrentAnonymousMethod;
4748 Block b = ec.CurrentBlock;
4751 IParameterData[] p = b.Toplevel.Parameters.FixedParameters;
4752 for (int i = 0; i < p.Length; ++i) {
4753 if (p [i] != Parameter)
4757 // Don't capture local parameters
4759 if (b == ec.CurrentBlock.Toplevel && !am.IsIterator)
4763 ec.Report.Error (1628, loc,
4764 "Parameter `{0}' cannot be used inside `{1}' when using `ref' or `out' modifier",
4765 Name, am.ContainerType);
4768 if (pi.Parameter.HasAddressTaken)
4769 AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, this, loc);
4771 if (ec.IsVariableCapturingRequired && !b.Toplevel.IsExpressionTree) {
4772 AnonymousMethodStorey storey = pi.Block.CreateAnonymousMethodStorey (ec);
4773 storey.CaptureParameter (ec, this);
4785 public override int GetHashCode ()
4787 return Name.GetHashCode ();
4790 public override bool Equals (object obj)
4792 ParameterReference pr = obj as ParameterReference;
4796 return Name == pr.Name;
4799 public override void AddressOf (EmitContext ec, AddressOp mode)
4802 // ParameterReferences might already be a reference
4809 base.AddressOf (ec, mode);
4812 protected override void CloneTo (CloneContext clonectx, Expression target)
4817 public override Expression CreateExpressionTree (ResolveContext ec)
4819 HoistedVariable hv = GetHoistedVariable (ec);
4821 return hv.CreateExpressionTree ();
4823 return Parameter.ExpressionTreeVariableReference ();
4827 // Notice that for ref/out parameters, the type exposed is not the
4828 // same type exposed externally.
4831 // externally we expose "int&"
4832 // here we expose "int".
4834 // We record this in "is_ref". This means that the type system can treat
4835 // the type as it is expected, but when we generate the code, we generate
4836 // the alternate kind of code.
4838 protected override Expression DoResolve (ResolveContext ec)
4840 if (!DoResolveBase (ec))
4843 // HACK: Variables are not captured in probing mode
4844 if (ec.IsInProbingMode)
4847 if (HasOutModifier && ec.DoFlowAnalysis &&
4848 (!ec.OmitStructFlowAnalysis || !VariableInfo.TypeInfo.IsStruct) && !IsAssigned (ec, loc))
4854 override public Expression DoResolveLValue (ResolveContext ec, Expression right_side)
4856 if (!DoResolveBase (ec))
4863 static public void EmitLdArg (EmitContext ec, int x)
4866 case 0: ec.Emit (OpCodes.Ldarg_0); break;
4867 case 1: ec.Emit (OpCodes.Ldarg_1); break;
4868 case 2: ec.Emit (OpCodes.Ldarg_2); break;
4869 case 3: ec.Emit (OpCodes.Ldarg_3); break;
4871 if (x > byte.MaxValue)
4872 ec.Emit (OpCodes.Ldarg, x);
4874 ec.Emit (OpCodes.Ldarg_S, (byte) x);
4881 /// Invocation of methods or delegates.
4883 public class Invocation : ExpressionStatement
4885 protected Arguments arguments;
4886 protected Expression expr;
4887 protected MethodGroupExpr mg;
4888 bool arguments_resolved;
4891 // arguments is an ArrayList, but we do not want to typecast,
4892 // as it might be null.
4894 public Invocation (Expression expr, Arguments arguments)
4896 SimpleName sn = expr as SimpleName;
4898 this.expr = sn.GetMethodGroup ();
4902 this.arguments = arguments;
4904 loc = expr.Location;
4907 public Invocation (Expression expr, Arguments arguments, bool arguments_resolved)
4908 : this (expr, arguments)
4910 this.arguments_resolved = arguments_resolved;
4913 public override Expression CreateExpressionTree (ResolveContext ec)
4915 Expression instance = mg.IsInstance ?
4916 mg.InstanceExpression.CreateExpressionTree (ec) :
4917 new NullLiteral (loc);
4919 var args = Arguments.CreateForExpressionTree (ec, arguments,
4921 mg.CreateExpressionTree (ec));
4923 return CreateExpressionFactoryCall (ec, "Call", args);
4926 protected override Expression DoResolve (ResolveContext ec)
4928 Expression member_expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4929 if (member_expr == null)
4933 // Next, evaluate all the expressions in the argument list
4935 bool dynamic_arg = false;
4936 if (arguments != null && !arguments_resolved)
4937 arguments.Resolve (ec, out dynamic_arg);
4939 TypeSpec expr_type = member_expr.Type;
4940 mg = member_expr as MethodGroupExpr;
4942 bool dynamic_member = expr_type == InternalType.Dynamic;
4944 if (!dynamic_member) {
4945 Expression invoke = null;
4948 if (expr_type != null && TypeManager.IsDelegateType (expr_type)) {
4949 invoke = new DelegateInvocation (member_expr, arguments, loc);
4950 invoke = invoke.Resolve (ec);
4951 if (invoke == null || !dynamic_arg)
4954 MemberExpr me = member_expr as MemberExpr;
4956 member_expr.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup, loc);
4960 mg = ec.LookupExtensionMethod (me.Type, me.Name, -1, loc);
4962 ec.Report.Error (1955, loc, "The member `{0}' cannot be used as method or delegate",
4963 member_expr.GetSignatureForError ());
4967 ((ExtensionMethodGroupExpr) mg).ExtensionExpression = me.InstanceExpression;
4971 if (invoke == null) {
4972 mg = DoResolveOverload (ec);
4978 if (dynamic_arg || dynamic_member)
4979 return DoResolveDynamic (ec, member_expr);
4981 var method = mg.BestCandidate;
4982 if (method != null) {
4983 type = method.ReturnType;
4987 // Only base will allow this invocation to happen.
4989 if (mg.IsBase && method.IsAbstract){
4990 Error_CannotCallAbstractBase (ec, TypeManager.CSharpSignature (method));
4994 if (arguments == null && method.DeclaringType == TypeManager.object_type && method.Name == Destructor.MetadataName) {
4996 ec.Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
4998 ec.Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
5002 IsSpecialMethodInvocation (ec, method, loc);
5004 if (mg.InstanceExpression != null)
5005 mg.InstanceExpression.CheckMarshalByRefAccess (ec);
5007 eclass = ExprClass.Value;
5011 Expression DoResolveDynamic (ResolveContext ec, Expression memberExpr)
5014 DynamicMemberBinder dmb = memberExpr as DynamicMemberBinder;
5016 args = dmb.Arguments;
5017 if (arguments != null)
5018 args.AddRange (arguments);
5019 } else if (mg == null) {
5020 if (arguments == null)
5021 args = new Arguments (1);
5025 args.Insert (0, new Argument (memberExpr));
5029 ec.Report.Error (1971, loc,
5030 "The base call to method `{0}' cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access",
5035 if (arguments == null)
5036 args = new Arguments (1);
5040 MemberAccess ma = expr as MemberAccess;
5042 var left_type = ma.Left as TypeExpr;
5043 if (left_type != null) {
5044 args.Insert (0, new Argument (new TypeOf (left_type, loc).Resolve (ec), Argument.AType.DynamicTypeName));
5046 args.Insert (0, new Argument (ma.Left));
5048 } else { // is SimpleName
5050 args.Insert (0, new Argument (new TypeOf (new TypeExpression (ec.CurrentType, loc), loc).Resolve (ec), Argument.AType.DynamicTypeName));
5052 args.Insert (0, new Argument (new This (loc).Resolve (ec)));
5057 return new DynamicInvocation (expr as ATypeNameExpression, args, loc).Resolve (ec);
5060 protected virtual MethodGroupExpr DoResolveOverload (ResolveContext ec)
5062 return mg.OverloadResolve (ec, ref arguments, false, loc);
5065 public static bool IsSpecialMethodInvocation (ResolveContext ec, MethodSpec method, Location loc)
5067 if (!method.IsReservedMethod)
5070 if (ec.HasSet (ResolveContext.Options.InvokeSpecialName))
5073 ec.Report.SymbolRelatedToPreviousError (method);
5074 ec.Report.Error (571, loc, "`{0}': cannot explicitly call operator or accessor",
5075 method.GetSignatureForError ());
5080 static Type[] GetVarargsTypes (MethodSpec mb, Arguments arguments)
5082 AParametersCollection pd = mb.Parameters;
5084 Argument a = arguments [pd.Count - 1];
5085 Arglist list = (Arglist) a.Expr;
5087 return list.ArgumentTypes;
5091 /// is_base tells whether we want to force the use of the `call'
5092 /// opcode instead of using callvirt. Call is required to call
5093 /// a specific method, while callvirt will always use the most
5094 /// recent method in the vtable.
5096 /// is_static tells whether this is an invocation on a static method
5098 /// instance_expr is an expression that represents the instance
5099 /// it must be non-null if is_static is false.
5101 /// method is the method to invoke.
5103 /// Arguments is the list of arguments to pass to the method or constructor.
5105 public static void EmitCall (EmitContext ec, Expression instance_expr,
5106 MethodSpec method, Arguments Arguments, Location loc)
5108 EmitCall (ec, instance_expr, method, Arguments, loc, false, false);
5111 // `dup_args' leaves an extra copy of the arguments on the stack
5112 // `omit_args' does not leave any arguments at all.
5113 // So, basically, you could make one call with `dup_args' set to true,
5114 // and then another with `omit_args' set to true, and the two calls
5115 // would have the same set of arguments. However, each argument would
5116 // only have been evaluated once.
5117 public static void EmitCall (EmitContext ec, Expression instance_expr,
5118 MethodSpec method, Arguments Arguments, Location loc,
5119 bool dup_args, bool omit_args)
5121 LocalTemporary this_arg = null;
5123 TypeSpec decl_type = method.DeclaringType;
5125 // Speed up the check by not doing it on not allowed targets
5126 if (method.ReturnType == TypeManager.void_type && method.IsConditionallyExcluded (loc))
5130 TypeSpec iexpr_type;
5132 if (method.IsStatic) {
5134 call_op = OpCodes.Call;
5136 iexpr_type = instance_expr.Type;
5138 if (decl_type.IsStruct || decl_type.IsEnum || (instance_expr is This && !method.IsVirtual) || (instance_expr is BaseThis)) {
5139 call_op = OpCodes.Call;
5141 call_op = OpCodes.Callvirt;
5145 // If this is ourselves, push "this"
5148 TypeSpec t = iexpr_type;
5151 // Push the instance expression
5153 if ((iexpr_type.IsStruct && (call_op == OpCodes.Callvirt || (call_op == OpCodes.Call && decl_type == iexpr_type))) ||
5154 iexpr_type.IsGenericParameter || TypeManager.IsNullableType (decl_type)) {
5156 // If the expression implements IMemoryLocation, then
5157 // we can optimize and use AddressOf on the
5160 // If not we have to use some temporary storage for
5162 var iml = instance_expr as IMemoryLocation;
5164 iml.AddressOf (ec, AddressOp.LoadStore);
5166 LocalTemporary temp = new LocalTemporary (iexpr_type);
5167 instance_expr.Emit (ec);
5169 temp.AddressOf (ec, AddressOp.Load);
5172 // avoid the overhead of doing this all the time.
5174 t = ReferenceContainer.MakeType (iexpr_type);
5175 } else if (iexpr_type.IsEnum || iexpr_type.IsStruct) {
5176 instance_expr.Emit (ec);
5177 ec.Emit (OpCodes.Box, iexpr_type);
5178 t = iexpr_type = TypeManager.object_type;
5180 instance_expr.Emit (ec);
5184 ec.Emit (OpCodes.Dup);
5185 if (Arguments != null && Arguments.Count != 0) {
5186 this_arg = new LocalTemporary (t);
5187 this_arg.Store (ec);
5193 if (!omit_args && Arguments != null)
5194 Arguments.Emit (ec, dup_args, this_arg);
5196 if (call_op == OpCodes.Callvirt && (iexpr_type.IsGenericParameter || iexpr_type.IsStruct)) {
5197 ec.Emit (OpCodes.Constrained, iexpr_type);
5200 if (method.Parameters.HasArglist) {
5201 Type[] varargs_types = GetVarargsTypes (method, Arguments);
5202 ec.Emit (call_op, method, varargs_types);
5209 // and DoFoo is not virtual, you can omit the callvirt,
5210 // because you don't need the null checking behavior.
5212 ec.Emit (call_op, method);
5215 public override void Emit (EmitContext ec)
5217 mg.EmitCall (ec, arguments);
5220 public override void EmitStatement (EmitContext ec)
5225 // Pop the return value if there is one
5227 if (type != TypeManager.void_type)
5228 ec.Emit (OpCodes.Pop);
5231 protected override void CloneTo (CloneContext clonectx, Expression t)
5233 Invocation target = (Invocation) t;
5235 if (arguments != null)
5236 target.arguments = arguments.Clone (clonectx);
5238 target.expr = expr.Clone (clonectx);
5241 public override SLE.Expression MakeExpression (BuilderContext ctx)
5243 return MakeExpression (ctx, mg.InstanceExpression, mg.BestCandidate, arguments);
5246 public static SLE.Expression MakeExpression (BuilderContext ctx, Expression instance, MethodSpec mi, Arguments args)
5248 var instance_expr = instance == null ? null : instance.MakeExpression (ctx);
5249 return SLE.Expression.Call (instance_expr, (MethodInfo) mi.GetMetaInfo (), Arguments.MakeExpression (args, ctx));
5254 /// Implements the new expression
5256 public class New : ExpressionStatement, IMemoryLocation {
5257 protected Arguments Arguments;
5260 // During bootstrap, it contains the RequestedType,
5261 // but if `type' is not null, it *might* contain a NewDelegate
5262 // (because of field multi-initialization)
5264 protected Expression RequestedType;
5266 protected MethodGroupExpr method;
5268 public New (Expression requested_type, Arguments arguments, Location l)
5270 RequestedType = requested_type;
5271 Arguments = arguments;
5276 /// Converts complex core type syntax like 'new int ()' to simple constant
5278 public static Constant Constantify (TypeSpec t)
5280 if (t == TypeManager.int32_type)
5281 return new IntConstant (0, Location.Null);
5282 if (t == TypeManager.uint32_type)
5283 return new UIntConstant (0, Location.Null);
5284 if (t == TypeManager.int64_type)
5285 return new LongConstant (0, Location.Null);
5286 if (t == TypeManager.uint64_type)
5287 return new ULongConstant (0, Location.Null);
5288 if (t == TypeManager.float_type)
5289 return new FloatConstant (0, Location.Null);
5290 if (t == TypeManager.double_type)
5291 return new DoubleConstant (0, Location.Null);
5292 if (t == TypeManager.short_type)
5293 return new ShortConstant (0, Location.Null);
5294 if (t == TypeManager.ushort_type)
5295 return new UShortConstant (0, Location.Null);
5296 if (t == TypeManager.sbyte_type)
5297 return new SByteConstant (0, Location.Null);
5298 if (t == TypeManager.byte_type)
5299 return new ByteConstant (0, Location.Null);
5300 if (t == TypeManager.char_type)
5301 return new CharConstant ('\0', Location.Null);
5302 if (t == TypeManager.bool_type)
5303 return new BoolConstant (false, Location.Null);
5304 if (t == TypeManager.decimal_type)
5305 return new DecimalConstant (0, Location.Null);
5306 if (TypeManager.IsEnumType (t))
5307 return new EnumConstant (Constantify (EnumSpec.GetUnderlyingType (t)), t);
5308 if (TypeManager.IsNullableType (t))
5309 return Nullable.LiftedNull.Create (t, Location.Null);
5315 // Checks whether the type is an interface that has the
5316 // [ComImport, CoClass] attributes and must be treated
5319 public Expression CheckComImport (ResolveContext ec)
5321 if (!type.IsInterface)
5325 // Turn the call into:
5326 // (the-interface-stated) (new class-referenced-in-coclassattribute ())
5328 var real_class = type.MemberDefinition.GetAttributeCoClass ();
5329 if (real_class == null)
5332 New proxy = new New (new TypeExpression (real_class, loc), Arguments, loc);
5333 Cast cast = new Cast (new TypeExpression (type, loc), proxy, loc);
5334 return cast.Resolve (ec);
5337 public override Expression CreateExpressionTree (ResolveContext ec)
5340 if (method == null) {
5341 args = new Arguments (1);
5342 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
5344 args = Arguments.CreateForExpressionTree (ec,
5346 method.CreateExpressionTree (ec));
5349 return CreateExpressionFactoryCall (ec, "New", args);
5352 protected override Expression DoResolve (ResolveContext ec)
5354 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec, false);
5360 if (type.IsPointer) {
5361 ec.Report.Error (1919, loc, "Unsafe type `{0}' cannot be used in an object creation expression",
5362 TypeManager.CSharpName (type));
5366 if (Arguments == null) {
5367 Constant c = Constantify (type);
5369 return ReducedExpression.Create (c.Resolve (ec), this);
5372 if (TypeManager.IsDelegateType (type)) {
5373 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5376 var tparam = type as TypeParameterSpec;
5377 if (tparam != null) {
5378 if (!tparam.HasSpecialConstructor && !tparam.HasSpecialStruct) {
5379 ec.Report.Error (304, loc,
5380 "Cannot create an instance of the variable type `{0}' because it does not have the new() constraint",
5381 TypeManager.CSharpName (type));
5384 if ((Arguments != null) && (Arguments.Count != 0)) {
5385 ec.Report.Error (417, loc,
5386 "`{0}': cannot provide arguments when creating an instance of a variable type",
5387 TypeManager.CSharpName (type));
5390 if (TypeManager.activator_create_instance == null) {
5391 TypeSpec activator_type = TypeManager.CoreLookupType (ec.Compiler, "System", "Activator", MemberKind.Class, true);
5392 if (activator_type != null) {
5393 TypeManager.activator_create_instance = TypeManager.GetPredefinedMethod (
5394 activator_type, MemberFilter.Method ("CreateInstance", 1, ParametersCompiled.EmptyReadOnlyParameters, null), loc);
5398 eclass = ExprClass.Value;
5402 if (type.IsStatic) {
5403 ec.Report.SymbolRelatedToPreviousError (type);
5404 ec.Report.Error (712, loc, "Cannot create an instance of the static class `{0}'", TypeManager.CSharpName (type));
5408 if (type.IsInterface || type.IsAbstract){
5409 if (!TypeManager.IsGenericType (type)) {
5410 RequestedType = CheckComImport (ec);
5411 if (RequestedType != null)
5412 return RequestedType;
5415 ec.Report.SymbolRelatedToPreviousError (type);
5416 ec.Report.Error (144, loc, "Cannot create an instance of the abstract class or interface `{0}'", TypeManager.CSharpName (type));
5420 bool is_struct = TypeManager.IsStruct (type);
5421 eclass = ExprClass.Value;
5424 // SRE returns a match for .ctor () on structs (the object constructor),
5425 // so we have to manually ignore it.
5427 if (is_struct && Arguments == null)
5430 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
5431 Expression ml = MemberLookupFinal (ec, type, type, ConstructorInfo.ConstructorName, 0,
5432 MemberKind.Constructor, BindingRestriction.AccessibleOnly | BindingRestriction.DeclaredOnly, loc);
5435 if (Arguments != null) {
5436 Arguments.Resolve (ec, out dynamic);
5444 method = ml as MethodGroupExpr;
5445 if (method == null) {
5446 ml.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup, loc);
5450 method = method.OverloadResolve (ec, ref Arguments, false, loc);
5455 Arguments.Insert (0, new Argument (new TypeOf (texpr, loc).Resolve (ec), Argument.AType.DynamicTypeName));
5456 return new DynamicConstructorBinder (type, Arguments, loc).Resolve (ec);
5462 bool DoEmitTypeParameter (EmitContext ec)
5464 var ctor_factory = TypeManager.activator_create_instance.MakeGenericMethod (type);
5465 var tparam = (TypeParameterSpec) type;
5467 if (tparam.IsReferenceType) {
5468 ec.Emit (OpCodes.Call, ctor_factory);
5472 // Allow DoEmit() to be called multiple times.
5473 // We need to create a new LocalTemporary each time since
5474 // you can't share LocalBuilders among ILGeneators.
5475 LocalTemporary temp = new LocalTemporary (type);
5477 Label label_activator = ec.DefineLabel ();
5478 Label label_end = ec.DefineLabel ();
5480 temp.AddressOf (ec, AddressOp.Store);
5481 ec.Emit (OpCodes.Initobj, type);
5484 ec.Emit (OpCodes.Box, type);
5485 ec.Emit (OpCodes.Brfalse, label_activator);
5487 temp.AddressOf (ec, AddressOp.Store);
5488 ec.Emit (OpCodes.Initobj, type);
5490 ec.Emit (OpCodes.Br_S, label_end);
5492 ec.MarkLabel (label_activator);
5494 ec.Emit (OpCodes.Call, ctor_factory);
5495 ec.MarkLabel (label_end);
5500 // This Emit can be invoked in two contexts:
5501 // * As a mechanism that will leave a value on the stack (new object)
5502 // * As one that wont (init struct)
5504 // If we are dealing with a ValueType, we have a few
5505 // situations to deal with:
5507 // * The target is a ValueType, and we have been provided
5508 // the instance (this is easy, we are being assigned).
5510 // * The target of New is being passed as an argument,
5511 // to a boxing operation or a function that takes a
5514 // In this case, we need to create a temporary variable
5515 // that is the argument of New.
5517 // Returns whether a value is left on the stack
5519 // *** Implementation note ***
5521 // To benefit from this optimization, each assignable expression
5522 // has to manually cast to New and call this Emit.
5524 // TODO: It's worth to implement it for arrays and fields
5526 public virtual bool Emit (EmitContext ec, IMemoryLocation target)
5528 bool is_value_type = TypeManager.IsValueType (type);
5529 VariableReference vr = target as VariableReference;
5531 if (target != null && is_value_type && (vr != null || method == null)) {
5532 target.AddressOf (ec, AddressOp.Store);
5533 } else if (vr != null && vr.IsRef) {
5537 if (Arguments != null)
5538 Arguments.Emit (ec);
5540 if (is_value_type) {
5541 if (method == null) {
5542 ec.Emit (OpCodes.Initobj, type);
5547 ec.Emit (OpCodes.Call, method.BestCandidate);
5552 if (type is TypeParameterSpec)
5553 return DoEmitTypeParameter (ec);
5555 ec.Emit (OpCodes.Newobj, method.BestCandidate);
5559 public override void Emit (EmitContext ec)
5561 LocalTemporary v = null;
5562 if (method == null && TypeManager.IsValueType (type)) {
5563 // TODO: Use temporary variable from pool
5564 v = new LocalTemporary (type);
5571 public override void EmitStatement (EmitContext ec)
5573 LocalTemporary v = null;
5574 if (method == null && TypeManager.IsValueType (type)) {
5575 // TODO: Use temporary variable from pool
5576 v = new LocalTemporary (type);
5580 ec.Emit (OpCodes.Pop);
5583 public virtual bool HasInitializer {
5589 public void AddressOf (EmitContext ec, AddressOp mode)
5591 EmitAddressOf (ec, mode);
5594 protected virtual IMemoryLocation EmitAddressOf (EmitContext ec, AddressOp mode)
5596 LocalTemporary value_target = new LocalTemporary (type);
5598 if (type is TypeParameterSpec) {
5599 DoEmitTypeParameter (ec);
5600 value_target.Store (ec);
5601 value_target.AddressOf (ec, mode);
5602 return value_target;
5605 if (!TypeManager.IsStruct (type)){
5607 // We throw an exception. So far, I believe we only need to support
5609 // foreach (int j in new StructType ())
5612 throw new Exception ("AddressOf should not be used for classes");
5615 value_target.AddressOf (ec, AddressOp.Store);
5617 if (method == null) {
5618 ec.Emit (OpCodes.Initobj, type);
5620 if (Arguments != null)
5621 Arguments.Emit (ec);
5623 ec.Emit (OpCodes.Call, method.BestCandidate);
5626 value_target.AddressOf (ec, mode);
5627 return value_target;
5630 protected override void CloneTo (CloneContext clonectx, Expression t)
5632 New target = (New) t;
5634 target.RequestedType = RequestedType.Clone (clonectx);
5635 if (Arguments != null){
5636 target.Arguments = Arguments.Clone (clonectx);
5640 public override SLE.Expression MakeExpression (BuilderContext ctx)
5642 return SLE.Expression.New ((ConstructorInfo) method.BestCandidate.GetMetaInfo (), Arguments.MakeExpression (Arguments, ctx));
5646 public class ArrayInitializer : Expression
5648 List<Expression> elements;
5650 public ArrayInitializer (List<Expression> init, Location loc)
5656 public ArrayInitializer (int count, Location loc)
5658 elements = new List<Expression> (count);
5662 public ArrayInitializer (Location loc)
5667 public void Add (Expression expr)
5669 elements.Add (expr);
5672 public override Expression CreateExpressionTree (ResolveContext ec)
5674 throw new NotSupportedException ("ET");
5677 protected override void CloneTo (CloneContext clonectx, Expression t)
5679 var target = (ArrayInitializer) t;
5681 target.elements = new List<Expression> (elements.Count);
5682 foreach (var element in elements)
5683 target.elements.Add (element.Clone (clonectx));
5687 get { return elements.Count; }
5690 protected override Expression DoResolve (ResolveContext rc)
5692 var current_field = rc.CurrentMemberDefinition as FieldBase;
5693 return new ArrayCreation (new TypeExpression (current_field.MemberType, current_field.Location), this).Resolve (rc);
5696 public override void Emit (EmitContext ec)
5698 throw new InternalErrorException ("Missing Resolve call");
5701 public Expression this [int index] {
5702 get { return elements [index]; }
5707 /// 14.5.10.2: Represents an array creation expression.
5711 /// There are two possible scenarios here: one is an array creation
5712 /// expression that specifies the dimensions and optionally the
5713 /// initialization data and the other which does not need dimensions
5714 /// specified but where initialization data is mandatory.
5716 public class ArrayCreation : Expression
5718 FullNamedExpression requested_base_type;
5719 ArrayInitializer initializers;
5722 // The list of Argument types.
5723 // This is used to construct the `newarray' or constructor signature
5725 protected List<Expression> arguments;
5727 protected TypeSpec array_element_type;
5728 int num_arguments = 0;
5729 protected int dimensions;
5730 protected readonly ComposedTypeSpecifier rank;
5731 Expression first_emit;
5732 LocalTemporary first_emit_temp;
5734 protected List<Expression> array_data;
5736 Dictionary<int, int> bounds;
5738 // The number of constants in array initializers
5739 int const_initializers_count;
5740 bool only_constant_initializers;
5742 public ArrayCreation (FullNamedExpression requested_base_type, List<Expression> exprs, ComposedTypeSpecifier rank, ArrayInitializer initializers, Location l)
5743 : this (requested_base_type, rank, initializers, l)
5745 arguments = new List<Expression> (exprs);
5746 num_arguments = arguments.Count;
5750 // For expressions like int[] foo = new int[] { 1, 2, 3 };
5752 public ArrayCreation (FullNamedExpression requested_base_type, ComposedTypeSpecifier rank, ArrayInitializer initializers, Location loc)
5754 this.requested_base_type = requested_base_type;
5756 this.initializers = initializers;
5760 num_arguments = rank.Dimension;
5764 // For compiler generated single dimensional arrays only
5766 public ArrayCreation (FullNamedExpression requested_base_type, ArrayInitializer initializers, Location loc)
5767 : this (requested_base_type, ComposedTypeSpecifier.SingleDimension, initializers, loc)
5772 // For expressions like int[] foo = { 1, 2, 3 };
5774 public ArrayCreation (FullNamedExpression requested_base_type, ArrayInitializer initializers)
5775 : this (requested_base_type, null, initializers, initializers.Location)
5779 protected override void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
5781 ec.Report.Error (248, loc, "Cannot create an array with a negative size");
5784 bool CheckIndices (ResolveContext ec, ArrayInitializer probe, int idx, bool specified_dims, int child_bounds)
5786 if (initializers != null && bounds == null) {
5788 // We use this to store all the date values in the order in which we
5789 // will need to store them in the byte blob later
5791 array_data = new List<Expression> ();
5792 bounds = new Dictionary<int, int> ();
5795 if (specified_dims) {
5796 Expression a = arguments [idx];
5801 a = ConvertExpressionToArrayIndex (ec, a);
5807 if (initializers != null) {
5808 Constant c = a as Constant;
5809 if (c == null && a is ArrayIndexCast)
5810 c = ((ArrayIndexCast) a).Child as Constant;
5813 ec.Report.Error (150, a.Location, "A constant value is expected");
5819 value = System.Convert.ToInt32 (c.GetValue ());
5821 ec.Report.Error (150, a.Location, "A constant value is expected");
5825 // TODO: probe.Count does not fit ulong in
5826 if (value != probe.Count) {
5827 ec.Report.Error (847, loc, "An array initializer of length `{0}' was expected", value.ToString ());
5831 bounds[idx] = value;
5835 if (initializers == null)
5838 only_constant_initializers = true;
5839 for (int i = 0; i < probe.Count; ++i) {
5841 if (o is ArrayInitializer) {
5842 var sub_probe = o as ArrayInitializer;
5843 if (idx + 1 >= dimensions){
5844 ec.Report.Error (623, loc, "Array initializers can only be used in a variable or field initializer. Try using a new expression instead");
5848 bool ret = CheckIndices (ec, sub_probe, idx + 1, specified_dims, child_bounds - 1);
5851 } else if (child_bounds > 1) {
5852 ec.Report.Error (846, o.Location, "A nested array initializer was expected");
5854 Expression element = ResolveArrayElement (ec, o);
5855 if (element == null)
5858 // Initializers with the default values can be ignored
5859 Constant c = element as Constant;
5861 if (!c.IsDefaultInitializer (array_element_type)) {
5862 ++const_initializers_count;
5865 only_constant_initializers = false;
5868 array_data.Add (element);
5875 public override Expression CreateExpressionTree (ResolveContext ec)
5879 if (array_data == null) {
5880 args = new Arguments (arguments.Count + 1);
5881 args.Add (new Argument (new TypeOf (new TypeExpression (array_element_type, loc), loc)));
5882 foreach (Expression a in arguments)
5883 args.Add (new Argument (a.CreateExpressionTree (ec)));
5885 return CreateExpressionFactoryCall (ec, "NewArrayBounds", args);
5888 if (dimensions > 1) {
5889 ec.Report.Error (838, loc, "An expression tree cannot contain a multidimensional array initializer");
5893 args = new Arguments (array_data == null ? 1 : array_data.Count + 1);
5894 args.Add (new Argument (new TypeOf (new TypeExpression (array_element_type, loc), loc)));
5895 if (array_data != null) {
5896 for (int i = 0; i < array_data.Count; ++i) {
5897 Expression e = array_data [i];
5898 args.Add (new Argument (e.CreateExpressionTree (ec)));
5902 return CreateExpressionFactoryCall (ec, "NewArrayInit", args);
5905 public void UpdateIndices ()
5908 for (var probe = initializers; probe != null;) {
5909 if (probe.Count > 0 && probe [0] is ArrayInitializer) {
5910 Expression e = new IntConstant (probe.Count, Location.Null);
5913 bounds [i++] = probe.Count;
5915 probe = (ArrayInitializer) probe[0];
5918 Expression e = new IntConstant (probe.Count, Location.Null);
5921 bounds [i++] = probe.Count;
5927 protected virtual Expression ResolveArrayElement (ResolveContext ec, Expression element)
5929 element = element.Resolve (ec);
5930 if (element == null)
5933 if (element is CompoundAssign.TargetExpression) {
5934 if (first_emit != null)
5935 throw new InternalErrorException ("Can only handle one mutator at a time");
5936 first_emit = element;
5937 element = first_emit_temp = new LocalTemporary (element.Type);
5940 return Convert.ImplicitConversionRequired (
5941 ec, element, array_element_type, loc);
5944 protected bool ResolveInitializers (ResolveContext ec)
5946 if (arguments != null) {
5948 for (int i = 0; i < arguments.Count; ++i) {
5949 res &= CheckIndices (ec, initializers, i, true, dimensions);
5950 if (initializers != null)
5957 arguments = new List<Expression> ();
5959 if (!CheckIndices (ec, initializers, 0, false, dimensions))
5968 // Resolved the type of the array
5970 bool ResolveArrayType (ResolveContext ec)
5972 if (requested_base_type is VarExpr) {
5973 ec.Report.Error (820, loc, "An implicitly typed local variable declarator cannot use an array initializer");
5980 FullNamedExpression array_type_expr;
5981 if (num_arguments > 0) {
5982 array_type_expr = new ComposedCast (requested_base_type, rank);
5984 array_type_expr = requested_base_type;
5987 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec, false);
5988 if (array_type_expr == null)
5991 type = array_type_expr.Type;
5992 var ac = type as ArrayContainer;
5994 ec.Report.Error (622, loc, "Can only use array initializer expressions to assign to array types. Try using a new expression instead");
5998 array_element_type = ac.Element;
5999 dimensions = ac.Rank;
6004 protected override Expression DoResolve (ResolveContext ec)
6009 if (!ResolveArrayType (ec))
6013 // validate the initializers and fill in any missing bits
6015 if (!ResolveInitializers (ec))
6018 eclass = ExprClass.Value;
6022 byte [] MakeByteBlob ()
6027 int count = array_data.Count;
6029 TypeSpec element_type = array_element_type;
6030 if (TypeManager.IsEnumType (element_type))
6031 element_type = EnumSpec.GetUnderlyingType (element_type);
6033 factor = GetTypeSize (element_type);
6035 throw new Exception ("unrecognized type in MakeByteBlob: " + element_type);
6037 data = new byte [(count * factor + 3) & ~3];
6040 for (int i = 0; i < count; ++i) {
6041 object v = array_data [i];
6043 if (v is EnumConstant)
6044 v = ((EnumConstant) v).Child;
6046 if (v is Constant && !(v is StringConstant))
6047 v = ((Constant) v).GetValue ();
6053 if (element_type == TypeManager.int64_type){
6054 if (!(v is Expression)){
6055 long val = (long) v;
6057 for (int j = 0; j < factor; ++j) {
6058 data [idx + j] = (byte) (val & 0xFF);
6062 } else if (element_type == TypeManager.uint64_type){
6063 if (!(v is Expression)){
6064 ulong val = (ulong) v;
6066 for (int j = 0; j < factor; ++j) {
6067 data [idx + j] = (byte) (val & 0xFF);
6071 } else if (element_type == TypeManager.float_type) {
6072 if (!(v is Expression)){
6073 element = BitConverter.GetBytes ((float) v);
6075 for (int j = 0; j < factor; ++j)
6076 data [idx + j] = element [j];
6077 if (!BitConverter.IsLittleEndian)
6078 System.Array.Reverse (data, idx, 4);
6080 } else if (element_type == TypeManager.double_type) {
6081 if (!(v is Expression)){
6082 element = BitConverter.GetBytes ((double) v);
6084 for (int j = 0; j < factor; ++j)
6085 data [idx + j] = element [j];
6087 // FIXME: Handle the ARM float format.
6088 if (!BitConverter.IsLittleEndian)
6089 System.Array.Reverse (data, idx, 8);
6091 } else if (element_type == TypeManager.char_type){
6092 if (!(v is Expression)){
6093 int val = (int) ((char) v);
6095 data [idx] = (byte) (val & 0xff);
6096 data [idx+1] = (byte) (val >> 8);
6098 } else if (element_type == TypeManager.short_type){
6099 if (!(v is Expression)){
6100 int val = (int) ((short) v);
6102 data [idx] = (byte) (val & 0xff);
6103 data [idx+1] = (byte) (val >> 8);
6105 } else if (element_type == TypeManager.ushort_type){
6106 if (!(v is Expression)){
6107 int val = (int) ((ushort) v);
6109 data [idx] = (byte) (val & 0xff);
6110 data [idx+1] = (byte) (val >> 8);
6112 } else if (element_type == TypeManager.int32_type) {
6113 if (!(v is Expression)){
6116 data [idx] = (byte) (val & 0xff);
6117 data [idx+1] = (byte) ((val >> 8) & 0xff);
6118 data [idx+2] = (byte) ((val >> 16) & 0xff);
6119 data [idx+3] = (byte) (val >> 24);
6121 } else if (element_type == TypeManager.uint32_type) {
6122 if (!(v is Expression)){
6123 uint val = (uint) v;
6125 data [idx] = (byte) (val & 0xff);
6126 data [idx+1] = (byte) ((val >> 8) & 0xff);
6127 data [idx+2] = (byte) ((val >> 16) & 0xff);
6128 data [idx+3] = (byte) (val >> 24);
6130 } else if (element_type == TypeManager.sbyte_type) {
6131 if (!(v is Expression)){
6132 sbyte val = (sbyte) v;
6133 data [idx] = (byte) val;
6135 } else if (element_type == TypeManager.byte_type) {
6136 if (!(v is Expression)){
6137 byte val = (byte) v;
6138 data [idx] = (byte) val;
6140 } else if (element_type == TypeManager.bool_type) {
6141 if (!(v is Expression)){
6142 bool val = (bool) v;
6143 data [idx] = (byte) (val ? 1 : 0);
6145 } else if (element_type == TypeManager.decimal_type){
6146 if (!(v is Expression)){
6147 int [] bits = Decimal.GetBits ((decimal) v);
6150 // FIXME: For some reason, this doesn't work on the MS runtime.
6151 int [] nbits = new int [4];
6152 nbits [0] = bits [3];
6153 nbits [1] = bits [2];
6154 nbits [2] = bits [0];
6155 nbits [3] = bits [1];
6157 for (int j = 0; j < 4; j++){
6158 data [p++] = (byte) (nbits [j] & 0xff);
6159 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6160 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6161 data [p++] = (byte) (nbits [j] >> 24);
6165 throw new Exception ("Unrecognized type in MakeByteBlob: " + element_type);
6175 public override SLE.Expression MakeExpression (BuilderContext ctx)
6177 var initializers = new SLE.Expression [array_data.Count];
6178 for (var i = 0; i < initializers.Length; i++) {
6179 if (array_data [i] == null)
6180 initializers [i] = SLE.Expression.Default (array_element_type.GetMetaInfo ());
6182 initializers [i] = array_data [i].MakeExpression (ctx);
6185 return SLE.Expression.NewArrayInit (array_element_type.GetMetaInfo (), initializers);
6189 // Emits the initializers for the array
6191 void EmitStaticInitializers (EmitContext ec)
6193 // FIXME: This should go to Resolve !
6194 if (TypeManager.void_initializearray_array_fieldhandle == null) {
6195 TypeManager.void_initializearray_array_fieldhandle = TypeManager.GetPredefinedMethod (
6196 TypeManager.runtime_helpers_type, "InitializeArray", loc,
6197 TypeManager.array_type, TypeManager.runtime_field_handle_type);
6198 if (TypeManager.void_initializearray_array_fieldhandle == null)
6203 // First, the static data
6207 byte [] data = MakeByteBlob ();
6209 fb = RootContext.MakeStaticData (data);
6211 ec.Emit (OpCodes.Dup);
6212 ec.Emit (OpCodes.Ldtoken, fb);
6213 ec.Emit (OpCodes.Call, TypeManager.void_initializearray_array_fieldhandle);
6217 // Emits pieces of the array that can not be computed at compile
6218 // time (variables and string locations).
6220 // This always expect the top value on the stack to be the array
6222 void EmitDynamicInitializers (EmitContext ec, bool emitConstants)
6224 int dims = bounds.Count;
6225 var current_pos = new int [dims];
6227 for (int i = 0; i < array_data.Count; i++){
6229 Expression e = array_data [i];
6230 var c = e as Constant;
6232 // Constant can be initialized via StaticInitializer
6233 if (c == null || (c != null && emitConstants && !c.IsDefaultInitializer (array_element_type))) {
6234 TypeSpec etype = e.Type;
6236 ec.Emit (OpCodes.Dup);
6238 for (int idx = 0; idx < dims; idx++)
6239 ec.EmitInt (current_pos [idx]);
6242 // If we are dealing with a struct, get the
6243 // address of it, so we can store it.
6245 if ((dims == 1) && TypeManager.IsStruct (etype) &&
6246 (!TypeManager.IsBuiltinOrEnum (etype) ||
6247 etype == TypeManager.decimal_type)) {
6249 ec.Emit (OpCodes.Ldelema, etype);
6254 ec.EmitArrayStore ((ArrayContainer) type);
6260 for (int j = dims - 1; j >= 0; j--){
6262 if (current_pos [j] < bounds [j])
6264 current_pos [j] = 0;
6269 public override void Emit (EmitContext ec)
6271 if (first_emit != null) {
6272 first_emit.Emit (ec);
6273 first_emit_temp.Store (ec);
6276 foreach (Expression e in arguments)
6279 ec.EmitArrayNew ((ArrayContainer) type);
6281 if (initializers == null)
6284 // Emit static initializer for arrays which have contain more than 2 items and
6285 // the static initializer will initialize at least 25% of array values.
6286 // NOTE: const_initializers_count does not contain default constant values.
6287 if (const_initializers_count > 2 && const_initializers_count * 4 > (array_data.Count) &&
6288 (TypeManager.IsPrimitiveType (array_element_type) || TypeManager.IsEnumType (array_element_type))) {
6289 EmitStaticInitializers (ec);
6291 if (!only_constant_initializers)
6292 EmitDynamicInitializers (ec, false);
6294 EmitDynamicInitializers (ec, true);
6297 if (first_emit_temp != null)
6298 first_emit_temp.Release (ec);
6301 public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
6303 // no multi dimensional or jagged arrays
6304 if (arguments.Count != 1 || array_element_type.IsArray) {
6305 base.EncodeAttributeValue (rc, enc, targetType);
6309 // No array covariance, except for array -> object
6310 if (type != targetType) {
6311 if (targetType != TypeManager.object_type) {
6312 base.EncodeAttributeValue (rc, enc, targetType);
6319 // Single dimensional array of 0 size
6320 if (array_data == null) {
6321 IntConstant ic = arguments[0] as IntConstant;
6322 if (ic == null || !ic.IsDefaultValue) {
6323 base.EncodeAttributeValue (rc, enc, targetType);
6325 enc.Stream.Write (0);
6331 enc.Stream.Write ((int) array_data.Count);
6332 foreach (var element in array_data) {
6333 element.EncodeAttributeValue (rc, enc, array_element_type);
6337 protected override void CloneTo (CloneContext clonectx, Expression t)
6339 ArrayCreation target = (ArrayCreation) t;
6341 if (requested_base_type != null)
6342 target.requested_base_type = (FullNamedExpression)requested_base_type.Clone (clonectx);
6344 if (arguments != null){
6345 target.arguments = new List<Expression> (arguments.Count);
6346 foreach (Expression e in arguments)
6347 target.arguments.Add (e.Clone (clonectx));
6350 if (initializers != null)
6351 target.initializers = (ArrayInitializer) initializers.Clone (clonectx);
6356 // Represents an implicitly typed array epxression
6358 class ImplicitlyTypedArrayCreation : ArrayCreation
6360 public ImplicitlyTypedArrayCreation (ComposedTypeSpecifier rank, ArrayInitializer initializers, Location loc)
6361 : base (null, rank, initializers, loc)
6365 public ImplicitlyTypedArrayCreation (ArrayInitializer initializers, Location loc)
6366 : base (null, initializers, loc)
6370 protected override Expression DoResolve (ResolveContext ec)
6375 dimensions = rank.Dimension;
6377 if (!ResolveInitializers (ec))
6380 if (array_element_type == null || array_element_type == TypeManager.null_type ||
6381 array_element_type == TypeManager.void_type || array_element_type == InternalType.AnonymousMethod ||
6382 array_element_type == InternalType.MethodGroup ||
6383 arguments.Count != rank.Dimension) {
6384 Error_NoBestType (ec);
6389 // At this point we found common base type for all initializer elements
6390 // but we have to be sure that all static initializer elements are of
6393 UnifyInitializerElement (ec);
6395 type = ArrayContainer.MakeType (array_element_type, dimensions);
6396 eclass = ExprClass.Value;
6400 void Error_NoBestType (ResolveContext ec)
6402 ec.Report.Error (826, loc,
6403 "The type of an implicitly typed array cannot be inferred from the initializer. Try specifying array type explicitly");
6407 // Converts static initializer only
6409 void UnifyInitializerElement (ResolveContext ec)
6411 for (int i = 0; i < array_data.Count; ++i) {
6412 Expression e = (Expression)array_data[i];
6414 array_data [i] = Convert.ImplicitConversion (ec, e, array_element_type, Location.Null);
6418 protected override Expression ResolveArrayElement (ResolveContext ec, Expression element)
6420 element = element.Resolve (ec);
6421 if (element == null)
6424 if (array_element_type == null) {
6425 if (element.Type != TypeManager.null_type)
6426 array_element_type = element.Type;
6431 if (Convert.ImplicitConversionExists (ec, element, array_element_type)) {
6435 if (Convert.ImplicitConversionExists (ec, new TypeExpression (array_element_type, loc), element.Type)) {
6436 array_element_type = element.Type;
6440 Error_NoBestType (ec);
6445 public sealed class CompilerGeneratedThis : This
6447 public static This Instance = new CompilerGeneratedThis ();
6449 private CompilerGeneratedThis ()
6450 : base (Location.Null)
6454 public CompilerGeneratedThis (TypeSpec type, Location loc)
6460 protected override Expression DoResolve (ResolveContext ec)
6462 eclass = ExprClass.Variable;
6464 type = ec.CurrentType;
6469 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
6476 /// Represents the `this' construct
6479 public class This : VariableReference
6481 sealed class ThisVariable : ILocalVariable
6483 public static readonly ILocalVariable Instance = new ThisVariable ();
6485 public void Emit (EmitContext ec)
6487 ec.Emit (OpCodes.Ldarg_0);
6490 public void EmitAssign (EmitContext ec)
6492 throw new InvalidOperationException ();
6495 public void EmitAddressOf (EmitContext ec)
6497 ec.Emit (OpCodes.Ldarg_0);
6501 VariableInfo variable_info;
6503 public This (Location loc)
6508 public override VariableInfo VariableInfo {
6509 get { return variable_info; }
6512 public override bool IsFixed {
6513 get { return false; }
6516 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
6521 AnonymousMethodStorey storey = ae.Storey;
6522 while (storey != null) {
6523 AnonymousMethodStorey temp = storey.Parent as AnonymousMethodStorey;
6525 return storey.HoistedThis;
6533 public override bool IsRef {
6534 get { return type.IsStruct; }
6537 protected override ILocalVariable Variable {
6538 get { return ThisVariable.Instance; }
6541 public static bool IsThisAvailable (ResolveContext ec, bool ignoreAnonymous)
6543 if (ec.IsStatic || ec.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.BaseInitializer | ResolveContext.Options.ConstantScope))
6546 if (ignoreAnonymous || ec.CurrentAnonymousMethod == null)
6549 if (TypeManager.IsStruct (ec.CurrentType) && ec.CurrentIterator == null)
6555 public bool ResolveBase (ResolveContext ec)
6557 eclass = ExprClass.Variable;
6558 type = ec.CurrentType;
6560 if (!IsThisAvailable (ec, false)) {
6561 if (ec.IsStatic && !ec.HasSet (ResolveContext.Options.ConstantScope)) {
6562 ec.Report.Error (26, loc, "Keyword `this' is not valid in a static property, static method, or static field initializer");
6563 } else if (ec.CurrentAnonymousMethod != null) {
6564 ec.Report.Error (1673, loc,
6565 "Anonymous methods inside structs cannot access instance members of `this'. " +
6566 "Consider copying `this' to a local variable outside the anonymous method and using the local instead");
6568 ec.Report.Error (27, loc, "Keyword `this' is not available in the current context");
6572 var block = ec.CurrentBlock;
6573 if (block != null) {
6574 if (block.Toplevel.ThisVariable != null)
6575 variable_info = block.Toplevel.ThisVariable.VariableInfo;
6577 AnonymousExpression am = ec.CurrentAnonymousMethod;
6578 if (am != null && ec.IsVariableCapturingRequired) {
6579 am.SetHasThisAccess ();
6587 // Called from Invocation to check if the invocation is correct
6589 public override void CheckMarshalByRefAccess (ResolveContext ec)
6591 if ((variable_info != null) && !(TypeManager.IsStruct (type) && ec.OmitStructFlowAnalysis) &&
6592 !variable_info.IsAssigned (ec)) {
6593 ec.Report.Error (188, loc,
6594 "The `this' object cannot be used before all of its fields are assigned to");
6595 variable_info.SetAssigned (ec);
6599 public override Expression CreateExpressionTree (ResolveContext ec)
6601 Arguments args = new Arguments (1);
6602 args.Add (new Argument (this));
6604 // Use typeless constant for ldarg.0 to save some
6605 // space and avoid problems with anonymous stories
6606 return CreateExpressionFactoryCall (ec, "Constant", args);
6609 protected override Expression DoResolve (ResolveContext ec)
6615 override public Expression DoResolveLValue (ResolveContext ec, Expression right_side)
6617 if (!ResolveBase (ec))
6620 if (variable_info != null)
6621 variable_info.SetAssigned (ec);
6623 if (ec.CurrentType.IsClass){
6624 if (right_side == EmptyExpression.UnaryAddress)
6625 ec.Report.Error (459, loc, "Cannot take the address of `this' because it is read-only");
6626 else if (right_side == EmptyExpression.OutAccess.Instance)
6627 ec.Report.Error (1605, loc, "Cannot pass `this' as a ref or out argument because it is read-only");
6629 ec.Report.Error (1604, loc, "Cannot assign to `this' because it is read-only");
6635 public override int GetHashCode()
6637 throw new NotImplementedException ();
6640 public override string Name {
6641 get { return "this"; }
6644 public override bool Equals (object obj)
6646 This t = obj as This;
6653 protected override void CloneTo (CloneContext clonectx, Expression t)
6658 public override void SetHasAddressTaken ()
6665 /// Represents the `__arglist' construct
6667 public class ArglistAccess : Expression
6669 public ArglistAccess (Location loc)
6674 public override Expression CreateExpressionTree (ResolveContext ec)
6676 throw new NotSupportedException ("ET");
6679 protected override Expression DoResolve (ResolveContext ec)
6681 eclass = ExprClass.Variable;
6682 type = TypeManager.runtime_argument_handle_type;
6684 if (ec.HasSet (ResolveContext.Options.FieldInitializerScope) || !ec.CurrentBlock.Toplevel.Parameters.HasArglist) {
6685 ec.Report.Error (190, loc,
6686 "The __arglist construct is valid only within a variable argument method");
6692 public override void Emit (EmitContext ec)
6694 ec.Emit (OpCodes.Arglist);
6697 protected override void CloneTo (CloneContext clonectx, Expression target)
6704 /// Represents the `__arglist (....)' construct
6706 public class Arglist : Expression
6708 Arguments Arguments;
6710 public Arglist (Location loc)
6715 public Arglist (Arguments args, Location l)
6721 public Type[] ArgumentTypes {
6723 if (Arguments == null)
6724 return System.Type.EmptyTypes;
6726 var retval = new Type [Arguments.Count];
6727 for (int i = 0; i < retval.Length; i++)
6728 retval[i] = Arguments[i].Expr.Type.GetMetaInfo ();
6734 public override Expression CreateExpressionTree (ResolveContext ec)
6736 ec.Report.Error (1952, loc, "An expression tree cannot contain a method with variable arguments");
6740 protected override Expression DoResolve (ResolveContext ec)
6742 eclass = ExprClass.Variable;
6743 type = InternalType.Arglist;
6744 if (Arguments != null) {
6745 bool dynamic; // Can be ignored as there is always only 1 overload
6746 Arguments.Resolve (ec, out dynamic);
6752 public override void Emit (EmitContext ec)
6754 if (Arguments != null)
6755 Arguments.Emit (ec);
6758 protected override void CloneTo (CloneContext clonectx, Expression t)
6760 Arglist target = (Arglist) t;
6762 if (Arguments != null)
6763 target.Arguments = Arguments.Clone (clonectx);
6768 /// Implements the typeof operator
6770 public class TypeOf : Expression {
6771 FullNamedExpression QueriedType;
6774 public TypeOf (FullNamedExpression queried_type, Location l)
6776 QueriedType = queried_type;
6781 public TypeSpec TypeArgument {
6787 public FullNamedExpression TypeExpression {
6795 public override Expression CreateExpressionTree (ResolveContext ec)
6797 Arguments args = new Arguments (2);
6798 args.Add (new Argument (this));
6799 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
6800 return CreateExpressionFactoryCall (ec, "Constant", args);
6803 protected override Expression DoResolve (ResolveContext ec)
6805 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
6809 typearg = texpr.Type;
6811 if (typearg == TypeManager.void_type && !(QueriedType is TypeExpression)) {
6812 ec.Report.Error (673, loc, "System.Void cannot be used from C#. Use typeof (void) to get the void type object");
6813 } else if (typearg.IsPointer && !ec.IsUnsafe){
6814 UnsafeError (ec, loc);
6815 } else if (texpr is DynamicTypeExpr) {
6816 ec.Report.Error (1962, QueriedType.Location,
6817 "The typeof operator cannot be used on the dynamic type");
6820 type = TypeManager.type_type;
6822 return DoResolveBase ();
6825 protected Expression DoResolveBase ()
6827 if (TypeManager.system_type_get_type_from_handle == null) {
6828 TypeManager.system_type_get_type_from_handle = TypeManager.GetPredefinedMethod (
6829 TypeManager.type_type, "GetTypeFromHandle", loc, TypeManager.runtime_handle_type);
6832 // Even though what is returned is a type object, it's treated as a value by the compiler.
6833 // In particular, 'typeof (Foo).X' is something totally different from 'Foo.X'.
6834 eclass = ExprClass.Value;
6838 static bool ContainsTypeParameter (TypeSpec type)
6840 if (type.Kind == MemberKind.TypeParameter)
6843 var element_container = type as ElementTypeSpec;
6844 if (element_container != null)
6845 return ContainsTypeParameter (element_container.Element);
6847 foreach (var t in type.TypeArguments) {
6848 if (ContainsTypeParameter (t)) {
6856 public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
6858 // Target type is not System.Type therefore must be object
6859 // and we need to use different encoding sequence
6860 if (targetType != type)
6863 if (ContainsTypeParameter (typearg)) {
6864 rc.Compiler.Report.Error (416, loc, "`{0}': an attribute argument cannot use type parameters",
6865 TypeManager.CSharpName (typearg));
6869 enc.EncodeTypeName (typearg);
6872 public override void Emit (EmitContext ec)
6874 ec.Emit (OpCodes.Ldtoken, typearg);
6875 ec.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6878 protected override void CloneTo (CloneContext clonectx, Expression t)
6880 TypeOf target = (TypeOf) t;
6881 if (QueriedType != null)
6882 target.QueriedType = (FullNamedExpression) QueriedType.Clone (clonectx);
6886 class TypeOfMethod : TypeOfMember<MethodSpec>
6888 public TypeOfMethod (MethodSpec method, Location loc)
6889 : base (method, loc)
6893 protected override Expression DoResolve (ResolveContext ec)
6895 if (member.IsConstructor) {
6896 type = TypeManager.ctorinfo_type;
6898 type = TypeManager.ctorinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", "ConstructorInfo", MemberKind.Class, true);
6900 type = TypeManager.methodinfo_type;
6902 type = TypeManager.methodinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", "MethodInfo", MemberKind.Class, true);
6905 return base.DoResolve (ec);
6908 public override void Emit (EmitContext ec)
6910 ec.Emit (OpCodes.Ldtoken, member);
6913 ec.Emit (OpCodes.Castclass, type);
6916 protected override string GetMethodName {
6917 get { return "GetMethodFromHandle"; }
6920 protected override string RuntimeHandleName {
6921 get { return "RuntimeMethodHandle"; }
6924 protected override MethodSpec TypeFromHandle {
6926 return TypeManager.methodbase_get_type_from_handle;
6929 TypeManager.methodbase_get_type_from_handle = value;
6933 protected override MethodSpec TypeFromHandleGeneric {
6935 return TypeManager.methodbase_get_type_from_handle_generic;
6938 TypeManager.methodbase_get_type_from_handle_generic = value;
6942 protected override string TypeName {
6943 get { return "MethodBase"; }
6947 abstract class TypeOfMember<T> : Expression where T : MemberSpec
6949 protected readonly T member;
6951 protected TypeOfMember (T member, Location loc)
6953 this.member = member;
6957 public override Expression CreateExpressionTree (ResolveContext ec)
6959 Arguments args = new Arguments (2);
6960 args.Add (new Argument (this));
6961 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
6962 return CreateExpressionFactoryCall (ec, "Constant", args);
6965 protected override Expression DoResolve (ResolveContext ec)
6967 bool is_generic = member.DeclaringType.IsGenericOrParentIsGeneric;
6968 var mi = is_generic ? TypeFromHandleGeneric : TypeFromHandle;
6971 TypeSpec t = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", TypeName, MemberKind.Class, true);
6972 TypeSpec handle_type = TypeManager.CoreLookupType (ec.Compiler, "System", RuntimeHandleName, MemberKind.Struct, true);
6974 if (t == null || handle_type == null)
6977 mi = TypeManager.GetPredefinedMethod (t, GetMethodName, loc,
6979 new TypeSpec[] { handle_type, TypeManager.runtime_handle_type } :
6980 new TypeSpec[] { handle_type } );
6983 TypeFromHandleGeneric = mi;
6985 TypeFromHandle = mi;
6988 eclass = ExprClass.Value;
6992 public override void Emit (EmitContext ec)
6994 bool is_generic = member.DeclaringType.IsGenericOrParentIsGeneric;
6997 mi = TypeFromHandleGeneric;
6998 ec.Emit (OpCodes.Ldtoken, member.DeclaringType);
7000 mi = TypeFromHandle;
7003 ec.Emit (OpCodes.Call, mi);
7006 protected abstract string GetMethodName { get; }
7007 protected abstract string RuntimeHandleName { get; }
7008 protected abstract MethodSpec TypeFromHandle { get; set; }
7009 protected abstract MethodSpec TypeFromHandleGeneric { get; set; }
7010 protected abstract string TypeName { get; }
7013 class TypeOfField : TypeOfMember<FieldSpec>
7015 public TypeOfField (FieldSpec field, Location loc)
7020 protected override Expression DoResolve (ResolveContext ec)
7022 if (TypeManager.fieldinfo_type == null)
7023 TypeManager.fieldinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", TypeName, MemberKind.Class, true);
7025 type = TypeManager.fieldinfo_type;
7026 return base.DoResolve (ec);
7029 public override void Emit (EmitContext ec)
7031 ec.Emit (OpCodes.Ldtoken, member);
7035 protected override string GetMethodName {
7036 get { return "GetFieldFromHandle"; }
7039 protected override string RuntimeHandleName {
7040 get { return "RuntimeFieldHandle"; }
7043 protected override MethodSpec TypeFromHandle {
7045 return TypeManager.fieldinfo_get_field_from_handle;
7048 TypeManager.fieldinfo_get_field_from_handle = value;
7052 protected override MethodSpec TypeFromHandleGeneric {
7054 return TypeManager.fieldinfo_get_field_from_handle_generic;
7057 TypeManager.fieldinfo_get_field_from_handle_generic = value;
7061 protected override string TypeName {
7062 get { return "FieldInfo"; }
7067 /// Implements the sizeof expression
7069 public class SizeOf : Expression {
7070 readonly Expression QueriedType;
7071 TypeSpec type_queried;
7073 public SizeOf (Expression queried_type, Location l)
7075 this.QueriedType = queried_type;
7079 public override Expression CreateExpressionTree (ResolveContext ec)
7081 Error_PointerInsideExpressionTree (ec);
7085 protected override Expression DoResolve (ResolveContext ec)
7087 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
7091 type_queried = texpr.Type;
7092 if (TypeManager.IsEnumType (type_queried))
7093 type_queried = EnumSpec.GetUnderlyingType (type_queried);
7095 int size_of = GetTypeSize (type_queried);
7097 return new IntConstant (size_of, loc).Resolve (ec);
7100 if (!TypeManager.VerifyUnmanaged (ec.Compiler, type_queried, loc)){
7105 ec.Report.Error (233, loc,
7106 "`{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)",
7107 TypeManager.CSharpName (type_queried));
7110 type = TypeManager.int32_type;
7111 eclass = ExprClass.Value;
7115 public override void Emit (EmitContext ec)
7117 ec.Emit (OpCodes.Sizeof, type_queried);
7120 protected override void CloneTo (CloneContext clonectx, Expression t)
7126 /// Implements the qualified-alias-member (::) expression.
7128 public class QualifiedAliasMember : MemberAccess
7130 readonly string alias;
7131 public static readonly string GlobalAlias = "global";
7133 public QualifiedAliasMember (string alias, string identifier, Location l)
7134 : base (null, identifier, l)
7139 public QualifiedAliasMember (string alias, string identifier, TypeArguments targs, Location l)
7140 : base (null, identifier, targs, l)
7145 public QualifiedAliasMember (string alias, string identifier, int arity, Location l)
7146 : base (null, identifier, arity, l)
7151 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
7153 if (alias == GlobalAlias) {
7154 expr = GlobalRootNamespace.Instance;
7155 return base.ResolveAsTypeStep (ec, silent);
7158 int errors = ec.Compiler.Report.Errors;
7159 expr = ec.LookupNamespaceAlias (alias);
7161 if (errors == ec.Compiler.Report.Errors)
7162 ec.Compiler.Report.Error (432, loc, "Alias `{0}' not found", alias);
7166 FullNamedExpression fne = base.ResolveAsTypeStep (ec, silent);
7170 if (expr.eclass == ExprClass.Type) {
7172 ec.Compiler.Report.Error (431, loc,
7173 "Alias `{0}' cannot be used with '::' since it denotes a type. Consider replacing '::' with '.'", alias);
7181 protected override Expression DoResolve (ResolveContext ec)
7183 return ResolveAsTypeStep (ec, false);
7186 protected override void Error_IdentifierNotFound (IMemberContext rc, TypeSpec expr_type, string identifier)
7188 rc.Compiler.Report.Error (687, loc,
7189 "A namespace alias qualifier `{0}' did not resolve to a namespace or a type",
7190 GetSignatureForError ());
7193 public override string GetSignatureForError ()
7196 if (targs != null) {
7197 name = Name + "<" + targs.GetSignatureForError () + ">";
7200 return alias + "::" + name;
7203 protected override void CloneTo (CloneContext clonectx, Expression t)
7210 /// Implements the member access expression
7212 public class MemberAccess : ATypeNameExpression {
7213 protected Expression expr;
7215 public MemberAccess (Expression expr, string id)
7216 : base (id, expr.Location)
7221 public MemberAccess (Expression expr, string identifier, Location loc)
7222 : base (identifier, loc)
7227 public MemberAccess (Expression expr, string identifier, TypeArguments args, Location loc)
7228 : base (identifier, args, loc)
7233 public MemberAccess (Expression expr, string identifier, int arity, Location loc)
7234 : base (identifier, arity, loc)
7239 Expression DoResolve (ResolveContext ec, Expression right_side)
7242 throw new Exception ();
7245 // Resolve the expression with flow analysis turned off, we'll do the definite
7246 // assignment checks later. This is because we don't know yet what the expression
7247 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7248 // definite assignment check on the actual field and not on the whole struct.
7251 SimpleName original = expr as SimpleName;
7252 Expression expr_resolved;
7253 const ResolveFlags flags = ResolveFlags.VariableOrValue | ResolveFlags.Type;
7255 using (ec.Set (ResolveContext.Options.OmitStructFlowAnalysis)) {
7256 if (original != null) {
7257 expr_resolved = original.DoResolve (ec, true);
7258 if (expr_resolved != null) {
7259 // Ugly, simulate skipped Resolve
7260 if (expr_resolved is ConstantExpr) {
7261 expr_resolved = expr_resolved.Resolve (ec);
7262 } else if (expr_resolved is FieldExpr || expr_resolved is PropertyExpr) {
7264 } else if ((flags & expr_resolved.ExprClassToResolveFlags) == 0) {
7265 expr_resolved.Error_UnexpectedKind (ec, flags, expr.Location);
7266 expr_resolved = null;
7270 expr_resolved = expr.Resolve (ec, flags);
7274 if (expr_resolved == null)
7277 Namespace ns = expr_resolved as Namespace;
7279 FullNamedExpression retval = ns.Lookup (ec.Compiler, Name, Arity, loc);
7282 ns.Error_NamespaceDoesNotExist (loc, Name, Arity, ec);
7283 else if (HasTypeArguments)
7284 retval = new GenericTypeExpr (retval.Type, targs, loc).ResolveAsTypeStep (ec, false);
7286 expr = expr_resolved;
7290 TypeSpec expr_type = expr_resolved.Type;
7291 if (expr_type == InternalType.Dynamic) {
7292 Arguments args = new Arguments (1);
7293 args.Add (new Argument (expr_resolved.Resolve (ec)));
7294 expr = new DynamicMemberBinder (Name, args, loc);
7295 if (right_side != null)
7296 return expr.DoResolveLValue (ec, right_side);
7298 return expr.Resolve (ec);
7302 const MemberKind dot_kinds = MemberKind.Class | MemberKind.Struct | MemberKind.Delegate | MemberKind.Enum |
7303 MemberKind.Interface | MemberKind.TypeParameter | MemberKind.ArrayType;
7305 if ((expr_type.Kind & dot_kinds) == 0 || expr_type == TypeManager.void_type) {
7306 Unary.Error_OperatorCannotBeApplied (ec, loc, ".", expr_type);
7310 var arity = HasTypeArguments ? targs.Count : -1;
7312 var member_lookup = MemberLookup (ec.Compiler,
7313 ec.CurrentType, expr_type, expr_type, Name, arity, BindingRestriction.DefaultMemberLookup, loc);
7315 if (member_lookup == null) {
7316 expr = expr_resolved.Resolve (ec);
7318 ExprClass expr_eclass = expr.eclass;
7321 // Extension methods are not allowed on all expression types
7323 if (expr_eclass == ExprClass.Value || expr_eclass == ExprClass.Variable ||
7324 expr_eclass == ExprClass.IndexerAccess || expr_eclass == ExprClass.PropertyAccess ||
7325 expr_eclass == ExprClass.EventAccess) {
7326 ExtensionMethodGroupExpr ex_method_lookup = ec.LookupExtensionMethod (expr_type, Name, arity, loc);
7327 if (ex_method_lookup != null) {
7328 ex_method_lookup.ExtensionExpression = expr;
7330 if (HasTypeArguments) {
7331 if (!targs.Resolve (ec))
7334 ex_method_lookup.SetTypeArguments (ec, targs);
7337 return ex_method_lookup.Resolve (ec);
7341 member_lookup = Error_MemberLookupFailed (ec,
7342 ec.CurrentType, expr_type, expr_type, Name, arity, null,
7343 MemberKind.All, BindingRestriction.AccessibleOnly);
7344 if (member_lookup == null)
7348 expr = expr_resolved;
7351 TypeExpr texpr = member_lookup as TypeExpr;
7352 if (texpr != null) {
7353 if (!(expr_resolved is TypeExpr)) {
7354 me = expr_resolved as MemberExpr;
7355 if (me == null || me.ProbeIdenticalTypeName (ec, expr_resolved, original) == expr_resolved) {
7356 ec.Report.Error (572, loc, "`{0}': cannot reference a type through an expression; try `{1}' instead",
7357 Name, member_lookup.GetSignatureForError ());
7362 if (!texpr.CheckAccessLevel (ec.MemberContext)) {
7363 ec.Report.SymbolRelatedToPreviousError (member_lookup.Type);
7364 ErrorIsInaccesible (loc, TypeManager.CSharpName (member_lookup.Type), ec.Report);
7368 if (HasTypeArguments) {
7369 var ct = new GenericTypeExpr (member_lookup.Type, targs, loc);
7370 return ct.ResolveAsTypeStep (ec, false);
7373 return member_lookup;
7376 me = (MemberExpr) member_lookup;
7378 if (original != null && me.IsStatic)
7379 expr_resolved = me.ProbeIdenticalTypeName (ec, expr_resolved, original);
7381 me = me.ResolveMemberAccess (ec, expr_resolved, original);
7383 if (HasTypeArguments) {
7384 if (!targs.Resolve (ec))
7387 me.SetTypeArguments (ec, targs);
7390 if (original != null && (!TypeManager.IsValueType (expr_type) || me is PropertyExpr)) {
7391 if (me.IsInstance) {
7392 LocalVariableReference var = expr_resolved as LocalVariableReference;
7393 if (var != null && !var.VerifyAssigned (ec))
7398 // The following DoResolve/DoResolveLValue will do the definite assignment
7401 if (right_side != null)
7402 return me.DoResolveLValue (ec, right_side);
7404 return me.Resolve (ec);
7407 protected override Expression DoResolve (ResolveContext ec)
7409 return DoResolve (ec, null);
7412 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
7414 return DoResolve (ec, right_side);
7417 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
7419 return ResolveNamespaceOrType (ec, silent);
7422 public FullNamedExpression ResolveNamespaceOrType (IMemberContext rc, bool silent)
7424 FullNamedExpression expr_resolved = expr.ResolveAsTypeStep (rc, silent);
7426 if (expr_resolved == null)
7429 Namespace ns = expr_resolved as Namespace;
7431 FullNamedExpression retval = ns.Lookup (rc.Compiler, Name, Arity, loc);
7433 if (retval == null) {
7435 ns.Error_NamespaceDoesNotExist (loc, Name, Arity, rc);
7436 } else if (HasTypeArguments) {
7437 retval = new GenericTypeExpr (retval.Type, targs, loc).ResolveAsTypeStep (rc, silent);
7443 TypeExpr tnew_expr = expr_resolved.ResolveAsTypeTerminal (rc, false);
7444 if (tnew_expr == null)
7447 TypeSpec expr_type = tnew_expr.Type;
7448 if (TypeManager.IsGenericParameter (expr_type)) {
7449 rc.Compiler.Report.Error (704, loc, "A nested type cannot be specified through a type parameter `{0}'",
7450 tnew_expr.GetSignatureForError ());
7454 var nested = MemberCache.FindNestedType (expr_type, Name, Arity);
7455 if (nested == null) {
7459 Error_IdentifierNotFound (rc, expr_type, Name);
7464 if (!IsMemberAccessible (rc.CurrentType ?? InternalType.FakeInternalType, nested, out extra_check)) {
7465 ErrorIsInaccesible (loc, nested.GetSignatureForError (), rc.Compiler.Report);
7469 if (HasTypeArguments) {
7470 texpr = new GenericTypeExpr (nested, targs, loc);
7472 texpr = new TypeExpression (nested, loc);
7475 return texpr.ResolveAsTypeStep (rc, false);
7478 protected virtual void Error_IdentifierNotFound (IMemberContext rc, TypeSpec expr_type, string identifier)
7480 var nested = MemberCache.FindNestedType (expr_type, Name, -System.Math.Max (1, Arity));
7482 if (nested != null) {
7483 Error_TypeArgumentsCannotBeUsed (rc.Compiler.Report, expr.Location, nested, Arity);
7487 var member_lookup = MemberLookup (rc.Compiler,
7488 rc.CurrentType, expr_type, expr_type, identifier, -1,
7489 MemberKind.All, BindingRestriction.None, loc);
7491 if (member_lookup == null) {
7492 rc.Compiler.Report.Error (426, loc, "The nested type `{0}' does not exist in the type `{1}'",
7493 Name, expr_type.GetSignatureForError ());
7495 // TODO: Report.SymbolRelatedToPreviousError
7496 member_lookup.Error_UnexpectedKind (rc.Compiler.Report, null, "type", loc);
7500 protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
7502 if (RootContext.Version > LanguageVersion.ISO_2 && !ec.Compiler.IsRuntimeBinder &&
7503 ((expr.eclass & (ExprClass.Value | ExprClass.Variable)) != 0)) {
7504 ec.Report.Error (1061, loc, "Type `{0}' does not contain a definition for `{1}' and no " +
7505 "extension method `{1}' of type `{0}' could be found " +
7506 "(are you missing a using directive or an assembly reference?)",
7507 TypeManager.CSharpName (type), name);
7511 base.Error_TypeDoesNotContainDefinition (ec, type, name);
7514 public override string GetSignatureForError ()
7516 return expr.GetSignatureForError () + "." + base.GetSignatureForError ();
7519 public Expression Left {
7525 protected override void CloneTo (CloneContext clonectx, Expression t)
7527 MemberAccess target = (MemberAccess) t;
7529 target.expr = expr.Clone (clonectx);
7534 /// Implements checked expressions
7536 public class CheckedExpr : Expression {
7538 public Expression Expr;
7540 public CheckedExpr (Expression e, Location l)
7546 public override Expression CreateExpressionTree (ResolveContext ec)
7548 using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
7549 return Expr.CreateExpressionTree (ec);
7552 protected override Expression DoResolve (ResolveContext ec)
7554 using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
7555 Expr = Expr.Resolve (ec);
7560 if (Expr is Constant || Expr is MethodGroupExpr || Expr is AnonymousMethodExpression || Expr is DefaultValueExpression)
7563 eclass = Expr.eclass;
7568 public override void Emit (EmitContext ec)
7570 using (ec.With (EmitContext.Options.AllCheckStateFlags, true))
7574 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
7576 using (ec.With (EmitContext.Options.AllCheckStateFlags, true))
7577 Expr.EmitBranchable (ec, target, on_true);
7580 public override SLE.Expression MakeExpression (BuilderContext ctx)
7582 using (ctx.With (BuilderContext.Options.AllCheckStateFlags, true)) {
7583 return Expr.MakeExpression (ctx);
7587 protected override void CloneTo (CloneContext clonectx, Expression t)
7589 CheckedExpr target = (CheckedExpr) t;
7591 target.Expr = Expr.Clone (clonectx);
7596 /// Implements the unchecked expression
7598 public class UnCheckedExpr : Expression {
7600 public Expression Expr;
7602 public UnCheckedExpr (Expression e, Location l)
7608 public override Expression CreateExpressionTree (ResolveContext ec)
7610 using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
7611 return Expr.CreateExpressionTree (ec);
7614 protected override Expression DoResolve (ResolveContext ec)
7616 using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
7617 Expr = Expr.Resolve (ec);
7622 if (Expr is Constant || Expr is MethodGroupExpr || Expr is AnonymousMethodExpression || Expr is DefaultValueExpression)
7625 eclass = Expr.eclass;
7630 public override void Emit (EmitContext ec)
7632 using (ec.With (EmitContext.Options.AllCheckStateFlags, false))
7636 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
7638 using (ec.With (EmitContext.Options.AllCheckStateFlags, false))
7639 Expr.EmitBranchable (ec, target, on_true);
7642 protected override void CloneTo (CloneContext clonectx, Expression t)
7644 UnCheckedExpr target = (UnCheckedExpr) t;
7646 target.Expr = Expr.Clone (clonectx);
7651 /// An Element Access expression.
7653 /// During semantic analysis these are transformed into
7654 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7656 public class ElementAccess : Expression {
7657 public Arguments Arguments;
7658 public Expression Expr;
7660 public ElementAccess (Expression e, Arguments args, Location loc)
7664 this.Arguments = args;
7667 public override Expression CreateExpressionTree (ResolveContext ec)
7669 Arguments args = Arguments.CreateForExpressionTree (ec, Arguments,
7670 Expr.CreateExpressionTree (ec));
7672 return CreateExpressionFactoryCall (ec, "ArrayIndex", args);
7675 Expression MakePointerAccess (ResolveContext ec, TypeSpec t)
7677 if (Arguments.Count != 1){
7678 ec.Report.Error (196, loc, "A pointer must be indexed by only one value");
7682 if (Arguments [0] is NamedArgument)
7683 Error_NamedArgument ((NamedArgument) Arguments[0], ec.Report);
7685 Expression p = new PointerArithmetic (Binary.Operator.Addition, Expr, Arguments [0].Expr.Resolve (ec), t, loc);
7686 return new Indirection (p, loc).Resolve (ec);
7689 protected override Expression DoResolve (ResolveContext ec)
7691 Expr = Expr.Resolve (ec);
7696 // We perform some simple tests, and then to "split" the emit and store
7697 // code we create an instance of a different class, and return that.
7699 // I am experimenting with this pattern.
7701 TypeSpec t = Expr.Type;
7703 if (t == TypeManager.array_type){
7704 ec.Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `System.Array'");
7709 return (new ArrayAccess (this, loc)).Resolve (ec);
7711 return MakePointerAccess (ec, t);
7713 FieldExpr fe = Expr as FieldExpr;
7715 var ff = fe.Spec as FixedFieldSpec;
7717 return MakePointerAccess (ec, ff.ElementType);
7720 return (new IndexerAccess (this, loc)).Resolve (ec);
7723 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
7725 Expr = Expr.Resolve (ec);
7731 return (new ArrayAccess (this, loc)).DoResolveLValue (ec, right_side);
7734 return MakePointerAccess (ec, type);
7736 if (Expr.eclass != ExprClass.Variable && TypeManager.IsStruct (type))
7737 Error_CannotModifyIntermediateExpressionValue (ec);
7739 return (new IndexerAccess (this, loc)).DoResolveLValue (ec, right_side);
7742 public override void Emit (EmitContext ec)
7744 throw new Exception ("Should never be reached");
7747 public static void Error_NamedArgument (NamedArgument na, Report Report)
7749 Report.Error (1742, na.Location, "An element access expression cannot use named argument");
7752 public override string GetSignatureForError ()
7754 return Expr.GetSignatureForError ();
7757 protected override void CloneTo (CloneContext clonectx, Expression t)
7759 ElementAccess target = (ElementAccess) t;
7761 target.Expr = Expr.Clone (clonectx);
7762 if (Arguments != null)
7763 target.Arguments = Arguments.Clone (clonectx);
7768 /// Implements array access
7770 public class ArrayAccess : Expression, IDynamicAssign, IMemoryLocation {
7772 // Points to our "data" repository
7776 LocalTemporary temp;
7780 public ArrayAccess (ElementAccess ea_data, Location l)
7786 public override Expression CreateExpressionTree (ResolveContext ec)
7788 return ea.CreateExpressionTree (ec);
7791 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
7793 return DoResolve (ec);
7796 protected override Expression DoResolve (ResolveContext ec)
7798 // dynamic is used per argument in ConvertExpressionToArrayIndex case
7800 ea.Arguments.Resolve (ec, out dynamic);
7802 var ac = ea.Expr.Type as ArrayContainer;
7803 int rank = ea.Arguments.Count;
7804 if (ac.Rank != rank) {
7805 ec.Report.Error (22, ea.Location, "Wrong number of indexes `{0}' inside [], expected `{1}'",
7806 rank.ToString (), ac.Rank.ToString ());
7811 if (type.IsPointer && !ec.IsUnsafe) {
7812 UnsafeError (ec, ea.Location);
7815 foreach (Argument a in ea.Arguments) {
7816 if (a is NamedArgument)
7817 ElementAccess.Error_NamedArgument ((NamedArgument) a, ec.Report);
7819 a.Expr = ConvertExpressionToArrayIndex (ec, a.Expr);
7822 eclass = ExprClass.Variable;
7827 protected override void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
7829 ec.Report.Warning (251, 2, loc, "Indexing an array with a negative index (array indices always start at zero)");
7833 // Load the array arguments into the stack.
7835 void LoadArrayAndArguments (EmitContext ec)
7839 for (int i = 0; i < ea.Arguments.Count; ++i) {
7840 ea.Arguments [i].Emit (ec);
7844 public void Emit (EmitContext ec, bool leave_copy)
7846 var ac = ea.Expr.Type as ArrayContainer;
7849 ec.EmitLoadFromPtr (type);
7851 LoadArrayAndArguments (ec);
7852 ec.EmitArrayLoad (ac);
7856 ec.Emit (OpCodes.Dup);
7857 temp = new LocalTemporary (this.type);
7862 public override void Emit (EmitContext ec)
7867 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
7869 var ac = (ArrayContainer) ea.Expr.Type;
7870 TypeSpec t = source.Type;
7871 prepared = prepare_for_load;
7874 AddressOf (ec, AddressOp.LoadStore);
7875 ec.Emit (OpCodes.Dup);
7877 LoadArrayAndArguments (ec);
7880 // If we are dealing with a struct, get the
7881 // address of it, so we can store it.
7883 // The stobj opcode used by value types will need
7884 // an address on the stack, not really an array/array
7887 if (ac.Rank == 1 && TypeManager.IsStruct (t) &&
7888 (!TypeManager.IsBuiltinOrEnum (t) ||
7889 t == TypeManager.decimal_type)) {
7891 ec.Emit (OpCodes.Ldelema, t);
7897 ec.Emit (OpCodes.Dup);
7898 temp = new LocalTemporary (this.type);
7903 ec.EmitStoreFromPtr (t);
7905 ec.EmitArrayStore (ac);
7914 public void EmitNew (EmitContext ec, New source, bool leave_copy)
7916 if (!source.Emit (ec, this)) {
7918 throw new NotImplementedException ();
7923 throw new NotImplementedException ();
7926 public void AddressOf (EmitContext ec, AddressOp mode)
7928 var ac = (ArrayContainer) ea.Expr.Type;
7930 LoadArrayAndArguments (ec);
7931 ec.EmitArrayAddress (ac);
7935 public SLE.Expression MakeAssignExpression (BuilderContext ctx)
7937 return SLE.Expression.ArrayAccess (
7938 ea.Expr.MakeExpression (ctx),
7939 Arguments.MakeExpression (ea.Arguments, ctx));
7943 public override SLE.Expression MakeExpression (BuilderContext ctx)
7945 return SLE.Expression.ArrayIndex (
7946 ea.Expr.MakeExpression (ctx),
7947 Arguments.MakeExpression (ea.Arguments, ctx));
7952 /// Expressions that represent an indexer call.
7954 class IndexerAccess : Expression, IDynamicAssign
7956 class IndexerMethodGroupExpr : MethodGroupExpr
7958 IEnumerable<IndexerSpec> candidates;
7960 public IndexerMethodGroupExpr (IEnumerable<IndexerSpec> indexers, Location loc)
7961 : base (FilterAccessors (indexers).ToList (), null, loc)
7963 candidates = indexers;
7966 public IndexerSpec BestIndexer ()
7968 return MemberCache.FindIndexers (BestCandidate.DeclaringType, BindingRestriction.None).
7970 (l.HasGet && l.Get.MemberDefinition == BestCandidate.MemberDefinition) ||
7971 (l.HasSet && l.Set.MemberDefinition == BestCandidate.MemberDefinition)).First ();
7974 static IEnumerable<MemberSpec> FilterAccessors (IEnumerable<IndexerSpec> indexers)
7976 foreach (IndexerSpec i in indexers) {
7984 protected override IList<MemberSpec> GetBaseTypeMethods (ResolveContext rc, TypeSpec type)
7986 candidates = GetIndexersForType (type);
7987 if (candidates == null)
7990 return FilterAccessors (candidates).ToList ();
7993 public override string Name {
7999 protected override int GetApplicableParametersCount (MethodSpec method, AParametersCollection parameters)
8002 // Here is the trick, decrease number of arguments by 1 when only
8003 // available property method is setter. This makes overload resolution
8004 // work correctly for indexers.
8007 if (method.Name [0] == 'g')
8008 return parameters.Count;
8010 return parameters.Count - 1;
8015 // Points to our "data" repository
8019 LocalTemporary temp;
8020 LocalTemporary prepared_value;
8021 Expression set_expr;
8023 protected TypeSpec indexer_type;
8024 protected Expression instance_expr;
8025 protected Arguments arguments;
8027 public IndexerAccess (ElementAccess ea, Location loc)
8029 this.instance_expr = ea.Expr;
8030 this.arguments = ea.Arguments;
8034 static string GetAccessorName (bool isSet)
8036 return isSet ? "set" : "get";
8039 public override Expression CreateExpressionTree (ResolveContext ec)
8041 Arguments args = Arguments.CreateForExpressionTree (ec, arguments,
8042 instance_expr.CreateExpressionTree (ec),
8043 new TypeOfMethod (spec.Get, loc));
8045 return CreateExpressionFactoryCall (ec, "Call", args);
8048 static IEnumerable<IndexerSpec> GetIndexersForType (TypeSpec lookup_type)
8050 return MemberCache.FindIndexers (lookup_type, BindingRestriction.AccessibleOnly | BindingRestriction.DefaultMemberLookup);
8053 protected override Expression DoResolve (ResolveContext ec)
8055 return ResolveAccessor (ec, null);
8058 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
8060 if (right_side == EmptyExpression.OutAccess.Instance) {
8061 right_side.DoResolveLValue (ec, this);
8065 // if the indexer returns a value type, and we try to set a field in it
8066 if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess) {
8067 Error_CannotModifyIntermediateExpressionValue (ec);
8070 return ResolveAccessor (ec, right_side);
8073 Expression ResolveAccessor (ResolveContext ec, Expression right_side)
8075 indexer_type = instance_expr.Type;
8078 arguments.Resolve (ec, out dynamic);
8080 if (indexer_type == InternalType.Dynamic) {
8083 var ilist = GetIndexersForType (indexer_type);
8084 if (ilist == null) {
8085 ec.Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
8086 TypeManager.CSharpName (indexer_type));
8090 var mg = new IndexerMethodGroupExpr (ilist, loc) {
8091 InstanceExpression = instance_expr
8094 mg = mg.OverloadResolve (ec, ref arguments, false, loc) as IndexerMethodGroupExpr;
8099 spec = mg.BestIndexer ();
8103 Arguments args = new Arguments (arguments.Count + 1);
8104 if (instance_expr is BaseThis) {
8105 ec.Report.Error (1972, loc, "The indexer base access cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access");
8107 args.Add (new Argument (instance_expr));
8109 args.AddRange (arguments);
8111 var expr = new DynamicIndexBinder (args, loc);
8112 if (right_side != null)
8113 return expr.ResolveLValue (ec, right_side);
8115 return expr.Resolve (ec);
8118 type = spec.MemberType;
8119 if (type.IsPointer && !ec.IsUnsafe)
8120 UnsafeError (ec, loc);
8122 MethodSpec accessor;
8123 if (right_side == null) {
8124 accessor = spec.Get;
8126 accessor = spec.Set;
8127 if (!spec.HasSet && spec.HasGet) {
8128 ec.Report.SymbolRelatedToPreviousError (spec);
8129 ec.Report.Error (200, loc, "The read only property or indexer `{0}' cannot be assigned to",
8130 spec.GetSignatureForError ());
8134 set_expr = Convert.ImplicitConversion (ec, right_side, type, loc);
8137 if (accessor == null) {
8138 ec.Report.SymbolRelatedToPreviousError (spec);
8139 ec.Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks a `{1}' accessor",
8140 spec.GetSignatureForError (), GetAccessorName (right_side != null));
8145 // Only base will allow this invocation to happen.
8147 if (spec.IsAbstract && instance_expr is BaseThis) {
8148 Error_CannotCallAbstractBase (ec, spec.GetSignatureForError ());
8151 bool must_do_cs1540_check;
8152 if (!IsMemberAccessible (ec.CurrentType, accessor, out must_do_cs1540_check)) {
8153 if (spec.HasDifferentAccessibility) {
8154 ec.Report.SymbolRelatedToPreviousError (accessor);
8155 ec.Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because a `{1}' accessor is inaccessible",
8156 TypeManager.GetFullNameSignature (spec), GetAccessorName (right_side != null));
8158 ec.Report.SymbolRelatedToPreviousError (spec);
8159 ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (spec), ec.Report);
8163 instance_expr.CheckMarshalByRefAccess (ec);
8165 if (must_do_cs1540_check && (instance_expr != EmptyExpression.Null) &&
8166 !(instance_expr is BaseThis) &&
8167 !TypeManager.IsInstantiationOfSameGenericType (instance_expr.Type, ec.CurrentType) &&
8168 !TypeManager.IsNestedChildOf (ec.CurrentType, instance_expr.Type) &&
8169 !TypeManager.IsSubclassOf (instance_expr.Type, ec.CurrentType)) {
8170 ec.Report.SymbolRelatedToPreviousError (accessor);
8171 Error_CannotAccessProtected (ec, loc, spec, instance_expr.Type, ec.CurrentType);
8175 eclass = ExprClass.IndexerAccess;
8179 public override void Emit (EmitContext ec)
8184 public void Emit (EmitContext ec, bool leave_copy)
8187 prepared_value.Emit (ec);
8189 Invocation.EmitCall (ec, instance_expr, spec.Get,
8190 arguments, loc, false, false);
8194 ec.Emit (OpCodes.Dup);
8195 temp = new LocalTemporary (Type);
8201 // source is ignored, because we already have a copy of it from the
8202 // LValue resolution and we have already constructed a pre-cached
8203 // version of the arguments (ea.set_arguments);
8205 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8207 prepared = prepare_for_load;
8208 Expression value = set_expr;
8211 Invocation.EmitCall (ec, instance_expr, spec.Get,
8212 arguments, loc, true, false);
8214 prepared_value = new LocalTemporary (type);
8215 prepared_value.Store (ec);
8217 prepared_value.Release (ec);
8220 ec.Emit (OpCodes.Dup);
8221 temp = new LocalTemporary (Type);
8224 } else if (leave_copy) {
8225 temp = new LocalTemporary (Type);
8232 arguments.Add (new Argument (value));
8234 Invocation.EmitCall (ec, instance_expr, spec.Set, arguments, loc, false, prepared);
8242 public override string GetSignatureForError ()
8244 return spec.GetSignatureForError ();
8248 public SLE.Expression MakeAssignExpression (BuilderContext ctx)
8250 var value = new[] { set_expr.MakeExpression (ctx) };
8251 var args = Arguments.MakeExpression (arguments, ctx).Concat (value);
8253 return SLE.Expression.Block (
8254 SLE.Expression.Call (instance_expr.MakeExpression (ctx), (MethodInfo) spec.Set.GetMetaInfo (), args),
8259 public override SLE.Expression MakeExpression (BuilderContext ctx)
8261 var args = Arguments.MakeExpression (arguments, ctx);
8262 return SLE.Expression.Call (instance_expr.MakeExpression (ctx), (MethodInfo) spec.Get.GetMetaInfo (), args);
8265 protected override void CloneTo (CloneContext clonectx, Expression t)
8267 IndexerAccess target = (IndexerAccess) t;
8269 if (arguments != null)
8270 target.arguments = arguments.Clone (clonectx);
8272 if (instance_expr != null)
8273 target.instance_expr = instance_expr.Clone (clonectx);
8278 // A base access expression
8280 public class BaseThis : Expression
8282 public BaseThis (Location loc)
8287 public BaseThis (TypeSpec type, Location loc)
8290 eclass = ExprClass.Variable;
8294 public override Expression CreateExpressionTree (ResolveContext ec)
8296 ec.Report.Error (831, loc, "An expression tree may not contain a base access");
8298 Arguments args = new Arguments (1);
8299 args.Add (new Argument (this));
8300 return CreateExpressionFactoryCall (ec, "Constant", args);
8303 protected override Expression DoResolve (ResolveContext rc)
8305 type = rc.CurrentType.BaseType;
8307 if (!This.IsThisAvailable (rc, false)) {
8309 rc.Report.Error (1511, loc, "Keyword `base' is not available in a static method");
8311 rc.Report.Error (1512, loc, "Keyword `base' is not available in the current context");
8315 eclass = ExprClass.Variable;
8319 public override void Emit (EmitContext ec)
8321 ec.Emit (OpCodes.Ldarg_0);
8323 if (ec.CurrentType.IsStruct) {
8324 ec.Emit (OpCodes.Ldobj, ec.CurrentType);
8325 ec.Emit (OpCodes.Box, ec.CurrentType);
8331 /// This class exists solely to pass the Type around and to be a dummy
8332 /// that can be passed to the conversion functions (this is used by
8333 /// foreach implementation to typecast the object return value from
8334 /// get_Current into the proper type. All code has been generated and
8335 /// we only care about the side effect conversions to be performed
8337 /// This is also now used as a placeholder where a no-action expression
8338 /// is needed (the `New' class).
8340 public class EmptyExpression : Expression {
8341 public static readonly Expression Null = new EmptyExpression ();
8343 public class OutAccess : EmptyExpression
8345 public static readonly OutAccess Instance = new OutAccess ();
8347 public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
8349 rc.Report.Error (206, right_side.Location,
8350 "A property, indexer or dynamic member access may not be passed as `ref' or `out' parameter");
8356 public static readonly EmptyExpression LValueMemberAccess = new EmptyExpression ();
8357 public static readonly EmptyExpression LValueMemberOutAccess = new EmptyExpression ();
8358 public static readonly EmptyExpression UnaryAddress = new EmptyExpression ();
8360 static EmptyExpression temp = new EmptyExpression ();
8361 public static EmptyExpression Grab ()
8363 EmptyExpression retval = temp == null ? new EmptyExpression () : temp;
8368 public static void Release (EmptyExpression e)
8375 // FIXME: Don't set to object
8376 type = TypeManager.object_type;
8377 eclass = ExprClass.Value;
8378 loc = Location.Null;
8381 public EmptyExpression (TypeSpec t)
8384 eclass = ExprClass.Value;
8385 loc = Location.Null;
8388 public override Expression CreateExpressionTree (ResolveContext ec)
8390 throw new NotSupportedException ("ET");
8393 protected override Expression DoResolve (ResolveContext ec)
8398 public override void Emit (EmitContext ec)
8400 // nothing, as we only exist to not do anything.
8403 public override void EmitSideEffect (EmitContext ec)
8408 // This is just because we might want to reuse this bad boy
8409 // instead of creating gazillions of EmptyExpressions.
8410 // (CanImplicitConversion uses it)
8412 public void SetType (TypeSpec t)
8419 // Empty statement expression
8421 public sealed class EmptyExpressionStatement : ExpressionStatement
8423 public static readonly EmptyExpressionStatement Instance = new EmptyExpressionStatement ();
8425 private EmptyExpressionStatement ()
8427 loc = Location.Null;
8430 public override Expression CreateExpressionTree (ResolveContext ec)
8435 public override void EmitStatement (EmitContext ec)
8440 protected override Expression DoResolve (ResolveContext ec)
8442 eclass = ExprClass.Value;
8443 type = TypeManager.object_type;
8447 public override void Emit (EmitContext ec)
8453 public class UserCast : Expression {
8457 public UserCast (MethodSpec method, Expression source, Location l)
8459 this.method = method;
8460 this.source = source;
8461 type = method.ReturnType;
8465 public Expression Source {
8471 public override Expression CreateExpressionTree (ResolveContext ec)
8473 Arguments args = new Arguments (3);
8474 args.Add (new Argument (source.CreateExpressionTree (ec)));
8475 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
8476 args.Add (new Argument (new TypeOfMethod (method, loc)));
8477 return CreateExpressionFactoryCall (ec, "Convert", args);
8480 protected override Expression DoResolve (ResolveContext ec)
8482 ObsoleteAttribute oa = method.GetAttributeObsolete ();
8484 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
8486 eclass = ExprClass.Value;
8490 public override void Emit (EmitContext ec)
8493 ec.Emit (OpCodes.Call, method);
8496 public override string GetSignatureForError ()
8498 return TypeManager.CSharpSignature (method);
8501 public override SLE.Expression MakeExpression (BuilderContext ctx)
8503 return SLE.Expression.Convert (source.MakeExpression (ctx), type.GetMetaInfo (), (MethodInfo) method.GetMetaInfo ());
8508 // Holds additional type specifiers like ?, *, []
8510 public class ComposedTypeSpecifier
8512 public static readonly ComposedTypeSpecifier SingleDimension = new ComposedTypeSpecifier (1, Location.Null);
8514 public readonly int Dimension;
8515 public readonly Location Location;
8517 public ComposedTypeSpecifier (int specifier, Location loc)
8519 this.Dimension = specifier;
8520 this.Location = loc;
8524 public bool IsNullable {
8526 return Dimension == -1;
8530 public bool IsPointer {
8532 return Dimension == -2;
8536 public ComposedTypeSpecifier Next { get; set; }
8540 public static ComposedTypeSpecifier CreateArrayDimension (int dimension, Location loc)
8542 return new ComposedTypeSpecifier (dimension, loc);
8545 public static ComposedTypeSpecifier CreateNullable (Location loc)
8547 return new ComposedTypeSpecifier (-1, loc);
8550 public static ComposedTypeSpecifier CreatePointer (Location loc)
8552 return new ComposedTypeSpecifier (-2, loc);
8555 public string GetSignatureForError ()
8560 ArrayContainer.GetPostfixSignature (Dimension);
8562 return Next != null ? s + Next.GetSignatureForError () : s;
8567 // This class is used to "construct" the type during a typecast
8568 // operation. Since the Type.GetType class in .NET can parse
8569 // the type specification, we just use this to construct the type
8570 // one bit at a time.
8572 public class ComposedCast : TypeExpr {
8573 FullNamedExpression left;
8574 ComposedTypeSpecifier spec;
8576 public ComposedCast (FullNamedExpression left, ComposedTypeSpecifier spec)
8579 throw new ArgumentNullException ("spec");
8583 this.loc = spec.Location;
8586 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
8588 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec, false);
8593 eclass = ExprClass.Type;
8595 var single_spec = spec;
8597 if (single_spec.IsNullable) {
8598 lexpr = new Nullable.NullableType (lexpr, loc);
8599 lexpr = lexpr.ResolveAsTypeTerminal (ec, false);
8603 single_spec = single_spec.Next;
8604 } else if (single_spec.IsPointer) {
8605 if (!TypeManager.VerifyUnmanaged (ec.Compiler, type, loc))
8609 UnsafeError (ec.Compiler.Report, loc);
8612 type = PointerContainer.MakeType (type);
8613 single_spec = single_spec.Next;
8616 if (single_spec != null && single_spec.Dimension > 0) {
8617 if (TypeManager.IsSpecialType (type)) {
8618 ec.Compiler.Report.Error (611, loc, "Array elements cannot be of type `{0}'", type.GetSignatureForError ());
8619 } else if (type.IsStatic) {
8620 ec.Compiler.Report.SymbolRelatedToPreviousError (type);
8621 ec.Compiler.Report.Error (719, loc, "Array elements cannot be of static type `{0}'",
8622 type.GetSignatureForError ());
8624 MakeArray (single_spec);
8631 void MakeArray (ComposedTypeSpecifier spec)
8633 if (spec.Next != null)
8634 MakeArray (spec.Next);
8636 type = ArrayContainer.MakeType (type, spec.Dimension);
8639 public override string GetSignatureForError ()
8641 return left.GetSignatureForError () + spec.GetSignatureForError ();
8645 public class FixedBufferPtr : Expression {
8648 public FixedBufferPtr (Expression array, TypeSpec array_type, Location l)
8653 type = PointerContainer.MakeType (array_type);
8654 eclass = ExprClass.Value;
8657 public override Expression CreateExpressionTree (ResolveContext ec)
8659 Error_PointerInsideExpressionTree (ec);
8663 public override void Emit(EmitContext ec)
8668 protected override Expression DoResolve (ResolveContext ec)
8671 // We are born fully resolved
8679 // This class is used to represent the address of an array, used
8680 // only by the Fixed statement, this generates "&a [0]" construct
8681 // for fixed (char *pa = a)
8683 public class ArrayPtr : FixedBufferPtr {
8684 TypeSpec array_type;
8686 public ArrayPtr (Expression array, TypeSpec array_type, Location l):
8687 base (array, array_type, l)
8689 this.array_type = array_type;
8692 public override void Emit (EmitContext ec)
8697 ec.Emit (OpCodes.Ldelema, array_type);
8702 // Encapsulates a conversion rules required for array indexes
8704 public class ArrayIndexCast : TypeCast
8706 public ArrayIndexCast (Expression expr)
8707 : base (expr, TypeManager.int32_type)
8709 if (expr.Type == TypeManager.int32_type)
8710 throw new ArgumentException ("unnecessary array index conversion");
8713 public override Expression CreateExpressionTree (ResolveContext ec)
8715 using (ec.Set (ResolveContext.Options.CheckedScope)) {
8716 return base.CreateExpressionTree (ec);
8720 public override void Emit (EmitContext ec)
8724 var expr_type = child.Type;
8726 if (expr_type == TypeManager.uint32_type)
8727 ec.Emit (OpCodes.Conv_U);
8728 else if (expr_type == TypeManager.int64_type)
8729 ec.Emit (OpCodes.Conv_Ovf_I);
8730 else if (expr_type == TypeManager.uint64_type)
8731 ec.Emit (OpCodes.Conv_Ovf_I_Un);
8733 throw new InternalErrorException ("Cannot emit cast to unknown array element type", type);
8738 // Implements the `stackalloc' keyword
8740 public class StackAlloc : Expression {
8745 public StackAlloc (Expression type, Expression count, Location l)
8752 public override Expression CreateExpressionTree (ResolveContext ec)
8754 throw new NotSupportedException ("ET");
8757 protected override Expression DoResolve (ResolveContext ec)
8759 count = count.Resolve (ec);
8763 if (count.Type != TypeManager.uint32_type){
8764 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8769 Constant c = count as Constant;
8770 if (c != null && c.IsNegative) {
8771 ec.Report.Error (247, loc, "Cannot use a negative size with stackalloc");
8774 if (ec.HasAny (ResolveContext.Options.CatchScope | ResolveContext.Options.FinallyScope)) {
8775 ec.Report.Error (255, loc, "Cannot use stackalloc in finally or catch");
8778 TypeExpr texpr = t.ResolveAsTypeTerminal (ec, false);
8784 if (!TypeManager.VerifyUnmanaged (ec.Compiler, otype, loc))
8787 type = PointerContainer.MakeType (otype);
8788 eclass = ExprClass.Value;
8793 public override void Emit (EmitContext ec)
8795 int size = GetTypeSize (otype);
8800 ec.Emit (OpCodes.Sizeof, otype);
8804 ec.Emit (OpCodes.Mul_Ovf_Un);
8805 ec.Emit (OpCodes.Localloc);
8808 protected override void CloneTo (CloneContext clonectx, Expression t)
8810 StackAlloc target = (StackAlloc) t;
8811 target.count = count.Clone (clonectx);
8812 target.t = t.Clone (clonectx);
8817 // An object initializer expression
8819 public class ElementInitializer : Assign
8821 public readonly string Name;
8823 public ElementInitializer (string name, Expression initializer, Location loc)
8824 : base (null, initializer, loc)
8829 protected override void CloneTo (CloneContext clonectx, Expression t)
8831 ElementInitializer target = (ElementInitializer) t;
8832 target.source = source.Clone (clonectx);
8835 public override Expression CreateExpressionTree (ResolveContext ec)
8837 Arguments args = new Arguments (2);
8838 FieldExpr fe = target as FieldExpr;
8840 args.Add (new Argument (fe.CreateTypeOfExpression ()));
8842 args.Add (new Argument (((PropertyExpr)target).CreateSetterTypeOfExpression ()));
8844 args.Add (new Argument (source.CreateExpressionTree (ec)));
8845 return CreateExpressionFactoryCall (ec,
8846 source is CollectionOrObjectInitializers ? "ListBind" : "Bind",
8850 protected override Expression DoResolve (ResolveContext ec)
8853 return EmptyExpressionStatement.Instance;
8855 MemberExpr me = MemberLookupFinal (ec, ec.CurrentInitializerVariable.Type, ec.CurrentInitializerVariable.Type,
8856 Name, 0, MemberKind.Field | MemberKind.Property, BindingRestriction.AccessibleOnly | BindingRestriction.InstanceOnly | BindingRestriction.DefaultMemberLookup, loc) as MemberExpr;
8862 me.InstanceExpression = ec.CurrentInitializerVariable;
8864 if (source is CollectionOrObjectInitializers) {
8865 Expression previous = ec.CurrentInitializerVariable;
8866 ec.CurrentInitializerVariable = target;
8867 source = source.Resolve (ec);
8868 ec.CurrentInitializerVariable = previous;
8872 eclass = source.eclass;
8877 return base.DoResolve (ec);
8880 protected override MemberExpr Error_MemberLookupFailed (ResolveContext ec, TypeSpec type, IList<MemberSpec> members)
8882 var member = members.First ();
8883 if (member.Kind != MemberKind.Property && member.Kind != MemberKind.Field)
8884 ec.Report.Error (1913, loc, "Member `{0}' cannot be initialized. An object " +
8885 "initializer may only be used for fields, or properties", TypeManager.GetFullNameSignature (member));
8887 ec.Report.Error (1914, loc, " Static field or property `{0}' cannot be assigned in an object initializer",
8888 TypeManager.GetFullNameSignature (member));
8893 public override void EmitStatement (EmitContext ec)
8895 if (source is CollectionOrObjectInitializers)
8898 base.EmitStatement (ec);
8903 // A collection initializer expression
8905 class CollectionElementInitializer : Invocation
8907 public class ElementInitializerArgument : Argument
8909 public ElementInitializerArgument (Expression e)
8915 sealed class AddMemberAccess : MemberAccess
8917 public AddMemberAccess (Expression expr, Location loc)
8918 : base (expr, "Add", loc)
8922 protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
8924 if (TypeManager.HasElementType (type))
8927 base.Error_TypeDoesNotContainDefinition (ec, type, name);
8931 public CollectionElementInitializer (Expression argument)
8932 : base (null, new Arguments (1))
8934 base.arguments.Add (new ElementInitializerArgument (argument));
8935 this.loc = argument.Location;
8938 public CollectionElementInitializer (List<Expression> arguments, Location loc)
8939 : base (null, new Arguments (arguments.Count))
8941 foreach (Expression e in arguments)
8942 base.arguments.Add (new ElementInitializerArgument (e));
8947 public override Expression CreateExpressionTree (ResolveContext ec)
8949 Arguments args = new Arguments (2);
8950 args.Add (new Argument (mg.CreateExpressionTree (ec)));
8952 var expr_initializers = new ArrayInitializer (arguments.Count, loc);
8953 foreach (Argument a in arguments)
8954 expr_initializers.Add (a.CreateExpressionTree (ec));
8956 args.Add (new Argument (new ArrayCreation (
8957 CreateExpressionTypeExpression (ec, loc), expr_initializers, loc)));
8958 return CreateExpressionFactoryCall (ec, "ElementInit", args);
8961 protected override void CloneTo (CloneContext clonectx, Expression t)
8963 CollectionElementInitializer target = (CollectionElementInitializer) t;
8964 if (arguments != null)
8965 target.arguments = arguments.Clone (clonectx);
8968 protected override Expression DoResolve (ResolveContext ec)
8970 base.expr = new AddMemberAccess (ec.CurrentInitializerVariable, loc);
8972 return base.DoResolve (ec);
8977 // A block of object or collection initializers
8979 public class CollectionOrObjectInitializers : ExpressionStatement
8981 IList<Expression> initializers;
8982 bool is_collection_initialization;
8984 public static readonly CollectionOrObjectInitializers Empty =
8985 new CollectionOrObjectInitializers (Array.AsReadOnly (new Expression [0]), Location.Null);
8987 public CollectionOrObjectInitializers (IList<Expression> initializers, Location loc)
8989 this.initializers = initializers;
8993 public bool IsEmpty {
8995 return initializers.Count == 0;
8999 public bool IsCollectionInitializer {
9001 return is_collection_initialization;
9005 protected override void CloneTo (CloneContext clonectx, Expression target)
9007 CollectionOrObjectInitializers t = (CollectionOrObjectInitializers) target;
9009 t.initializers = new List<Expression> (initializers.Count);
9010 foreach (var e in initializers)
9011 t.initializers.Add (e.Clone (clonectx));
9014 public override Expression CreateExpressionTree (ResolveContext ec)
9016 var expr_initializers = new ArrayInitializer (initializers.Count, loc);
9017 foreach (Expression e in initializers) {
9018 Expression expr = e.CreateExpressionTree (ec);
9020 expr_initializers.Add (expr);
9023 return new ImplicitlyTypedArrayCreation (expr_initializers, loc);
9026 protected override Expression DoResolve (ResolveContext ec)
9028 List<string> element_names = null;
9029 for (int i = 0; i < initializers.Count; ++i) {
9030 Expression initializer = initializers [i];
9031 ElementInitializer element_initializer = initializer as ElementInitializer;
9034 if (element_initializer != null) {
9035 element_names = new List<string> (initializers.Count);
9036 element_names.Add (element_initializer.Name);
9037 } else if (initializer is CompletingExpression){
9038 initializer.Resolve (ec);
9039 throw new InternalErrorException ("This line should never be reached");
9041 if (!ec.CurrentInitializerVariable.Type.ImplementsInterface (TypeManager.ienumerable_type)) {
9042 ec.Report.Error (1922, loc, "A field or property `{0}' cannot be initialized with a collection " +
9043 "object initializer because type `{1}' does not implement `{2}' interface",
9044 ec.CurrentInitializerVariable.GetSignatureForError (),
9045 TypeManager.CSharpName (ec.CurrentInitializerVariable.Type),
9046 TypeManager.CSharpName (TypeManager.ienumerable_type));
9049 is_collection_initialization = true;
9052 if (is_collection_initialization != (element_initializer == null)) {
9053 ec.Report.Error (747, initializer.Location, "Inconsistent `{0}' member declaration",
9054 is_collection_initialization ? "collection initializer" : "object initializer");
9058 if (!is_collection_initialization) {
9059 if (element_names.Contains (element_initializer.Name)) {
9060 ec.Report.Error (1912, element_initializer.Location,
9061 "An object initializer includes more than one member `{0}' initialization",
9062 element_initializer.Name);
9064 element_names.Add (element_initializer.Name);
9069 Expression e = initializer.Resolve (ec);
9070 if (e == EmptyExpressionStatement.Instance)
9071 initializers.RemoveAt (i--);
9073 initializers [i] = e;
9076 type = ec.CurrentInitializerVariable.Type;
9077 if (is_collection_initialization) {
9078 if (TypeManager.HasElementType (type)) {
9079 ec.Report.Error (1925, loc, "Cannot initialize object of type `{0}' with a collection initializer",
9080 TypeManager.CSharpName (type));
9084 eclass = ExprClass.Variable;
9088 public override void Emit (EmitContext ec)
9093 public override void EmitStatement (EmitContext ec)
9095 foreach (ExpressionStatement e in initializers)
9096 e.EmitStatement (ec);
9101 // New expression with element/object initializers
9103 public class NewInitialize : New
9106 // This class serves as a proxy for variable initializer target instances.
9107 // A real variable is assigned later when we resolve left side of an
9110 sealed class InitializerTargetExpression : Expression, IMemoryLocation
9112 NewInitialize new_instance;
9114 public InitializerTargetExpression (NewInitialize newInstance)
9116 this.type = newInstance.type;
9117 this.loc = newInstance.loc;
9118 this.eclass = newInstance.eclass;
9119 this.new_instance = newInstance;
9122 public override Expression CreateExpressionTree (ResolveContext ec)
9124 // Should not be reached
9125 throw new NotSupportedException ("ET");
9128 protected override Expression DoResolve (ResolveContext ec)
9133 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
9138 public override void Emit (EmitContext ec)
9140 Expression e = (Expression) new_instance.instance;
9144 #region IMemoryLocation Members
9146 public void AddressOf (EmitContext ec, AddressOp mode)
9148 new_instance.instance.AddressOf (ec, mode);
9154 CollectionOrObjectInitializers initializers;
9155 IMemoryLocation instance;
9157 public NewInitialize (FullNamedExpression requested_type, Arguments arguments, CollectionOrObjectInitializers initializers, Location l)
9158 : base (requested_type, arguments, l)
9160 this.initializers = initializers;
9163 protected override IMemoryLocation EmitAddressOf (EmitContext ec, AddressOp Mode)
9165 instance = base.EmitAddressOf (ec, Mode);
9167 if (!initializers.IsEmpty)
9168 initializers.Emit (ec);
9173 protected override void CloneTo (CloneContext clonectx, Expression t)
9175 base.CloneTo (clonectx, t);
9177 NewInitialize target = (NewInitialize) t;
9178 target.initializers = (CollectionOrObjectInitializers) initializers.Clone (clonectx);
9181 public override Expression CreateExpressionTree (ResolveContext ec)
9183 Arguments args = new Arguments (2);
9184 args.Add (new Argument (base.CreateExpressionTree (ec)));
9185 if (!initializers.IsEmpty)
9186 args.Add (new Argument (initializers.CreateExpressionTree (ec)));
9188 return CreateExpressionFactoryCall (ec,
9189 initializers.IsCollectionInitializer ? "ListInit" : "MemberInit",
9193 protected override Expression DoResolve (ResolveContext ec)
9195 Expression e = base.DoResolve (ec);
9199 Expression previous = ec.CurrentInitializerVariable;
9200 ec.CurrentInitializerVariable = new InitializerTargetExpression (this);
9201 initializers.Resolve (ec);
9202 ec.CurrentInitializerVariable = previous;
9206 public override bool Emit (EmitContext ec, IMemoryLocation target)
9208 bool left_on_stack = base.Emit (ec, target);
9210 if (initializers.IsEmpty)
9211 return left_on_stack;
9213 LocalTemporary temp = target as LocalTemporary;
9215 if (!left_on_stack) {
9216 VariableReference vr = target as VariableReference;
9218 // FIXME: This still does not work correctly for pre-set variables
9219 if (vr != null && vr.IsRef)
9220 target.AddressOf (ec, AddressOp.Load);
9222 ((Expression) target).Emit (ec);
9223 left_on_stack = true;
9226 temp = new LocalTemporary (type);
9233 initializers.Emit (ec);
9235 if (left_on_stack) {
9240 return left_on_stack;
9243 public override bool HasInitializer {
9245 return !initializers.IsEmpty;
9250 public class NewAnonymousType : New
9252 static readonly AnonymousTypeParameter[] EmptyParameters = new AnonymousTypeParameter[0];
9254 List<AnonymousTypeParameter> parameters;
9255 readonly TypeContainer parent;
9256 AnonymousTypeClass anonymous_type;
9258 public NewAnonymousType (List<AnonymousTypeParameter> parameters, TypeContainer parent, Location loc)
9259 : base (null, null, loc)
9261 this.parameters = parameters;
9262 this.parent = parent;
9265 protected override void CloneTo (CloneContext clonectx, Expression target)
9267 if (parameters == null)
9270 NewAnonymousType t = (NewAnonymousType) target;
9271 t.parameters = new List<AnonymousTypeParameter> (parameters.Count);
9272 foreach (AnonymousTypeParameter atp in parameters)
9273 t.parameters.Add ((AnonymousTypeParameter) atp.Clone (clonectx));
9276 AnonymousTypeClass CreateAnonymousType (ResolveContext ec, IList<AnonymousTypeParameter> parameters)
9278 AnonymousTypeClass type = parent.Module.Compiled.GetAnonymousType (parameters);
9282 type = AnonymousTypeClass.Create (ec.Compiler, parent, parameters, loc);
9288 type.ResolveTypeParameters ();
9291 if (ec.Report.Errors == 0)
9294 parent.Module.Compiled.AddAnonymousType (type);
9298 public override Expression CreateExpressionTree (ResolveContext ec)
9300 if (parameters == null)
9301 return base.CreateExpressionTree (ec);
9303 var init = new ArrayInitializer (parameters.Count, loc);
9304 foreach (Property p in anonymous_type.Properties)
9305 init.Add (new TypeOfMethod (MemberCache.GetMember (type, p.Get.Spec), loc));
9307 var ctor_args = new ArrayInitializer (Arguments.Count, loc);
9308 foreach (Argument a in Arguments)
9309 ctor_args.Add (a.CreateExpressionTree (ec));
9311 Arguments args = new Arguments (3);
9312 args.Add (new Argument (method.CreateExpressionTree (ec)));
9313 args.Add (new Argument (new ArrayCreation (TypeManager.expression_type_expr, ctor_args, loc)));
9314 args.Add (new Argument (new ImplicitlyTypedArrayCreation (init, loc)));
9316 return CreateExpressionFactoryCall (ec, "New", args);
9319 protected override Expression DoResolve (ResolveContext ec)
9321 if (ec.HasSet (ResolveContext.Options.ConstantScope)) {
9322 ec.Report.Error (836, loc, "Anonymous types cannot be used in this expression");
9326 if (parameters == null) {
9327 anonymous_type = CreateAnonymousType (ec, EmptyParameters);
9328 RequestedType = new TypeExpression (anonymous_type.Definition, loc);
9329 return base.DoResolve (ec);
9333 Arguments = new Arguments (parameters.Count);
9334 TypeExpression [] t_args = new TypeExpression [parameters.Count];
9335 for (int i = 0; i < parameters.Count; ++i) {
9336 Expression e = ((AnonymousTypeParameter) parameters [i]).Resolve (ec);
9342 Arguments.Add (new Argument (e));
9343 t_args [i] = new TypeExpression (e.Type, e.Location);
9349 anonymous_type = CreateAnonymousType (ec, parameters);
9350 if (anonymous_type == null)
9353 RequestedType = new GenericTypeExpr (anonymous_type.Definition, new TypeArguments (t_args), loc);
9354 return base.DoResolve (ec);
9358 public class AnonymousTypeParameter : ShimExpression
9360 public readonly string Name;
9362 public AnonymousTypeParameter (Expression initializer, string name, Location loc)
9363 : base (initializer)
9369 public AnonymousTypeParameter (Parameter parameter)
9370 : base (new SimpleName (parameter.Name, parameter.Location))
9372 this.Name = parameter.Name;
9373 this.loc = parameter.Location;
9376 public override bool Equals (object o)
9378 AnonymousTypeParameter other = o as AnonymousTypeParameter;
9379 return other != null && Name == other.Name;
9382 public override int GetHashCode ()
9384 return Name.GetHashCode ();
9387 protected override Expression DoResolve (ResolveContext ec)
9389 Expression e = expr.Resolve (ec);
9393 if (e.eclass == ExprClass.MethodGroup) {
9394 Error_InvalidInitializer (ec, e.ExprClassName);
9399 if (type == TypeManager.void_type || type == TypeManager.null_type ||
9400 type == InternalType.AnonymousMethod || type.IsPointer) {
9401 Error_InvalidInitializer (ec, e.GetSignatureForError ());
9408 protected virtual void Error_InvalidInitializer (ResolveContext ec, string initializer)
9410 ec.Report.Error (828, loc, "An anonymous type property `{0}' cannot be initialized with `{1}'",