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.
12 namespace Mono.CSharp {
14 using System.Collections.Generic;
15 using System.Reflection;
16 using System.Reflection.Emit;
19 using SLE = System.Linq.Expressions;
22 // This is an user operator expression, automatically created during
25 public class UserOperatorCall : Expression {
26 protected readonly Arguments arguments;
27 protected readonly MethodSpec oper;
28 readonly Func<ResolveContext, Expression, Expression> expr_tree;
30 public UserOperatorCall (MethodSpec oper, Arguments args, Func<ResolveContext, Expression, Expression> expr_tree, Location loc)
33 this.arguments = args;
34 this.expr_tree = expr_tree;
36 type = oper.ReturnType;
37 eclass = ExprClass.Value;
41 public override Expression CreateExpressionTree (ResolveContext ec)
43 if (expr_tree != null)
44 return expr_tree (ec, new TypeOfMethod (oper, loc));
46 Arguments args = Arguments.CreateForExpressionTree (ec, arguments,
47 new NullLiteral (loc),
48 new TypeOfMethod (oper, loc));
50 return CreateExpressionFactoryCall (ec, "Call", args);
53 protected override void CloneTo (CloneContext context, Expression target)
58 protected override Expression DoResolve (ResolveContext ec)
61 // We are born fully resolved
66 public override void Emit (EmitContext ec)
68 Invocation.EmitCall (ec, null, oper, arguments, loc);
71 public override SLE.Expression MakeExpression (BuilderContext ctx)
73 var method = oper.GetMetaInfo () as MethodInfo;
74 return SLE.Expression.Call (method, Arguments.MakeExpression (arguments, ctx));
78 public class ParenthesizedExpression : ShimExpression
80 public ParenthesizedExpression (Expression expr)
86 protected override Expression DoResolve (ResolveContext ec)
88 return expr.Resolve (ec);
91 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
93 return expr.DoResolveLValue (ec, right_side);
98 // Unary implements unary expressions.
100 public class Unary : Expression
102 public enum Operator : byte {
103 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
107 static TypeSpec[][] predefined_operators;
109 public readonly Operator Oper;
110 public Expression Expr;
111 Expression enum_conversion;
113 public Unary (Operator op, Expression expr, Location loc)
121 // This routine will attempt to simplify the unary expression when the
122 // argument is a constant.
124 Constant TryReduceConstant (ResolveContext ec, Constant e)
126 if (e is EmptyConstantCast)
127 return TryReduceConstant (ec, ((EmptyConstantCast) e).child);
129 if (e is SideEffectConstant) {
130 Constant r = TryReduceConstant (ec, ((SideEffectConstant) e).value);
131 return r == null ? null : new SideEffectConstant (r, e, r.Location);
134 TypeSpec expr_type = e.Type;
137 case Operator.UnaryPlus:
138 // Unary numeric promotions
139 if (expr_type == TypeManager.byte_type)
140 return new IntConstant (((ByteConstant)e).Value, e.Location);
141 if (expr_type == TypeManager.sbyte_type)
142 return new IntConstant (((SByteConstant)e).Value, e.Location);
143 if (expr_type == TypeManager.short_type)
144 return new IntConstant (((ShortConstant)e).Value, e.Location);
145 if (expr_type == TypeManager.ushort_type)
146 return new IntConstant (((UShortConstant)e).Value, e.Location);
147 if (expr_type == TypeManager.char_type)
148 return new IntConstant (((CharConstant)e).Value, e.Location);
150 // Predefined operators
151 if (expr_type == TypeManager.int32_type || expr_type == TypeManager.uint32_type ||
152 expr_type == TypeManager.int64_type || expr_type == TypeManager.uint64_type ||
153 expr_type == TypeManager.float_type || expr_type == TypeManager.double_type ||
154 expr_type == TypeManager.decimal_type) {
160 case Operator.UnaryNegation:
161 // Unary numeric promotions
162 if (expr_type == TypeManager.byte_type)
163 return new IntConstant (-((ByteConstant)e).Value, e.Location);
164 if (expr_type == TypeManager.sbyte_type)
165 return new IntConstant (-((SByteConstant)e).Value, e.Location);
166 if (expr_type == TypeManager.short_type)
167 return new IntConstant (-((ShortConstant)e).Value, e.Location);
168 if (expr_type == TypeManager.ushort_type)
169 return new IntConstant (-((UShortConstant)e).Value, e.Location);
170 if (expr_type == TypeManager.char_type)
171 return new IntConstant (-((CharConstant)e).Value, e.Location);
173 // Predefined operators
174 if (expr_type == TypeManager.int32_type) {
175 int value = ((IntConstant)e).Value;
176 if (value == int.MinValue) {
177 if (ec.ConstantCheckState) {
178 ConstantFold.Error_CompileTimeOverflow (ec, loc);
183 return new IntConstant (-value, e.Location);
185 if (expr_type == TypeManager.int64_type) {
186 long value = ((LongConstant)e).Value;
187 if (value == long.MinValue) {
188 if (ec.ConstantCheckState) {
189 ConstantFold.Error_CompileTimeOverflow (ec, loc);
194 return new LongConstant (-value, e.Location);
197 if (expr_type == TypeManager.uint32_type) {
198 UIntLiteral uil = e as UIntLiteral;
200 if (uil.Value == int.MaxValue + (uint) 1)
201 return new IntLiteral (int.MinValue, e.Location);
202 return new LongLiteral (-uil.Value, e.Location);
204 return new LongConstant (-((UIntConstant)e).Value, e.Location);
207 if (expr_type == TypeManager.uint64_type) {
208 ULongLiteral ull = e as ULongLiteral;
209 if (ull != null && ull.Value == 9223372036854775808)
210 return new LongLiteral (long.MinValue, e.Location);
214 if (expr_type == TypeManager.float_type) {
215 FloatLiteral fl = e as FloatLiteral;
216 // For better error reporting
218 return new FloatLiteral (-fl.Value, e.Location);
220 return new FloatConstant (-((FloatConstant)e).Value, e.Location);
222 if (expr_type == TypeManager.double_type) {
223 DoubleLiteral dl = e as DoubleLiteral;
224 // For better error reporting
226 return new DoubleLiteral (-dl.Value, e.Location);
228 return new DoubleConstant (-((DoubleConstant)e).Value, e.Location);
230 if (expr_type == TypeManager.decimal_type)
231 return new DecimalConstant (-((DecimalConstant)e).Value, e.Location);
235 case Operator.LogicalNot:
236 if (expr_type != TypeManager.bool_type)
239 bool b = (bool)e.GetValue ();
240 return new BoolConstant (!b, e.Location);
242 case Operator.OnesComplement:
243 // Unary numeric promotions
244 if (expr_type == TypeManager.byte_type)
245 return new IntConstant (~((ByteConstant)e).Value, e.Location);
246 if (expr_type == TypeManager.sbyte_type)
247 return new IntConstant (~((SByteConstant)e).Value, e.Location);
248 if (expr_type == TypeManager.short_type)
249 return new IntConstant (~((ShortConstant)e).Value, e.Location);
250 if (expr_type == TypeManager.ushort_type)
251 return new IntConstant (~((UShortConstant)e).Value, e.Location);
252 if (expr_type == TypeManager.char_type)
253 return new IntConstant (~((CharConstant)e).Value, e.Location);
255 // Predefined operators
256 if (expr_type == TypeManager.int32_type)
257 return new IntConstant (~((IntConstant)e).Value, e.Location);
258 if (expr_type == TypeManager.uint32_type)
259 return new UIntConstant (~((UIntConstant)e).Value, e.Location);
260 if (expr_type == TypeManager.int64_type)
261 return new LongConstant (~((LongConstant)e).Value, e.Location);
262 if (expr_type == TypeManager.uint64_type){
263 return new ULongConstant (~((ULongConstant)e).Value, e.Location);
265 if (e is EnumConstant) {
266 e = TryReduceConstant (ec, ((EnumConstant)e).Child);
268 e = new EnumConstant (e, expr_type);
273 throw new Exception ("Can not constant fold: " + Oper.ToString());
276 protected Expression ResolveOperator (ResolveContext ec, Expression expr)
278 eclass = ExprClass.Value;
280 if (predefined_operators == null)
281 CreatePredefinedOperatorsTable ();
283 TypeSpec expr_type = expr.Type;
284 Expression best_expr;
287 // Primitive types first
289 if (TypeManager.IsPrimitiveType (expr_type)) {
290 best_expr = ResolvePrimitivePredefinedType (expr);
291 if (best_expr == null)
294 type = best_expr.Type;
300 // E operator ~(E x);
302 if (Oper == Operator.OnesComplement && TypeManager.IsEnumType (expr_type))
303 return ResolveEnumOperator (ec, expr);
305 return ResolveUserType (ec, expr);
308 protected virtual Expression ResolveEnumOperator (ResolveContext ec, Expression expr)
310 TypeSpec underlying_type = EnumSpec.GetUnderlyingType (expr.Type);
311 Expression best_expr = ResolvePrimitivePredefinedType (EmptyCast.Create (expr, underlying_type));
312 if (best_expr == null)
316 enum_conversion = Convert.ExplicitNumericConversion (new EmptyExpression (best_expr.Type), underlying_type);
318 return EmptyCast.Create (this, type);
321 public override Expression CreateExpressionTree (ResolveContext ec)
323 return CreateExpressionTree (ec, null);
326 Expression CreateExpressionTree (ResolveContext ec, Expression user_op)
330 case Operator.AddressOf:
331 Error_PointerInsideExpressionTree (ec);
333 case Operator.UnaryNegation:
334 if (ec.HasSet (ResolveContext.Options.CheckedScope) && user_op == null && !IsFloat (type))
335 method_name = "NegateChecked";
337 method_name = "Negate";
339 case Operator.OnesComplement:
340 case Operator.LogicalNot:
343 case Operator.UnaryPlus:
344 method_name = "UnaryPlus";
347 throw new InternalErrorException ("Unknown unary operator " + Oper.ToString ());
350 Arguments args = new Arguments (2);
351 args.Add (new Argument (Expr.CreateExpressionTree (ec)));
353 args.Add (new Argument (user_op));
355 return CreateExpressionFactoryCall (ec, method_name, args);
358 static void CreatePredefinedOperatorsTable ()
360 predefined_operators = new TypeSpec [(int) Operator.TOP] [];
363 // 7.6.1 Unary plus operator
365 predefined_operators [(int) Operator.UnaryPlus] = new TypeSpec [] {
366 TypeManager.int32_type, TypeManager.uint32_type,
367 TypeManager.int64_type, TypeManager.uint64_type,
368 TypeManager.float_type, TypeManager.double_type,
369 TypeManager.decimal_type
373 // 7.6.2 Unary minus operator
375 predefined_operators [(int) Operator.UnaryNegation] = new TypeSpec [] {
376 TypeManager.int32_type,
377 TypeManager.int64_type,
378 TypeManager.float_type, TypeManager.double_type,
379 TypeManager.decimal_type
383 // 7.6.3 Logical negation operator
385 predefined_operators [(int) Operator.LogicalNot] = new TypeSpec [] {
386 TypeManager.bool_type
390 // 7.6.4 Bitwise complement operator
392 predefined_operators [(int) Operator.OnesComplement] = new TypeSpec [] {
393 TypeManager.int32_type, TypeManager.uint32_type,
394 TypeManager.int64_type, TypeManager.uint64_type
399 // Unary numeric promotions
401 static Expression DoNumericPromotion (Operator op, Expression expr)
403 TypeSpec expr_type = expr.Type;
404 if ((op == Operator.UnaryPlus || op == Operator.UnaryNegation || op == Operator.OnesComplement) &&
405 expr_type == TypeManager.byte_type || expr_type == TypeManager.sbyte_type ||
406 expr_type == TypeManager.short_type || expr_type == TypeManager.ushort_type ||
407 expr_type == TypeManager.char_type)
408 return Convert.ImplicitNumericConversion (expr, TypeManager.int32_type);
410 if (op == Operator.UnaryNegation && expr_type == TypeManager.uint32_type)
411 return Convert.ImplicitNumericConversion (expr, TypeManager.int64_type);
416 protected override Expression DoResolve (ResolveContext ec)
418 if (Oper == Operator.AddressOf) {
419 return ResolveAddressOf (ec);
422 Expr = Expr.Resolve (ec);
426 if (Expr.Type == InternalType.Dynamic) {
427 Arguments args = new Arguments (1);
428 args.Add (new Argument (Expr));
429 return new DynamicUnaryConversion (GetOperatorExpressionTypeName (), args, loc).Resolve (ec);
432 if (TypeManager.IsNullableType (Expr.Type))
433 return new Nullable.LiftedUnaryOperator (Oper, Expr, loc).Resolve (ec);
436 // Attempt to use a constant folding operation.
438 Constant cexpr = Expr as Constant;
440 cexpr = TryReduceConstant (ec, cexpr);
442 return cexpr.Resolve (ec);
445 Expression expr = ResolveOperator (ec, Expr);
447 Error_OperatorCannotBeApplied (ec, loc, OperName (Oper), Expr.Type);
450 // Reduce unary operator on predefined types
452 if (expr == this && Oper == Operator.UnaryPlus)
458 public override Expression DoResolveLValue (ResolveContext ec, Expression right)
463 public override void Emit (EmitContext ec)
465 EmitOperator (ec, type);
468 protected void EmitOperator (EmitContext ec, TypeSpec type)
471 case Operator.UnaryPlus:
475 case Operator.UnaryNegation:
476 if (ec.HasSet (EmitContext.Options.CheckedScope) && !IsFloat (type)) {
477 ec.Emit (OpCodes.Ldc_I4_0);
478 if (type == TypeManager.int64_type)
479 ec.Emit (OpCodes.Conv_U8);
481 ec.Emit (OpCodes.Sub_Ovf);
484 ec.Emit (OpCodes.Neg);
489 case Operator.LogicalNot:
491 ec.Emit (OpCodes.Ldc_I4_0);
492 ec.Emit (OpCodes.Ceq);
495 case Operator.OnesComplement:
497 ec.Emit (OpCodes.Not);
500 case Operator.AddressOf:
501 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
505 throw new Exception ("This should not happen: Operator = "
510 // Same trick as in Binary expression
512 if (enum_conversion != null)
513 enum_conversion.Emit (ec);
516 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
518 if (Oper == Operator.LogicalNot)
519 Expr.EmitBranchable (ec, target, !on_true);
521 base.EmitBranchable (ec, target, on_true);
524 public override void EmitSideEffect (EmitContext ec)
526 Expr.EmitSideEffect (ec);
529 public static void Error_OperatorCannotBeApplied (ResolveContext ec, Location loc, string oper, TypeSpec t)
531 ec.Report.Error (23, loc, "The `{0}' operator cannot be applied to operand of type `{1}'",
532 oper, TypeManager.CSharpName (t));
536 // Converts operator to System.Linq.Expressions.ExpressionType enum name
538 string GetOperatorExpressionTypeName ()
541 case Operator.OnesComplement:
542 return "OnesComplement";
543 case Operator.LogicalNot:
545 case Operator.UnaryNegation:
547 case Operator.UnaryPlus:
550 throw new NotImplementedException ("Unknown express type operator " + Oper.ToString ());
554 static bool IsFloat (TypeSpec t)
556 return t == TypeManager.float_type || t == TypeManager.double_type;
560 // Returns a stringified representation of the Operator
562 public static string OperName (Operator oper)
565 case Operator.UnaryPlus:
567 case Operator.UnaryNegation:
569 case Operator.LogicalNot:
571 case Operator.OnesComplement:
573 case Operator.AddressOf:
577 throw new NotImplementedException (oper.ToString ());
580 public override SLE.Expression MakeExpression (BuilderContext ctx)
582 var expr = Expr.MakeExpression (ctx);
583 bool is_checked = ctx.HasSet (BuilderContext.Options.CheckedScope);
586 case Operator.UnaryNegation:
587 return is_checked ? SLE.Expression.NegateChecked (expr) : SLE.Expression.Negate (expr);
588 case Operator.LogicalNot:
589 return SLE.Expression.Not (expr);
591 case Operator.OnesComplement:
592 return SLE.Expression.OnesComplement (expr);
595 throw new NotImplementedException (Oper.ToString ());
599 public static void Reset ()
601 predefined_operators = null;
604 Expression ResolveAddressOf (ResolveContext ec)
607 UnsafeError (ec, loc);
609 Expr = Expr.DoResolveLValue (ec, EmptyExpression.UnaryAddress);
610 if (Expr == null || Expr.eclass != ExprClass.Variable) {
611 ec.Report.Error (211, loc, "Cannot take the address of the given expression");
615 if (!TypeManager.VerifyUnmanaged (ec.Compiler, Expr.Type, loc)) {
619 IVariableReference vr = Expr as IVariableReference;
622 VariableInfo vi = vr.VariableInfo;
624 if (vi.LocalInfo != null)
625 vi.LocalInfo.Used = true;
628 // A variable is considered definitely assigned if you take its address.
633 is_fixed = vr.IsFixed;
634 vr.SetHasAddressTaken ();
637 AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, vr, loc);
640 IFixedExpression fe = Expr as IFixedExpression;
641 is_fixed = fe != null && fe.IsFixed;
644 if (!is_fixed && !ec.HasSet (ResolveContext.Options.FixedInitializerScope)) {
645 ec.Report.Error (212, loc, "You can only take the address of unfixed expression inside of a fixed statement initializer");
648 type = PointerContainer.MakeType (Expr.Type);
649 eclass = ExprClass.Value;
653 Expression ResolvePrimitivePredefinedType (Expression expr)
655 expr = DoNumericPromotion (Oper, expr);
656 TypeSpec expr_type = expr.Type;
657 TypeSpec[] predefined = predefined_operators [(int) Oper];
658 foreach (TypeSpec t in predefined) {
666 // Perform user-operator overload resolution
668 protected virtual Expression ResolveUserOperator (ResolveContext ec, Expression expr)
670 CSharp.Operator.OpType op_type;
672 case Operator.LogicalNot:
673 op_type = CSharp.Operator.OpType.LogicalNot; break;
674 case Operator.OnesComplement:
675 op_type = CSharp.Operator.OpType.OnesComplement; break;
676 case Operator.UnaryNegation:
677 op_type = CSharp.Operator.OpType.UnaryNegation; break;
678 case Operator.UnaryPlus:
679 op_type = CSharp.Operator.OpType.UnaryPlus; break;
681 throw new InternalErrorException (Oper.ToString ());
684 var methods = MemberCache.GetUserOperator (expr.Type, op_type, false);
688 Arguments args = new Arguments (1);
689 args.Add (new Argument (expr));
691 var res = new OverloadResolver (methods, OverloadResolver.Restrictions.NoBaseMembers, loc);
692 var oper = res.ResolveOperator (ec, ref args);
697 Expr = args [0].Expr;
698 return new UserOperatorCall (oper, args, CreateExpressionTree, expr.Location);
702 // Unary user type overload resolution
704 Expression ResolveUserType (ResolveContext ec, Expression expr)
706 Expression best_expr = ResolveUserOperator (ec, expr);
707 if (best_expr != null)
710 TypeSpec[] predefined = predefined_operators [(int) Oper];
711 foreach (TypeSpec t in predefined) {
712 Expression oper_expr = Convert.ImplicitUserConversion (ec, expr, t, expr.Location);
713 if (oper_expr == null)
717 // decimal type is predefined but has user-operators
719 if (oper_expr.Type == TypeManager.decimal_type)
720 oper_expr = ResolveUserType (ec, oper_expr);
722 oper_expr = ResolvePrimitivePredefinedType (oper_expr);
724 if (oper_expr == null)
727 if (best_expr == null) {
728 best_expr = oper_expr;
732 int result = OverloadResolver.BetterTypeConversion (ec, best_expr.Type, t);
734 ec.Report.Error (35, loc, "Operator `{0}' is ambiguous on an operand of type `{1}'",
735 OperName (Oper), TypeManager.CSharpName (expr.Type));
740 best_expr = oper_expr;
743 if (best_expr == null)
747 // HACK: Decimal user-operator is included in standard operators
749 if (best_expr.Type == TypeManager.decimal_type)
753 type = best_expr.Type;
757 protected override void CloneTo (CloneContext clonectx, Expression t)
759 Unary target = (Unary) t;
761 target.Expr = Expr.Clone (clonectx);
766 // Unary operators are turned into Indirection expressions
767 // after semantic analysis (this is so we can take the address
768 // of an indirection).
770 public class Indirection : Expression, IMemoryLocation, IAssignMethod, IFixedExpression {
772 LocalTemporary temporary;
775 public Indirection (Expression expr, Location l)
781 public override Expression CreateExpressionTree (ResolveContext ec)
783 Error_PointerInsideExpressionTree (ec);
787 protected override void CloneTo (CloneContext clonectx, Expression t)
789 Indirection target = (Indirection) t;
790 target.expr = expr.Clone (clonectx);
793 public override void Emit (EmitContext ec)
798 ec.EmitLoadFromPtr (Type);
801 public void Emit (EmitContext ec, bool leave_copy)
805 ec.Emit (OpCodes.Dup);
806 temporary = new LocalTemporary (expr.Type);
807 temporary.Store (ec);
811 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
813 prepared = prepare_for_load;
817 if (prepare_for_load)
818 ec.Emit (OpCodes.Dup);
822 ec.Emit (OpCodes.Dup);
823 temporary = new LocalTemporary (expr.Type);
824 temporary.Store (ec);
827 ec.EmitStoreFromPtr (type);
829 if (temporary != null) {
831 temporary.Release (ec);
835 public void AddressOf (EmitContext ec, AddressOp Mode)
840 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
842 return DoResolve (ec);
845 protected override Expression DoResolve (ResolveContext ec)
847 expr = expr.Resolve (ec);
852 UnsafeError (ec, loc);
854 if (!expr.Type.IsPointer) {
855 ec.Report.Error (193, loc, "The * or -> operator must be applied to a pointer");
859 if (expr.Type == TypeManager.void_ptr_type) {
860 ec.Report.Error (242, loc, "The operation in question is undefined on void pointers");
864 type = TypeManager.GetElementType (expr.Type);
865 eclass = ExprClass.Variable;
869 public bool IsFixed {
873 public override string ToString ()
875 return "*(" + expr + ")";
880 /// Unary Mutator expressions (pre and post ++ and --)
884 /// UnaryMutator implements ++ and -- expressions. It derives from
885 /// ExpressionStatement becuase the pre/post increment/decrement
886 /// operators can be used in a statement context.
888 /// FIXME: Idea, we could split this up in two classes, one simpler
889 /// for the common case, and one with the extra fields for more complex
890 /// classes (indexers require temporary access; overloaded require method)
893 public class UnaryMutator : ExpressionStatement
895 class DynamicPostMutator : Expression, IAssignMethod
900 public DynamicPostMutator (Expression expr)
903 this.type = expr.Type;
904 this.loc = expr.Location;
907 public override Expression CreateExpressionTree (ResolveContext ec)
909 throw new NotImplementedException ("ET");
912 protected override Expression DoResolve (ResolveContext rc)
914 eclass = expr.eclass;
918 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
920 expr.DoResolveLValue (ec, right_side);
921 return DoResolve (ec);
924 public override void Emit (EmitContext ec)
929 public void Emit (EmitContext ec, bool leave_copy)
931 throw new NotImplementedException ();
935 // Emits target assignment using unmodified source value
937 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
940 // Allocate temporary variable to keep original value before it's modified
942 temp = new LocalTemporary (type);
946 ((IAssignMethod) expr).EmitAssign (ec, source, false, prepare_for_load);
957 public enum Mode : byte {
964 PreDecrement = IsDecrement,
965 PostIncrement = IsPost,
966 PostDecrement = IsPost | IsDecrement
970 bool is_expr, recurse;
974 // Holds the real operation
975 Expression operation;
977 public UnaryMutator (Mode m, Expression e, Location loc)
984 public override Expression CreateExpressionTree (ResolveContext ec)
986 return new SimpleAssign (this, this).CreateExpressionTree (ec);
989 protected override Expression DoResolve (ResolveContext ec)
991 expr = expr.Resolve (ec);
996 if (expr.Type == InternalType.Dynamic) {
998 // Handle postfix unary operators using local
999 // temporary variable
1001 if ((mode & Mode.IsPost) != 0)
1002 expr = new DynamicPostMutator (expr);
1004 Arguments args = new Arguments (1);
1005 args.Add (new Argument (expr));
1006 return new SimpleAssign (expr, new DynamicUnaryConversion (GetOperatorExpressionTypeName (), args, loc)).Resolve (ec);
1009 if (TypeManager.IsNullableType (expr.Type))
1010 return new Nullable.LiftedUnaryMutator (mode, expr, loc).Resolve (ec);
1012 eclass = ExprClass.Value;
1014 return ResolveOperator (ec);
1017 void EmitCode (EmitContext ec, bool is_expr)
1020 this.is_expr = is_expr;
1021 ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
1024 public override void Emit (EmitContext ec)
1027 // We use recurse to allow ourselfs to be the source
1028 // of an assignment. This little hack prevents us from
1029 // having to allocate another expression
1032 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
1034 operation.Emit (ec);
1040 EmitCode (ec, true);
1043 public override void EmitStatement (EmitContext ec)
1045 EmitCode (ec, false);
1049 // Converts operator to System.Linq.Expressions.ExpressionType enum name
1051 string GetOperatorExpressionTypeName ()
1053 return IsDecrement ? "Decrement" : "Increment";
1057 get { return (mode & Mode.IsDecrement) != 0; }
1061 // Returns whether an object of type `t' can be incremented
1062 // or decremented with add/sub (ie, basically whether we can
1063 // use pre-post incr-decr operations on it, but it is not a
1064 // System.Decimal, which we require operator overloading to catch)
1066 static bool IsPredefinedOperator (TypeSpec t)
1068 return (TypeManager.IsPrimitiveType (t) && t != TypeManager.bool_type) ||
1069 TypeManager.IsEnumType (t) ||
1070 t.IsPointer && t != TypeManager.void_ptr_type;
1074 public override SLE.Expression MakeExpression (BuilderContext ctx)
1076 var target = ((RuntimeValueExpression) expr).MetaObject.Expression;
1077 var source = SLE.Expression.Convert (operation.MakeExpression (ctx), target.Type);
1078 return SLE.Expression.Assign (target, source);
1082 protected override void CloneTo (CloneContext clonectx, Expression t)
1084 UnaryMutator target = (UnaryMutator) t;
1086 target.expr = expr.Clone (clonectx);
1089 Expression ResolveOperator (ResolveContext ec)
1091 if (expr is RuntimeValueExpression) {
1094 // Use itself at the top of the stack
1095 operation = new EmptyExpression (type);
1099 // The operand of the prefix/postfix increment decrement operators
1100 // should be an expression that is classified as a variable,
1101 // a property access or an indexer access
1103 if (expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.IndexerAccess || expr.eclass == ExprClass.PropertyAccess) {
1104 expr = expr.ResolveLValue (ec, expr);
1106 ec.Report.Error (1059, loc, "The operand of an increment or decrement operator must be a variable, property or indexer");
1110 // 1. Check predefined types
1112 if (IsPredefinedOperator (type)) {
1113 // TODO: Move to IntConstant once I get rid of int32_type
1114 var one = new IntConstant (1, loc);
1116 // TODO: Cache this based on type when using EmptyExpression in
1118 Binary.Operator op = IsDecrement ? Binary.Operator.Subtraction : Binary.Operator.Addition;
1119 operation = new Binary (op, operation, one, loc);
1120 operation = operation.Resolve (ec);
1121 if (operation != null && operation.Type != type)
1122 operation = Convert.ExplicitNumericConversion (operation, type);
1128 // Step 2: Perform Operator Overload location
1130 var user_op = IsDecrement ? Operator.OpType.Decrement : Operator.OpType.Increment;
1131 var methods = MemberCache.GetUserOperator (type, user_op, false);
1133 if (methods != null) {
1134 Arguments args = new Arguments (1);
1135 args.Add (new Argument (expr));
1137 var res = new OverloadResolver (methods, OverloadResolver.Restrictions.NoBaseMembers, loc);
1138 var op = res.ResolveOperator (ec, ref args);
1142 args[0].Expr = operation;
1143 operation = new UserOperatorCall (op, args, null, loc);
1144 operation = Convert.ImplicitConversionRequired (ec, operation, type, loc);
1148 string name = IsDecrement ?
1149 Operator.GetName (Operator.OpType.Decrement) :
1150 Operator.GetName (Operator.OpType.Increment);
1152 Unary.Error_OperatorCannotBeApplied (ec, loc, name, type);
1158 /// Base class for the `Is' and `As' classes.
1162 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1165 public abstract class Probe : Expression {
1166 public Expression ProbeType;
1167 protected Expression expr;
1168 protected TypeExpr probe_type_expr;
1170 public Probe (Expression expr, Expression probe_type, Location l)
1172 ProbeType = probe_type;
1177 public Expression Expr {
1183 protected override Expression DoResolve (ResolveContext ec)
1185 probe_type_expr = ProbeType.ResolveAsTypeTerminal (ec, false);
1186 if (probe_type_expr == null)
1189 expr = expr.Resolve (ec);
1193 if (probe_type_expr.Type.IsStatic) {
1194 ec.Report.Error (-244, loc, "The `{0}' operator cannot be applied to an operand of a static type",
1198 if (expr.Type.IsPointer || probe_type_expr.Type.IsPointer) {
1199 ec.Report.Error (244, loc, "The `{0}' operator cannot be applied to an operand of pointer type",
1204 if (expr.Type == InternalType.AnonymousMethod) {
1205 ec.Report.Error (837, loc, "The `{0}' operator cannot be applied to a lambda expression or anonymous method",
1213 protected abstract string OperatorName { get; }
1215 protected override void CloneTo (CloneContext clonectx, Expression t)
1217 Probe target = (Probe) t;
1219 target.expr = expr.Clone (clonectx);
1220 target.ProbeType = ProbeType.Clone (clonectx);
1226 /// Implementation of the `is' operator.
1228 public class Is : Probe {
1229 Nullable.Unwrap expr_unwrap;
1231 public Is (Expression expr, Expression probe_type, Location l)
1232 : base (expr, probe_type, l)
1236 public override Expression CreateExpressionTree (ResolveContext ec)
1238 Arguments args = Arguments.CreateForExpressionTree (ec, null,
1239 expr.CreateExpressionTree (ec),
1240 new TypeOf (probe_type_expr, loc));
1242 return CreateExpressionFactoryCall (ec, "TypeIs", args);
1245 public override void Emit (EmitContext ec)
1247 if (expr_unwrap != null) {
1248 expr_unwrap.EmitCheck (ec);
1253 ec.Emit (OpCodes.Isinst, probe_type_expr.Type);
1254 ec.Emit (OpCodes.Ldnull);
1255 ec.Emit (OpCodes.Cgt_Un);
1258 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
1260 if (expr_unwrap != null) {
1261 expr_unwrap.EmitCheck (ec);
1264 ec.Emit (OpCodes.Isinst, probe_type_expr.Type);
1266 ec.Emit (on_true ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1269 Expression CreateConstantResult (ResolveContext ec, bool result)
1272 ec.Report.Warning (183, 1, loc, "The given expression is always of the provided (`{0}') type",
1273 TypeManager.CSharpName (probe_type_expr.Type));
1275 ec.Report.Warning (184, 1, loc, "The given expression is never of the provided (`{0}') type",
1276 TypeManager.CSharpName (probe_type_expr.Type));
1278 return ReducedExpression.Create (new BoolConstant (result, loc).Resolve (ec), this);
1281 protected override Expression DoResolve (ResolveContext ec)
1283 if (base.DoResolve (ec) == null)
1286 TypeSpec d = expr.Type;
1287 bool d_is_nullable = false;
1290 // If E is a method group or the null literal, or if the type of E is a reference
1291 // type or a nullable type and the value of E is null, the result is false
1293 if (expr.IsNull || expr.eclass == ExprClass.MethodGroup)
1294 return CreateConstantResult (ec, false);
1296 if (TypeManager.IsNullableType (d)) {
1297 var ut = Nullable.NullableInfo.GetUnderlyingType (d);
1298 if (!ut.IsGenericParameter) {
1300 d_is_nullable = true;
1304 type = TypeManager.bool_type;
1305 eclass = ExprClass.Value;
1306 TypeSpec t = probe_type_expr.Type;
1307 bool t_is_nullable = false;
1308 if (TypeManager.IsNullableType (t)) {
1309 var ut = Nullable.NullableInfo.GetUnderlyingType (t);
1310 if (!ut.IsGenericParameter) {
1312 t_is_nullable = true;
1316 if (TypeManager.IsStruct (t)) {
1319 // D and T are the same value types but D can be null
1321 if (d_is_nullable && !t_is_nullable) {
1322 expr_unwrap = Nullable.Unwrap.Create (expr, false);
1327 // The result is true if D and T are the same value types
1329 return CreateConstantResult (ec, true);
1332 var tp = d as TypeParameterSpec;
1334 return ResolveGenericParameter (ec, t, tp);
1337 // An unboxing conversion exists
1339 if (Convert.ExplicitReferenceConversionExists (d, t))
1342 if (TypeManager.IsGenericParameter (t))
1343 return ResolveGenericParameter (ec, d, (TypeParameterSpec) t);
1345 if (TypeManager.IsStruct (d)) {
1346 if (Convert.ImplicitBoxingConversion (null, d, t) != null)
1347 return CreateConstantResult (ec, true);
1349 if (TypeManager.IsGenericParameter (d))
1350 return ResolveGenericParameter (ec, t, (TypeParameterSpec) d);
1352 if (TypeManager.ContainsGenericParameters (d))
1355 if (Convert.ImplicitReferenceConversionExists (expr, t) ||
1356 Convert.ExplicitReferenceConversionExists (d, t)) {
1362 return CreateConstantResult (ec, false);
1365 Expression ResolveGenericParameter (ResolveContext ec, TypeSpec d, TypeParameterSpec t)
1367 if (t.IsReferenceType) {
1368 if (TypeManager.IsStruct (d))
1369 return CreateConstantResult (ec, false);
1372 if (TypeManager.IsGenericParameter (expr.Type)) {
1373 if (t.IsValueType && expr.Type == t)
1374 return CreateConstantResult (ec, true);
1376 expr = new BoxedCast (expr, d);
1382 protected override string OperatorName {
1383 get { return "is"; }
1388 /// Implementation of the `as' operator.
1390 public class As : Probe {
1392 Expression resolved_type;
1394 public As (Expression expr, Expression probe_type, Location l)
1395 : base (expr, probe_type, l)
1399 public override Expression CreateExpressionTree (ResolveContext ec)
1401 Arguments args = Arguments.CreateForExpressionTree (ec, null,
1402 expr.CreateExpressionTree (ec),
1403 new TypeOf (probe_type_expr, loc));
1405 return CreateExpressionFactoryCall (ec, "TypeAs", args);
1408 public override void Emit (EmitContext ec)
1413 ec.Emit (OpCodes.Isinst, type);
1415 if (TypeManager.IsGenericParameter (type) || TypeManager.IsNullableType (type))
1416 ec.Emit (OpCodes.Unbox_Any, type);
1419 protected override Expression DoResolve (ResolveContext ec)
1421 if (resolved_type == null) {
1422 resolved_type = base.DoResolve (ec);
1424 if (resolved_type == null)
1428 type = probe_type_expr.Type;
1429 eclass = ExprClass.Value;
1430 TypeSpec etype = expr.Type;
1432 if (!TypeManager.IsReferenceType (type) && !TypeManager.IsNullableType (type)) {
1433 if (TypeManager.IsGenericParameter (type)) {
1434 ec.Report.Error (413, loc,
1435 "The `as' operator cannot be used with a non-reference type parameter `{0}'. Consider adding `class' or a reference type constraint",
1436 probe_type_expr.GetSignatureForError ());
1438 ec.Report.Error (77, loc,
1439 "The `as' operator cannot be used with a non-nullable value type `{0}'",
1440 TypeManager.CSharpName (type));
1445 if (expr.IsNull && TypeManager.IsNullableType (type)) {
1446 return Nullable.LiftedNull.CreateFromExpression (ec, this);
1449 Expression e = Convert.ImplicitConversion (ec, expr, type, loc);
1456 if (Convert.ExplicitReferenceConversionExists (etype, type)){
1457 if (TypeManager.IsGenericParameter (etype))
1458 expr = new BoxedCast (expr, etype);
1464 if (TypeManager.ContainsGenericParameters (etype) ||
1465 TypeManager.ContainsGenericParameters (type)) {
1466 expr = new BoxedCast (expr, etype);
1471 ec.Report.Error (39, loc, "Cannot convert type `{0}' to `{1}' via a built-in conversion",
1472 TypeManager.CSharpName (etype), TypeManager.CSharpName (type));
1477 protected override string OperatorName {
1478 get { return "as"; }
1483 // This represents a typecast in the source language.
1485 public class Cast : ShimExpression {
1486 Expression target_type;
1488 public Cast (Expression cast_type, Expression expr, Location loc)
1491 this.target_type = cast_type;
1495 public Expression TargetType {
1496 get { return target_type; }
1499 protected override Expression DoResolve (ResolveContext ec)
1501 expr = expr.Resolve (ec);
1505 TypeExpr target = target_type.ResolveAsTypeTerminal (ec, false);
1511 if (type.IsStatic) {
1512 ec.Report.Error (716, loc, "Cannot convert to static type `{0}'", TypeManager.CSharpName (type));
1516 eclass = ExprClass.Value;
1518 Constant c = expr as Constant;
1520 c = c.TryReduce (ec, type, loc);
1525 if (type.IsPointer && !ec.IsUnsafe) {
1526 UnsafeError (ec, loc);
1527 } else if (expr.Type == InternalType.Dynamic) {
1528 Arguments arg = new Arguments (1);
1529 arg.Add (new Argument (expr));
1530 return new DynamicConversion (type, CSharpBinderFlags.ConvertExplicit, arg, loc).Resolve (ec);
1533 var res = Convert.ExplicitConversion (ec, expr, type, loc);
1535 return EmptyCast.Create (res, type);
1540 protected override void CloneTo (CloneContext clonectx, Expression t)
1542 Cast target = (Cast) t;
1544 target.target_type = target_type.Clone (clonectx);
1545 target.expr = expr.Clone (clonectx);
1549 public class ImplicitCast : ShimExpression
1553 public ImplicitCast (Expression expr, TypeSpec target, bool arrayAccess)
1556 this.loc = expr.Location;
1558 this.arrayAccess = arrayAccess;
1561 protected override Expression DoResolve (ResolveContext ec)
1563 expr = expr.Resolve (ec);
1568 expr = ConvertExpressionToArrayIndex (ec, expr);
1570 expr = Convert.ImplicitConversionRequired (ec, expr, type, loc);
1577 // C# 2.0 Default value expression
1579 public class DefaultValueExpression : Expression
1583 public DefaultValueExpression (Expression expr, Location loc)
1589 public override Expression CreateExpressionTree (ResolveContext ec)
1591 Arguments args = new Arguments (2);
1592 args.Add (new Argument (this));
1593 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
1594 return CreateExpressionFactoryCall (ec, "Constant", args);
1597 protected override Expression DoResolve (ResolveContext ec)
1599 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
1605 if (type.IsStatic) {
1606 ec.Report.Error (-244, loc, "The `default value' operator cannot be applied to an operand of a static type");
1610 return new NullLiteral (Location).ConvertImplicitly (ec, type);
1612 if (TypeManager.IsReferenceType (type))
1613 return new NullConstant (type, loc);
1615 Constant c = New.Constantify (type);
1617 return c.Resolve (ec);
1619 eclass = ExprClass.Variable;
1623 public override void Emit (EmitContext ec)
1625 LocalTemporary temp_storage = new LocalTemporary(type);
1627 temp_storage.AddressOf(ec, AddressOp.LoadStore);
1628 ec.Emit(OpCodes.Initobj, type);
1629 temp_storage.Emit(ec);
1632 protected override void CloneTo (CloneContext clonectx, Expression t)
1634 DefaultValueExpression target = (DefaultValueExpression) t;
1636 target.expr = expr.Clone (clonectx);
1641 /// Binary operators
1643 public class Binary : Expression, IDynamicBinder
1645 protected class PredefinedOperator {
1646 protected readonly TypeSpec left;
1647 protected readonly TypeSpec right;
1648 public readonly Operator OperatorsMask;
1649 public TypeSpec ReturnType;
1651 public PredefinedOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
1652 : this (ltype, rtype, op_mask, ltype)
1656 public PredefinedOperator (TypeSpec type, Operator op_mask, TypeSpec return_type)
1657 : this (type, type, op_mask, return_type)
1661 public PredefinedOperator (TypeSpec type, Operator op_mask)
1662 : this (type, type, op_mask, type)
1666 public PredefinedOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask, TypeSpec return_type)
1668 if ((op_mask & Operator.ValuesOnlyMask) != 0)
1669 throw new InternalErrorException ("Only masked values can be used");
1673 this.OperatorsMask = op_mask;
1674 this.ReturnType = return_type;
1677 public virtual Expression ConvertResult (ResolveContext ec, Binary b)
1679 b.type = ReturnType;
1681 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1682 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
1685 // A user operators does not support multiple user conversions, but decimal type
1686 // is considered to be predefined type therefore we apply predefined operators rules
1687 // and then look for decimal user-operator implementation
1689 if (left == TypeManager.decimal_type)
1690 return b.ResolveUserOperator (ec, b.left.Type, b.right.Type);
1692 var c = b.right as Constant;
1694 if (c.IsDefaultValue && (b.oper == Operator.Addition || b.oper == Operator.BitwiseOr || b.oper == Operator.Subtraction))
1695 return ReducedExpression.Create (b.left, b).Resolve (ec);
1696 if ((b.oper == Operator.Multiply || b.oper == Operator.Division) && c.IsOneInteger)
1697 return ReducedExpression.Create (b.left, b).Resolve (ec);
1701 c = b.left as Constant;
1703 if (c.IsDefaultValue && (b.oper == Operator.Addition || b.oper == Operator.BitwiseOr))
1704 return ReducedExpression.Create (b.right, b).Resolve (ec);
1705 if (b.oper == Operator.Multiply && c.IsOneInteger)
1706 return ReducedExpression.Create (b.right, b).Resolve (ec);
1713 public bool IsPrimitiveApplicable (TypeSpec ltype, TypeSpec rtype)
1716 // We are dealing with primitive types only
1718 return left == ltype && ltype == rtype;
1721 public virtual bool IsApplicable (ResolveContext ec, Expression lexpr, Expression rexpr)
1723 if (TypeManager.IsEqual (left, lexpr.Type) &&
1724 TypeManager.IsEqual (right, rexpr.Type))
1727 return Convert.ImplicitConversionExists (ec, lexpr, left) &&
1728 Convert.ImplicitConversionExists (ec, rexpr, right);
1731 public PredefinedOperator ResolveBetterOperator (ResolveContext ec, PredefinedOperator best_operator)
1734 if (left != null && best_operator.left != null) {
1735 result = OverloadResolver.BetterTypeConversion (ec, best_operator.left, left);
1739 // When second argument is same as the first one, the result is same
1741 if (right != null && (left != right || best_operator.left != best_operator.right)) {
1742 result |= OverloadResolver.BetterTypeConversion (ec, best_operator.right, right);
1745 if (result == 0 || result > 2)
1748 return result == 1 ? best_operator : this;
1752 class PredefinedStringOperator : PredefinedOperator {
1753 public PredefinedStringOperator (TypeSpec type, Operator op_mask)
1754 : base (type, op_mask, type)
1756 ReturnType = TypeManager.string_type;
1759 public PredefinedStringOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
1760 : base (ltype, rtype, op_mask)
1762 ReturnType = TypeManager.string_type;
1765 public override Expression ConvertResult (ResolveContext ec, Binary b)
1768 // Use original expression for nullable arguments
1770 Nullable.Unwrap unwrap = b.left as Nullable.Unwrap;
1772 b.left = unwrap.Original;
1774 unwrap = b.right as Nullable.Unwrap;
1776 b.right = unwrap.Original;
1778 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1779 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
1782 // Start a new concat expression using converted expression
1784 return StringConcat.Create (ec, b.left, b.right, b.loc);
1788 class PredefinedShiftOperator : PredefinedOperator {
1789 public PredefinedShiftOperator (TypeSpec ltype, Operator op_mask) :
1790 base (ltype, TypeManager.int32_type, op_mask)
1794 public override Expression ConvertResult (ResolveContext ec, Binary b)
1796 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1798 Expression expr_tree_expr = Convert.ImplicitConversion (ec, b.right, TypeManager.int32_type, b.right.Location);
1800 int right_mask = left == TypeManager.int32_type || left == TypeManager.uint32_type ? 0x1f : 0x3f;
1803 // b = b.left >> b.right & (0x1f|0x3f)
1805 b.right = new Binary (Operator.BitwiseAnd,
1806 b.right, new IntConstant (right_mask, b.right.Location), b.loc).Resolve (ec);
1809 // Expression tree representation does not use & mask
1811 b.right = ReducedExpression.Create (b.right, expr_tree_expr).Resolve (ec);
1812 b.type = ReturnType;
1815 // Optimize shift by 0
1817 var c = b.right as Constant;
1818 if (c != null && c.IsDefaultValue)
1819 return ReducedExpression.Create (b.left, b).Resolve (ec);
1825 class PredefinedEqualityOperator : PredefinedOperator
1827 MethodSpec equal_method, inequal_method;
1829 public PredefinedEqualityOperator (TypeSpec arg, TypeSpec retType)
1830 : base (arg, arg, Operator.EqualityMask, retType)
1834 public override Expression ConvertResult (ResolveContext ec, Binary b)
1836 b.type = ReturnType;
1838 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1839 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
1841 Arguments args = new Arguments (2);
1842 args.Add (new Argument (b.left));
1843 args.Add (new Argument (b.right));
1846 if (b.oper == Operator.Equality) {
1847 if (equal_method == null) {
1848 equal_method = TypeManager.GetPredefinedMethod (left,
1849 new MemberFilter (CSharp.Operator.GetMetadataName (CSharp.Operator.OpType.Equality), 0, MemberKind.Operator, null, ReturnType), b.loc);
1852 method = equal_method;
1854 if (inequal_method == null) {
1855 inequal_method = TypeManager.GetPredefinedMethod (left,
1856 new MemberFilter (CSharp.Operator.GetMetadataName (CSharp.Operator.OpType.Inequality), 0, MemberKind.Operator, null, ReturnType), b.loc);
1859 method = inequal_method;
1862 return new UserOperatorCall (method, args, b.CreateExpressionTree, b.loc);
1866 class PredefinedPointerOperator : PredefinedOperator
1868 public PredefinedPointerOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
1869 : base (ltype, rtype, op_mask)
1873 public PredefinedPointerOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask, TypeSpec retType)
1874 : base (ltype, rtype, op_mask, retType)
1878 public PredefinedPointerOperator (TypeSpec type, Operator op_mask, TypeSpec return_type)
1879 : base (type, op_mask, return_type)
1883 public override bool IsApplicable (ResolveContext ec, Expression lexpr, Expression rexpr)
1886 if (!lexpr.Type.IsPointer)
1889 if (!Convert.ImplicitConversionExists (ec, lexpr, left))
1893 if (right == null) {
1894 if (!rexpr.Type.IsPointer)
1897 if (!Convert.ImplicitConversionExists (ec, rexpr, right))
1904 public override Expression ConvertResult (ResolveContext ec, Binary b)
1907 b.left = EmptyCast.Create (b.left, left);
1908 } else if (right != null) {
1909 b.right = EmptyCast.Create (b.right, right);
1912 TypeSpec r_type = ReturnType;
1913 Expression left_arg, right_arg;
1914 if (r_type == null) {
1917 right_arg = b.right;
1918 r_type = b.left.Type;
1922 r_type = b.right.Type;
1926 right_arg = b.right;
1929 return new PointerArithmetic (b.oper, left_arg, right_arg, r_type, b.loc).Resolve (ec);
1934 public enum Operator {
1935 Multiply = 0 | ArithmeticMask,
1936 Division = 1 | ArithmeticMask,
1937 Modulus = 2 | ArithmeticMask,
1938 Addition = 3 | ArithmeticMask | AdditionMask,
1939 Subtraction = 4 | ArithmeticMask | SubtractionMask,
1941 LeftShift = 5 | ShiftMask,
1942 RightShift = 6 | ShiftMask,
1944 LessThan = 7 | ComparisonMask | RelationalMask,
1945 GreaterThan = 8 | ComparisonMask | RelationalMask,
1946 LessThanOrEqual = 9 | ComparisonMask | RelationalMask,
1947 GreaterThanOrEqual = 10 | ComparisonMask | RelationalMask,
1948 Equality = 11 | ComparisonMask | EqualityMask,
1949 Inequality = 12 | ComparisonMask | EqualityMask,
1951 BitwiseAnd = 13 | BitwiseMask,
1952 ExclusiveOr = 14 | BitwiseMask,
1953 BitwiseOr = 15 | BitwiseMask,
1955 LogicalAnd = 16 | LogicalMask,
1956 LogicalOr = 17 | LogicalMask,
1961 ValuesOnlyMask = ArithmeticMask - 1,
1962 ArithmeticMask = 1 << 5,
1964 ComparisonMask = 1 << 7,
1965 EqualityMask = 1 << 8,
1966 BitwiseMask = 1 << 9,
1967 LogicalMask = 1 << 10,
1968 AdditionMask = 1 << 11,
1969 SubtractionMask = 1 << 12,
1970 RelationalMask = 1 << 13
1973 readonly Operator oper;
1974 protected Expression left, right;
1975 readonly bool is_compound;
1976 Expression enum_conversion;
1978 static PredefinedOperator[] standard_operators;
1979 static PredefinedOperator[] equality_operators;
1980 static PredefinedOperator[] pointer_operators;
1982 public Binary (Operator oper, Expression left, Expression right, bool isCompound, Location loc)
1983 : this (oper, left, right, loc)
1985 this.is_compound = isCompound;
1988 public Binary (Operator oper, Expression left, Expression right, Location loc)
1996 public Operator Oper {
2003 /// Returns a stringified representation of the Operator
2005 string OperName (Operator oper)
2009 case Operator.Multiply:
2012 case Operator.Division:
2015 case Operator.Modulus:
2018 case Operator.Addition:
2021 case Operator.Subtraction:
2024 case Operator.LeftShift:
2027 case Operator.RightShift:
2030 case Operator.LessThan:
2033 case Operator.GreaterThan:
2036 case Operator.LessThanOrEqual:
2039 case Operator.GreaterThanOrEqual:
2042 case Operator.Equality:
2045 case Operator.Inequality:
2048 case Operator.BitwiseAnd:
2051 case Operator.BitwiseOr:
2054 case Operator.ExclusiveOr:
2057 case Operator.LogicalOr:
2060 case Operator.LogicalAnd:
2064 s = oper.ToString ();
2074 public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, Operator oper, Location loc)
2076 new Binary (oper, left, right, loc).Error_OperatorCannotBeApplied (ec, left, right);
2079 public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, string oper, Location loc)
2082 l = TypeManager.CSharpName (left.Type);
2083 r = TypeManager.CSharpName (right.Type);
2085 ec.Report.Error (19, loc, "Operator `{0}' cannot be applied to operands of type `{1}' and `{2}'",
2089 protected void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right)
2091 Error_OperatorCannotBeApplied (ec, left, right, OperName (oper), loc);
2095 // Converts operator to System.Linq.Expressions.ExpressionType enum name
2097 string GetOperatorExpressionTypeName ()
2100 case Operator.Addition:
2101 return is_compound ? "AddAssign" : "Add";
2102 case Operator.BitwiseAnd:
2103 return is_compound ? "AndAssign" : "And";
2104 case Operator.BitwiseOr:
2105 return is_compound ? "OrAssign" : "Or";
2106 case Operator.Division:
2107 return is_compound ? "DivideAssign" : "Divide";
2108 case Operator.ExclusiveOr:
2109 return is_compound ? "ExclusiveOrAssign" : "ExclusiveOr";
2110 case Operator.Equality:
2112 case Operator.GreaterThan:
2113 return "GreaterThan";
2114 case Operator.GreaterThanOrEqual:
2115 return "GreaterThanOrEqual";
2116 case Operator.Inequality:
2118 case Operator.LeftShift:
2119 return is_compound ? "LeftShiftAssign" : "LeftShift";
2120 case Operator.LessThan:
2122 case Operator.LessThanOrEqual:
2123 return "LessThanOrEqual";
2124 case Operator.LogicalAnd:
2126 case Operator.LogicalOr:
2128 case Operator.Modulus:
2129 return is_compound ? "ModuloAssign" : "Modulo";
2130 case Operator.Multiply:
2131 return is_compound ? "MultiplyAssign" : "Multiply";
2132 case Operator.RightShift:
2133 return is_compound ? "RightShiftAssign" : "RightShift";
2134 case Operator.Subtraction:
2135 return is_compound ? "SubtractAssign" : "Subtract";
2137 throw new NotImplementedException ("Unknown expression type operator " + oper.ToString ());
2141 static CSharp.Operator.OpType ConvertBinaryToUserOperator (Operator op)
2144 case Operator.Addition:
2145 return CSharp.Operator.OpType.Addition;
2146 case Operator.BitwiseAnd:
2147 case Operator.LogicalAnd:
2148 return CSharp.Operator.OpType.BitwiseAnd;
2149 case Operator.BitwiseOr:
2150 case Operator.LogicalOr:
2151 return CSharp.Operator.OpType.BitwiseOr;
2152 case Operator.Division:
2153 return CSharp.Operator.OpType.Division;
2154 case Operator.Equality:
2155 return CSharp.Operator.OpType.Equality;
2156 case Operator.ExclusiveOr:
2157 return CSharp.Operator.OpType.ExclusiveOr;
2158 case Operator.GreaterThan:
2159 return CSharp.Operator.OpType.GreaterThan;
2160 case Operator.GreaterThanOrEqual:
2161 return CSharp.Operator.OpType.GreaterThanOrEqual;
2162 case Operator.Inequality:
2163 return CSharp.Operator.OpType.Inequality;
2164 case Operator.LeftShift:
2165 return CSharp.Operator.OpType.LeftShift;
2166 case Operator.LessThan:
2167 return CSharp.Operator.OpType.LessThan;
2168 case Operator.LessThanOrEqual:
2169 return CSharp.Operator.OpType.LessThanOrEqual;
2170 case Operator.Modulus:
2171 return CSharp.Operator.OpType.Modulus;
2172 case Operator.Multiply:
2173 return CSharp.Operator.OpType.Multiply;
2174 case Operator.RightShift:
2175 return CSharp.Operator.OpType.RightShift;
2176 case Operator.Subtraction:
2177 return CSharp.Operator.OpType.Subtraction;
2179 throw new InternalErrorException (op.ToString ());
2183 public static void EmitOperatorOpcode (EmitContext ec, Operator oper, TypeSpec l)
2188 case Operator.Multiply:
2189 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2190 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2191 opcode = OpCodes.Mul_Ovf;
2192 else if (!IsFloat (l))
2193 opcode = OpCodes.Mul_Ovf_Un;
2195 opcode = OpCodes.Mul;
2197 opcode = OpCodes.Mul;
2201 case Operator.Division:
2203 opcode = OpCodes.Div_Un;
2205 opcode = OpCodes.Div;
2208 case Operator.Modulus:
2210 opcode = OpCodes.Rem_Un;
2212 opcode = OpCodes.Rem;
2215 case Operator.Addition:
2216 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2217 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2218 opcode = OpCodes.Add_Ovf;
2219 else if (!IsFloat (l))
2220 opcode = OpCodes.Add_Ovf_Un;
2222 opcode = OpCodes.Add;
2224 opcode = OpCodes.Add;
2227 case Operator.Subtraction:
2228 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2229 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2230 opcode = OpCodes.Sub_Ovf;
2231 else if (!IsFloat (l))
2232 opcode = OpCodes.Sub_Ovf_Un;
2234 opcode = OpCodes.Sub;
2236 opcode = OpCodes.Sub;
2239 case Operator.RightShift:
2241 opcode = OpCodes.Shr_Un;
2243 opcode = OpCodes.Shr;
2246 case Operator.LeftShift:
2247 opcode = OpCodes.Shl;
2250 case Operator.Equality:
2251 opcode = OpCodes.Ceq;
2254 case Operator.Inequality:
2255 ec.Emit (OpCodes.Ceq);
2256 ec.Emit (OpCodes.Ldc_I4_0);
2258 opcode = OpCodes.Ceq;
2261 case Operator.LessThan:
2263 opcode = OpCodes.Clt_Un;
2265 opcode = OpCodes.Clt;
2268 case Operator.GreaterThan:
2270 opcode = OpCodes.Cgt_Un;
2272 opcode = OpCodes.Cgt;
2275 case Operator.LessThanOrEqual:
2276 if (IsUnsigned (l) || IsFloat (l))
2277 ec.Emit (OpCodes.Cgt_Un);
2279 ec.Emit (OpCodes.Cgt);
2280 ec.Emit (OpCodes.Ldc_I4_0);
2282 opcode = OpCodes.Ceq;
2285 case Operator.GreaterThanOrEqual:
2286 if (IsUnsigned (l) || IsFloat (l))
2287 ec.Emit (OpCodes.Clt_Un);
2289 ec.Emit (OpCodes.Clt);
2291 ec.Emit (OpCodes.Ldc_I4_0);
2293 opcode = OpCodes.Ceq;
2296 case Operator.BitwiseOr:
2297 opcode = OpCodes.Or;
2300 case Operator.BitwiseAnd:
2301 opcode = OpCodes.And;
2304 case Operator.ExclusiveOr:
2305 opcode = OpCodes.Xor;
2309 throw new InternalErrorException (oper.ToString ());
2315 static bool IsUnsigned (TypeSpec t)
2320 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2321 t == TypeManager.ushort_type || t == TypeManager.byte_type);
2324 static bool IsFloat (TypeSpec t)
2326 return t == TypeManager.float_type || t == TypeManager.double_type;
2329 public static void Reset ()
2331 equality_operators = pointer_operators = standard_operators = null;
2334 Expression ResolveOperator (ResolveContext ec)
2336 TypeSpec l = left.Type;
2337 TypeSpec r = right.Type;
2339 bool primitives_only = false;
2341 if (standard_operators == null)
2342 CreateStandardOperatorsTable ();
2345 // Handles predefined primitive types
2347 if (TypeManager.IsPrimitiveType (l) && TypeManager.IsPrimitiveType (r)) {
2348 if ((oper & Operator.ShiftMask) == 0) {
2349 if (l != TypeManager.bool_type && !DoBinaryOperatorPromotion (ec))
2352 primitives_only = true;
2356 if (l.IsPointer || r.IsPointer)
2357 return ResolveOperatorPointer (ec, l, r);
2360 bool lenum = TypeManager.IsEnumType (l);
2361 bool renum = TypeManager.IsEnumType (r);
2362 if (lenum || renum) {
2363 expr = ResolveOperatorEnum (ec, lenum, renum, l, r);
2365 // TODO: Can this be ambiguous
2371 if ((oper == Operator.Addition || oper == Operator.Subtraction) && (l.IsDelegate || r.IsDelegate)) {
2373 expr = ResolveOperatorDelegate (ec, l, r);
2375 // TODO: Can this be ambiguous
2381 expr = ResolveUserOperator (ec, l, r);
2385 // Predefined reference types equality
2386 if ((oper & Operator.EqualityMask) != 0) {
2387 expr = ResolveOperatorEquality (ec, l, r);
2393 return ResolveOperatorPredefined (ec, standard_operators, primitives_only, null);
2396 // at least one of 'left' or 'right' is an enumeration constant (EnumConstant or SideEffectConstant or ...)
2397 // if 'left' is not an enumeration constant, create one from the type of 'right'
2398 Constant EnumLiftUp (ResolveContext ec, Constant left, Constant right, Location loc)
2401 case Operator.BitwiseOr:
2402 case Operator.BitwiseAnd:
2403 case Operator.ExclusiveOr:
2404 case Operator.Equality:
2405 case Operator.Inequality:
2406 case Operator.LessThan:
2407 case Operator.LessThanOrEqual:
2408 case Operator.GreaterThan:
2409 case Operator.GreaterThanOrEqual:
2410 if (TypeManager.IsEnumType (left.Type))
2413 if (left.IsZeroInteger)
2414 return left.TryReduce (ec, right.Type, loc);
2418 case Operator.Addition:
2419 case Operator.Subtraction:
2422 case Operator.Multiply:
2423 case Operator.Division:
2424 case Operator.Modulus:
2425 case Operator.LeftShift:
2426 case Operator.RightShift:
2427 if (TypeManager.IsEnumType (right.Type) || TypeManager.IsEnumType (left.Type))
2431 Error_OperatorCannotBeApplied (ec, this.left, this.right);
2436 // The `|' operator used on types which were extended is dangerous
2438 void CheckBitwiseOrOnSignExtended (ResolveContext ec)
2440 OpcodeCast lcast = left as OpcodeCast;
2441 if (lcast != null) {
2442 if (IsUnsigned (lcast.UnderlyingType))
2446 OpcodeCast rcast = right as OpcodeCast;
2447 if (rcast != null) {
2448 if (IsUnsigned (rcast.UnderlyingType))
2452 if (lcast == null && rcast == null)
2455 // FIXME: consider constants
2457 ec.Report.Warning (675, 3, loc,
2458 "The operator `|' used on the sign-extended type `{0}'. Consider casting to a smaller unsigned type first",
2459 TypeManager.CSharpName (lcast != null ? lcast.UnderlyingType : rcast.UnderlyingType));
2462 static void CreatePointerOperatorsTable ()
2464 var temp = new List<PredefinedPointerOperator> ();
2467 // Pointer arithmetic:
2469 // T* operator + (T* x, int y); T* operator - (T* x, int y);
2470 // T* operator + (T* x, uint y); T* operator - (T* x, uint y);
2471 // T* operator + (T* x, long y); T* operator - (T* x, long y);
2472 // T* operator + (T* x, ulong y); T* operator - (T* x, ulong y);
2474 temp.Add (new PredefinedPointerOperator (null, TypeManager.int32_type, Operator.AdditionMask | Operator.SubtractionMask));
2475 temp.Add (new PredefinedPointerOperator (null, TypeManager.uint32_type, Operator.AdditionMask | Operator.SubtractionMask));
2476 temp.Add (new PredefinedPointerOperator (null, TypeManager.int64_type, Operator.AdditionMask | Operator.SubtractionMask));
2477 temp.Add (new PredefinedPointerOperator (null, TypeManager.uint64_type, Operator.AdditionMask | Operator.SubtractionMask));
2480 // T* operator + (int y, T* x);
2481 // T* operator + (uint y, T *x);
2482 // T* operator + (long y, T *x);
2483 // T* operator + (ulong y, T *x);
2485 temp.Add (new PredefinedPointerOperator (TypeManager.int32_type, null, Operator.AdditionMask, null));
2486 temp.Add (new PredefinedPointerOperator (TypeManager.uint32_type, null, Operator.AdditionMask, null));
2487 temp.Add (new PredefinedPointerOperator (TypeManager.int64_type, null, Operator.AdditionMask, null));
2488 temp.Add (new PredefinedPointerOperator (TypeManager.uint64_type, null, Operator.AdditionMask, null));
2491 // long operator - (T* x, T *y)
2493 temp.Add (new PredefinedPointerOperator (null, Operator.SubtractionMask, TypeManager.int64_type));
2495 pointer_operators = temp.ToArray ();
2498 static void CreateStandardOperatorsTable ()
2500 var temp = new List<PredefinedOperator> ();
2501 TypeSpec bool_type = TypeManager.bool_type;
2503 temp.Add (new PredefinedOperator (TypeManager.int32_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2504 temp.Add (new PredefinedOperator (TypeManager.uint32_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2505 temp.Add (new PredefinedOperator (TypeManager.int64_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2506 temp.Add (new PredefinedOperator (TypeManager.uint64_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2507 temp.Add (new PredefinedOperator (TypeManager.float_type, Operator.ArithmeticMask));
2508 temp.Add (new PredefinedOperator (TypeManager.double_type, Operator.ArithmeticMask));
2509 temp.Add (new PredefinedOperator (TypeManager.decimal_type, Operator.ArithmeticMask));
2511 temp.Add (new PredefinedOperator (TypeManager.int32_type, Operator.ComparisonMask, bool_type));
2512 temp.Add (new PredefinedOperator (TypeManager.uint32_type, Operator.ComparisonMask, bool_type));
2513 temp.Add (new PredefinedOperator (TypeManager.int64_type, Operator.ComparisonMask, bool_type));
2514 temp.Add (new PredefinedOperator (TypeManager.uint64_type, Operator.ComparisonMask, bool_type));
2515 temp.Add (new PredefinedOperator (TypeManager.float_type, Operator.ComparisonMask, bool_type));
2516 temp.Add (new PredefinedOperator (TypeManager.double_type, Operator.ComparisonMask, bool_type));
2517 temp.Add (new PredefinedOperator (TypeManager.decimal_type, Operator.ComparisonMask, bool_type));
2519 temp.Add (new PredefinedStringOperator (TypeManager.string_type, Operator.AdditionMask));
2520 temp.Add (new PredefinedStringOperator (TypeManager.string_type, TypeManager.object_type, Operator.AdditionMask));
2521 temp.Add (new PredefinedStringOperator (TypeManager.object_type, TypeManager.string_type, Operator.AdditionMask));
2523 temp.Add (new PredefinedOperator (bool_type,
2524 Operator.BitwiseMask | Operator.LogicalMask | Operator.EqualityMask, bool_type));
2526 temp.Add (new PredefinedShiftOperator (TypeManager.int32_type, Operator.ShiftMask));
2527 temp.Add (new PredefinedShiftOperator (TypeManager.uint32_type, Operator.ShiftMask));
2528 temp.Add (new PredefinedShiftOperator (TypeManager.int64_type, Operator.ShiftMask));
2529 temp.Add (new PredefinedShiftOperator (TypeManager.uint64_type, Operator.ShiftMask));
2531 standard_operators = temp.ToArray ();
2533 var equality = new List<PredefinedOperator> () {
2534 new PredefinedEqualityOperator (TypeManager.string_type, bool_type),
2535 new PredefinedEqualityOperator (TypeManager.delegate_type, bool_type),
2536 new PredefinedOperator (bool_type, Operator.EqualityMask, bool_type)
2539 equality_operators = equality.ToArray ();
2543 // Rules used during binary numeric promotion
2545 static bool DoNumericPromotion (ResolveContext rc, ref Expression prim_expr, ref Expression second_expr, TypeSpec type)
2550 Constant c = prim_expr as Constant;
2552 temp = c.ConvertImplicitly (rc, type);
2559 if (type == TypeManager.uint32_type) {
2560 etype = prim_expr.Type;
2561 if (etype == TypeManager.int32_type || etype == TypeManager.short_type || etype == TypeManager.sbyte_type) {
2562 type = TypeManager.int64_type;
2564 if (type != second_expr.Type) {
2565 c = second_expr as Constant;
2567 temp = c.ConvertImplicitly (rc, type);
2569 temp = Convert.ImplicitNumericConversion (second_expr, type);
2575 } else if (type == TypeManager.uint64_type) {
2577 // A compile-time error occurs if the other operand is of type sbyte, short, int, or long
2579 if (type == TypeManager.int32_type || type == TypeManager.int64_type ||
2580 type == TypeManager.short_type || type == TypeManager.sbyte_type)
2584 temp = Convert.ImplicitNumericConversion (prim_expr, type);
2593 // 7.2.6.2 Binary numeric promotions
2595 public bool DoBinaryOperatorPromotion (ResolveContext ec)
2597 TypeSpec ltype = left.Type;
2598 TypeSpec rtype = right.Type;
2601 foreach (TypeSpec t in ConstantFold.BinaryPromotionsTypes) {
2603 return t == rtype || DoNumericPromotion (ec, ref right, ref left, t);
2606 return t == ltype || DoNumericPromotion (ec, ref left, ref right, t);
2609 TypeSpec int32 = TypeManager.int32_type;
2610 if (ltype != int32) {
2611 Constant c = left as Constant;
2613 temp = c.ConvertImplicitly (ec, int32);
2615 temp = Convert.ImplicitNumericConversion (left, int32);
2622 if (rtype != int32) {
2623 Constant c = right as Constant;
2625 temp = c.ConvertImplicitly (ec, int32);
2627 temp = Convert.ImplicitNumericConversion (right, int32);
2637 protected override Expression DoResolve (ResolveContext ec)
2642 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2643 left = ((ParenthesizedExpression) left).Expr;
2644 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2648 if (left.eclass == ExprClass.Type) {
2649 ec.Report.Error (75, loc, "To cast a negative value, you must enclose the value in parentheses");
2653 left = left.Resolve (ec);
2658 Constant lc = left as Constant;
2660 if (lc != null && lc.Type == TypeManager.bool_type &&
2661 ((oper == Operator.LogicalAnd && lc.IsDefaultValue) ||
2662 (oper == Operator.LogicalOr && !lc.IsDefaultValue))) {
2664 // FIXME: resolve right expression as unreachable
2665 // right.Resolve (ec);
2667 ec.Report.Warning (429, 4, loc, "Unreachable expression code detected");
2671 right = right.Resolve (ec);
2675 eclass = ExprClass.Value;
2676 Constant rc = right as Constant;
2678 // The conversion rules are ignored in enum context but why
2679 if (!ec.HasSet (ResolveContext.Options.EnumScope) && lc != null && rc != null && (TypeManager.IsEnumType (left.Type) || TypeManager.IsEnumType (right.Type))) {
2680 lc = EnumLiftUp (ec, lc, rc, loc);
2682 rc = EnumLiftUp (ec, rc, lc, loc);
2685 if (rc != null && lc != null) {
2686 int prev_e = ec.Report.Errors;
2687 Expression e = ConstantFold.BinaryFold (ec, oper, lc, rc, loc);
2691 if (e != null || ec.Report.Errors != prev_e)
2695 // Comparison warnings
2696 if ((oper & Operator.ComparisonMask) != 0) {
2697 if (left.Equals (right)) {
2698 ec.Report.Warning (1718, 3, loc, "A comparison made to same variable. Did you mean to compare something else?");
2700 CheckUselessComparison (ec, lc, right.Type);
2701 CheckUselessComparison (ec, rc, left.Type);
2704 if (left.Type == InternalType.Dynamic || right.Type == InternalType.Dynamic) {
2705 Arguments args = new Arguments (2);
2706 args.Add (new Argument (left));
2707 args.Add (new Argument (right));
2708 return new DynamicExpressionStatement (this, args, loc).Resolve (ec);
2711 if (RootContext.Version >= LanguageVersion.ISO_2 &&
2712 ((TypeManager.IsNullableType (left.Type) && (right is NullLiteral || TypeManager.IsNullableType (right.Type) || TypeManager.IsValueType (right.Type))) ||
2713 (TypeManager.IsValueType (left.Type) && right is NullLiteral) ||
2714 (TypeManager.IsNullableType (right.Type) && (left is NullLiteral || TypeManager.IsNullableType (left.Type) || TypeManager.IsValueType (left.Type))) ||
2715 (TypeManager.IsValueType (right.Type) && left is NullLiteral)))
2716 return new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
2718 return DoResolveCore (ec, left, right);
2721 protected Expression DoResolveCore (ResolveContext ec, Expression left_orig, Expression right_orig)
2723 Expression expr = ResolveOperator (ec);
2725 Error_OperatorCannotBeApplied (ec, left_orig, right_orig);
2727 if (left == null || right == null)
2728 throw new InternalErrorException ("Invalid conversion");
2730 if (oper == Operator.BitwiseOr)
2731 CheckBitwiseOrOnSignExtended (ec);
2736 public override SLE.Expression MakeExpression (BuilderContext ctx)
2738 var le = left.MakeExpression (ctx);
2739 var re = right.MakeExpression (ctx);
2740 bool is_checked = ctx.HasSet (BuilderContext.Options.CheckedScope);
2743 case Operator.Addition:
2744 return is_checked ? SLE.Expression.AddChecked (le, re) : SLE.Expression.Add (le, re);
2745 case Operator.BitwiseAnd:
2746 return SLE.Expression.And (le, re);
2747 case Operator.BitwiseOr:
2748 return SLE.Expression.Or (le, re);
2749 case Operator.Division:
2750 return SLE.Expression.Divide (le, re);
2751 case Operator.Equality:
2752 return SLE.Expression.Equal (le, re);
2753 case Operator.ExclusiveOr:
2754 return SLE.Expression.ExclusiveOr (le, re);
2755 case Operator.GreaterThan:
2756 return SLE.Expression.GreaterThan (le, re);
2757 case Operator.GreaterThanOrEqual:
2758 return SLE.Expression.GreaterThanOrEqual (le, re);
2759 case Operator.Inequality:
2760 return SLE.Expression.NotEqual (le, re);
2761 case Operator.LeftShift:
2762 return SLE.Expression.LeftShift (le, re);
2763 case Operator.LessThan:
2764 return SLE.Expression.LessThan (le, re);
2765 case Operator.LessThanOrEqual:
2766 return SLE.Expression.LessThanOrEqual (le, re);
2767 case Operator.LogicalAnd:
2768 return SLE.Expression.AndAlso (le, re);
2769 case Operator.LogicalOr:
2770 return SLE.Expression.OrElse (le, re);
2771 case Operator.Modulus:
2772 return SLE.Expression.Modulo (le, re);
2773 case Operator.Multiply:
2774 return is_checked ? SLE.Expression.MultiplyChecked (le, re) : SLE.Expression.Multiply (le, re);
2775 case Operator.RightShift:
2776 return SLE.Expression.RightShift (le, re);
2777 case Operator.Subtraction:
2778 return is_checked ? SLE.Expression.SubtractChecked (le, re) : SLE.Expression.Subtract (le, re);
2780 throw new NotImplementedException (oper.ToString ());
2785 // D operator + (D x, D y)
2786 // D operator - (D x, D y)
2788 Expression ResolveOperatorDelegate (ResolveContext ec, TypeSpec l, TypeSpec r)
2790 if (!TypeManager.IsEqual (l, r) && !TypeSpecComparer.Variant.IsEqual (r, l)) {
2792 if (right.eclass == ExprClass.MethodGroup || r == InternalType.AnonymousMethod || r == InternalType.Null) {
2793 tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2798 } else if (left.eclass == ExprClass.MethodGroup || (l == InternalType.AnonymousMethod)) {
2799 tmp = Convert.ImplicitConversionRequired (ec, left, r, loc);
2810 Arguments args = new Arguments (2);
2811 args.Add (new Argument (left));
2812 args.Add (new Argument (right));
2814 if (oper == Operator.Addition) {
2815 if (TypeManager.delegate_combine_delegate_delegate == null) {
2816 TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
2817 TypeManager.delegate_type, "Combine", loc, TypeManager.delegate_type, TypeManager.delegate_type);
2820 method = TypeManager.delegate_combine_delegate_delegate;
2821 } else if (oper == Operator.Subtraction) {
2822 if (TypeManager.delegate_remove_delegate_delegate == null) {
2823 TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
2824 TypeManager.delegate_type, "Remove", loc, TypeManager.delegate_type, TypeManager.delegate_type);
2827 method = TypeManager.delegate_remove_delegate_delegate;
2829 return new EmptyExpression (TypeManager.decimal_type);
2832 MethodGroupExpr mg = MethodGroupExpr.CreatePredefined (method, TypeManager.delegate_type, loc);
2833 Expression expr = new UserOperatorCall (mg.BestCandidate, args, CreateExpressionTree, loc);
2834 return new ClassCast (expr, l);
2838 // Enumeration operators
2840 Expression ResolveOperatorEnum (ResolveContext ec, bool lenum, bool renum, TypeSpec ltype, TypeSpec rtype)
2843 // bool operator == (E x, E y);
2844 // bool operator != (E x, E y);
2845 // bool operator < (E x, E y);
2846 // bool operator > (E x, E y);
2847 // bool operator <= (E x, E y);
2848 // bool operator >= (E x, E y);
2850 // E operator & (E x, E y);
2851 // E operator | (E x, E y);
2852 // E operator ^ (E x, E y);
2854 // U operator - (E e, E f)
2855 // E operator - (E e, U x)
2857 // E operator + (U x, E e)
2858 // E operator + (E e, U x)
2860 if (!((oper & (Operator.ComparisonMask | Operator.BitwiseMask)) != 0 ||
2861 (oper == Operator.Subtraction && lenum) ||
2862 (oper == Operator.Addition && (lenum != renum || type != null)))) // type != null for lifted null
2865 Expression ltemp = left;
2866 Expression rtemp = right;
2867 TypeSpec underlying_type;
2870 if ((oper & (Operator.ComparisonMask | Operator.BitwiseMask)) != 0) {
2872 expr = Convert.ImplicitConversion (ec, left, rtype, loc);
2878 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
2886 if (TypeManager.IsEqual (ltype, rtype)) {
2887 underlying_type = EnumSpec.GetUnderlyingType (ltype);
2889 if (left is Constant)
2890 left = ((Constant) left).ConvertExplicitly (false, underlying_type).Resolve (ec);
2892 left = EmptyCast.Create (left, underlying_type);
2894 if (right is Constant)
2895 right = ((Constant) right).ConvertExplicitly (false, underlying_type).Resolve (ec);
2897 right = EmptyCast.Create (right, underlying_type);
2899 underlying_type = EnumSpec.GetUnderlyingType (ltype);
2901 if (oper != Operator.Subtraction && oper != Operator.Addition) {
2902 Constant c = right as Constant;
2903 if (c == null || !c.IsDefaultValue)
2906 if (!Convert.ImplicitStandardConversionExists (right, underlying_type))
2909 right = Convert.ImplicitConversionStandard (ec, right, underlying_type, right.Location);
2912 if (left is Constant)
2913 left = ((Constant) left).ConvertExplicitly (false, underlying_type).Resolve (ec);
2915 left = EmptyCast.Create (left, underlying_type);
2918 underlying_type = EnumSpec.GetUnderlyingType (rtype);
2920 if (oper != Operator.Addition) {
2921 Constant c = left as Constant;
2922 if (c == null || !c.IsDefaultValue)
2925 if (!Convert.ImplicitStandardConversionExists (left, underlying_type))
2928 left = Convert.ImplicitConversionStandard (ec, left, underlying_type, left.Location);
2931 if (right is Constant)
2932 right = ((Constant) right).ConvertExplicitly (false, underlying_type).Resolve (ec);
2934 right = EmptyCast.Create (right, underlying_type);
2941 // C# specification uses explicit cast syntax which means binary promotion
2942 // should happen, however it seems that csc does not do that
2944 if (!DoBinaryOperatorPromotion (ec)) {
2950 TypeSpec res_type = null;
2951 if ((oper & Operator.BitwiseMask) != 0 || oper == Operator.Subtraction || oper == Operator.Addition) {
2952 TypeSpec promoted_type = lenum ? left.Type : right.Type;
2953 enum_conversion = Convert.ExplicitNumericConversion (
2954 new EmptyExpression (promoted_type), underlying_type);
2956 if (oper == Operator.Subtraction && renum && lenum)
2957 res_type = underlying_type;
2958 else if (oper == Operator.Addition && renum)
2964 expr = ResolveOperatorPredefined (ec, standard_operators, true, res_type);
2965 if (!is_compound || expr == null)
2973 // If the return type of the selected operator is implicitly convertible to the type of x
2975 if (Convert.ImplicitConversionExists (ec, expr, ltype))
2979 // Otherwise, if the selected operator is a predefined operator, if the return type of the
2980 // selected operator is explicitly convertible to the type of x, and if y is implicitly
2981 // convertible to the type of x or the operator is a shift operator, then the operation
2982 // is evaluated as x = (T)(x op y), where T is the type of x
2984 expr = Convert.ExplicitConversion (ec, expr, ltype, loc);
2988 if (Convert.ImplicitConversionExists (ec, ltemp, ltype))
2995 // 7.9.6 Reference type equality operators
2997 Expression ResolveOperatorEquality (ResolveContext ec, TypeSpec l, TypeSpec r)
3000 type = TypeManager.bool_type;
3003 // a, Both operands are reference-type values or the value null
3004 // b, One operand is a value of type T where T is a type-parameter and
3005 // the other operand is the value null. Furthermore T does not have the
3006 // value type constraint
3008 // LAMESPEC: Very confusing details in the specification, basically any
3009 // reference like type-parameter is allowed
3011 var tparam_l = l as TypeParameterSpec;
3012 var tparam_r = r as TypeParameterSpec;
3013 if (tparam_l != null) {
3014 if (right is NullLiteral && !tparam_l.HasSpecialStruct) {
3015 left = new BoxedCast (left, TypeManager.object_type);
3019 if (!tparam_l.IsReferenceType)
3022 l = tparam_l.GetEffectiveBase ();
3023 left = new BoxedCast (left, l);
3024 } else if (left is NullLiteral && tparam_r == null) {
3025 if (!TypeManager.IsReferenceType (r) || r.Kind == MemberKind.InternalCompilerType)
3031 if (tparam_r != null) {
3032 if (left is NullLiteral && !tparam_r.HasSpecialStruct) {
3033 right = new BoxedCast (right, TypeManager.object_type);
3037 if (!tparam_r.IsReferenceType)
3040 r = tparam_r.GetEffectiveBase ();
3041 right = new BoxedCast (right, r);
3042 } else if (right is NullLiteral) {
3043 if (!TypeManager.IsReferenceType (l) || l.Kind == MemberKind.InternalCompilerType)
3050 // LAMESPEC: method groups can be compared when they convert to other side delegate
3053 if (right.eclass == ExprClass.MethodGroup) {
3054 result = Convert.ImplicitConversion (ec, right, l, loc);
3060 } else if (r.IsDelegate && l != r) {
3063 } else if (left.eclass == ExprClass.MethodGroup && r.IsDelegate) {
3064 result = Convert.ImplicitConversionRequired (ec, left, r, loc);
3073 // bool operator != (string a, string b)
3074 // bool operator == (string a, string b)
3076 // bool operator != (Delegate a, Delegate b)
3077 // bool operator == (Delegate a, Delegate b)
3079 // bool operator != (bool a, bool b)
3080 // bool operator == (bool a, bool b)
3082 // LAMESPEC: Reference equality comparison can apply to value types when
3083 // they implement an implicit conversion to any of types above.
3085 if (r != TypeManager.object_type && l != TypeManager.object_type) {
3086 result = ResolveOperatorPredefined (ec, equality_operators, false, null);
3092 // bool operator != (object a, object b)
3093 // bool operator == (object a, object b)
3095 // An explicit reference conversion exists from the
3096 // type of either operand to the type of the other operand.
3099 // Optimize common path
3101 return l.Kind == MemberKind.InternalCompilerType || l.Kind == MemberKind.Struct ? null : this;
3104 if (!Convert.ExplicitReferenceConversionExists (l, r) &&
3105 !Convert.ExplicitReferenceConversionExists (r, l))
3108 // Reject allowed explicit conversions like int->object
3109 if (!TypeManager.IsReferenceType (l) || !TypeManager.IsReferenceType (r))
3112 if (l == TypeManager.string_type || l == TypeManager.delegate_type || MemberCache.GetUserOperator (l, CSharp.Operator.OpType.Equality, false) != null)
3113 ec.Report.Warning (253, 2, loc,
3114 "Possible unintended reference comparison. Consider casting the right side expression to type `{0}' to get value comparison",
3115 l.GetSignatureForError ());
3117 if (r == TypeManager.string_type || r == TypeManager.delegate_type || MemberCache.GetUserOperator (r, CSharp.Operator.OpType.Equality, false) != null)
3118 ec.Report.Warning (252, 2, loc,
3119 "Possible unintended reference comparison. Consider casting the left side expression to type `{0}' to get value comparison",
3120 r.GetSignatureForError ());
3126 Expression ResolveOperatorPointer (ResolveContext ec, TypeSpec l, TypeSpec r)
3129 // bool operator == (void* x, void* y);
3130 // bool operator != (void* x, void* y);
3131 // bool operator < (void* x, void* y);
3132 // bool operator > (void* x, void* y);
3133 // bool operator <= (void* x, void* y);
3134 // bool operator >= (void* x, void* y);
3136 if ((oper & Operator.ComparisonMask) != 0) {
3139 temp = Convert.ImplicitConversion (ec, left, r, left.Location);
3146 temp = Convert.ImplicitConversion (ec, right, l, right.Location);
3152 type = TypeManager.bool_type;
3156 if (pointer_operators == null)
3157 CreatePointerOperatorsTable ();
3159 return ResolveOperatorPredefined (ec, pointer_operators, false, null);
3163 // Build-in operators method overloading
3165 protected virtual Expression ResolveOperatorPredefined (ResolveContext ec, PredefinedOperator [] operators, bool primitives_only, TypeSpec enum_type)
3167 PredefinedOperator best_operator = null;
3168 TypeSpec l = left.Type;
3169 TypeSpec r = right.Type;
3170 Operator oper_mask = oper & ~Operator.ValuesOnlyMask;
3172 foreach (PredefinedOperator po in operators) {
3173 if ((po.OperatorsMask & oper_mask) == 0)
3176 if (primitives_only) {
3177 if (!po.IsPrimitiveApplicable (l, r))
3180 if (!po.IsApplicable (ec, left, right))
3184 if (best_operator == null) {
3186 if (primitives_only)
3192 best_operator = po.ResolveBetterOperator (ec, best_operator);
3194 if (best_operator == null) {
3195 ec.Report.Error (34, loc, "Operator `{0}' is ambiguous on operands of type `{1}' and `{2}'",
3196 OperName (oper), TypeManager.CSharpName (l), TypeManager.CSharpName (r));
3203 if (best_operator == null)
3206 Expression expr = best_operator.ConvertResult (ec, this);
3209 // Optimize &/&& constant expressions with 0 value
3211 if (oper == Operator.BitwiseAnd || oper == Operator.LogicalAnd) {
3212 Constant rc = right as Constant;
3213 Constant lc = left as Constant;
3214 if ((lc != null && lc.IsDefaultValue) || (rc != null && rc.IsDefaultValue)) {
3216 // The result is a constant with side-effect
3218 Constant side_effect = rc == null ?
3219 new SideEffectConstant (lc, right, loc) :
3220 new SideEffectConstant (rc, left, loc);
3222 return ReducedExpression.Create (side_effect.Resolve (ec), expr);
3226 if (enum_type == null)
3230 // HACK: required by enum_conversion
3232 expr.Type = enum_type;
3233 return EmptyCast.Create (expr, enum_type);
3237 // Performs user-operator overloading
3239 protected virtual Expression ResolveUserOperator (ResolveContext ec, TypeSpec l, TypeSpec r)
3241 var op = ConvertBinaryToUserOperator (oper);
3242 IList<MemberSpec> left_operators = MemberCache.GetUserOperator (l, op, false);
3243 IList<MemberSpec> right_operators = null;
3246 right_operators = MemberCache.GetUserOperator (r, op, false);
3247 if (right_operators == null && left_operators == null)
3249 } else if (left_operators == null) {
3253 Arguments args = new Arguments (2);
3254 Argument larg = new Argument (left);
3256 Argument rarg = new Argument (right);
3260 // User-defined operator implementations always take precedence
3261 // over predefined operator implementations
3263 if (left_operators != null && right_operators != null) {
3264 left_operators = CombineUserOperators (left_operators, right_operators);
3265 } else if (right_operators != null) {
3266 left_operators = right_operators;
3269 var res = new OverloadResolver (left_operators, OverloadResolver.Restrictions.ProbingOnly, loc);
3271 var oper_method = res.ResolveOperator (ec, ref args);
3272 if (oper_method == null)
3275 Expression oper_expr;
3277 // TODO: CreateExpressionTree is allocated every time
3278 if ((oper & Operator.LogicalMask) != 0) {
3279 oper_expr = new ConditionalLogicalOperator (oper_method, args, CreateExpressionTree,
3280 oper == Operator.LogicalAnd, loc).Resolve (ec);
3282 oper_expr = new UserOperatorCall (oper_method, args, CreateExpressionTree, loc);
3291 // Merge two sets of user operators into one, they are mostly distinguish
3292 // expect when they share base type and it contains an operator
3294 static IList<MemberSpec> CombineUserOperators (IList<MemberSpec> left, IList<MemberSpec> right)
3296 var combined = new List<MemberSpec> (left.Count + right.Count);
3297 combined.AddRange (left);
3298 foreach (var r in right) {
3300 foreach (var l in left) {
3301 if (l.DeclaringType == r.DeclaringType) {
3314 public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
3319 private void CheckUselessComparison (ResolveContext ec, Constant c, TypeSpec type)
3321 if (c == null || !IsTypeIntegral (type)
3322 || c is StringConstant
3323 || c is BoolConstant
3324 || c is FloatConstant
3325 || c is DoubleConstant
3326 || c is DecimalConstant
3332 if (c is ULongConstant) {
3333 ulong uvalue = ((ULongConstant) c).Value;
3334 if (uvalue > long.MaxValue) {
3335 if (type == TypeManager.byte_type ||
3336 type == TypeManager.sbyte_type ||
3337 type == TypeManager.short_type ||
3338 type == TypeManager.ushort_type ||
3339 type == TypeManager.int32_type ||
3340 type == TypeManager.uint32_type ||
3341 type == TypeManager.int64_type ||
3342 type == TypeManager.char_type)
3343 WarnUselessComparison (ec, type);
3346 value = (long) uvalue;
3348 else if (c is ByteConstant)
3349 value = ((ByteConstant) c).Value;
3350 else if (c is SByteConstant)
3351 value = ((SByteConstant) c).Value;
3352 else if (c is ShortConstant)
3353 value = ((ShortConstant) c).Value;
3354 else if (c is UShortConstant)
3355 value = ((UShortConstant) c).Value;
3356 else if (c is IntConstant)
3357 value = ((IntConstant) c).Value;
3358 else if (c is UIntConstant)
3359 value = ((UIntConstant) c).Value;
3360 else if (c is LongConstant)
3361 value = ((LongConstant) c).Value;
3362 else if (c is CharConstant)
3363 value = ((CharConstant)c).Value;
3368 if (IsValueOutOfRange (value, type))
3369 WarnUselessComparison (ec, type);
3372 static bool IsValueOutOfRange (long value, TypeSpec type)
3374 if (IsTypeUnsigned (type) && value < 0)
3376 return type == TypeManager.sbyte_type && (value >= 0x80 || value < -0x80) ||
3377 type == TypeManager.byte_type && value >= 0x100 ||
3378 type == TypeManager.short_type && (value >= 0x8000 || value < -0x8000) ||
3379 type == TypeManager.ushort_type && value >= 0x10000 ||
3380 type == TypeManager.int32_type && (value >= 0x80000000 || value < -0x80000000) ||
3381 type == TypeManager.uint32_type && value >= 0x100000000;
3384 private static bool IsTypeIntegral (TypeSpec type)
3386 return type == TypeManager.uint64_type ||
3387 type == TypeManager.int64_type ||
3388 type == TypeManager.uint32_type ||
3389 type == TypeManager.int32_type ||
3390 type == TypeManager.ushort_type ||
3391 type == TypeManager.short_type ||
3392 type == TypeManager.sbyte_type ||
3393 type == TypeManager.byte_type ||
3394 type == TypeManager.char_type;
3397 private static bool IsTypeUnsigned (TypeSpec type)
3399 return type == TypeManager.uint64_type ||
3400 type == TypeManager.uint32_type ||
3401 type == TypeManager.ushort_type ||
3402 type == TypeManager.byte_type ||
3403 type == TypeManager.char_type;
3406 private void WarnUselessComparison (ResolveContext ec, TypeSpec type)
3408 ec.Report.Warning (652, 2, loc, "A comparison between a constant and a variable is useless. The constant is out of the range of the variable type `{0}'",
3409 TypeManager.CSharpName (type));
3413 /// EmitBranchable is called from Statement.EmitBoolExpression in the
3414 /// context of a conditional bool expression. This function will return
3415 /// false if it is was possible to use EmitBranchable, or true if it was.
3417 /// The expression's code is generated, and we will generate a branch to `target'
3418 /// if the resulting expression value is equal to isTrue
3420 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
3423 // This is more complicated than it looks, but its just to avoid
3424 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
3425 // but on top of that we want for == and != to use a special path
3426 // if we are comparing against null
3428 if ((oper & Operator.EqualityMask) != 0 && (left is Constant || right is Constant)) {
3429 bool my_on_true = oper == Operator.Inequality ? on_true : !on_true;
3432 // put the constant on the rhs, for simplicity
3434 if (left is Constant) {
3435 Expression swap = right;
3441 // brtrue/brfalse works with native int only
3443 if (((Constant) right).IsZeroInteger && right.Type != TypeManager.int64_type && right.Type != TypeManager.uint64_type) {
3444 left.EmitBranchable (ec, target, my_on_true);
3447 if (right.Type == TypeManager.bool_type) {
3448 // right is a boolean, and it's not 'false' => it is 'true'
3449 left.EmitBranchable (ec, target, !my_on_true);
3453 } else if (oper == Operator.LogicalAnd) {
3456 Label tests_end = ec.DefineLabel ();
3458 left.EmitBranchable (ec, tests_end, false);
3459 right.EmitBranchable (ec, target, true);
3460 ec.MarkLabel (tests_end);
3463 // This optimizes code like this
3464 // if (true && i > 4)
3466 if (!(left is Constant))
3467 left.EmitBranchable (ec, target, false);
3469 if (!(right is Constant))
3470 right.EmitBranchable (ec, target, false);
3475 } else if (oper == Operator.LogicalOr){
3477 left.EmitBranchable (ec, target, true);
3478 right.EmitBranchable (ec, target, true);
3481 Label tests_end = ec.DefineLabel ();
3482 left.EmitBranchable (ec, tests_end, true);
3483 right.EmitBranchable (ec, target, false);
3484 ec.MarkLabel (tests_end);
3489 } else if ((oper & Operator.ComparisonMask) == 0) {
3490 base.EmitBranchable (ec, target, on_true);
3497 TypeSpec t = left.Type;
3498 bool is_float = IsFloat (t);
3499 bool is_unsigned = is_float || IsUnsigned (t);
3502 case Operator.Equality:
3504 ec.Emit (OpCodes.Beq, target);
3506 ec.Emit (OpCodes.Bne_Un, target);
3509 case Operator.Inequality:
3511 ec.Emit (OpCodes.Bne_Un, target);
3513 ec.Emit (OpCodes.Beq, target);
3516 case Operator.LessThan:
3518 if (is_unsigned && !is_float)
3519 ec.Emit (OpCodes.Blt_Un, target);
3521 ec.Emit (OpCodes.Blt, target);
3524 ec.Emit (OpCodes.Bge_Un, target);
3526 ec.Emit (OpCodes.Bge, target);
3529 case Operator.GreaterThan:
3531 if (is_unsigned && !is_float)
3532 ec.Emit (OpCodes.Bgt_Un, target);
3534 ec.Emit (OpCodes.Bgt, target);
3537 ec.Emit (OpCodes.Ble_Un, target);
3539 ec.Emit (OpCodes.Ble, target);
3542 case Operator.LessThanOrEqual:
3544 if (is_unsigned && !is_float)
3545 ec.Emit (OpCodes.Ble_Un, target);
3547 ec.Emit (OpCodes.Ble, target);
3550 ec.Emit (OpCodes.Bgt_Un, target);
3552 ec.Emit (OpCodes.Bgt, target);
3556 case Operator.GreaterThanOrEqual:
3558 if (is_unsigned && !is_float)
3559 ec.Emit (OpCodes.Bge_Un, target);
3561 ec.Emit (OpCodes.Bge, target);
3564 ec.Emit (OpCodes.Blt_Un, target);
3566 ec.Emit (OpCodes.Blt, target);
3569 throw new InternalErrorException (oper.ToString ());
3573 public override void Emit (EmitContext ec)
3575 EmitOperator (ec, left.Type);
3578 protected virtual void EmitOperator (EmitContext ec, TypeSpec l)
3581 // Handle short-circuit operators differently
3584 if ((oper & Operator.LogicalMask) != 0) {
3585 Label load_result = ec.DefineLabel ();
3586 Label end = ec.DefineLabel ();
3588 bool is_or = oper == Operator.LogicalOr;
3589 left.EmitBranchable (ec, load_result, is_or);
3591 ec.Emit (OpCodes.Br_S, end);
3593 ec.MarkLabel (load_result);
3594 ec.Emit (is_or ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
3600 // Optimize zero-based operations which cannot be optimized at expression level
3602 if (oper == Operator.Subtraction) {
3603 var lc = left as IntegralConstant;
3604 if (lc != null && lc.IsDefaultValue) {
3606 ec.Emit (OpCodes.Neg);
3613 EmitOperatorOpcode (ec, oper, l);
3616 // Nullable enum could require underlying type cast and we cannot simply wrap binary
3617 // expression because that would wrap lifted binary operation
3619 if (enum_conversion != null)
3620 enum_conversion.Emit (ec);
3623 public override void EmitSideEffect (EmitContext ec)
3625 if ((oper & Operator.LogicalMask) != 0 ||
3626 (ec.HasSet (EmitContext.Options.CheckedScope) && (oper == Operator.Multiply || oper == Operator.Addition || oper == Operator.Subtraction))) {
3627 base.EmitSideEffect (ec);
3629 left.EmitSideEffect (ec);
3630 right.EmitSideEffect (ec);
3634 protected override void CloneTo (CloneContext clonectx, Expression t)
3636 Binary target = (Binary) t;
3638 target.left = left.Clone (clonectx);
3639 target.right = right.Clone (clonectx);
3642 public Expression CreateCallSiteBinder (ResolveContext ec, Arguments args)
3644 Arguments binder_args = new Arguments (4);
3646 MemberAccess sle = new MemberAccess (new MemberAccess (
3647 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Linq", loc), "Expressions", loc);
3649 CSharpBinderFlags flags = 0;
3650 if (ec.HasSet (ResolveContext.Options.CheckedScope))
3651 flags = CSharpBinderFlags.CheckedContext;
3653 if ((oper & Operator.LogicalMask) != 0)
3654 flags |= CSharpBinderFlags.BinaryOperationLogical;
3656 binder_args.Add (new Argument (new EnumConstant (new IntLiteral ((int) flags, loc), TypeManager.binder_flags)));
3657 binder_args.Add (new Argument (new MemberAccess (new MemberAccess (sle, "ExpressionType", loc), GetOperatorExpressionTypeName (), loc)));
3658 binder_args.Add (new Argument (new TypeOf (new TypeExpression (ec.CurrentType, loc), loc)));
3659 binder_args.Add (new Argument (new ImplicitlyTypedArrayCreation (args.CreateDynamicBinderArguments (ec), loc)));
3661 return new Invocation (DynamicExpressionStatement.GetBinder ("BinaryOperation", loc), binder_args);
3664 public override Expression CreateExpressionTree (ResolveContext ec)
3666 return CreateExpressionTree (ec, null);
3669 Expression CreateExpressionTree (ResolveContext ec, Expression method)
3672 bool lift_arg = false;
3675 case Operator.Addition:
3676 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
3677 method_name = "AddChecked";
3679 method_name = "Add";
3681 case Operator.BitwiseAnd:
3682 method_name = "And";
3684 case Operator.BitwiseOr:
3687 case Operator.Division:
3688 method_name = "Divide";
3690 case Operator.Equality:
3691 method_name = "Equal";
3694 case Operator.ExclusiveOr:
3695 method_name = "ExclusiveOr";
3697 case Operator.GreaterThan:
3698 method_name = "GreaterThan";
3701 case Operator.GreaterThanOrEqual:
3702 method_name = "GreaterThanOrEqual";
3705 case Operator.Inequality:
3706 method_name = "NotEqual";
3709 case Operator.LeftShift:
3710 method_name = "LeftShift";
3712 case Operator.LessThan:
3713 method_name = "LessThan";
3716 case Operator.LessThanOrEqual:
3717 method_name = "LessThanOrEqual";
3720 case Operator.LogicalAnd:
3721 method_name = "AndAlso";
3723 case Operator.LogicalOr:
3724 method_name = "OrElse";
3726 case Operator.Modulus:
3727 method_name = "Modulo";
3729 case Operator.Multiply:
3730 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
3731 method_name = "MultiplyChecked";
3733 method_name = "Multiply";
3735 case Operator.RightShift:
3736 method_name = "RightShift";
3738 case Operator.Subtraction:
3739 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
3740 method_name = "SubtractChecked";
3742 method_name = "Subtract";
3746 throw new InternalErrorException ("Unknown expression tree binary operator " + oper);
3749 Arguments args = new Arguments (2);
3750 args.Add (new Argument (left.CreateExpressionTree (ec)));
3751 args.Add (new Argument (right.CreateExpressionTree (ec)));
3752 if (method != null) {
3754 args.Add (new Argument (new BoolConstant (false, loc)));
3756 args.Add (new Argument (method));
3759 return CreateExpressionFactoryCall (ec, method_name, args);
3764 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3765 // b, c, d... may be strings or objects.
3767 public class StringConcat : Expression {
3768 Arguments arguments;
3769 static IList<MemberSpec> concat_members;
3771 public StringConcat (Expression left, Expression right, Location loc)
3774 type = TypeManager.string_type;
3775 eclass = ExprClass.Value;
3777 arguments = new Arguments (2);
3780 public static StringConcat Create (ResolveContext rc, Expression left, Expression right, Location loc)
3782 if (left.eclass == ExprClass.Unresolved || right.eclass == ExprClass.Unresolved)
3783 throw new ArgumentException ();
3785 var s = new StringConcat (left, right, loc);
3786 s.Append (rc, left);
3787 s.Append (rc, right);
3791 public override Expression CreateExpressionTree (ResolveContext ec)
3793 Argument arg = arguments [0];
3794 return CreateExpressionAddCall (ec, arg, arg.CreateExpressionTree (ec), 1);
3798 // Creates nested calls tree from an array of arguments used for IL emit
3800 Expression CreateExpressionAddCall (ResolveContext ec, Argument left, Expression left_etree, int pos)
3802 Arguments concat_args = new Arguments (2);
3803 Arguments add_args = new Arguments (3);
3805 concat_args.Add (left);
3806 add_args.Add (new Argument (left_etree));
3808 concat_args.Add (arguments [pos]);
3809 add_args.Add (new Argument (arguments [pos].CreateExpressionTree (ec)));
3811 var methods = CreateConcatMethodCandidates ();
3812 if (methods == null)
3815 var res = new OverloadResolver (methods, OverloadResolver.Restrictions.NoBaseMembers, loc);
3816 var method = res.ResolveMember<MethodSpec> (ec, ref concat_args);
3820 add_args.Add (new Argument (new TypeOfMethod (method, loc)));
3822 Expression expr = CreateExpressionFactoryCall (ec, "Add", add_args);
3823 if (++pos == arguments.Count)
3826 left = new Argument (new EmptyExpression (method.ReturnType));
3827 return CreateExpressionAddCall (ec, left, expr, pos);
3830 protected override Expression DoResolve (ResolveContext ec)
3835 void Append (ResolveContext rc, Expression operand)
3840 StringConstant sc = operand as StringConstant;
3842 if (arguments.Count != 0) {
3843 Argument last_argument = arguments [arguments.Count - 1];
3844 StringConstant last_expr_constant = last_argument.Expr as StringConstant;
3845 if (last_expr_constant != null) {
3846 last_argument.Expr = new StringConstant (
3847 last_expr_constant.Value + sc.Value, sc.Location).Resolve (rc);
3853 // Multiple (3+) concatenation are resolved as multiple StringConcat instances
3855 StringConcat concat_oper = operand as StringConcat;
3856 if (concat_oper != null) {
3857 arguments.AddRange (concat_oper.arguments);
3862 arguments.Add (new Argument (operand));
3865 IList<MemberSpec> CreateConcatMethodCandidates ()
3867 if (concat_members == null) {
3868 concat_members = MemberCache.FindMembers (type, "Concat", true);
3871 return concat_members;
3874 public override void Emit (EmitContext ec)
3876 var members = CreateConcatMethodCandidates ();
3877 var res = new OverloadResolver (members, OverloadResolver.Restrictions.NoBaseMembers, loc);
3878 var method = res.ResolveMember<MethodSpec> (new ResolveContext (ec.MemberContext), ref arguments);
3880 Invocation.EmitCall (ec, null, method, arguments, loc);
3883 public override SLE.Expression MakeExpression (BuilderContext ctx)
3885 if (arguments.Count != 2)
3886 throw new NotImplementedException ("arguments.Count != 2");
3888 var concat = typeof (string).GetMethod ("Concat", new[] { typeof (object), typeof (object) });
3889 return SLE.Expression.Add (arguments[0].Expr.MakeExpression (ctx), arguments[1].Expr.MakeExpression (ctx), concat);
3892 public static void Reset ()
3894 concat_members = null;
3899 // User-defined conditional logical operator
3901 public class ConditionalLogicalOperator : UserOperatorCall {
3902 readonly bool is_and;
3903 Expression oper_expr;
3905 public ConditionalLogicalOperator (MethodSpec oper, Arguments arguments, Func<ResolveContext, Expression, Expression> expr_tree, bool is_and, Location loc)
3906 : base (oper, arguments, expr_tree, loc)
3908 this.is_and = is_and;
3909 eclass = ExprClass.Unresolved;
3912 protected override Expression DoResolve (ResolveContext ec)
3914 AParametersCollection pd = oper.Parameters;
3915 if (!TypeManager.IsEqual (type, type) || !TypeManager.IsEqual (type, pd.Types [0]) || !TypeManager.IsEqual (type, pd.Types [1])) {
3916 ec.Report.Error (217, loc,
3917 "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",
3918 oper.GetSignatureForError ());
3922 Expression left_dup = new EmptyExpression (type);
3923 Expression op_true = GetOperatorTrue (ec, left_dup, loc);
3924 Expression op_false = GetOperatorFalse (ec, left_dup, loc);
3925 if (op_true == null || op_false == null) {
3926 ec.Report.Error (218, loc,
3927 "The type `{0}' must have operator `true' and operator `false' defined when `{1}' is used as a short circuit operator",
3928 TypeManager.CSharpName (type), oper.GetSignatureForError ());
3932 oper_expr = is_and ? op_false : op_true;
3933 eclass = ExprClass.Value;
3937 public override void Emit (EmitContext ec)
3939 Label end_target = ec.DefineLabel ();
3942 // Emit and duplicate left argument
3944 arguments [0].Expr.Emit (ec);
3945 ec.Emit (OpCodes.Dup);
3946 arguments.RemoveAt (0);
3948 oper_expr.EmitBranchable (ec, end_target, true);
3950 ec.MarkLabel (end_target);
3954 public class PointerArithmetic : Expression {
3955 Expression left, right;
3959 // We assume that `l' is always a pointer
3961 public PointerArithmetic (Binary.Operator op, Expression l, Expression r, TypeSpec t, Location loc)
3970 public override Expression CreateExpressionTree (ResolveContext ec)
3972 Error_PointerInsideExpressionTree (ec);
3976 protected override Expression DoResolve (ResolveContext ec)
3978 eclass = ExprClass.Variable;
3980 if (left.Type == TypeManager.void_ptr_type) {
3981 ec.Report.Error (242, loc, "The operation in question is undefined on void pointers");
3988 public override void Emit (EmitContext ec)
3990 TypeSpec op_type = left.Type;
3992 // It must be either array or fixed buffer
3994 if (TypeManager.HasElementType (op_type)) {
3995 element = TypeManager.GetElementType (op_type);
3997 FieldExpr fe = left as FieldExpr;
3999 element = ((FixedFieldSpec) (fe.Spec)).ElementType;
4004 int size = GetTypeSize (element);
4005 TypeSpec rtype = right.Type;
4007 if ((op & Binary.Operator.SubtractionMask) != 0 && rtype.IsPointer){
4009 // handle (pointer - pointer)
4013 ec.Emit (OpCodes.Sub);
4017 ec.Emit (OpCodes.Sizeof, element);
4020 ec.Emit (OpCodes.Div);
4022 ec.Emit (OpCodes.Conv_I8);
4025 // handle + and - on (pointer op int)
4027 Constant left_const = left as Constant;
4028 if (left_const != null) {
4030 // Optimize ((T*)null) pointer operations
4032 if (left_const.IsDefaultValue) {
4033 left = EmptyExpression.Null;
4041 var right_const = right as Constant;
4042 if (right_const != null) {
4044 // Optimize 0-based arithmetic
4046 if (right_const.IsDefaultValue)
4050 right = new IntConstant (size, right.Location);
4052 right = new SizeOf (new TypeExpression (element, right.Location), right.Location);
4054 // TODO: Should be the checks resolve context sensitive?
4055 ResolveContext rc = new ResolveContext (ec.MemberContext, ResolveContext.Options.UnsafeScope);
4056 right = new Binary (Binary.Operator.Multiply, right, right_const, loc).Resolve (rc);
4062 if (rtype == TypeManager.sbyte_type || rtype == TypeManager.byte_type ||
4063 rtype == TypeManager.short_type || rtype == TypeManager.ushort_type) {
4064 ec.Emit (OpCodes.Conv_I);
4065 } else if (rtype == TypeManager.uint32_type) {
4066 ec.Emit (OpCodes.Conv_U);
4069 if (right_const == null && size != 1){
4071 ec.Emit (OpCodes.Sizeof, element);
4074 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
4075 ec.Emit (OpCodes.Conv_I8);
4077 Binary.EmitOperatorOpcode (ec, Binary.Operator.Multiply, rtype);
4080 if (left_const == null) {
4081 if (rtype == TypeManager.int64_type)
4082 ec.Emit (OpCodes.Conv_I);
4083 else if (rtype == TypeManager.uint64_type)
4084 ec.Emit (OpCodes.Conv_U);
4086 Binary.EmitOperatorOpcode (ec, op, op_type);
4093 // A boolean-expression is an expression that yields a result
4096 public class BooleanExpression : ShimExpression
4098 public BooleanExpression (Expression expr)
4101 this.loc = expr.Location;
4104 public override Expression CreateExpressionTree (ResolveContext ec)
4106 // TODO: We should emit IsTrue (v4) instead of direct user operator
4107 // call but that would break csc compatibility
4108 return base.CreateExpressionTree (ec);
4111 protected override Expression DoResolve (ResolveContext ec)
4113 // A boolean-expression is required to be of a type
4114 // that can be implicitly converted to bool or of
4115 // a type that implements operator true
4117 expr = expr.Resolve (ec);
4121 Assign ass = expr as Assign;
4122 if (ass != null && ass.Source is Constant) {
4123 ec.Report.Warning (665, 3, loc,
4124 "Assignment in conditional expression is always constant. Did you mean to use `==' instead ?");
4127 if (expr.Type == TypeManager.bool_type)
4130 if (expr.Type == InternalType.Dynamic) {
4131 Arguments args = new Arguments (1);
4132 args.Add (new Argument (expr));
4133 return new DynamicUnaryConversion ("IsTrue", args, loc).Resolve (ec);
4136 type = TypeManager.bool_type;
4137 Expression converted = Convert.ImplicitConversion (ec, expr, type, loc);
4138 if (converted != null)
4142 // If no implicit conversion to bool exists, try using `operator true'
4144 converted = GetOperatorTrue (ec, expr, loc);
4145 if (converted == null) {
4146 expr.Error_ValueCannotBeConverted (ec, loc, type, false);
4155 /// Implements the ternary conditional operator (?:)
4157 public class Conditional : Expression {
4158 Expression expr, true_expr, false_expr;
4160 public Conditional (BooleanExpression expr, Expression true_expr, Expression false_expr, Location loc)
4163 this.true_expr = true_expr;
4164 this.false_expr = false_expr;
4168 public Expression Expr {
4174 public Expression TrueExpr {
4180 public Expression FalseExpr {
4186 public override Expression CreateExpressionTree (ResolveContext ec)
4188 Arguments args = new Arguments (3);
4189 args.Add (new Argument (expr.CreateExpressionTree (ec)));
4190 args.Add (new Argument (true_expr.CreateExpressionTree (ec)));
4191 args.Add (new Argument (false_expr.CreateExpressionTree (ec)));
4192 return CreateExpressionFactoryCall (ec, "Condition", args);
4195 protected override Expression DoResolve (ResolveContext ec)
4197 expr = expr.Resolve (ec);
4198 true_expr = true_expr.Resolve (ec);
4199 false_expr = false_expr.Resolve (ec);
4201 if (true_expr == null || false_expr == null || expr == null)
4204 eclass = ExprClass.Value;
4205 TypeSpec true_type = true_expr.Type;
4206 TypeSpec false_type = false_expr.Type;
4210 // First, if an implicit conversion exists from true_expr
4211 // to false_expr, then the result type is of type false_expr.Type
4213 if (!TypeManager.IsEqual (true_type, false_type)) {
4214 Expression conv = Convert.ImplicitConversion (ec, true_expr, false_type, loc);
4217 // Check if both can convert implicitly to each other's type
4219 if (Convert.ImplicitConversion (ec, false_expr, true_type, loc) != null) {
4220 ec.Report.Error (172, true_expr.Location,
4221 "Type of conditional expression cannot be determined as `{0}' and `{1}' convert implicitly to each other",
4222 TypeManager.CSharpName (true_type), TypeManager.CSharpName (false_type));
4227 } else if ((conv = Convert.ImplicitConversion (ec, false_expr, true_type, loc)) != null) {
4230 ec.Report.Error (173, true_expr.Location,
4231 "Type of conditional expression cannot be determined because there is no implicit conversion between `{0}' and `{1}'",
4232 TypeManager.CSharpName (true_type), TypeManager.CSharpName (false_type));
4237 // Dead code optimalization
4238 Constant c = expr as Constant;
4240 bool is_false = c.IsDefaultValue;
4241 ec.Report.Warning (429, 4, is_false ? true_expr.Location : false_expr.Location, "Unreachable expression code detected");
4242 return ReducedExpression.Create (is_false ? false_expr : true_expr, this).Resolve (ec);
4248 public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
4253 public override void Emit (EmitContext ec)
4255 Label false_target = ec.DefineLabel ();
4256 Label end_target = ec.DefineLabel ();
4258 expr.EmitBranchable (ec, false_target, false);
4259 true_expr.Emit (ec);
4261 if (type.IsInterface) {
4262 LocalBuilder temp = ec.GetTemporaryLocal (type);
4263 ec.Emit (OpCodes.Stloc, temp);
4264 ec.Emit (OpCodes.Ldloc, temp);
4265 ec.FreeTemporaryLocal (temp, type);
4268 ec.Emit (OpCodes.Br, end_target);
4269 ec.MarkLabel (false_target);
4270 false_expr.Emit (ec);
4271 ec.MarkLabel (end_target);
4274 protected override void CloneTo (CloneContext clonectx, Expression t)
4276 Conditional target = (Conditional) t;
4278 target.expr = expr.Clone (clonectx);
4279 target.true_expr = true_expr.Clone (clonectx);
4280 target.false_expr = false_expr.Clone (clonectx);
4284 public abstract class VariableReference : Expression, IAssignMethod, IMemoryLocation, IVariableReference {
4285 LocalTemporary temp;
4288 public abstract HoistedVariable GetHoistedVariable (AnonymousExpression ae);
4289 public abstract bool IsFixed { get; }
4290 public abstract bool IsRef { get; }
4291 public abstract string Name { get; }
4292 public abstract void SetHasAddressTaken ();
4295 // Variable IL data, it has to be protected to encapsulate hoisted variables
4297 protected abstract ILocalVariable Variable { get; }
4300 // Variable flow-analysis data
4302 public abstract VariableInfo VariableInfo { get; }
4305 public virtual void AddressOf (EmitContext ec, AddressOp mode)
4307 HoistedVariable hv = GetHoistedVariable (ec);
4309 hv.AddressOf (ec, mode);
4313 Variable.EmitAddressOf (ec);
4316 public HoistedVariable GetHoistedVariable (ResolveContext rc)
4318 return GetHoistedVariable (rc.CurrentAnonymousMethod);
4321 public HoistedVariable GetHoistedVariable (EmitContext ec)
4323 return GetHoistedVariable (ec.CurrentAnonymousMethod);
4326 public override string GetSignatureForError ()
4331 public override void Emit (EmitContext ec)
4336 public override void EmitSideEffect (EmitContext ec)
4342 // This method is used by parameters that are references, that are
4343 // being passed as references: we only want to pass the pointer (that
4344 // is already stored in the parameter, not the address of the pointer,
4345 // and not the value of the variable).
4347 public void EmitLoad (EmitContext ec)
4352 public void Emit (EmitContext ec, bool leave_copy)
4354 Report.Debug (64, "VARIABLE EMIT", this, Variable, type, IsRef, loc);
4356 HoistedVariable hv = GetHoistedVariable (ec);
4358 hv.Emit (ec, leave_copy);
4366 // If we are a reference, we loaded on the stack a pointer
4367 // Now lets load the real value
4369 ec.EmitLoadFromPtr (type);
4373 ec.Emit (OpCodes.Dup);
4376 temp = new LocalTemporary (Type);
4382 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy,
4383 bool prepare_for_load)
4385 HoistedVariable hv = GetHoistedVariable (ec);
4387 hv.EmitAssign (ec, source, leave_copy, prepare_for_load);
4391 New n_source = source as New;
4392 if (n_source != null) {
4393 if (!n_source.Emit (ec, this)) {
4406 ec.Emit (OpCodes.Dup);
4408 temp = new LocalTemporary (Type);
4414 ec.EmitStoreFromPtr (type);
4416 Variable.EmitAssign (ec);
4424 public bool IsHoisted {
4425 get { return GetHoistedVariable ((AnonymousExpression) null) != null; }
4432 public class LocalVariableReference : VariableReference {
4433 readonly string name;
4435 public LocalInfo local_info;
4438 public LocalVariableReference (Block block, string name, Location l)
4446 // Setting `is_readonly' to false will allow you to create a writable
4447 // reference to a read-only variable. This is used by foreach and using.
4449 public LocalVariableReference (Block block, string name, Location l,
4450 LocalInfo local_info, bool is_readonly)
4451 : this (block, name, l)
4453 this.local_info = local_info;
4454 this.is_readonly = is_readonly;
4457 public override VariableInfo VariableInfo {
4458 get { return local_info.VariableInfo; }
4461 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
4463 return local_info.HoistedVariant;
4467 // A local variable is always fixed
4469 public override bool IsFixed {
4470 get { return true; }
4473 public override bool IsRef {
4474 get { return false; }
4477 public bool IsReadOnly {
4478 get { return is_readonly; }
4481 public override string Name {
4482 get { return name; }
4485 public bool VerifyAssigned (ResolveContext ec)
4487 VariableInfo variable_info = local_info.VariableInfo;
4488 return variable_info == null || variable_info.IsAssigned (ec, loc);
4491 void ResolveLocalInfo ()
4493 if (local_info == null) {
4494 local_info = Block.GetLocalInfo (Name);
4495 type = local_info.VariableType;
4496 is_readonly = local_info.ReadOnly;
4500 public override void SetHasAddressTaken ()
4502 local_info.AddressTaken = true;
4505 public override Expression CreateExpressionTree (ResolveContext ec)
4507 HoistedVariable hv = GetHoistedVariable (ec);
4509 return hv.CreateExpressionTree ();
4511 Arguments arg = new Arguments (1);
4512 arg.Add (new Argument (this));
4513 return CreateExpressionFactoryCall (ec, "Constant", arg);
4516 Expression DoResolveBase (ResolveContext ec)
4518 Expression e = Block.GetConstantExpression (Name);
4520 return e.Resolve (ec);
4522 VerifyAssigned (ec);
4525 // If we are referencing a variable from the external block
4526 // flag it for capturing
4528 if (ec.MustCaptureVariable (local_info)) {
4529 if (local_info.AddressTaken)
4530 AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, this, loc);
4532 if (ec.IsVariableCapturingRequired) {
4533 AnonymousMethodStorey storey = local_info.Block.Explicit.CreateAnonymousMethodStorey (ec);
4534 storey.CaptureLocalVariable (ec, local_info);
4538 eclass = ExprClass.Variable;
4539 type = local_info.VariableType;
4543 protected override Expression DoResolve (ResolveContext ec)
4545 ResolveLocalInfo ();
4546 local_info.Used = true;
4548 if (type == null && local_info.Type is VarExpr) {
4549 local_info.VariableType = TypeManager.object_type;
4550 Error_VariableIsUsedBeforeItIsDeclared (ec.Report, Name);
4554 return DoResolveBase (ec);
4557 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
4559 ResolveLocalInfo ();
4562 if (right_side == EmptyExpression.OutAccess.Instance)
4563 local_info.Used = true;
4565 // Infer implicitly typed local variable
4567 VarExpr ve = local_info.Type as VarExpr;
4569 if (!ve.InferType (ec, right_side))
4571 type = local_info.VariableType = ve.Type;
4578 if (right_side == EmptyExpression.OutAccess.Instance) {
4579 code = 1657; msg = "Cannot pass `{0}' as a ref or out argument because it is a `{1}'";
4580 } else if (right_side == EmptyExpression.LValueMemberAccess) {
4581 code = 1654; msg = "Cannot assign to members of `{0}' because it is a `{1}'";
4582 } else if (right_side == EmptyExpression.LValueMemberOutAccess) {
4583 code = 1655; msg = "Cannot pass members of `{0}' as ref or out arguments because it is a `{1}'";
4584 } else if (right_side == EmptyExpression.UnaryAddress) {
4585 code = 459; msg = "Cannot take the address of {1} `{0}'";
4587 code = 1656; msg = "Cannot assign to `{0}' because it is a `{1}'";
4589 ec.Report.Error (code, loc, msg, Name, local_info.GetReadOnlyContext ());
4590 } else if (VariableInfo != null) {
4591 VariableInfo.SetAssigned (ec);
4594 return DoResolveBase (ec);
4597 public override int GetHashCode ()
4599 return Name.GetHashCode ();
4602 public override bool Equals (object obj)
4604 LocalVariableReference lvr = obj as LocalVariableReference;
4608 return Name == lvr.Name && Block == lvr.Block;
4611 protected override ILocalVariable Variable {
4612 get { return local_info; }
4615 public override string ToString ()
4617 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
4620 protected override void CloneTo (CloneContext clonectx, Expression t)
4622 LocalVariableReference target = (LocalVariableReference) t;
4624 target.Block = clonectx.LookupBlock (Block);
4625 if (local_info != null)
4626 target.local_info = clonectx.LookupVariable (local_info);
4631 /// This represents a reference to a parameter in the intermediate
4634 public class ParameterReference : VariableReference {
4635 readonly ToplevelParameterInfo pi;
4637 public ParameterReference (ToplevelParameterInfo pi, Location loc)
4643 public override bool IsRef {
4644 get { return (pi.Parameter.ModFlags & Parameter.Modifier.ISBYREF) != 0; }
4647 bool HasOutModifier {
4648 get { return pi.Parameter.ModFlags == Parameter.Modifier.OUT; }
4651 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
4653 return pi.Parameter.HoistedVariant;
4657 // A ref or out parameter is classified as a moveable variable, even
4658 // if the argument given for the parameter is a fixed variable
4660 public override bool IsFixed {
4661 get { return !IsRef; }
4664 public override string Name {
4665 get { return Parameter.Name; }
4668 public Parameter Parameter {
4669 get { return pi.Parameter; }
4672 public override VariableInfo VariableInfo {
4673 get { return pi.VariableInfo; }
4676 protected override ILocalVariable Variable {
4677 get { return Parameter; }
4680 public bool IsAssigned (ResolveContext ec, Location loc)
4682 // HACK: Variables are not captured in probing mode
4683 if (ec.IsInProbingMode)
4686 if (!ec.DoFlowAnalysis || !HasOutModifier || ec.CurrentBranching.IsAssigned (VariableInfo))
4689 ec.Report.Error (269, loc, "Use of unassigned out parameter `{0}'", Name);
4693 public override void SetHasAddressTaken ()
4695 Parameter.HasAddressTaken = true;
4698 void SetAssigned (ResolveContext ec)
4700 if (HasOutModifier && ec.DoFlowAnalysis)
4701 ec.CurrentBranching.SetAssigned (VariableInfo);
4704 bool DoResolveBase (ResolveContext ec)
4706 type = pi.ParameterType;
4707 eclass = ExprClass.Variable;
4709 AnonymousExpression am = ec.CurrentAnonymousMethod;
4713 Block b = ec.CurrentBlock;
4716 IParameterData[] p = b.Toplevel.Parameters.FixedParameters;
4717 for (int i = 0; i < p.Length; ++i) {
4718 if (p [i] != Parameter)
4722 // Don't capture local parameters
4724 if (b == ec.CurrentBlock.Toplevel && !am.IsIterator)
4728 ec.Report.Error (1628, loc,
4729 "Parameter `{0}' cannot be used inside `{1}' when using `ref' or `out' modifier",
4730 Name, am.ContainerType);
4733 if (pi.Parameter.HasAddressTaken)
4734 AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, this, loc);
4736 if (ec.IsVariableCapturingRequired && !b.Toplevel.IsExpressionTree) {
4737 AnonymousMethodStorey storey = pi.Block.CreateAnonymousMethodStorey (ec);
4738 storey.CaptureParameter (ec, this);
4750 public override int GetHashCode ()
4752 return Name.GetHashCode ();
4755 public override bool Equals (object obj)
4757 ParameterReference pr = obj as ParameterReference;
4761 return Name == pr.Name;
4764 public override void AddressOf (EmitContext ec, AddressOp mode)
4767 // ParameterReferences might already be a reference
4774 base.AddressOf (ec, mode);
4777 protected override void CloneTo (CloneContext clonectx, Expression target)
4782 public override Expression CreateExpressionTree (ResolveContext ec)
4784 HoistedVariable hv = GetHoistedVariable (ec);
4786 return hv.CreateExpressionTree ();
4788 return Parameter.ExpressionTreeVariableReference ();
4792 // Notice that for ref/out parameters, the type exposed is not the
4793 // same type exposed externally.
4796 // externally we expose "int&"
4797 // here we expose "int".
4799 // We record this in "is_ref". This means that the type system can treat
4800 // the type as it is expected, but when we generate the code, we generate
4801 // the alternate kind of code.
4803 protected override Expression DoResolve (ResolveContext ec)
4805 if (!DoResolveBase (ec))
4808 // HACK: Variables are not captured in probing mode
4809 if (ec.IsInProbingMode)
4812 if (HasOutModifier && ec.DoFlowAnalysis &&
4813 (!ec.OmitStructFlowAnalysis || !VariableInfo.TypeInfo.IsStruct) && !IsAssigned (ec, loc))
4819 override public Expression DoResolveLValue (ResolveContext ec, Expression right_side)
4821 if (!DoResolveBase (ec))
4828 static public void EmitLdArg (EmitContext ec, int x)
4831 case 0: ec.Emit (OpCodes.Ldarg_0); break;
4832 case 1: ec.Emit (OpCodes.Ldarg_1); break;
4833 case 2: ec.Emit (OpCodes.Ldarg_2); break;
4834 case 3: ec.Emit (OpCodes.Ldarg_3); break;
4836 if (x > byte.MaxValue)
4837 ec.Emit (OpCodes.Ldarg, x);
4839 ec.Emit (OpCodes.Ldarg_S, (byte) x);
4846 /// Invocation of methods or delegates.
4848 public class Invocation : ExpressionStatement
4850 protected Arguments arguments;
4851 protected Expression expr;
4852 protected MethodGroupExpr mg;
4854 public Invocation (Expression expr, Arguments arguments)
4857 this.arguments = arguments;
4859 loc = expr.Location;
4863 public Arguments Arguments {
4869 public Expression Expression {
4876 public override Expression CreateExpressionTree (ResolveContext ec)
4878 Expression instance = mg.IsInstance ?
4879 mg.InstanceExpression.CreateExpressionTree (ec) :
4880 new NullLiteral (loc);
4882 var args = Arguments.CreateForExpressionTree (ec, arguments,
4884 mg.CreateExpressionTree (ec));
4886 return CreateExpressionFactoryCall (ec, "Call", args);
4889 protected override Expression DoResolve (ResolveContext ec)
4891 Expression member_expr;
4892 var atn = expr as ATypeNameExpression;
4894 member_expr = atn.LookupNameExpression (ec, true, true);
4895 if (member_expr != null)
4896 member_expr = member_expr.Resolve (ec);
4898 member_expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4901 if (member_expr == null)
4905 // Next, evaluate all the expressions in the argument list
4907 bool dynamic_arg = false;
4908 if (arguments != null)
4909 arguments.Resolve (ec, out dynamic_arg);
4911 TypeSpec expr_type = member_expr.Type;
4912 mg = member_expr as MethodGroupExpr;
4914 bool dynamic_member = expr_type == InternalType.Dynamic;
4916 if (!dynamic_member) {
4917 Expression invoke = null;
4920 if (expr_type != null && TypeManager.IsDelegateType (expr_type)) {
4921 invoke = new DelegateInvocation (member_expr, arguments, loc);
4922 invoke = invoke.Resolve (ec);
4923 if (invoke == null || !dynamic_arg)
4926 MemberExpr me = member_expr as MemberExpr;
4928 member_expr.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup, loc);
4932 ec.Report.Error (1955, loc, "The member `{0}' cannot be used as method or delegate",
4933 member_expr.GetSignatureForError ());
4938 if (invoke == null) {
4939 mg = DoResolveOverload (ec);
4945 if (dynamic_arg || dynamic_member)
4946 return DoResolveDynamic (ec, member_expr);
4948 var method = mg.BestCandidate;
4949 if (method != null) {
4950 type = method.ReturnType;
4953 if (arguments == null && method.DeclaringType == TypeManager.object_type && method.Name == Destructor.MetadataName) {
4955 ec.Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
4957 ec.Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
4961 IsSpecialMethodInvocation (ec, method, loc);
4963 if (mg.InstanceExpression != null)
4964 mg.InstanceExpression.CheckMarshalByRefAccess (ec);
4966 eclass = ExprClass.Value;
4970 Expression DoResolveDynamic (ResolveContext ec, Expression memberExpr)
4973 DynamicMemberBinder dmb = memberExpr as DynamicMemberBinder;
4975 args = dmb.Arguments;
4976 if (arguments != null)
4977 args.AddRange (arguments);
4978 } else if (mg == null) {
4979 if (arguments == null)
4980 args = new Arguments (1);
4984 args.Insert (0, new Argument (memberExpr));
4988 ec.Report.Error (1971, loc,
4989 "The base call to method `{0}' cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access",
4994 if (arguments == null)
4995 args = new Arguments (1);
4999 MemberAccess ma = expr as MemberAccess;
5001 var left_type = ma.LeftExpression as TypeExpr;
5002 if (left_type != null) {
5003 args.Insert (0, new Argument (new TypeOf (left_type, loc).Resolve (ec), Argument.AType.DynamicTypeName));
5005 args.Insert (0, new Argument (ma.LeftExpression.Resolve (ec)));
5007 } else { // is SimpleName
5009 args.Insert (0, new Argument (new TypeOf (new TypeExpression (ec.CurrentType, loc), loc).Resolve (ec), Argument.AType.DynamicTypeName));
5011 args.Insert (0, new Argument (new This (loc).Resolve (ec)));
5016 return new DynamicInvocation (expr as ATypeNameExpression, args, loc).Resolve (ec);
5019 protected virtual MethodGroupExpr DoResolveOverload (ResolveContext ec)
5021 return mg.OverloadResolve (ec, ref arguments, null, OverloadResolver.Restrictions.None);
5025 // If a member is a method or event, or if it is a constant, field or property of either a delegate type
5026 // or the type dynamic, then the member is invocable
5028 public static bool IsMemberInvocable (MemberSpec member)
5030 switch (member.Kind) {
5031 case MemberKind.Event:
5033 case MemberKind.Field:
5034 case MemberKind.Property:
5035 var m = member as IInterfaceMemberSpec;
5036 return m.MemberType.IsDelegate || m.MemberType == InternalType.Dynamic;
5042 public static bool IsSpecialMethodInvocation (ResolveContext ec, MethodSpec method, Location loc)
5044 if (!method.IsReservedMethod)
5047 if (ec.HasSet (ResolveContext.Options.InvokeSpecialName) || ec.CurrentMemberDefinition.IsCompilerGenerated)
5050 ec.Report.SymbolRelatedToPreviousError (method);
5051 ec.Report.Error (571, loc, "`{0}': cannot explicitly call operator or accessor",
5052 method.GetSignatureForError ());
5057 static Type[] GetVarargsTypes (MethodSpec mb, Arguments arguments)
5059 AParametersCollection pd = mb.Parameters;
5061 Argument a = arguments [pd.Count - 1];
5062 Arglist list = (Arglist) a.Expr;
5064 return list.ArgumentTypes;
5068 /// is_base tells whether we want to force the use of the `call'
5069 /// opcode instead of using callvirt. Call is required to call
5070 /// a specific method, while callvirt will always use the most
5071 /// recent method in the vtable.
5073 /// is_static tells whether this is an invocation on a static method
5075 /// instance_expr is an expression that represents the instance
5076 /// it must be non-null if is_static is false.
5078 /// method is the method to invoke.
5080 /// Arguments is the list of arguments to pass to the method or constructor.
5082 public static void EmitCall (EmitContext ec, Expression instance_expr,
5083 MethodSpec method, Arguments Arguments, Location loc)
5085 EmitCall (ec, instance_expr, method, Arguments, loc, false, false);
5088 // `dup_args' leaves an extra copy of the arguments on the stack
5089 // `omit_args' does not leave any arguments at all.
5090 // So, basically, you could make one call with `dup_args' set to true,
5091 // and then another with `omit_args' set to true, and the two calls
5092 // would have the same set of arguments. However, each argument would
5093 // only have been evaluated once.
5094 public static void EmitCall (EmitContext ec, Expression instance_expr,
5095 MethodSpec method, Arguments Arguments, Location loc,
5096 bool dup_args, bool omit_args)
5098 LocalTemporary this_arg = null;
5100 TypeSpec decl_type = method.DeclaringType;
5102 // Speed up the check by not doing it on not allowed targets
5103 if (method.ReturnType == TypeManager.void_type && method.IsConditionallyExcluded (loc))
5107 TypeSpec iexpr_type;
5109 if (method.IsStatic) {
5111 call_op = OpCodes.Call;
5113 iexpr_type = instance_expr.Type;
5115 if (decl_type.IsStruct || decl_type.IsEnum || (instance_expr is This && !method.IsVirtual) || (instance_expr is BaseThis)) {
5116 call_op = OpCodes.Call;
5118 call_op = OpCodes.Callvirt;
5122 // If this is ourselves, push "this"
5125 TypeSpec t = iexpr_type;
5128 // Push the instance expression
5130 if ((iexpr_type.IsStruct && (call_op == OpCodes.Callvirt || (call_op == OpCodes.Call && decl_type == iexpr_type))) ||
5131 iexpr_type.IsGenericParameter || TypeManager.IsNullableType (decl_type)) {
5133 // If the expression implements IMemoryLocation, then
5134 // we can optimize and use AddressOf on the
5137 // If not we have to use some temporary storage for
5139 var iml = instance_expr as IMemoryLocation;
5141 iml.AddressOf (ec, AddressOp.LoadStore);
5143 LocalTemporary temp = new LocalTemporary (iexpr_type);
5144 instance_expr.Emit (ec);
5146 temp.AddressOf (ec, AddressOp.Load);
5149 // avoid the overhead of doing this all the time.
5151 t = ReferenceContainer.MakeType (iexpr_type);
5152 } else if (iexpr_type.IsEnum || iexpr_type.IsStruct) {
5153 instance_expr.Emit (ec);
5154 ec.Emit (OpCodes.Box, iexpr_type);
5155 t = iexpr_type = TypeManager.object_type;
5157 instance_expr.Emit (ec);
5161 ec.Emit (OpCodes.Dup);
5162 if (Arguments != null && Arguments.Count != 0) {
5163 this_arg = new LocalTemporary (t);
5164 this_arg.Store (ec);
5170 if (!omit_args && Arguments != null)
5171 Arguments.Emit (ec, dup_args, this_arg);
5173 if (call_op == OpCodes.Callvirt && (iexpr_type.IsGenericParameter || iexpr_type.IsStruct)) {
5174 ec.Emit (OpCodes.Constrained, iexpr_type);
5177 if (method.Parameters.HasArglist) {
5178 Type[] varargs_types = GetVarargsTypes (method, Arguments);
5179 ec.Emit (call_op, method, varargs_types);
5186 // and DoFoo is not virtual, you can omit the callvirt,
5187 // because you don't need the null checking behavior.
5189 ec.Emit (call_op, method);
5192 public override void Emit (EmitContext ec)
5194 mg.EmitCall (ec, arguments);
5197 public override void EmitStatement (EmitContext ec)
5202 // Pop the return value if there is one
5204 if (type != TypeManager.void_type)
5205 ec.Emit (OpCodes.Pop);
5208 protected override void CloneTo (CloneContext clonectx, Expression t)
5210 Invocation target = (Invocation) t;
5212 if (arguments != null)
5213 target.arguments = arguments.Clone (clonectx);
5215 target.expr = expr.Clone (clonectx);
5218 public override SLE.Expression MakeExpression (BuilderContext ctx)
5220 return MakeExpression (ctx, mg.InstanceExpression, mg.BestCandidate, arguments);
5223 public static SLE.Expression MakeExpression (BuilderContext ctx, Expression instance, MethodSpec mi, Arguments args)
5225 var instance_expr = instance == null ? null : instance.MakeExpression (ctx);
5226 return SLE.Expression.Call (instance_expr, (MethodInfo) mi.GetMetaInfo (), Arguments.MakeExpression (args, ctx));
5231 /// Implements the new expression
5233 public class New : ExpressionStatement, IMemoryLocation {
5234 protected Arguments Arguments;
5237 // During bootstrap, it contains the RequestedType,
5238 // but if `type' is not null, it *might* contain a NewDelegate
5239 // (because of field multi-initialization)
5241 protected Expression RequestedType;
5243 protected MethodSpec method;
5245 public New (Expression requested_type, Arguments arguments, Location l)
5247 RequestedType = requested_type;
5248 Arguments = arguments;
5253 /// Converts complex core type syntax like 'new int ()' to simple constant
5255 public static Constant Constantify (TypeSpec t)
5257 if (t == TypeManager.int32_type)
5258 return new IntConstant (0, Location.Null);
5259 if (t == TypeManager.uint32_type)
5260 return new UIntConstant (0, Location.Null);
5261 if (t == TypeManager.int64_type)
5262 return new LongConstant (0, Location.Null);
5263 if (t == TypeManager.uint64_type)
5264 return new ULongConstant (0, Location.Null);
5265 if (t == TypeManager.float_type)
5266 return new FloatConstant (0, Location.Null);
5267 if (t == TypeManager.double_type)
5268 return new DoubleConstant (0, Location.Null);
5269 if (t == TypeManager.short_type)
5270 return new ShortConstant (0, Location.Null);
5271 if (t == TypeManager.ushort_type)
5272 return new UShortConstant (0, Location.Null);
5273 if (t == TypeManager.sbyte_type)
5274 return new SByteConstant (0, Location.Null);
5275 if (t == TypeManager.byte_type)
5276 return new ByteConstant (0, Location.Null);
5277 if (t == TypeManager.char_type)
5278 return new CharConstant ('\0', Location.Null);
5279 if (t == TypeManager.bool_type)
5280 return new BoolConstant (false, Location.Null);
5281 if (t == TypeManager.decimal_type)
5282 return new DecimalConstant (0, Location.Null);
5283 if (TypeManager.IsEnumType (t))
5284 return new EnumConstant (Constantify (EnumSpec.GetUnderlyingType (t)), t);
5285 if (TypeManager.IsNullableType (t))
5286 return Nullable.LiftedNull.Create (t, Location.Null);
5292 // Checks whether the type is an interface that has the
5293 // [ComImport, CoClass] attributes and must be treated
5296 public Expression CheckComImport (ResolveContext ec)
5298 if (!type.IsInterface)
5302 // Turn the call into:
5303 // (the-interface-stated) (new class-referenced-in-coclassattribute ())
5305 var real_class = type.MemberDefinition.GetAttributeCoClass ();
5306 if (real_class == null)
5309 New proxy = new New (new TypeExpression (real_class, loc), Arguments, loc);
5310 Cast cast = new Cast (new TypeExpression (type, loc), proxy, loc);
5311 return cast.Resolve (ec);
5314 public override Expression CreateExpressionTree (ResolveContext ec)
5317 if (method == null) {
5318 args = new Arguments (1);
5319 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
5321 args = Arguments.CreateForExpressionTree (ec,
5322 Arguments, new TypeOfMethod (method, loc));
5325 return CreateExpressionFactoryCall (ec, "New", args);
5328 protected override Expression DoResolve (ResolveContext ec)
5330 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec, false);
5335 eclass = ExprClass.Value;
5337 if (type.IsPointer) {
5338 ec.Report.Error (1919, loc, "Unsafe type `{0}' cannot be used in an object creation expression",
5339 TypeManager.CSharpName (type));
5343 if (Arguments == null) {
5344 Constant c = Constantify (type);
5346 return ReducedExpression.Create (c.Resolve (ec), this);
5349 if (TypeManager.IsDelegateType (type)) {
5350 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5353 var tparam = type as TypeParameterSpec;
5354 if (tparam != null) {
5355 if (!tparam.HasSpecialConstructor && !tparam.HasSpecialStruct) {
5356 ec.Report.Error (304, loc,
5357 "Cannot create an instance of the variable type `{0}' because it does not have the new() constraint",
5358 TypeManager.CSharpName (type));
5361 if ((Arguments != null) && (Arguments.Count != 0)) {
5362 ec.Report.Error (417, loc,
5363 "`{0}': cannot provide arguments when creating an instance of a variable type",
5364 TypeManager.CSharpName (type));
5367 if (TypeManager.activator_create_instance == null) {
5368 TypeSpec activator_type = TypeManager.CoreLookupType (ec.Compiler, "System", "Activator", MemberKind.Class, true);
5369 if (activator_type != null) {
5370 TypeManager.activator_create_instance = TypeManager.GetPredefinedMethod (
5371 activator_type, MemberFilter.Method ("CreateInstance", 1, ParametersCompiled.EmptyReadOnlyParameters, null), loc);
5378 if (type.IsStatic) {
5379 ec.Report.SymbolRelatedToPreviousError (type);
5380 ec.Report.Error (712, loc, "Cannot create an instance of the static class `{0}'", TypeManager.CSharpName (type));
5384 if (type.IsInterface || type.IsAbstract){
5385 if (!TypeManager.IsGenericType (type)) {
5386 RequestedType = CheckComImport (ec);
5387 if (RequestedType != null)
5388 return RequestedType;
5391 ec.Report.SymbolRelatedToPreviousError (type);
5392 ec.Report.Error (144, loc, "Cannot create an instance of the abstract class or interface `{0}'", TypeManager.CSharpName (type));
5397 // Any struct always defines parameterless constructor
5399 if (type.IsStruct && Arguments == null)
5403 if (Arguments != null) {
5404 Arguments.Resolve (ec, out dynamic);
5409 method = ConstructorLookup (ec, type, ref Arguments, loc);
5412 Arguments.Insert (0, new Argument (new TypeOf (texpr, loc).Resolve (ec), Argument.AType.DynamicTypeName));
5413 return new DynamicConstructorBinder (type, Arguments, loc).Resolve (ec);
5419 bool DoEmitTypeParameter (EmitContext ec)
5421 var ctor_factory = TypeManager.activator_create_instance.MakeGenericMethod (type);
5422 var tparam = (TypeParameterSpec) type;
5424 if (tparam.IsReferenceType) {
5425 ec.Emit (OpCodes.Call, ctor_factory);
5429 // Allow DoEmit() to be called multiple times.
5430 // We need to create a new LocalTemporary each time since
5431 // you can't share LocalBuilders among ILGeneators.
5432 LocalTemporary temp = new LocalTemporary (type);
5434 Label label_activator = ec.DefineLabel ();
5435 Label label_end = ec.DefineLabel ();
5437 temp.AddressOf (ec, AddressOp.Store);
5438 ec.Emit (OpCodes.Initobj, type);
5441 ec.Emit (OpCodes.Box, type);
5442 ec.Emit (OpCodes.Brfalse, label_activator);
5444 temp.AddressOf (ec, AddressOp.Store);
5445 ec.Emit (OpCodes.Initobj, type);
5447 ec.Emit (OpCodes.Br_S, label_end);
5449 ec.MarkLabel (label_activator);
5451 ec.Emit (OpCodes.Call, ctor_factory);
5452 ec.MarkLabel (label_end);
5457 // This Emit can be invoked in two contexts:
5458 // * As a mechanism that will leave a value on the stack (new object)
5459 // * As one that wont (init struct)
5461 // If we are dealing with a ValueType, we have a few
5462 // situations to deal with:
5464 // * The target is a ValueType, and we have been provided
5465 // the instance (this is easy, we are being assigned).
5467 // * The target of New is being passed as an argument,
5468 // to a boxing operation or a function that takes a
5471 // In this case, we need to create a temporary variable
5472 // that is the argument of New.
5474 // Returns whether a value is left on the stack
5476 // *** Implementation note ***
5478 // To benefit from this optimization, each assignable expression
5479 // has to manually cast to New and call this Emit.
5481 // TODO: It's worth to implement it for arrays and fields
5483 public virtual bool Emit (EmitContext ec, IMemoryLocation target)
5485 bool is_value_type = TypeManager.IsValueType (type);
5486 VariableReference vr = target as VariableReference;
5488 if (target != null && is_value_type && (vr != null || method == null)) {
5489 target.AddressOf (ec, AddressOp.Store);
5490 } else if (vr != null && vr.IsRef) {
5494 if (Arguments != null)
5495 Arguments.Emit (ec);
5497 if (is_value_type) {
5498 if (method == null) {
5499 ec.Emit (OpCodes.Initobj, type);
5504 ec.Emit (OpCodes.Call, method);
5509 if (type is TypeParameterSpec)
5510 return DoEmitTypeParameter (ec);
5512 ec.Emit (OpCodes.Newobj, method);
5516 public override void Emit (EmitContext ec)
5518 LocalTemporary v = null;
5519 if (method == null && TypeManager.IsValueType (type)) {
5520 // TODO: Use temporary variable from pool
5521 v = new LocalTemporary (type);
5528 public override void EmitStatement (EmitContext ec)
5530 LocalTemporary v = null;
5531 if (method == null && TypeManager.IsValueType (type)) {
5532 // TODO: Use temporary variable from pool
5533 v = new LocalTemporary (type);
5537 ec.Emit (OpCodes.Pop);
5540 public virtual bool HasInitializer {
5546 public void AddressOf (EmitContext ec, AddressOp mode)
5548 EmitAddressOf (ec, mode);
5551 protected virtual IMemoryLocation EmitAddressOf (EmitContext ec, AddressOp mode)
5553 LocalTemporary value_target = new LocalTemporary (type);
5555 if (type is TypeParameterSpec) {
5556 DoEmitTypeParameter (ec);
5557 value_target.Store (ec);
5558 value_target.AddressOf (ec, mode);
5559 return value_target;
5562 if (!TypeManager.IsStruct (type)){
5564 // We throw an exception. So far, I believe we only need to support
5566 // foreach (int j in new StructType ())
5569 throw new Exception ("AddressOf should not be used for classes");
5572 value_target.AddressOf (ec, AddressOp.Store);
5574 if (method == null) {
5575 ec.Emit (OpCodes.Initobj, type);
5577 if (Arguments != null)
5578 Arguments.Emit (ec);
5580 ec.Emit (OpCodes.Call, method);
5583 value_target.AddressOf (ec, mode);
5584 return value_target;
5587 protected override void CloneTo (CloneContext clonectx, Expression t)
5589 New target = (New) t;
5591 target.RequestedType = RequestedType.Clone (clonectx);
5592 if (Arguments != null){
5593 target.Arguments = Arguments.Clone (clonectx);
5597 public override SLE.Expression MakeExpression (BuilderContext ctx)
5599 return SLE.Expression.New ((ConstructorInfo) method.GetMetaInfo (), Arguments.MakeExpression (Arguments, ctx));
5603 public class ArrayInitializer : Expression
5605 List<Expression> elements;
5607 public ArrayInitializer (List<Expression> init, Location loc)
5613 public ArrayInitializer (int count, Location loc)
5615 elements = new List<Expression> (count);
5619 public ArrayInitializer (Location loc)
5624 public void Add (Expression expr)
5626 elements.Add (expr);
5629 public override Expression CreateExpressionTree (ResolveContext ec)
5631 throw new NotSupportedException ("ET");
5634 protected override void CloneTo (CloneContext clonectx, Expression t)
5636 var target = (ArrayInitializer) t;
5638 target.elements = new List<Expression> (elements.Count);
5639 foreach (var element in elements)
5640 target.elements.Add (element.Clone (clonectx));
5644 get { return elements.Count; }
5647 protected override Expression DoResolve (ResolveContext rc)
5649 var current_field = rc.CurrentMemberDefinition as FieldBase;
5650 return new ArrayCreation (new TypeExpression (current_field.MemberType, current_field.Location), this).Resolve (rc);
5653 public override void Emit (EmitContext ec)
5655 throw new InternalErrorException ("Missing Resolve call");
5658 public Expression this [int index] {
5659 get { return elements [index]; }
5664 /// 14.5.10.2: Represents an array creation expression.
5668 /// There are two possible scenarios here: one is an array creation
5669 /// expression that specifies the dimensions and optionally the
5670 /// initialization data and the other which does not need dimensions
5671 /// specified but where initialization data is mandatory.
5673 public class ArrayCreation : Expression
5675 FullNamedExpression requested_base_type;
5676 ArrayInitializer initializers;
5679 // The list of Argument types.
5680 // This is used to construct the `newarray' or constructor signature
5682 protected List<Expression> arguments;
5684 protected TypeSpec array_element_type;
5685 int num_arguments = 0;
5686 protected int dimensions;
5687 protected readonly ComposedTypeSpecifier rank;
5688 Expression first_emit;
5689 LocalTemporary first_emit_temp;
5691 protected List<Expression> array_data;
5693 Dictionary<int, int> bounds;
5695 // The number of constants in array initializers
5696 int const_initializers_count;
5697 bool only_constant_initializers;
5699 public ArrayCreation (FullNamedExpression requested_base_type, List<Expression> exprs, ComposedTypeSpecifier rank, ArrayInitializer initializers, Location l)
5700 : this (requested_base_type, rank, initializers, l)
5702 arguments = new List<Expression> (exprs);
5703 num_arguments = arguments.Count;
5707 // For expressions like int[] foo = new int[] { 1, 2, 3 };
5709 public ArrayCreation (FullNamedExpression requested_base_type, ComposedTypeSpecifier rank, ArrayInitializer initializers, Location loc)
5711 this.requested_base_type = requested_base_type;
5713 this.initializers = initializers;
5717 num_arguments = rank.Dimension;
5721 // For compiler generated single dimensional arrays only
5723 public ArrayCreation (FullNamedExpression requested_base_type, ArrayInitializer initializers, Location loc)
5724 : this (requested_base_type, ComposedTypeSpecifier.SingleDimension, initializers, loc)
5729 // For expressions like int[] foo = { 1, 2, 3 };
5731 public ArrayCreation (FullNamedExpression requested_base_type, ArrayInitializer initializers)
5732 : this (requested_base_type, null, initializers, initializers.Location)
5736 protected override void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
5738 ec.Report.Error (248, loc, "Cannot create an array with a negative size");
5741 bool CheckIndices (ResolveContext ec, ArrayInitializer probe, int idx, bool specified_dims, int child_bounds)
5743 if (initializers != null && bounds == null) {
5745 // We use this to store all the date values in the order in which we
5746 // will need to store them in the byte blob later
5748 array_data = new List<Expression> ();
5749 bounds = new Dictionary<int, int> ();
5752 if (specified_dims) {
5753 Expression a = arguments [idx];
5758 a = ConvertExpressionToArrayIndex (ec, a);
5764 if (initializers != null) {
5765 Constant c = a as Constant;
5766 if (c == null && a is ArrayIndexCast)
5767 c = ((ArrayIndexCast) a).Child as Constant;
5770 ec.Report.Error (150, a.Location, "A constant value is expected");
5776 value = System.Convert.ToInt32 (c.GetValue ());
5778 ec.Report.Error (150, a.Location, "A constant value is expected");
5782 // TODO: probe.Count does not fit ulong in
5783 if (value != probe.Count) {
5784 ec.Report.Error (847, loc, "An array initializer of length `{0}' was expected", value.ToString ());
5788 bounds[idx] = value;
5792 if (initializers == null)
5795 only_constant_initializers = true;
5796 for (int i = 0; i < probe.Count; ++i) {
5798 if (o is ArrayInitializer) {
5799 var sub_probe = o as ArrayInitializer;
5800 if (idx + 1 >= dimensions){
5801 ec.Report.Error (623, loc, "Array initializers can only be used in a variable or field initializer. Try using a new expression instead");
5805 bool ret = CheckIndices (ec, sub_probe, idx + 1, specified_dims, child_bounds - 1);
5808 } else if (child_bounds > 1) {
5809 ec.Report.Error (846, o.Location, "A nested array initializer was expected");
5811 Expression element = ResolveArrayElement (ec, o);
5812 if (element == null)
5815 // Initializers with the default values can be ignored
5816 Constant c = element as Constant;
5818 if (!c.IsDefaultInitializer (array_element_type)) {
5819 ++const_initializers_count;
5822 only_constant_initializers = false;
5825 array_data.Add (element);
5832 public override Expression CreateExpressionTree (ResolveContext ec)
5836 if (array_data == null) {
5837 args = new Arguments (arguments.Count + 1);
5838 args.Add (new Argument (new TypeOf (new TypeExpression (array_element_type, loc), loc)));
5839 foreach (Expression a in arguments)
5840 args.Add (new Argument (a.CreateExpressionTree (ec)));
5842 return CreateExpressionFactoryCall (ec, "NewArrayBounds", args);
5845 if (dimensions > 1) {
5846 ec.Report.Error (838, loc, "An expression tree cannot contain a multidimensional array initializer");
5850 args = new Arguments (array_data == null ? 1 : array_data.Count + 1);
5851 args.Add (new Argument (new TypeOf (new TypeExpression (array_element_type, loc), loc)));
5852 if (array_data != null) {
5853 for (int i = 0; i < array_data.Count; ++i) {
5854 Expression e = array_data [i];
5855 args.Add (new Argument (e.CreateExpressionTree (ec)));
5859 return CreateExpressionFactoryCall (ec, "NewArrayInit", args);
5862 public void UpdateIndices ()
5865 for (var probe = initializers; probe != null;) {
5866 if (probe.Count > 0 && probe [0] is ArrayInitializer) {
5867 Expression e = new IntConstant (probe.Count, Location.Null);
5870 bounds [i++] = probe.Count;
5872 probe = (ArrayInitializer) probe[0];
5875 Expression e = new IntConstant (probe.Count, Location.Null);
5878 bounds [i++] = probe.Count;
5884 protected virtual Expression ResolveArrayElement (ResolveContext ec, Expression element)
5886 element = element.Resolve (ec);
5887 if (element == null)
5890 if (element is CompoundAssign.TargetExpression) {
5891 if (first_emit != null)
5892 throw new InternalErrorException ("Can only handle one mutator at a time");
5893 first_emit = element;
5894 element = first_emit_temp = new LocalTemporary (element.Type);
5897 return Convert.ImplicitConversionRequired (
5898 ec, element, array_element_type, loc);
5901 protected bool ResolveInitializers (ResolveContext ec)
5903 if (arguments != null) {
5905 for (int i = 0; i < arguments.Count; ++i) {
5906 res &= CheckIndices (ec, initializers, i, true, dimensions);
5907 if (initializers != null)
5914 arguments = new List<Expression> ();
5916 if (!CheckIndices (ec, initializers, 0, false, dimensions))
5925 // Resolved the type of the array
5927 bool ResolveArrayType (ResolveContext ec)
5929 if (requested_base_type is VarExpr) {
5930 ec.Report.Error (820, loc, "An implicitly typed local variable declarator cannot use an array initializer");
5937 FullNamedExpression array_type_expr;
5938 if (num_arguments > 0) {
5939 array_type_expr = new ComposedCast (requested_base_type, rank);
5941 array_type_expr = requested_base_type;
5944 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec, false);
5945 if (array_type_expr == null)
5948 type = array_type_expr.Type;
5949 var ac = type as ArrayContainer;
5951 ec.Report.Error (622, loc, "Can only use array initializer expressions to assign to array types. Try using a new expression instead");
5955 array_element_type = ac.Element;
5956 dimensions = ac.Rank;
5961 protected override Expression DoResolve (ResolveContext ec)
5966 if (!ResolveArrayType (ec))
5970 // validate the initializers and fill in any missing bits
5972 if (!ResolveInitializers (ec))
5975 eclass = ExprClass.Value;
5979 byte [] MakeByteBlob ()
5984 int count = array_data.Count;
5986 TypeSpec element_type = array_element_type;
5987 if (TypeManager.IsEnumType (element_type))
5988 element_type = EnumSpec.GetUnderlyingType (element_type);
5990 factor = GetTypeSize (element_type);
5992 throw new Exception ("unrecognized type in MakeByteBlob: " + element_type);
5994 data = new byte [(count * factor + 3) & ~3];
5997 for (int i = 0; i < count; ++i) {
5998 object v = array_data [i];
6000 if (v is EnumConstant)
6001 v = ((EnumConstant) v).Child;
6003 if (v is Constant && !(v is StringConstant))
6004 v = ((Constant) v).GetValue ();
6010 if (element_type == TypeManager.int64_type){
6011 if (!(v is Expression)){
6012 long val = (long) v;
6014 for (int j = 0; j < factor; ++j) {
6015 data [idx + j] = (byte) (val & 0xFF);
6019 } else if (element_type == TypeManager.uint64_type){
6020 if (!(v is Expression)){
6021 ulong val = (ulong) v;
6023 for (int j = 0; j < factor; ++j) {
6024 data [idx + j] = (byte) (val & 0xFF);
6028 } else if (element_type == TypeManager.float_type) {
6029 if (!(v is Expression)){
6030 element = BitConverter.GetBytes ((float) v);
6032 for (int j = 0; j < factor; ++j)
6033 data [idx + j] = element [j];
6034 if (!BitConverter.IsLittleEndian)
6035 System.Array.Reverse (data, idx, 4);
6037 } else if (element_type == TypeManager.double_type) {
6038 if (!(v is Expression)){
6039 element = BitConverter.GetBytes ((double) v);
6041 for (int j = 0; j < factor; ++j)
6042 data [idx + j] = element [j];
6044 // FIXME: Handle the ARM float format.
6045 if (!BitConverter.IsLittleEndian)
6046 System.Array.Reverse (data, idx, 8);
6048 } else if (element_type == TypeManager.char_type){
6049 if (!(v is Expression)){
6050 int val = (int) ((char) v);
6052 data [idx] = (byte) (val & 0xff);
6053 data [idx+1] = (byte) (val >> 8);
6055 } else if (element_type == TypeManager.short_type){
6056 if (!(v is Expression)){
6057 int val = (int) ((short) v);
6059 data [idx] = (byte) (val & 0xff);
6060 data [idx+1] = (byte) (val >> 8);
6062 } else if (element_type == TypeManager.ushort_type){
6063 if (!(v is Expression)){
6064 int val = (int) ((ushort) v);
6066 data [idx] = (byte) (val & 0xff);
6067 data [idx+1] = (byte) (val >> 8);
6069 } else if (element_type == TypeManager.int32_type) {
6070 if (!(v is Expression)){
6073 data [idx] = (byte) (val & 0xff);
6074 data [idx+1] = (byte) ((val >> 8) & 0xff);
6075 data [idx+2] = (byte) ((val >> 16) & 0xff);
6076 data [idx+3] = (byte) (val >> 24);
6078 } else if (element_type == TypeManager.uint32_type) {
6079 if (!(v is Expression)){
6080 uint val = (uint) v;
6082 data [idx] = (byte) (val & 0xff);
6083 data [idx+1] = (byte) ((val >> 8) & 0xff);
6084 data [idx+2] = (byte) ((val >> 16) & 0xff);
6085 data [idx+3] = (byte) (val >> 24);
6087 } else if (element_type == TypeManager.sbyte_type) {
6088 if (!(v is Expression)){
6089 sbyte val = (sbyte) v;
6090 data [idx] = (byte) val;
6092 } else if (element_type == TypeManager.byte_type) {
6093 if (!(v is Expression)){
6094 byte val = (byte) v;
6095 data [idx] = (byte) val;
6097 } else if (element_type == TypeManager.bool_type) {
6098 if (!(v is Expression)){
6099 bool val = (bool) v;
6100 data [idx] = (byte) (val ? 1 : 0);
6102 } else if (element_type == TypeManager.decimal_type){
6103 if (!(v is Expression)){
6104 int [] bits = Decimal.GetBits ((decimal) v);
6107 // FIXME: For some reason, this doesn't work on the MS runtime.
6108 int [] nbits = new int [4];
6109 nbits [0] = bits [3];
6110 nbits [1] = bits [2];
6111 nbits [2] = bits [0];
6112 nbits [3] = bits [1];
6114 for (int j = 0; j < 4; j++){
6115 data [p++] = (byte) (nbits [j] & 0xff);
6116 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6117 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6118 data [p++] = (byte) (nbits [j] >> 24);
6122 throw new Exception ("Unrecognized type in MakeByteBlob: " + element_type);
6132 public override SLE.Expression MakeExpression (BuilderContext ctx)
6134 var initializers = new SLE.Expression [array_data.Count];
6135 for (var i = 0; i < initializers.Length; i++) {
6136 if (array_data [i] == null)
6137 initializers [i] = SLE.Expression.Default (array_element_type.GetMetaInfo ());
6139 initializers [i] = array_data [i].MakeExpression (ctx);
6142 return SLE.Expression.NewArrayInit (array_element_type.GetMetaInfo (), initializers);
6146 // Emits the initializers for the array
6148 void EmitStaticInitializers (EmitContext ec)
6150 // FIXME: This should go to Resolve !
6151 if (TypeManager.void_initializearray_array_fieldhandle == null) {
6152 TypeManager.void_initializearray_array_fieldhandle = TypeManager.GetPredefinedMethod (
6153 TypeManager.runtime_helpers_type, "InitializeArray", loc,
6154 TypeManager.array_type, TypeManager.runtime_field_handle_type);
6155 if (TypeManager.void_initializearray_array_fieldhandle == null)
6160 // First, the static data
6164 byte [] data = MakeByteBlob ();
6166 fb = RootContext.MakeStaticData (data);
6168 ec.Emit (OpCodes.Dup);
6169 ec.Emit (OpCodes.Ldtoken, fb);
6170 ec.Emit (OpCodes.Call, TypeManager.void_initializearray_array_fieldhandle);
6174 // Emits pieces of the array that can not be computed at compile
6175 // time (variables and string locations).
6177 // This always expect the top value on the stack to be the array
6179 void EmitDynamicInitializers (EmitContext ec, bool emitConstants)
6181 int dims = bounds.Count;
6182 var current_pos = new int [dims];
6184 for (int i = 0; i < array_data.Count; i++){
6186 Expression e = array_data [i];
6187 var c = e as Constant;
6189 // Constant can be initialized via StaticInitializer
6190 if (c == null || (c != null && emitConstants && !c.IsDefaultInitializer (array_element_type))) {
6191 TypeSpec etype = e.Type;
6193 ec.Emit (OpCodes.Dup);
6195 for (int idx = 0; idx < dims; idx++)
6196 ec.EmitInt (current_pos [idx]);
6199 // If we are dealing with a struct, get the
6200 // address of it, so we can store it.
6202 if ((dims == 1) && TypeManager.IsStruct (etype) &&
6203 (!TypeManager.IsBuiltinOrEnum (etype) ||
6204 etype == TypeManager.decimal_type)) {
6206 ec.Emit (OpCodes.Ldelema, etype);
6211 ec.EmitArrayStore ((ArrayContainer) type);
6217 for (int j = dims - 1; j >= 0; j--){
6219 if (current_pos [j] < bounds [j])
6221 current_pos [j] = 0;
6226 public override void Emit (EmitContext ec)
6228 if (first_emit != null) {
6229 first_emit.Emit (ec);
6230 first_emit_temp.Store (ec);
6233 foreach (Expression e in arguments)
6236 ec.EmitArrayNew ((ArrayContainer) type);
6238 if (initializers == null)
6241 // Emit static initializer for arrays which have contain more than 2 items and
6242 // the static initializer will initialize at least 25% of array values.
6243 // NOTE: const_initializers_count does not contain default constant values.
6244 if (const_initializers_count > 2 && const_initializers_count * 4 > (array_data.Count) &&
6245 (TypeManager.IsPrimitiveType (array_element_type) || TypeManager.IsEnumType (array_element_type))) {
6246 EmitStaticInitializers (ec);
6248 if (!only_constant_initializers)
6249 EmitDynamicInitializers (ec, false);
6251 EmitDynamicInitializers (ec, true);
6254 if (first_emit_temp != null)
6255 first_emit_temp.Release (ec);
6258 public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
6260 // no multi dimensional or jagged arrays
6261 if (arguments.Count != 1 || array_element_type.IsArray) {
6262 base.EncodeAttributeValue (rc, enc, targetType);
6266 // No array covariance, except for array -> object
6267 if (type != targetType) {
6268 if (targetType != TypeManager.object_type) {
6269 base.EncodeAttributeValue (rc, enc, targetType);
6276 // Single dimensional array of 0 size
6277 if (array_data == null) {
6278 IntConstant ic = arguments[0] as IntConstant;
6279 if (ic == null || !ic.IsDefaultValue) {
6280 base.EncodeAttributeValue (rc, enc, targetType);
6282 enc.Stream.Write (0);
6288 enc.Stream.Write ((int) array_data.Count);
6289 foreach (var element in array_data) {
6290 element.EncodeAttributeValue (rc, enc, array_element_type);
6294 protected override void CloneTo (CloneContext clonectx, Expression t)
6296 ArrayCreation target = (ArrayCreation) t;
6298 if (requested_base_type != null)
6299 target.requested_base_type = (FullNamedExpression)requested_base_type.Clone (clonectx);
6301 if (arguments != null){
6302 target.arguments = new List<Expression> (arguments.Count);
6303 foreach (Expression e in arguments)
6304 target.arguments.Add (e.Clone (clonectx));
6307 if (initializers != null)
6308 target.initializers = (ArrayInitializer) initializers.Clone (clonectx);
6313 // Represents an implicitly typed array epxression
6315 class ImplicitlyTypedArrayCreation : ArrayCreation
6317 public ImplicitlyTypedArrayCreation (ComposedTypeSpecifier rank, ArrayInitializer initializers, Location loc)
6318 : base (null, rank, initializers, loc)
6322 public ImplicitlyTypedArrayCreation (ArrayInitializer initializers, Location loc)
6323 : base (null, initializers, loc)
6327 protected override Expression DoResolve (ResolveContext ec)
6332 dimensions = rank.Dimension;
6334 if (!ResolveInitializers (ec))
6337 if (array_element_type == null || array_element_type == TypeManager.null_type ||
6338 array_element_type == TypeManager.void_type || array_element_type == InternalType.AnonymousMethod ||
6339 array_element_type == InternalType.MethodGroup ||
6340 arguments.Count != rank.Dimension) {
6341 Error_NoBestType (ec);
6346 // At this point we found common base type for all initializer elements
6347 // but we have to be sure that all static initializer elements are of
6350 UnifyInitializerElement (ec);
6352 type = ArrayContainer.MakeType (array_element_type, dimensions);
6353 eclass = ExprClass.Value;
6357 void Error_NoBestType (ResolveContext ec)
6359 ec.Report.Error (826, loc,
6360 "The type of an implicitly typed array cannot be inferred from the initializer. Try specifying array type explicitly");
6364 // Converts static initializer only
6366 void UnifyInitializerElement (ResolveContext ec)
6368 for (int i = 0; i < array_data.Count; ++i) {
6369 Expression e = (Expression)array_data[i];
6371 array_data [i] = Convert.ImplicitConversion (ec, e, array_element_type, Location.Null);
6375 protected override Expression ResolveArrayElement (ResolveContext ec, Expression element)
6377 element = element.Resolve (ec);
6378 if (element == null)
6381 if (array_element_type == null) {
6382 if (element.Type != TypeManager.null_type)
6383 array_element_type = element.Type;
6388 if (Convert.ImplicitConversionExists (ec, element, array_element_type)) {
6392 if (Convert.ImplicitConversionExists (ec, new TypeExpression (array_element_type, loc), element.Type)) {
6393 array_element_type = element.Type;
6397 Error_NoBestType (ec);
6402 public sealed class CompilerGeneratedThis : This
6404 public static This Instance = new CompilerGeneratedThis ();
6406 private CompilerGeneratedThis ()
6407 : base (Location.Null)
6411 public CompilerGeneratedThis (TypeSpec type, Location loc)
6417 protected override Expression DoResolve (ResolveContext ec)
6419 eclass = ExprClass.Variable;
6421 type = ec.CurrentType;
6426 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
6433 /// Represents the `this' construct
6436 public class This : VariableReference
6438 sealed class ThisVariable : ILocalVariable
6440 public static readonly ILocalVariable Instance = new ThisVariable ();
6442 public void Emit (EmitContext ec)
6444 ec.Emit (OpCodes.Ldarg_0);
6447 public void EmitAssign (EmitContext ec)
6449 throw new InvalidOperationException ();
6452 public void EmitAddressOf (EmitContext ec)
6454 ec.Emit (OpCodes.Ldarg_0);
6458 VariableInfo variable_info;
6460 public This (Location loc)
6467 public override string Name {
6468 get { return "this"; }
6471 public override bool IsRef {
6472 get { return type.IsStruct; }
6475 protected override ILocalVariable Variable {
6476 get { return ThisVariable.Instance; }
6479 public override VariableInfo VariableInfo {
6480 get { return variable_info; }
6483 public override bool IsFixed {
6484 get { return false; }
6489 protected virtual void Error_ThisNotAvailable (ResolveContext ec)
6491 if (ec.IsStatic && !ec.HasSet (ResolveContext.Options.ConstantScope)) {
6492 ec.Report.Error (26, loc, "Keyword `this' is not valid in a static property, static method, or static field initializer");
6493 } else if (ec.CurrentAnonymousMethod != null) {
6494 ec.Report.Error (1673, loc,
6495 "Anonymous methods inside structs cannot access instance members of `this'. " +
6496 "Consider copying `this' to a local variable outside the anonymous method and using the local instead");
6498 ec.Report.Error (27, loc, "Keyword `this' is not available in the current context");
6502 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
6507 AnonymousMethodStorey storey = ae.Storey;
6508 while (storey != null) {
6509 AnonymousMethodStorey temp = storey.Parent as AnonymousMethodStorey;
6511 return storey.HoistedThis;
6519 public static bool IsThisAvailable (ResolveContext ec, bool ignoreAnonymous)
6521 if (ec.IsStatic || ec.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.BaseInitializer | ResolveContext.Options.ConstantScope))
6524 if (ignoreAnonymous || ec.CurrentAnonymousMethod == null)
6527 if (TypeManager.IsStruct (ec.CurrentType) && ec.CurrentIterator == null)
6533 public virtual void ResolveBase (ResolveContext ec)
6535 if (!IsThisAvailable (ec, false)) {
6536 Error_ThisNotAvailable (ec);
6539 var block = ec.CurrentBlock;
6540 if (block != null) {
6541 if (block.Toplevel.ThisVariable != null)
6542 variable_info = block.Toplevel.ThisVariable.VariableInfo;
6544 AnonymousExpression am = ec.CurrentAnonymousMethod;
6545 if (am != null && ec.IsVariableCapturingRequired) {
6546 am.SetHasThisAccess ();
6550 eclass = ExprClass.Variable;
6551 type = ec.CurrentType;
6555 // Called from Invocation to check if the invocation is correct
6557 public override void CheckMarshalByRefAccess (ResolveContext ec)
6559 if ((variable_info != null) && !(TypeManager.IsStruct (type) && ec.OmitStructFlowAnalysis) &&
6560 !variable_info.IsAssigned (ec)) {
6561 ec.Report.Error (188, loc,
6562 "The `this' object cannot be used before all of its fields are assigned to");
6563 variable_info.SetAssigned (ec);
6567 public override Expression CreateExpressionTree (ResolveContext ec)
6569 Arguments args = new Arguments (1);
6570 args.Add (new Argument (this));
6572 // Use typeless constant for ldarg.0 to save some
6573 // space and avoid problems with anonymous stories
6574 return CreateExpressionFactoryCall (ec, "Constant", args);
6577 protected override Expression DoResolve (ResolveContext ec)
6583 override public Expression DoResolveLValue (ResolveContext ec, Expression right_side)
6587 if (variable_info != null)
6588 variable_info.SetAssigned (ec);
6590 if (ec.CurrentType.IsClass){
6591 if (right_side == EmptyExpression.UnaryAddress)
6592 ec.Report.Error (459, loc, "Cannot take the address of `this' because it is read-only");
6593 else if (right_side == EmptyExpression.OutAccess.Instance)
6594 ec.Report.Error (1605, loc, "Cannot pass `this' as a ref or out argument because it is read-only");
6596 ec.Report.Error (1604, loc, "Cannot assign to `this' because it is read-only");
6602 public override int GetHashCode()
6604 throw new NotImplementedException ();
6607 public override bool Equals (object obj)
6609 This t = obj as This;
6616 protected override void CloneTo (CloneContext clonectx, Expression t)
6621 public override void SetHasAddressTaken ()
6628 /// Represents the `__arglist' construct
6630 public class ArglistAccess : Expression
6632 public ArglistAccess (Location loc)
6637 public override Expression CreateExpressionTree (ResolveContext ec)
6639 throw new NotSupportedException ("ET");
6642 protected override Expression DoResolve (ResolveContext ec)
6644 eclass = ExprClass.Variable;
6645 type = TypeManager.runtime_argument_handle_type;
6647 if (ec.HasSet (ResolveContext.Options.FieldInitializerScope) || !ec.CurrentBlock.Toplevel.Parameters.HasArglist) {
6648 ec.Report.Error (190, loc,
6649 "The __arglist construct is valid only within a variable argument method");
6655 public override void Emit (EmitContext ec)
6657 ec.Emit (OpCodes.Arglist);
6660 protected override void CloneTo (CloneContext clonectx, Expression target)
6667 /// Represents the `__arglist (....)' construct
6669 public class Arglist : Expression
6671 Arguments Arguments;
6673 public Arglist (Location loc)
6678 public Arglist (Arguments args, Location l)
6684 public Type[] ArgumentTypes {
6686 if (Arguments == null)
6687 return System.Type.EmptyTypes;
6689 var retval = new Type [Arguments.Count];
6690 for (int i = 0; i < retval.Length; i++)
6691 retval[i] = Arguments[i].Expr.Type.GetMetaInfo ();
6697 public override Expression CreateExpressionTree (ResolveContext ec)
6699 ec.Report.Error (1952, loc, "An expression tree cannot contain a method with variable arguments");
6703 protected override Expression DoResolve (ResolveContext ec)
6705 eclass = ExprClass.Variable;
6706 type = InternalType.Arglist;
6707 if (Arguments != null) {
6708 bool dynamic; // Can be ignored as there is always only 1 overload
6709 Arguments.Resolve (ec, out dynamic);
6715 public override void Emit (EmitContext ec)
6717 if (Arguments != null)
6718 Arguments.Emit (ec);
6721 protected override void CloneTo (CloneContext clonectx, Expression t)
6723 Arglist target = (Arglist) t;
6725 if (Arguments != null)
6726 target.Arguments = Arguments.Clone (clonectx);
6731 /// Implements the typeof operator
6733 public class TypeOf : Expression {
6734 FullNamedExpression QueriedType;
6737 public TypeOf (FullNamedExpression queried_type, Location l)
6739 QueriedType = queried_type;
6744 public TypeSpec TypeArgument {
6750 public FullNamedExpression TypeExpression {
6758 public override Expression CreateExpressionTree (ResolveContext ec)
6760 Arguments args = new Arguments (2);
6761 args.Add (new Argument (this));
6762 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
6763 return CreateExpressionFactoryCall (ec, "Constant", args);
6766 protected override Expression DoResolve (ResolveContext ec)
6768 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
6772 typearg = texpr.Type;
6774 if (typearg == TypeManager.void_type && !(QueriedType is TypeExpression)) {
6775 ec.Report.Error (673, loc, "System.Void cannot be used from C#. Use typeof (void) to get the void type object");
6776 } else if (typearg.IsPointer && !ec.IsUnsafe){
6777 UnsafeError (ec, loc);
6778 } else if (texpr is DynamicTypeExpr) {
6779 ec.Report.Error (1962, QueriedType.Location,
6780 "The typeof operator cannot be used on the dynamic type");
6783 type = TypeManager.type_type;
6785 return DoResolveBase ();
6788 protected Expression DoResolveBase ()
6790 if (TypeManager.system_type_get_type_from_handle == null) {
6791 TypeManager.system_type_get_type_from_handle = TypeManager.GetPredefinedMethod (
6792 TypeManager.type_type, "GetTypeFromHandle", loc, TypeManager.runtime_handle_type);
6795 // Even though what is returned is a type object, it's treated as a value by the compiler.
6796 // In particular, 'typeof (Foo).X' is something totally different from 'Foo.X'.
6797 eclass = ExprClass.Value;
6801 static bool ContainsTypeParameter (TypeSpec type)
6803 if (type.Kind == MemberKind.TypeParameter)
6806 var element_container = type as ElementTypeSpec;
6807 if (element_container != null)
6808 return ContainsTypeParameter (element_container.Element);
6810 foreach (var t in type.TypeArguments) {
6811 if (ContainsTypeParameter (t)) {
6819 public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
6821 // Target type is not System.Type therefore must be object
6822 // and we need to use different encoding sequence
6823 if (targetType != type)
6826 if (ContainsTypeParameter (typearg)) {
6827 rc.Compiler.Report.Error (416, loc, "`{0}': an attribute argument cannot use type parameters",
6828 TypeManager.CSharpName (typearg));
6832 enc.EncodeTypeName (typearg);
6835 public override void Emit (EmitContext ec)
6837 ec.Emit (OpCodes.Ldtoken, typearg);
6838 ec.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6841 protected override void CloneTo (CloneContext clonectx, Expression t)
6843 TypeOf target = (TypeOf) t;
6844 if (QueriedType != null)
6845 target.QueriedType = (FullNamedExpression) QueriedType.Clone (clonectx);
6849 class TypeOfMethod : TypeOfMember<MethodSpec>
6851 public TypeOfMethod (MethodSpec method, Location loc)
6852 : base (method, loc)
6856 protected override Expression DoResolve (ResolveContext ec)
6858 if (member.IsConstructor) {
6859 type = TypeManager.ctorinfo_type;
6861 type = TypeManager.ctorinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", "ConstructorInfo", MemberKind.Class, true);
6863 type = TypeManager.methodinfo_type;
6865 type = TypeManager.methodinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", "MethodInfo", MemberKind.Class, true);
6868 return base.DoResolve (ec);
6871 public override void Emit (EmitContext ec)
6873 ec.Emit (OpCodes.Ldtoken, member);
6876 ec.Emit (OpCodes.Castclass, type);
6879 protected override string GetMethodName {
6880 get { return "GetMethodFromHandle"; }
6883 protected override string RuntimeHandleName {
6884 get { return "RuntimeMethodHandle"; }
6887 protected override MethodSpec TypeFromHandle {
6889 return TypeManager.methodbase_get_type_from_handle;
6892 TypeManager.methodbase_get_type_from_handle = value;
6896 protected override MethodSpec TypeFromHandleGeneric {
6898 return TypeManager.methodbase_get_type_from_handle_generic;
6901 TypeManager.methodbase_get_type_from_handle_generic = value;
6905 protected override string TypeName {
6906 get { return "MethodBase"; }
6910 abstract class TypeOfMember<T> : Expression where T : MemberSpec
6912 protected readonly T member;
6914 protected TypeOfMember (T member, Location loc)
6916 this.member = member;
6920 public override Expression CreateExpressionTree (ResolveContext ec)
6922 Arguments args = new Arguments (2);
6923 args.Add (new Argument (this));
6924 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
6925 return CreateExpressionFactoryCall (ec, "Constant", args);
6928 protected override Expression DoResolve (ResolveContext ec)
6930 bool is_generic = member.DeclaringType.IsGenericOrParentIsGeneric;
6931 var mi = is_generic ? TypeFromHandleGeneric : TypeFromHandle;
6934 TypeSpec t = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", TypeName, MemberKind.Class, true);
6935 TypeSpec handle_type = TypeManager.CoreLookupType (ec.Compiler, "System", RuntimeHandleName, MemberKind.Struct, true);
6937 if (t == null || handle_type == null)
6940 mi = TypeManager.GetPredefinedMethod (t, GetMethodName, loc,
6942 new TypeSpec[] { handle_type, TypeManager.runtime_handle_type } :
6943 new TypeSpec[] { handle_type } );
6946 TypeFromHandleGeneric = mi;
6948 TypeFromHandle = mi;
6951 eclass = ExprClass.Value;
6955 public override void Emit (EmitContext ec)
6957 bool is_generic = member.DeclaringType.IsGenericOrParentIsGeneric;
6960 mi = TypeFromHandleGeneric;
6961 ec.Emit (OpCodes.Ldtoken, member.DeclaringType);
6963 mi = TypeFromHandle;
6966 ec.Emit (OpCodes.Call, mi);
6969 protected abstract string GetMethodName { get; }
6970 protected abstract string RuntimeHandleName { get; }
6971 protected abstract MethodSpec TypeFromHandle { get; set; }
6972 protected abstract MethodSpec TypeFromHandleGeneric { get; set; }
6973 protected abstract string TypeName { get; }
6976 class TypeOfField : TypeOfMember<FieldSpec>
6978 public TypeOfField (FieldSpec field, Location loc)
6983 protected override Expression DoResolve (ResolveContext ec)
6985 if (TypeManager.fieldinfo_type == null)
6986 TypeManager.fieldinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", TypeName, MemberKind.Class, true);
6988 type = TypeManager.fieldinfo_type;
6989 return base.DoResolve (ec);
6992 public override void Emit (EmitContext ec)
6994 ec.Emit (OpCodes.Ldtoken, member);
6998 protected override string GetMethodName {
6999 get { return "GetFieldFromHandle"; }
7002 protected override string RuntimeHandleName {
7003 get { return "RuntimeFieldHandle"; }
7006 protected override MethodSpec TypeFromHandle {
7008 return TypeManager.fieldinfo_get_field_from_handle;
7011 TypeManager.fieldinfo_get_field_from_handle = value;
7015 protected override MethodSpec TypeFromHandleGeneric {
7017 return TypeManager.fieldinfo_get_field_from_handle_generic;
7020 TypeManager.fieldinfo_get_field_from_handle_generic = value;
7024 protected override string TypeName {
7025 get { return "FieldInfo"; }
7030 /// Implements the sizeof expression
7032 public class SizeOf : Expression {
7033 readonly Expression QueriedType;
7034 TypeSpec type_queried;
7036 public SizeOf (Expression queried_type, Location l)
7038 this.QueriedType = queried_type;
7042 public override Expression CreateExpressionTree (ResolveContext ec)
7044 Error_PointerInsideExpressionTree (ec);
7048 protected override Expression DoResolve (ResolveContext ec)
7050 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
7054 type_queried = texpr.Type;
7055 if (TypeManager.IsEnumType (type_queried))
7056 type_queried = EnumSpec.GetUnderlyingType (type_queried);
7058 int size_of = GetTypeSize (type_queried);
7060 return new IntConstant (size_of, loc).Resolve (ec);
7063 if (!TypeManager.VerifyUnmanaged (ec.Compiler, type_queried, loc)){
7068 ec.Report.Error (233, loc,
7069 "`{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)",
7070 TypeManager.CSharpName (type_queried));
7073 type = TypeManager.int32_type;
7074 eclass = ExprClass.Value;
7078 public override void Emit (EmitContext ec)
7080 ec.Emit (OpCodes.Sizeof, type_queried);
7083 protected override void CloneTo (CloneContext clonectx, Expression t)
7089 /// Implements the qualified-alias-member (::) expression.
7091 public class QualifiedAliasMember : MemberAccess
7093 readonly string alias;
7094 public static readonly string GlobalAlias = "global";
7096 public QualifiedAliasMember (string alias, string identifier, Location l)
7097 : base (null, identifier, l)
7102 public QualifiedAliasMember (string alias, string identifier, TypeArguments targs, Location l)
7103 : base (null, identifier, targs, l)
7108 public QualifiedAliasMember (string alias, string identifier, int arity, Location l)
7109 : base (null, identifier, arity, l)
7114 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
7116 if (alias == GlobalAlias) {
7117 expr = GlobalRootNamespace.Instance;
7118 return base.ResolveAsTypeStep (ec, silent);
7121 int errors = ec.Compiler.Report.Errors;
7122 expr = ec.LookupNamespaceAlias (alias);
7124 if (errors == ec.Compiler.Report.Errors)
7125 ec.Compiler.Report.Error (432, loc, "Alias `{0}' not found", alias);
7129 FullNamedExpression fne = base.ResolveAsTypeStep (ec, silent);
7133 if (expr.eclass == ExprClass.Type) {
7135 ec.Compiler.Report.Error (431, loc,
7136 "Alias `{0}' cannot be used with '::' since it denotes a type. Consider replacing '::' with '.'", alias);
7144 protected override Expression DoResolve (ResolveContext ec)
7146 return ResolveAsTypeStep (ec, false);
7149 protected override void Error_IdentifierNotFound (IMemberContext rc, TypeSpec expr_type, string identifier)
7151 rc.Compiler.Report.Error (687, loc,
7152 "A namespace alias qualifier `{0}' did not resolve to a namespace or a type",
7153 GetSignatureForError ());
7156 public override string GetSignatureForError ()
7159 if (targs != null) {
7160 name = Name + "<" + targs.GetSignatureForError () + ">";
7163 return alias + "::" + name;
7166 public override Expression LookupNameExpression (ResolveContext rc, bool readMode, bool invocableOnly)
7168 return DoResolve (rc);
7171 protected override void CloneTo (CloneContext clonectx, Expression t)
7178 /// Implements the member access expression
7180 public class MemberAccess : ATypeNameExpression
7182 protected Expression expr;
7184 public MemberAccess (Expression expr, string id)
7185 : base (id, expr.Location)
7190 public MemberAccess (Expression expr, string identifier, Location loc)
7191 : base (identifier, loc)
7196 public MemberAccess (Expression expr, string identifier, TypeArguments args, Location loc)
7197 : base (identifier, args, loc)
7202 public MemberAccess (Expression expr, string identifier, int arity, Location loc)
7203 : base (identifier, arity, loc)
7208 public Expression LeftExpression {
7214 protected override Expression DoResolve (ResolveContext ec)
7216 return DoResolveName (ec, null);
7219 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
7221 return DoResolveName (ec, right_side);
7224 Expression DoResolveName (ResolveContext rc, Expression right_side)
7226 Expression e = LookupNameExpression (rc, right_side == null, false);
7230 if (right_side != null)
7231 e = e.ResolveLValue (rc, right_side);
7233 e = e.Resolve (rc, ResolveFlags.VariableOrValue | ResolveFlags.Type);
7238 public override Expression LookupNameExpression (ResolveContext rc, bool readMode, bool invocableOnly)
7240 var sn = expr as SimpleName;
7241 const ResolveFlags flags = ResolveFlags.VariableOrValue | ResolveFlags.Type;
7244 // Resolve the expression with flow analysis turned off, we'll do the definite
7245 // assignment checks later. This is because we don't know yet what the expression
7246 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7247 // definite assignment check on the actual field and not on the whole struct.
7249 using (rc.Set (ResolveContext.Options.OmitStructFlowAnalysis)) {
7251 expr = sn.LookupNameExpression (rc, true, false);
7253 // Call resolve on expression which does have type set as we need expression type
7254 // TODO: I should probably ensure that the type is always set and leave resolve for the final
7255 if (expr is VariableReference || expr is ConstantExpr || expr is Linq.TransparentMemberAccess) {
7256 using (rc.With (ResolveContext.Options.DoFlowAnalysis, false)) {
7257 expr = expr.Resolve (rc);
7259 } else if (expr is TypeParameterExpr) {
7260 expr.Error_UnexpectedKind (rc, flags, expr.Location);
7264 expr = expr.Resolve (rc, flags);
7271 Namespace ns = expr as Namespace;
7273 FullNamedExpression retval = ns.Lookup (rc.Compiler, Name, Arity, loc);
7275 if (retval == null) {
7276 ns.Error_NamespaceDoesNotExist (loc, Name, Arity, rc);
7280 if (HasTypeArguments)
7281 return new GenericTypeExpr (retval.Type, targs, loc);
7286 TypeSpec expr_type = expr.Type;
7287 if (expr_type == InternalType.Dynamic) {
7288 Arguments args = new Arguments (1);
7289 args.Add (new Argument (expr));
7290 return new DynamicMemberBinder (Name, args, loc);
7293 const MemberKind dot_kinds = MemberKind.Class | MemberKind.Struct | MemberKind.Delegate | MemberKind.Enum |
7294 MemberKind.Interface | MemberKind.TypeParameter | MemberKind.ArrayType;
7296 if ((expr_type.Kind & dot_kinds) == 0 || expr_type == TypeManager.void_type) {
7297 Unary.Error_OperatorCannotBeApplied (rc, loc, ".", expr_type);
7301 var current_type = rc.CurrentType;
7302 var lookup_arity = Arity;
7303 bool errorMode = false;
7304 Expression member_lookup;
7306 member_lookup = MemberLookup (errorMode ? null : rc, current_type, expr_type, Name, lookup_arity, invocableOnly, loc);
7307 if (member_lookup == null) {
7309 // Try to look for extension method when member lookup failed
7311 if (MethodGroupExpr.IsExtensionMethodArgument (expr)) {
7312 NamespaceEntry scope = null;
7313 var methods = rc.LookupExtensionMethod (expr_type, Name, lookup_arity, ref scope);
7314 if (methods != null) {
7315 var emg = new ExtensionMethodGroupExpr (methods, scope, expr, loc);
7316 if (HasTypeArguments) {
7317 if (!targs.Resolve (rc))
7320 emg.SetTypeArguments (rc, targs);
7323 // TODO: Should it really skip the checks bellow
7324 return emg.Resolve (rc);
7330 if (member_lookup == null) {
7331 if (expr is TypeExpr)
7332 base.Error_TypeDoesNotContainDefinition (rc, expr_type, Name);
7334 Error_TypeDoesNotContainDefinition (rc, expr_type, Name);
7339 if (member_lookup is MethodGroupExpr) {
7340 // Leave it to overload resolution to report correct error
7342 // TODO: rc.SymbolRelatedToPreviousError
7343 ErrorIsInaccesible (rc, member_lookup.GetSignatureForError (), loc);
7348 if (member_lookup != null)
7351 current_type = null;
7353 invocableOnly = false;
7358 TypeExpr texpr = member_lookup as TypeExpr;
7360 if (texpr != null) {
7361 if (!(expr is TypeExpr)) {
7362 me = expr as MemberExpr;
7363 if (me == null || me.ProbeIdenticalTypeName (rc, expr, sn) == expr) {
7364 rc.Report.Error (572, loc, "`{0}': cannot reference a type through an expression; try `{1}' instead",
7365 Name, member_lookup.GetSignatureForError ());
7370 if (!texpr.Type.IsAccessible (rc.CurrentType)) {
7371 rc.Report.SymbolRelatedToPreviousError (member_lookup.Type);
7372 ErrorIsInaccesible (rc, member_lookup.Type.GetSignatureForError (), loc);
7376 if (HasTypeArguments) {
7377 return new GenericTypeExpr (member_lookup.Type, targs, loc);
7380 return member_lookup;
7383 me = member_lookup as MemberExpr;
7385 if (sn != null && me.IsStatic)
7386 expr = me.ProbeIdenticalTypeName (rc, expr, sn);
7388 me = me.ResolveMemberAccess (rc, expr, sn);
7391 if (!targs.Resolve (rc))
7394 me.SetTypeArguments (rc, targs);
7397 if (sn != null && (!TypeManager.IsValueType (expr_type) || me is PropertyExpr)) {
7398 if (me.IsInstance) {
7399 LocalVariableReference var = expr as LocalVariableReference;
7400 if (var != null && !var.VerifyAssigned (rc))
7408 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
7410 return ResolveNamespaceOrType (ec, silent);
7413 public FullNamedExpression ResolveNamespaceOrType (IMemberContext rc, bool silent)
7415 FullNamedExpression expr_resolved = expr.ResolveAsTypeStep (rc, silent);
7417 if (expr_resolved == null)
7420 Namespace ns = expr_resolved as Namespace;
7422 FullNamedExpression retval = ns.Lookup (rc.Compiler, Name, Arity, loc);
7424 if (retval == null) {
7426 ns.Error_NamespaceDoesNotExist (loc, Name, Arity, rc);
7427 } else if (HasTypeArguments) {
7428 retval = new GenericTypeExpr (retval.Type, targs, loc).ResolveAsTypeStep (rc, silent);
7434 TypeExpr tnew_expr = expr_resolved.ResolveAsTypeTerminal (rc, false);
7435 if (tnew_expr == null)
7438 TypeSpec expr_type = tnew_expr.Type;
7439 if (TypeManager.IsGenericParameter (expr_type)) {
7440 rc.Compiler.Report.Error (704, loc, "A nested type cannot be specified through a type parameter `{0}'",
7441 tnew_expr.GetSignatureForError ());
7445 var nested = MemberCache.FindNestedType (expr_type, Name, Arity);
7446 if (nested == null) {
7450 Error_IdentifierNotFound (rc, expr_type, Name);
7454 if (!nested.IsAccessible (rc.CurrentType ?? InternalType.FakeInternalType)) {
7455 ErrorIsInaccesible (rc, nested.GetSignatureForError (), loc);
7459 if (HasTypeArguments) {
7460 texpr = new GenericTypeExpr (nested, targs, loc);
7462 texpr = new TypeExpression (nested, loc);
7465 return texpr.ResolveAsTypeStep (rc, false);
7468 protected virtual void Error_IdentifierNotFound (IMemberContext rc, TypeSpec expr_type, string identifier)
7470 var nested = MemberCache.FindNestedType (expr_type, Name, -System.Math.Max (1, Arity));
7472 if (nested != null) {
7473 Error_TypeArgumentsCannotBeUsed (rc.Compiler.Report, expr.Location, nested, Arity);
7477 var any_other_member = MemberLookup (null, rc.CurrentType, expr_type, Name, 0, false, loc);
7478 if (any_other_member != null) {
7479 any_other_member.Error_UnexpectedKind (rc.Compiler.Report, null, "type", loc);
7483 rc.Compiler.Report.Error (426, loc, "The nested type `{0}' does not exist in the type `{1}'",
7484 Name, expr_type.GetSignatureForError ());
7487 protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
7489 if (RootContext.Version > LanguageVersion.ISO_2 && !ec.Compiler.IsRuntimeBinder && MethodGroupExpr.IsExtensionMethodArgument (expr)) {
7490 ec.Report.Error (1061, loc,
7491 "Type `{0}' does not contain a definition for `{1}' and no extension method `{1}' of type `{0}' could be found (are you missing a using directive or an assembly reference?)",
7492 type.GetSignatureForError (), name);
7496 base.Error_TypeDoesNotContainDefinition (ec, type, name);
7499 public override string GetSignatureForError ()
7501 return expr.GetSignatureForError () + "." + base.GetSignatureForError ();
7504 protected override void CloneTo (CloneContext clonectx, Expression t)
7506 MemberAccess target = (MemberAccess) t;
7508 target.expr = expr.Clone (clonectx);
7513 /// Implements checked expressions
7515 public class CheckedExpr : Expression {
7517 public Expression Expr;
7519 public CheckedExpr (Expression e, Location l)
7525 public override Expression CreateExpressionTree (ResolveContext ec)
7527 using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
7528 return Expr.CreateExpressionTree (ec);
7531 protected override Expression DoResolve (ResolveContext ec)
7533 using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
7534 Expr = Expr.Resolve (ec);
7539 if (Expr is Constant || Expr is MethodGroupExpr || Expr is AnonymousMethodExpression || Expr is DefaultValueExpression)
7542 eclass = Expr.eclass;
7547 public override void Emit (EmitContext ec)
7549 using (ec.With (EmitContext.Options.AllCheckStateFlags, true))
7553 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
7555 using (ec.With (EmitContext.Options.AllCheckStateFlags, true))
7556 Expr.EmitBranchable (ec, target, on_true);
7559 public override SLE.Expression MakeExpression (BuilderContext ctx)
7561 using (ctx.With (BuilderContext.Options.AllCheckStateFlags, true)) {
7562 return Expr.MakeExpression (ctx);
7566 protected override void CloneTo (CloneContext clonectx, Expression t)
7568 CheckedExpr target = (CheckedExpr) t;
7570 target.Expr = Expr.Clone (clonectx);
7575 /// Implements the unchecked expression
7577 public class UnCheckedExpr : Expression {
7579 public Expression Expr;
7581 public UnCheckedExpr (Expression e, Location l)
7587 public override Expression CreateExpressionTree (ResolveContext ec)
7589 using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
7590 return Expr.CreateExpressionTree (ec);
7593 protected override Expression DoResolve (ResolveContext ec)
7595 using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
7596 Expr = Expr.Resolve (ec);
7601 if (Expr is Constant || Expr is MethodGroupExpr || Expr is AnonymousMethodExpression || Expr is DefaultValueExpression)
7604 eclass = Expr.eclass;
7609 public override void Emit (EmitContext ec)
7611 using (ec.With (EmitContext.Options.AllCheckStateFlags, false))
7615 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
7617 using (ec.With (EmitContext.Options.AllCheckStateFlags, false))
7618 Expr.EmitBranchable (ec, target, on_true);
7621 protected override void CloneTo (CloneContext clonectx, Expression t)
7623 UnCheckedExpr target = (UnCheckedExpr) t;
7625 target.Expr = Expr.Clone (clonectx);
7630 /// An Element Access expression.
7632 /// During semantic analysis these are transformed into
7633 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7635 public class ElementAccess : Expression {
7636 public Arguments Arguments;
7637 public Expression Expr;
7639 public ElementAccess (Expression e, Arguments args, Location loc)
7643 this.Arguments = args;
7647 // We perform some simple tests, and then to "split" the emit and store
7648 // code we create an instance of a different class, and return that.
7650 Expression CreateAccessExpression (ResolveContext ec)
7653 return (new ArrayAccess (this, loc));
7656 return MakePointerAccess (ec, type);
7658 FieldExpr fe = Expr as FieldExpr;
7660 var ff = fe.Spec as FixedFieldSpec;
7662 return MakePointerAccess (ec, ff.ElementType);
7666 var indexers = MemberCache.FindMembers (type, MemberCache.IndexerNameAlias, false);
7667 if (indexers != null || type == InternalType.Dynamic) {
7668 return new IndexerExpr (indexers, this);
7671 ec.Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
7672 type.GetSignatureForError ());
7676 public override Expression CreateExpressionTree (ResolveContext ec)
7678 Arguments args = Arguments.CreateForExpressionTree (ec, Arguments,
7679 Expr.CreateExpressionTree (ec));
7681 return CreateExpressionFactoryCall (ec, "ArrayIndex", args);
7684 Expression MakePointerAccess (ResolveContext ec, TypeSpec type)
7686 if (Arguments.Count != 1){
7687 ec.Report.Error (196, loc, "A pointer must be indexed by only one value");
7691 if (Arguments [0] is NamedArgument)
7692 Error_NamedArgument ((NamedArgument) Arguments[0], ec.Report);
7694 Expression p = new PointerArithmetic (Binary.Operator.Addition, Expr, Arguments [0].Expr.Resolve (ec), type, loc);
7695 return new Indirection (p, loc);
7698 protected override Expression DoResolve (ResolveContext ec)
7700 Expr = Expr.Resolve (ec);
7706 // TODO: Create 1 result for Resolve and ResolveLValue ?
7707 var res = CreateAccessExpression (ec);
7711 return res.Resolve (ec);
7714 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
7716 Expr = Expr.Resolve (ec);
7722 var res = CreateAccessExpression (ec);
7726 return res.ResolveLValue (ec, right_side);
7729 public override void Emit (EmitContext ec)
7731 throw new Exception ("Should never be reached");
7734 public static void Error_NamedArgument (NamedArgument na, Report Report)
7736 Report.Error (1742, na.Location, "An element access expression cannot use named argument");
7739 public override string GetSignatureForError ()
7741 return Expr.GetSignatureForError ();
7744 protected override void CloneTo (CloneContext clonectx, Expression t)
7746 ElementAccess target = (ElementAccess) t;
7748 target.Expr = Expr.Clone (clonectx);
7749 if (Arguments != null)
7750 target.Arguments = Arguments.Clone (clonectx);
7755 /// Implements array access
7757 public class ArrayAccess : Expression, IDynamicAssign, IMemoryLocation {
7759 // Points to our "data" repository
7763 LocalTemporary temp;
7767 public ArrayAccess (ElementAccess ea_data, Location l)
7773 public override Expression CreateExpressionTree (ResolveContext ec)
7775 return ea.CreateExpressionTree (ec);
7778 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
7780 return DoResolve (ec);
7783 protected override Expression DoResolve (ResolveContext ec)
7785 // dynamic is used per argument in ConvertExpressionToArrayIndex case
7787 ea.Arguments.Resolve (ec, out dynamic);
7789 var ac = ea.Expr.Type as ArrayContainer;
7790 int rank = ea.Arguments.Count;
7791 if (ac.Rank != rank) {
7792 ec.Report.Error (22, ea.Location, "Wrong number of indexes `{0}' inside [], expected `{1}'",
7793 rank.ToString (), ac.Rank.ToString ());
7798 if (type.IsPointer && !ec.IsUnsafe) {
7799 UnsafeError (ec, ea.Location);
7802 foreach (Argument a in ea.Arguments) {
7803 if (a is NamedArgument)
7804 ElementAccess.Error_NamedArgument ((NamedArgument) a, ec.Report);
7806 a.Expr = ConvertExpressionToArrayIndex (ec, a.Expr);
7809 eclass = ExprClass.Variable;
7814 protected override void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
7816 ec.Report.Warning (251, 2, loc, "Indexing an array with a negative index (array indices always start at zero)");
7820 // Load the array arguments into the stack.
7822 void LoadArrayAndArguments (EmitContext ec)
7826 for (int i = 0; i < ea.Arguments.Count; ++i) {
7827 ea.Arguments [i].Emit (ec);
7831 public void Emit (EmitContext ec, bool leave_copy)
7833 var ac = ea.Expr.Type as ArrayContainer;
7836 ec.EmitLoadFromPtr (type);
7838 LoadArrayAndArguments (ec);
7839 ec.EmitArrayLoad (ac);
7843 ec.Emit (OpCodes.Dup);
7844 temp = new LocalTemporary (this.type);
7849 public override void Emit (EmitContext ec)
7854 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
7856 var ac = (ArrayContainer) ea.Expr.Type;
7857 TypeSpec t = source.Type;
7858 prepared = prepare_for_load;
7861 AddressOf (ec, AddressOp.LoadStore);
7862 ec.Emit (OpCodes.Dup);
7864 LoadArrayAndArguments (ec);
7867 // If we are dealing with a struct, get the
7868 // address of it, so we can store it.
7870 // The stobj opcode used by value types will need
7871 // an address on the stack, not really an array/array
7874 if (ac.Rank == 1 && TypeManager.IsStruct (t) &&
7875 (!TypeManager.IsBuiltinOrEnum (t) ||
7876 t == TypeManager.decimal_type)) {
7878 ec.Emit (OpCodes.Ldelema, t);
7884 ec.Emit (OpCodes.Dup);
7885 temp = new LocalTemporary (this.type);
7890 ec.EmitStoreFromPtr (t);
7892 ec.EmitArrayStore (ac);
7901 public void EmitNew (EmitContext ec, New source, bool leave_copy)
7903 if (!source.Emit (ec, this)) {
7905 throw new NotImplementedException ();
7910 throw new NotImplementedException ();
7913 public void AddressOf (EmitContext ec, AddressOp mode)
7915 var ac = (ArrayContainer) ea.Expr.Type;
7917 LoadArrayAndArguments (ec);
7918 ec.EmitArrayAddress (ac);
7921 public SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
7924 return SLE.Expression.ArrayAccess (
7925 ea.Expr.MakeExpression (ctx),
7926 Arguments.MakeExpression (ea.Arguments, ctx));
7928 throw new NotImplementedException ();
7932 public override SLE.Expression MakeExpression (BuilderContext ctx)
7934 return SLE.Expression.ArrayIndex (
7935 ea.Expr.MakeExpression (ctx),
7936 Arguments.MakeExpression (ea.Arguments, ctx));
7941 // Indexer access expression
7943 class IndexerExpr : PropertyOrIndexerExpr<IndexerSpec>, OverloadResolver.IBaseMembersProvider
7945 LocalTemporary prepared_value;
7946 IList<MemberSpec> indexers;
7947 Arguments arguments;
7949 public IndexerExpr (IList<MemberSpec> indexers, ElementAccess ea)
7950 : base (ea.Location)
7952 this.indexers = indexers;
7953 this.InstanceExpression = ea.Expr;
7954 this.arguments = ea.Arguments;
7958 protected override TypeSpec DeclaringType {
7960 return best_candidate.DeclaringType;
7964 public override bool IsInstance {
7970 public override bool IsStatic {
7976 public override string Name {
7984 public override Expression CreateExpressionTree (ResolveContext ec)
7986 Arguments args = Arguments.CreateForExpressionTree (ec, arguments,
7987 InstanceExpression.CreateExpressionTree (ec),
7988 new TypeOfMethod (Getter, loc));
7990 return CreateExpressionFactoryCall (ec, "Call", args);
7993 public override void Emit (EmitContext ec, bool leave_copy)
7996 prepared_value.Emit (ec);
7998 Invocation.EmitCall (ec, InstanceExpression, Getter, arguments, loc, false, false);
8002 ec.Emit (OpCodes.Dup);
8003 temp = new LocalTemporary (Type);
8008 public override void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8010 prepared = prepare_for_load;
8011 Expression value = source;
8014 Invocation.EmitCall (ec, InstanceExpression, Getter,
8015 arguments, loc, true, false);
8017 prepared_value = new LocalTemporary (type);
8018 prepared_value.Store (ec);
8020 prepared_value.Release (ec);
8023 ec.Emit (OpCodes.Dup);
8024 temp = new LocalTemporary (Type);
8027 } else if (leave_copy) {
8028 temp = new LocalTemporary (Type);
8035 arguments.Add (new Argument (value));
8037 Invocation.EmitCall (ec, InstanceExpression, Setter, arguments, loc, false, prepared);
8045 public override string GetSignatureForError ()
8047 return best_candidate.GetSignatureForError ();
8050 public override SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
8052 var value = new[] { source.MakeExpression (ctx) };
8053 var args = Arguments.MakeExpression (arguments, ctx).Concat (value);
8055 return SLE.Expression.Block (
8056 SLE.Expression.Call (InstanceExpression.MakeExpression (ctx), (MethodInfo) Setter.GetMetaInfo (), args),
8059 return args.First ();
8063 public override SLE.Expression MakeExpression (BuilderContext ctx)
8065 var args = Arguments.MakeExpression (arguments, ctx);
8066 return SLE.Expression.Call (InstanceExpression.MakeExpression (ctx), (MethodInfo) Getter.GetMetaInfo (), args);
8069 protected override Expression OverloadResolve (ResolveContext rc, Expression right_side)
8071 if (best_candidate != null)
8074 eclass = ExprClass.IndexerAccess;
8077 arguments.Resolve (rc, out dynamic);
8079 if (indexers == null && InstanceExpression.Type == InternalType.Dynamic) {
8082 var res = new OverloadResolver (indexers, OverloadResolver.Restrictions.None, loc);
8083 res.BaseMembersProvider = this;
8085 // TODO: Do I need 2 argument sets?
8086 best_candidate = res.ResolveMember<IndexerSpec> (rc, ref arguments);
8087 if (best_candidate != null)
8088 type = best_candidate.MemberType;
8089 else if (!res.BestCandidateIsDynamic)
8093 if (dynamic || type == InternalType.Dynamic) {
8094 Arguments args = new Arguments (arguments.Count + 1);
8096 rc.Report.Error (1972, loc,
8097 "The indexer base access cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access");
8099 args.Add (new Argument (InstanceExpression));
8101 args.AddRange (arguments);
8103 best_candidate = null;
8104 return new DynamicIndexBinder (args, loc);
8107 ResolveInstanceExpression (rc);
8108 CheckProtectedMemberAccess (rc, best_candidate);
8112 protected override void CloneTo (CloneContext clonectx, Expression t)
8114 IndexerExpr target = (IndexerExpr) t;
8116 if (arguments != null)
8117 target.arguments = arguments.Clone (clonectx);
8120 public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
8122 Error_TypeArgumentsCannotBeUsed (ec.Report, "indexer", GetSignatureForError (), loc);
8125 #region IBaseMembersProvider Members
8127 IList<MemberSpec> OverloadResolver.IBaseMembersProvider.GetBaseMembers (TypeSpec baseType)
8129 return baseType == null ? null : MemberCache.FindMembers (baseType, MemberCache.IndexerNameAlias, false);
8132 MethodGroupExpr OverloadResolver.IBaseMembersProvider.LookupExtensionMethod (ResolveContext rc)
8141 // A base access expression
8143 public class BaseThis : This
8145 public BaseThis (Location loc)
8150 public BaseThis (TypeSpec type, Location loc)
8154 eclass = ExprClass.Variable;
8159 public override string Name {
8167 public override Expression CreateExpressionTree (ResolveContext ec)
8169 ec.Report.Error (831, loc, "An expression tree may not contain a base access");
8170 return base.CreateExpressionTree (ec);
8173 public override void Emit (EmitContext ec)
8177 if (ec.CurrentType.IsStruct) {
8178 ec.Emit (OpCodes.Ldobj, ec.CurrentType);
8179 ec.Emit (OpCodes.Box, ec.CurrentType);
8183 protected override void Error_ThisNotAvailable (ResolveContext ec)
8186 ec.Report.Error (1511, loc, "Keyword `base' is not available in a static method");
8188 ec.Report.Error (1512, loc, "Keyword `base' is not available in the current context");
8192 public override void ResolveBase (ResolveContext ec)
8194 base.ResolveBase (ec);
8195 type = ec.CurrentType.BaseType;
8200 /// This class exists solely to pass the Type around and to be a dummy
8201 /// that can be passed to the conversion functions (this is used by
8202 /// foreach implementation to typecast the object return value from
8203 /// get_Current into the proper type. All code has been generated and
8204 /// we only care about the side effect conversions to be performed
8206 /// This is also now used as a placeholder where a no-action expression
8207 /// is needed (the `New' class).
8209 public class EmptyExpression : Expression {
8210 public static readonly Expression Null = new EmptyExpression ();
8212 public class OutAccess : EmptyExpression
8214 public static readonly OutAccess Instance = new OutAccess ();
8216 public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
8218 rc.Report.Error (206, right_side.Location,
8219 "A property, indexer or dynamic member access may not be passed as `ref' or `out' parameter");
8225 public static readonly EmptyExpression LValueMemberAccess = new EmptyExpression ();
8226 public static readonly EmptyExpression LValueMemberOutAccess = new EmptyExpression ();
8227 public static readonly EmptyExpression UnaryAddress = new EmptyExpression ();
8228 public static readonly EmptyExpression EventAddition = new EmptyExpression ();
8229 public static readonly EmptyExpression EventSubtraction = new EmptyExpression ();
8231 static EmptyExpression temp = new EmptyExpression ();
8232 public static EmptyExpression Grab ()
8234 EmptyExpression retval = temp == null ? new EmptyExpression () : temp;
8239 public static void Release (EmptyExpression e)
8246 // FIXME: Don't set to object
8247 type = TypeManager.object_type;
8248 eclass = ExprClass.Value;
8249 loc = Location.Null;
8252 public EmptyExpression (TypeSpec t)
8255 eclass = ExprClass.Value;
8256 loc = Location.Null;
8259 public override Expression CreateExpressionTree (ResolveContext ec)
8261 throw new NotSupportedException ("ET");
8264 protected override Expression DoResolve (ResolveContext ec)
8269 public override void Emit (EmitContext ec)
8271 // nothing, as we only exist to not do anything.
8274 public override void EmitSideEffect (EmitContext ec)
8279 // This is just because we might want to reuse this bad boy
8280 // instead of creating gazillions of EmptyExpressions.
8281 // (CanImplicitConversion uses it)
8283 public void SetType (TypeSpec t)
8290 // Empty statement expression
8292 public sealed class EmptyExpressionStatement : ExpressionStatement
8294 public static readonly EmptyExpressionStatement Instance = new EmptyExpressionStatement ();
8296 private EmptyExpressionStatement ()
8298 loc = Location.Null;
8301 public override Expression CreateExpressionTree (ResolveContext ec)
8306 public override void EmitStatement (EmitContext ec)
8311 protected override Expression DoResolve (ResolveContext ec)
8313 eclass = ExprClass.Value;
8314 type = TypeManager.object_type;
8318 public override void Emit (EmitContext ec)
8324 public class UserCast : Expression {
8328 public UserCast (MethodSpec method, Expression source, Location l)
8330 this.method = method;
8331 this.source = source;
8332 type = method.ReturnType;
8336 public Expression Source {
8342 public override Expression CreateExpressionTree (ResolveContext ec)
8344 Arguments args = new Arguments (3);
8345 args.Add (new Argument (source.CreateExpressionTree (ec)));
8346 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
8347 args.Add (new Argument (new TypeOfMethod (method, loc)));
8348 return CreateExpressionFactoryCall (ec, "Convert", args);
8351 protected override Expression DoResolve (ResolveContext ec)
8353 ObsoleteAttribute oa = method.GetAttributeObsolete ();
8355 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
8357 eclass = ExprClass.Value;
8361 public override void Emit (EmitContext ec)
8364 ec.Emit (OpCodes.Call, method);
8367 public override string GetSignatureForError ()
8369 return TypeManager.CSharpSignature (method);
8372 public override SLE.Expression MakeExpression (BuilderContext ctx)
8374 return SLE.Expression.Convert (source.MakeExpression (ctx), type.GetMetaInfo (), (MethodInfo) method.GetMetaInfo ());
8379 // Holds additional type specifiers like ?, *, []
8381 public class ComposedTypeSpecifier
8383 public static readonly ComposedTypeSpecifier SingleDimension = new ComposedTypeSpecifier (1, Location.Null);
8385 public readonly int Dimension;
8386 public readonly Location Location;
8388 public ComposedTypeSpecifier (int specifier, Location loc)
8390 this.Dimension = specifier;
8391 this.Location = loc;
8395 public bool IsNullable {
8397 return Dimension == -1;
8401 public bool IsPointer {
8403 return Dimension == -2;
8407 public ComposedTypeSpecifier Next { get; set; }
8411 public static ComposedTypeSpecifier CreateArrayDimension (int dimension, Location loc)
8413 return new ComposedTypeSpecifier (dimension, loc);
8416 public static ComposedTypeSpecifier CreateNullable (Location loc)
8418 return new ComposedTypeSpecifier (-1, loc);
8421 public static ComposedTypeSpecifier CreatePointer (Location loc)
8423 return new ComposedTypeSpecifier (-2, loc);
8426 public string GetSignatureForError ()
8431 ArrayContainer.GetPostfixSignature (Dimension);
8433 return Next != null ? s + Next.GetSignatureForError () : s;
8438 // This class is used to "construct" the type during a typecast
8439 // operation. Since the Type.GetType class in .NET can parse
8440 // the type specification, we just use this to construct the type
8441 // one bit at a time.
8443 public class ComposedCast : TypeExpr {
8444 FullNamedExpression left;
8445 ComposedTypeSpecifier spec;
8447 public ComposedCast (FullNamedExpression left, ComposedTypeSpecifier spec)
8450 throw new ArgumentNullException ("spec");
8454 this.loc = spec.Location;
8457 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
8459 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec, false);
8464 eclass = ExprClass.Type;
8466 var single_spec = spec;
8468 if (single_spec.IsNullable) {
8469 lexpr = new Nullable.NullableType (lexpr, loc);
8470 lexpr = lexpr.ResolveAsTypeTerminal (ec, false);
8474 single_spec = single_spec.Next;
8475 } else if (single_spec.IsPointer) {
8476 if (!TypeManager.VerifyUnmanaged (ec.Compiler, type, loc))
8480 UnsafeError (ec.Compiler.Report, loc);
8483 type = PointerContainer.MakeType (type);
8484 single_spec = single_spec.Next;
8487 if (single_spec != null && single_spec.Dimension > 0) {
8488 if (TypeManager.IsSpecialType (type)) {
8489 ec.Compiler.Report.Error (611, loc, "Array elements cannot be of type `{0}'", type.GetSignatureForError ());
8490 } else if (type.IsStatic) {
8491 ec.Compiler.Report.SymbolRelatedToPreviousError (type);
8492 ec.Compiler.Report.Error (719, loc, "Array elements cannot be of static type `{0}'",
8493 type.GetSignatureForError ());
8495 MakeArray (single_spec);
8502 void MakeArray (ComposedTypeSpecifier spec)
8504 if (spec.Next != null)
8505 MakeArray (spec.Next);
8507 type = ArrayContainer.MakeType (type, spec.Dimension);
8510 public override string GetSignatureForError ()
8512 return left.GetSignatureForError () + spec.GetSignatureForError ();
8516 public class FixedBufferPtr : Expression {
8519 public FixedBufferPtr (Expression array, TypeSpec array_type, Location l)
8524 type = PointerContainer.MakeType (array_type);
8525 eclass = ExprClass.Value;
8528 public override Expression CreateExpressionTree (ResolveContext ec)
8530 Error_PointerInsideExpressionTree (ec);
8534 public override void Emit(EmitContext ec)
8539 protected override Expression DoResolve (ResolveContext ec)
8542 // We are born fully resolved
8550 // This class is used to represent the address of an array, used
8551 // only by the Fixed statement, this generates "&a [0]" construct
8552 // for fixed (char *pa = a)
8554 public class ArrayPtr : FixedBufferPtr {
8555 TypeSpec array_type;
8557 public ArrayPtr (Expression array, TypeSpec array_type, Location l):
8558 base (array, array_type, l)
8560 this.array_type = array_type;
8563 public override void Emit (EmitContext ec)
8568 ec.Emit (OpCodes.Ldelema, array_type);
8573 // Encapsulates a conversion rules required for array indexes
8575 public class ArrayIndexCast : TypeCast
8577 public ArrayIndexCast (Expression expr)
8578 : base (expr, TypeManager.int32_type)
8580 if (expr.Type == TypeManager.int32_type)
8581 throw new ArgumentException ("unnecessary array index conversion");
8584 public override Expression CreateExpressionTree (ResolveContext ec)
8586 using (ec.Set (ResolveContext.Options.CheckedScope)) {
8587 return base.CreateExpressionTree (ec);
8591 public override void Emit (EmitContext ec)
8595 var expr_type = child.Type;
8597 if (expr_type == TypeManager.uint32_type)
8598 ec.Emit (OpCodes.Conv_U);
8599 else if (expr_type == TypeManager.int64_type)
8600 ec.Emit (OpCodes.Conv_Ovf_I);
8601 else if (expr_type == TypeManager.uint64_type)
8602 ec.Emit (OpCodes.Conv_Ovf_I_Un);
8604 throw new InternalErrorException ("Cannot emit cast to unknown array element type", type);
8609 // Implements the `stackalloc' keyword
8611 public class StackAlloc : Expression {
8616 public StackAlloc (Expression type, Expression count, Location l)
8623 public override Expression CreateExpressionTree (ResolveContext ec)
8625 throw new NotSupportedException ("ET");
8628 protected override Expression DoResolve (ResolveContext ec)
8630 count = count.Resolve (ec);
8634 if (count.Type != TypeManager.uint32_type){
8635 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8640 Constant c = count as Constant;
8641 if (c != null && c.IsNegative) {
8642 ec.Report.Error (247, loc, "Cannot use a negative size with stackalloc");
8645 if (ec.HasAny (ResolveContext.Options.CatchScope | ResolveContext.Options.FinallyScope)) {
8646 ec.Report.Error (255, loc, "Cannot use stackalloc in finally or catch");
8649 TypeExpr texpr = t.ResolveAsTypeTerminal (ec, false);
8655 if (!TypeManager.VerifyUnmanaged (ec.Compiler, otype, loc))
8658 type = PointerContainer.MakeType (otype);
8659 eclass = ExprClass.Value;
8664 public override void Emit (EmitContext ec)
8666 int size = GetTypeSize (otype);
8671 ec.Emit (OpCodes.Sizeof, otype);
8675 ec.Emit (OpCodes.Mul_Ovf_Un);
8676 ec.Emit (OpCodes.Localloc);
8679 protected override void CloneTo (CloneContext clonectx, Expression t)
8681 StackAlloc target = (StackAlloc) t;
8682 target.count = count.Clone (clonectx);
8683 target.t = t.Clone (clonectx);
8688 // An object initializer expression
8690 public class ElementInitializer : Assign
8692 public readonly string Name;
8694 public ElementInitializer (string name, Expression initializer, Location loc)
8695 : base (null, initializer, loc)
8700 protected override void CloneTo (CloneContext clonectx, Expression t)
8702 ElementInitializer target = (ElementInitializer) t;
8703 target.source = source.Clone (clonectx);
8706 public override Expression CreateExpressionTree (ResolveContext ec)
8708 Arguments args = new Arguments (2);
8709 FieldExpr fe = target as FieldExpr;
8711 args.Add (new Argument (fe.CreateTypeOfExpression ()));
8713 args.Add (new Argument (((PropertyExpr)target).CreateSetterTypeOfExpression ()));
8715 args.Add (new Argument (source.CreateExpressionTree (ec)));
8716 return CreateExpressionFactoryCall (ec,
8717 source is CollectionOrObjectInitializers ? "ListBind" : "Bind",
8721 protected override Expression DoResolve (ResolveContext ec)
8724 return EmptyExpressionStatement.Instance;
8726 var t = ec.CurrentInitializerVariable.Type;
8728 var member = MemberLookup (ec, ec.CurrentType, t, Name, 0, false, loc);
8729 if (member == null) {
8730 member = Expression.MemberLookup (null, ec.CurrentType, t, Name, 0, false, loc);
8732 if (member != null) {
8733 // TODO: ec.Report.SymbolRelatedToPreviousError (member);
8734 ErrorIsInaccesible (ec, member.GetSignatureForError (), loc);
8739 if (member == null) {
8740 Error_TypeDoesNotContainDefinition (ec, loc, t, Name);
8744 if (!(member is PropertyExpr || member is FieldExpr)) {
8745 ec.Report.Error (1913, loc,
8746 "Member `{0}' cannot be initialized. An object initializer may only be used for fields, or properties",
8747 member.GetSignatureForError ());
8752 var me = member as MemberExpr;
8754 ec.Report.Error (1914, loc,
8755 "Static field or property `{0}' cannot be assigned in an object initializer",
8756 me.GetSignatureForError ());
8760 me.InstanceExpression = ec.CurrentInitializerVariable;
8762 if (source is CollectionOrObjectInitializers) {
8763 Expression previous = ec.CurrentInitializerVariable;
8764 ec.CurrentInitializerVariable = target;
8765 source = source.Resolve (ec);
8766 ec.CurrentInitializerVariable = previous;
8770 eclass = source.eclass;
8775 return base.DoResolve (ec);
8778 public override void EmitStatement (EmitContext ec)
8780 if (source is CollectionOrObjectInitializers)
8783 base.EmitStatement (ec);
8788 // A collection initializer expression
8790 class CollectionElementInitializer : Invocation
8792 public class ElementInitializerArgument : Argument
8794 public ElementInitializerArgument (Expression e)
8800 sealed class AddMemberAccess : MemberAccess
8802 public AddMemberAccess (Expression expr, Location loc)
8803 : base (expr, "Add", loc)
8807 protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
8809 if (TypeManager.HasElementType (type))
8812 base.Error_TypeDoesNotContainDefinition (ec, type, name);
8816 public CollectionElementInitializer (Expression argument)
8817 : base (null, new Arguments (1))
8819 base.arguments.Add (new ElementInitializerArgument (argument));
8820 this.loc = argument.Location;
8823 public CollectionElementInitializer (List<Expression> arguments, Location loc)
8824 : base (null, new Arguments (arguments.Count))
8826 foreach (Expression e in arguments)
8827 base.arguments.Add (new ElementInitializerArgument (e));
8832 public override Expression CreateExpressionTree (ResolveContext ec)
8834 Arguments args = new Arguments (2);
8835 args.Add (new Argument (mg.CreateExpressionTree (ec)));
8837 var expr_initializers = new ArrayInitializer (arguments.Count, loc);
8838 foreach (Argument a in arguments)
8839 expr_initializers.Add (a.CreateExpressionTree (ec));
8841 args.Add (new Argument (new ArrayCreation (
8842 CreateExpressionTypeExpression (ec, loc), expr_initializers, loc)));
8843 return CreateExpressionFactoryCall (ec, "ElementInit", args);
8846 protected override void CloneTo (CloneContext clonectx, Expression t)
8848 CollectionElementInitializer target = (CollectionElementInitializer) t;
8849 if (arguments != null)
8850 target.arguments = arguments.Clone (clonectx);
8853 protected override Expression DoResolve (ResolveContext ec)
8855 base.expr = new AddMemberAccess (ec.CurrentInitializerVariable, loc);
8857 return base.DoResolve (ec);
8862 // A block of object or collection initializers
8864 public class CollectionOrObjectInitializers : ExpressionStatement
8866 IList<Expression> initializers;
8867 bool is_collection_initialization;
8869 public static readonly CollectionOrObjectInitializers Empty =
8870 new CollectionOrObjectInitializers (Array.AsReadOnly (new Expression [0]), Location.Null);
8872 public CollectionOrObjectInitializers (IList<Expression> initializers, Location loc)
8874 this.initializers = initializers;
8878 public bool IsEmpty {
8880 return initializers.Count == 0;
8884 public bool IsCollectionInitializer {
8886 return is_collection_initialization;
8890 protected override void CloneTo (CloneContext clonectx, Expression target)
8892 CollectionOrObjectInitializers t = (CollectionOrObjectInitializers) target;
8894 t.initializers = new List<Expression> (initializers.Count);
8895 foreach (var e in initializers)
8896 t.initializers.Add (e.Clone (clonectx));
8899 public override Expression CreateExpressionTree (ResolveContext ec)
8901 var expr_initializers = new ArrayInitializer (initializers.Count, loc);
8902 foreach (Expression e in initializers) {
8903 Expression expr = e.CreateExpressionTree (ec);
8905 expr_initializers.Add (expr);
8908 return new ImplicitlyTypedArrayCreation (expr_initializers, loc);
8911 protected override Expression DoResolve (ResolveContext ec)
8913 List<string> element_names = null;
8914 for (int i = 0; i < initializers.Count; ++i) {
8915 Expression initializer = initializers [i];
8916 ElementInitializer element_initializer = initializer as ElementInitializer;
8919 if (element_initializer != null) {
8920 element_names = new List<string> (initializers.Count);
8921 element_names.Add (element_initializer.Name);
8922 } else if (initializer is CompletingExpression){
8923 initializer.Resolve (ec);
8924 throw new InternalErrorException ("This line should never be reached");
8926 if (!ec.CurrentInitializerVariable.Type.ImplementsInterface (TypeManager.ienumerable_type)) {
8927 ec.Report.Error (1922, loc, "A field or property `{0}' cannot be initialized with a collection " +
8928 "object initializer because type `{1}' does not implement `{2}' interface",
8929 ec.CurrentInitializerVariable.GetSignatureForError (),
8930 TypeManager.CSharpName (ec.CurrentInitializerVariable.Type),
8931 TypeManager.CSharpName (TypeManager.ienumerable_type));
8934 is_collection_initialization = true;
8937 if (is_collection_initialization != (element_initializer == null)) {
8938 ec.Report.Error (747, initializer.Location, "Inconsistent `{0}' member declaration",
8939 is_collection_initialization ? "collection initializer" : "object initializer");
8943 if (!is_collection_initialization) {
8944 if (element_names.Contains (element_initializer.Name)) {
8945 ec.Report.Error (1912, element_initializer.Location,
8946 "An object initializer includes more than one member `{0}' initialization",
8947 element_initializer.Name);
8949 element_names.Add (element_initializer.Name);
8954 Expression e = initializer.Resolve (ec);
8955 if (e == EmptyExpressionStatement.Instance)
8956 initializers.RemoveAt (i--);
8958 initializers [i] = e;
8961 type = ec.CurrentInitializerVariable.Type;
8962 if (is_collection_initialization) {
8963 if (TypeManager.HasElementType (type)) {
8964 ec.Report.Error (1925, loc, "Cannot initialize object of type `{0}' with a collection initializer",
8965 TypeManager.CSharpName (type));
8969 eclass = ExprClass.Variable;
8973 public override void Emit (EmitContext ec)
8978 public override void EmitStatement (EmitContext ec)
8980 foreach (ExpressionStatement e in initializers)
8981 e.EmitStatement (ec);
8986 // New expression with element/object initializers
8988 public class NewInitialize : New
8991 // This class serves as a proxy for variable initializer target instances.
8992 // A real variable is assigned later when we resolve left side of an
8995 sealed class InitializerTargetExpression : Expression, IMemoryLocation
8997 NewInitialize new_instance;
8999 public InitializerTargetExpression (NewInitialize newInstance)
9001 this.type = newInstance.type;
9002 this.loc = newInstance.loc;
9003 this.eclass = newInstance.eclass;
9004 this.new_instance = newInstance;
9007 public override Expression CreateExpressionTree (ResolveContext ec)
9009 // Should not be reached
9010 throw new NotSupportedException ("ET");
9013 protected override Expression DoResolve (ResolveContext ec)
9018 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
9023 public override void Emit (EmitContext ec)
9025 Expression e = (Expression) new_instance.instance;
9029 #region IMemoryLocation Members
9031 public void AddressOf (EmitContext ec, AddressOp mode)
9033 new_instance.instance.AddressOf (ec, mode);
9039 CollectionOrObjectInitializers initializers;
9040 IMemoryLocation instance;
9042 public NewInitialize (FullNamedExpression requested_type, Arguments arguments, CollectionOrObjectInitializers initializers, Location l)
9043 : base (requested_type, arguments, l)
9045 this.initializers = initializers;
9048 protected override IMemoryLocation EmitAddressOf (EmitContext ec, AddressOp Mode)
9050 instance = base.EmitAddressOf (ec, Mode);
9052 if (!initializers.IsEmpty)
9053 initializers.Emit (ec);
9058 protected override void CloneTo (CloneContext clonectx, Expression t)
9060 base.CloneTo (clonectx, t);
9062 NewInitialize target = (NewInitialize) t;
9063 target.initializers = (CollectionOrObjectInitializers) initializers.Clone (clonectx);
9066 public override Expression CreateExpressionTree (ResolveContext ec)
9068 Arguments args = new Arguments (2);
9069 args.Add (new Argument (base.CreateExpressionTree (ec)));
9070 if (!initializers.IsEmpty)
9071 args.Add (new Argument (initializers.CreateExpressionTree (ec)));
9073 return CreateExpressionFactoryCall (ec,
9074 initializers.IsCollectionInitializer ? "ListInit" : "MemberInit",
9078 protected override Expression DoResolve (ResolveContext ec)
9080 Expression e = base.DoResolve (ec);
9084 Expression previous = ec.CurrentInitializerVariable;
9085 ec.CurrentInitializerVariable = new InitializerTargetExpression (this);
9086 initializers.Resolve (ec);
9087 ec.CurrentInitializerVariable = previous;
9091 public override bool Emit (EmitContext ec, IMemoryLocation target)
9093 bool left_on_stack = base.Emit (ec, target);
9095 if (initializers.IsEmpty)
9096 return left_on_stack;
9098 LocalTemporary temp = target as LocalTemporary;
9100 if (!left_on_stack) {
9101 VariableReference vr = target as VariableReference;
9103 // FIXME: This still does not work correctly for pre-set variables
9104 if (vr != null && vr.IsRef)
9105 target.AddressOf (ec, AddressOp.Load);
9107 ((Expression) target).Emit (ec);
9108 left_on_stack = true;
9111 temp = new LocalTemporary (type);
9118 initializers.Emit (ec);
9120 if (left_on_stack) {
9125 return left_on_stack;
9128 public override bool HasInitializer {
9130 return !initializers.IsEmpty;
9135 public class NewAnonymousType : New
9137 static readonly AnonymousTypeParameter[] EmptyParameters = new AnonymousTypeParameter[0];
9139 List<AnonymousTypeParameter> parameters;
9140 readonly TypeContainer parent;
9141 AnonymousTypeClass anonymous_type;
9143 public NewAnonymousType (List<AnonymousTypeParameter> parameters, TypeContainer parent, Location loc)
9144 : base (null, null, loc)
9146 this.parameters = parameters;
9147 this.parent = parent;
9150 protected override void CloneTo (CloneContext clonectx, Expression target)
9152 if (parameters == null)
9155 NewAnonymousType t = (NewAnonymousType) target;
9156 t.parameters = new List<AnonymousTypeParameter> (parameters.Count);
9157 foreach (AnonymousTypeParameter atp in parameters)
9158 t.parameters.Add ((AnonymousTypeParameter) atp.Clone (clonectx));
9161 AnonymousTypeClass CreateAnonymousType (ResolveContext ec, IList<AnonymousTypeParameter> parameters)
9163 AnonymousTypeClass type = parent.Module.Compiled.GetAnonymousType (parameters);
9167 type = AnonymousTypeClass.Create (ec.Compiler, parent, parameters, loc);
9173 type.ResolveTypeParameters ();
9176 if (ec.Report.Errors == 0)
9179 parent.Module.Compiled.AddAnonymousType (type);
9183 public override Expression CreateExpressionTree (ResolveContext ec)
9185 if (parameters == null)
9186 return base.CreateExpressionTree (ec);
9188 var init = new ArrayInitializer (parameters.Count, loc);
9189 foreach (Property p in anonymous_type.Properties)
9190 init.Add (new TypeOfMethod (MemberCache.GetMember (type, p.Get.Spec), loc));
9192 var ctor_args = new ArrayInitializer (Arguments.Count, loc);
9193 foreach (Argument a in Arguments)
9194 ctor_args.Add (a.CreateExpressionTree (ec));
9196 Arguments args = new Arguments (3);
9197 args.Add (new Argument (new TypeOfMethod (method, loc)));
9198 args.Add (new Argument (new ArrayCreation (TypeManager.expression_type_expr, ctor_args, loc)));
9199 args.Add (new Argument (new ImplicitlyTypedArrayCreation (init, loc)));
9201 return CreateExpressionFactoryCall (ec, "New", args);
9204 protected override Expression DoResolve (ResolveContext ec)
9206 if (ec.HasSet (ResolveContext.Options.ConstantScope)) {
9207 ec.Report.Error (836, loc, "Anonymous types cannot be used in this expression");
9211 if (parameters == null) {
9212 anonymous_type = CreateAnonymousType (ec, EmptyParameters);
9213 RequestedType = new TypeExpression (anonymous_type.Definition, loc);
9214 return base.DoResolve (ec);
9218 Arguments = new Arguments (parameters.Count);
9219 TypeExpression [] t_args = new TypeExpression [parameters.Count];
9220 for (int i = 0; i < parameters.Count; ++i) {
9221 Expression e = ((AnonymousTypeParameter) parameters [i]).Resolve (ec);
9227 Arguments.Add (new Argument (e));
9228 t_args [i] = new TypeExpression (e.Type, e.Location);
9234 anonymous_type = CreateAnonymousType (ec, parameters);
9235 if (anonymous_type == null)
9238 RequestedType = new GenericTypeExpr (anonymous_type.Definition, new TypeArguments (t_args), loc);
9239 return base.DoResolve (ec);
9243 public class AnonymousTypeParameter : ShimExpression
9245 public readonly string Name;
9247 public AnonymousTypeParameter (Expression initializer, string name, Location loc)
9248 : base (initializer)
9254 public AnonymousTypeParameter (Parameter parameter)
9255 : base (new SimpleName (parameter.Name, parameter.Location))
9257 this.Name = parameter.Name;
9258 this.loc = parameter.Location;
9261 public override bool Equals (object o)
9263 AnonymousTypeParameter other = o as AnonymousTypeParameter;
9264 return other != null && Name == other.Name;
9267 public override int GetHashCode ()
9269 return Name.GetHashCode ();
9272 protected override Expression DoResolve (ResolveContext ec)
9274 Expression e = expr.Resolve (ec);
9278 if (e.eclass == ExprClass.MethodGroup) {
9279 Error_InvalidInitializer (ec, e.ExprClassName);
9284 if (type == TypeManager.void_type || type == TypeManager.null_type ||
9285 type == InternalType.AnonymousMethod || type.IsPointer) {
9286 Error_InvalidInitializer (ec, e.GetSignatureForError ());
9293 protected virtual void Error_InvalidInitializer (ResolveContext ec, string initializer)
9295 ec.Report.Error (828, loc, "An anonymous type property `{0}' cannot be initialized with `{1}'",