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 (t == InternalType.Dynamic) {
1346 ec.Report.Warning (1981, 3, loc,
1347 "Using `{0}' to test compatibility with `{1}' is identical to testing compatibility with `object'",
1348 OperatorName, t.GetSignatureForError ());
1351 if (TypeManager.IsStruct (d)) {
1352 if (Convert.ImplicitBoxingConversion (null, d, t) != null)
1353 return CreateConstantResult (ec, true);
1355 if (TypeManager.IsGenericParameter (d))
1356 return ResolveGenericParameter (ec, t, (TypeParameterSpec) d);
1358 if (TypeManager.ContainsGenericParameters (d))
1361 if (Convert.ImplicitReferenceConversionExists (expr, t) ||
1362 Convert.ExplicitReferenceConversionExists (d, t)) {
1368 return CreateConstantResult (ec, false);
1371 Expression ResolveGenericParameter (ResolveContext ec, TypeSpec d, TypeParameterSpec t)
1373 if (t.IsReferenceType) {
1374 if (TypeManager.IsStruct (d))
1375 return CreateConstantResult (ec, false);
1378 if (TypeManager.IsGenericParameter (expr.Type)) {
1379 if (t.IsValueType && expr.Type == t)
1380 return CreateConstantResult (ec, true);
1382 expr = new BoxedCast (expr, d);
1388 protected override string OperatorName {
1389 get { return "is"; }
1394 /// Implementation of the `as' operator.
1396 public class As : Probe {
1398 Expression resolved_type;
1400 public As (Expression expr, Expression probe_type, Location l)
1401 : base (expr, probe_type, l)
1405 public override Expression CreateExpressionTree (ResolveContext ec)
1407 Arguments args = Arguments.CreateForExpressionTree (ec, null,
1408 expr.CreateExpressionTree (ec),
1409 new TypeOf (probe_type_expr, loc));
1411 return CreateExpressionFactoryCall (ec, "TypeAs", args);
1414 public override void Emit (EmitContext ec)
1419 ec.Emit (OpCodes.Isinst, type);
1421 if (TypeManager.IsGenericParameter (type) || TypeManager.IsNullableType (type))
1422 ec.Emit (OpCodes.Unbox_Any, type);
1425 protected override Expression DoResolve (ResolveContext ec)
1427 if (resolved_type == null) {
1428 resolved_type = base.DoResolve (ec);
1430 if (resolved_type == null)
1434 type = probe_type_expr.Type;
1435 eclass = ExprClass.Value;
1436 TypeSpec etype = expr.Type;
1438 if (!TypeManager.IsReferenceType (type) && !TypeManager.IsNullableType (type)) {
1439 if (TypeManager.IsGenericParameter (type)) {
1440 ec.Report.Error (413, loc,
1441 "The `as' operator cannot be used with a non-reference type parameter `{0}'. Consider adding `class' or a reference type constraint",
1442 probe_type_expr.GetSignatureForError ());
1444 ec.Report.Error (77, loc,
1445 "The `as' operator cannot be used with a non-nullable value type `{0}'",
1446 TypeManager.CSharpName (type));
1451 if (expr.IsNull && TypeManager.IsNullableType (type)) {
1452 return Nullable.LiftedNull.CreateFromExpression (ec, this);
1455 // If the compile-time type of E is dynamic, unlike the cast operator the as operator is not dynamically bound
1456 if (etype == InternalType.Dynamic) {
1461 Expression e = Convert.ImplicitConversion (ec, expr, type, loc);
1467 if (Convert.ExplicitReferenceConversionExists (etype, type)){
1468 if (TypeManager.IsGenericParameter (etype))
1469 expr = new BoxedCast (expr, etype);
1475 if (TypeManager.ContainsGenericParameters (etype) ||
1476 TypeManager.ContainsGenericParameters (type)) {
1477 expr = new BoxedCast (expr, etype);
1482 ec.Report.Error (39, loc, "Cannot convert type `{0}' to `{1}' via a built-in conversion",
1483 TypeManager.CSharpName (etype), TypeManager.CSharpName (type));
1488 protected override string OperatorName {
1489 get { return "as"; }
1494 // This represents a typecast in the source language.
1496 public class Cast : ShimExpression {
1497 Expression target_type;
1499 public Cast (Expression cast_type, Expression expr, Location loc)
1502 this.target_type = cast_type;
1506 public Expression TargetType {
1507 get { return target_type; }
1510 protected override Expression DoResolve (ResolveContext ec)
1512 expr = expr.Resolve (ec);
1516 TypeExpr target = target_type.ResolveAsTypeTerminal (ec, false);
1522 if (type.IsStatic) {
1523 ec.Report.Error (716, loc, "Cannot convert to static type `{0}'", TypeManager.CSharpName (type));
1527 eclass = ExprClass.Value;
1529 Constant c = expr as Constant;
1531 c = c.TryReduce (ec, type, loc);
1536 if (type.IsPointer && !ec.IsUnsafe) {
1537 UnsafeError (ec, loc);
1540 var res = Convert.ExplicitConversion (ec, expr, type, loc);
1542 return EmptyCast.Create (res, type);
1547 protected override void CloneTo (CloneContext clonectx, Expression t)
1549 Cast target = (Cast) t;
1551 target.target_type = target_type.Clone (clonectx);
1552 target.expr = expr.Clone (clonectx);
1556 public class ImplicitCast : ShimExpression
1560 public ImplicitCast (Expression expr, TypeSpec target, bool arrayAccess)
1563 this.loc = expr.Location;
1565 this.arrayAccess = arrayAccess;
1568 protected override Expression DoResolve (ResolveContext ec)
1570 expr = expr.Resolve (ec);
1575 expr = ConvertExpressionToArrayIndex (ec, expr);
1577 expr = Convert.ImplicitConversionRequired (ec, expr, type, loc);
1584 // C# 2.0 Default value expression
1586 public class DefaultValueExpression : Expression
1590 public DefaultValueExpression (Expression expr, Location loc)
1596 public override Expression CreateExpressionTree (ResolveContext ec)
1598 Arguments args = new Arguments (2);
1599 args.Add (new Argument (this));
1600 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
1601 return CreateExpressionFactoryCall (ec, "Constant", args);
1604 protected override Expression DoResolve (ResolveContext ec)
1606 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
1612 if (type.IsStatic) {
1613 ec.Report.Error (-244, loc, "The `default value' operator cannot be applied to an operand of a static type");
1617 return new NullLiteral (Location).ConvertImplicitly (ec, type);
1619 if (TypeManager.IsReferenceType (type))
1620 return new NullConstant (type, loc);
1622 Constant c = New.Constantify (type);
1624 return c.Resolve (ec);
1626 eclass = ExprClass.Variable;
1630 public override void Emit (EmitContext ec)
1632 LocalTemporary temp_storage = new LocalTemporary(type);
1634 temp_storage.AddressOf(ec, AddressOp.LoadStore);
1635 ec.Emit(OpCodes.Initobj, type);
1636 temp_storage.Emit(ec);
1639 protected override void CloneTo (CloneContext clonectx, Expression t)
1641 DefaultValueExpression target = (DefaultValueExpression) t;
1643 target.expr = expr.Clone (clonectx);
1648 /// Binary operators
1650 public class Binary : Expression, IDynamicBinder
1652 protected class PredefinedOperator {
1653 protected readonly TypeSpec left;
1654 protected readonly TypeSpec right;
1655 public readonly Operator OperatorsMask;
1656 public TypeSpec ReturnType;
1658 public PredefinedOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
1659 : this (ltype, rtype, op_mask, ltype)
1663 public PredefinedOperator (TypeSpec type, Operator op_mask, TypeSpec return_type)
1664 : this (type, type, op_mask, return_type)
1668 public PredefinedOperator (TypeSpec type, Operator op_mask)
1669 : this (type, type, op_mask, type)
1673 public PredefinedOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask, TypeSpec return_type)
1675 if ((op_mask & Operator.ValuesOnlyMask) != 0)
1676 throw new InternalErrorException ("Only masked values can be used");
1680 this.OperatorsMask = op_mask;
1681 this.ReturnType = return_type;
1684 public virtual Expression ConvertResult (ResolveContext ec, Binary b)
1686 b.type = ReturnType;
1688 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1689 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
1692 // A user operators does not support multiple user conversions, but decimal type
1693 // is considered to be predefined type therefore we apply predefined operators rules
1694 // and then look for decimal user-operator implementation
1696 if (left == TypeManager.decimal_type)
1697 return b.ResolveUserOperator (ec, b.left.Type, b.right.Type);
1699 var c = b.right as Constant;
1701 if (c.IsDefaultValue && (b.oper == Operator.Addition || b.oper == Operator.BitwiseOr || b.oper == Operator.Subtraction))
1702 return ReducedExpression.Create (b.left, b).Resolve (ec);
1703 if ((b.oper == Operator.Multiply || b.oper == Operator.Division) && c.IsOneInteger)
1704 return ReducedExpression.Create (b.left, b).Resolve (ec);
1708 c = b.left as Constant;
1710 if (c.IsDefaultValue && (b.oper == Operator.Addition || b.oper == Operator.BitwiseOr))
1711 return ReducedExpression.Create (b.right, b).Resolve (ec);
1712 if (b.oper == Operator.Multiply && c.IsOneInteger)
1713 return ReducedExpression.Create (b.right, b).Resolve (ec);
1720 public bool IsPrimitiveApplicable (TypeSpec ltype, TypeSpec rtype)
1723 // We are dealing with primitive types only
1725 return left == ltype && ltype == rtype;
1728 public virtual bool IsApplicable (ResolveContext ec, Expression lexpr, Expression rexpr)
1731 if (left == lexpr.Type && right == rexpr.Type)
1734 return Convert.ImplicitConversionExists (ec, lexpr, left) &&
1735 Convert.ImplicitConversionExists (ec, rexpr, right);
1738 public PredefinedOperator ResolveBetterOperator (ResolveContext ec, PredefinedOperator best_operator)
1741 if (left != null && best_operator.left != null) {
1742 result = OverloadResolver.BetterTypeConversion (ec, best_operator.left, left);
1746 // When second argument is same as the first one, the result is same
1748 if (right != null && (left != right || best_operator.left != best_operator.right)) {
1749 result |= OverloadResolver.BetterTypeConversion (ec, best_operator.right, right);
1752 if (result == 0 || result > 2)
1755 return result == 1 ? best_operator : this;
1759 class PredefinedStringOperator : PredefinedOperator {
1760 public PredefinedStringOperator (TypeSpec type, Operator op_mask)
1761 : base (type, op_mask, type)
1763 ReturnType = TypeManager.string_type;
1766 public PredefinedStringOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
1767 : base (ltype, rtype, op_mask)
1769 ReturnType = TypeManager.string_type;
1772 public override Expression ConvertResult (ResolveContext ec, Binary b)
1775 // Use original expression for nullable arguments
1777 Nullable.Unwrap unwrap = b.left as Nullable.Unwrap;
1779 b.left = unwrap.Original;
1781 unwrap = b.right as Nullable.Unwrap;
1783 b.right = unwrap.Original;
1785 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1786 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
1789 // Start a new concat expression using converted expression
1791 return StringConcat.Create (ec, b.left, b.right, b.loc);
1795 class PredefinedShiftOperator : PredefinedOperator {
1796 public PredefinedShiftOperator (TypeSpec ltype, Operator op_mask) :
1797 base (ltype, TypeManager.int32_type, op_mask)
1801 public override Expression ConvertResult (ResolveContext ec, Binary b)
1803 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1805 Expression expr_tree_expr = Convert.ImplicitConversion (ec, b.right, TypeManager.int32_type, b.right.Location);
1807 int right_mask = left == TypeManager.int32_type || left == TypeManager.uint32_type ? 0x1f : 0x3f;
1810 // b = b.left >> b.right & (0x1f|0x3f)
1812 b.right = new Binary (Operator.BitwiseAnd,
1813 b.right, new IntConstant (right_mask, b.right.Location), b.loc).Resolve (ec);
1816 // Expression tree representation does not use & mask
1818 b.right = ReducedExpression.Create (b.right, expr_tree_expr).Resolve (ec);
1819 b.type = ReturnType;
1822 // Optimize shift by 0
1824 var c = b.right as Constant;
1825 if (c != null && c.IsDefaultValue)
1826 return ReducedExpression.Create (b.left, b).Resolve (ec);
1832 class PredefinedEqualityOperator : PredefinedOperator
1834 MethodSpec equal_method, inequal_method;
1836 public PredefinedEqualityOperator (TypeSpec arg, TypeSpec retType)
1837 : base (arg, arg, Operator.EqualityMask, retType)
1841 public override Expression ConvertResult (ResolveContext ec, Binary b)
1843 b.type = ReturnType;
1845 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1846 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
1848 Arguments args = new Arguments (2);
1849 args.Add (new Argument (b.left));
1850 args.Add (new Argument (b.right));
1853 if (b.oper == Operator.Equality) {
1854 if (equal_method == null) {
1855 equal_method = TypeManager.GetPredefinedMethod (left,
1856 new MemberFilter (CSharp.Operator.GetMetadataName (CSharp.Operator.OpType.Equality), 0, MemberKind.Operator, null, ReturnType), b.loc);
1859 method = equal_method;
1861 if (inequal_method == null) {
1862 inequal_method = TypeManager.GetPredefinedMethod (left,
1863 new MemberFilter (CSharp.Operator.GetMetadataName (CSharp.Operator.OpType.Inequality), 0, MemberKind.Operator, null, ReturnType), b.loc);
1866 method = inequal_method;
1869 return new UserOperatorCall (method, args, b.CreateExpressionTree, b.loc);
1873 class PredefinedPointerOperator : PredefinedOperator
1875 public PredefinedPointerOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
1876 : base (ltype, rtype, op_mask)
1880 public PredefinedPointerOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask, TypeSpec retType)
1881 : base (ltype, rtype, op_mask, retType)
1885 public PredefinedPointerOperator (TypeSpec type, Operator op_mask, TypeSpec return_type)
1886 : base (type, op_mask, return_type)
1890 public override bool IsApplicable (ResolveContext ec, Expression lexpr, Expression rexpr)
1893 if (!lexpr.Type.IsPointer)
1896 if (!Convert.ImplicitConversionExists (ec, lexpr, left))
1900 if (right == null) {
1901 if (!rexpr.Type.IsPointer)
1904 if (!Convert.ImplicitConversionExists (ec, rexpr, right))
1911 public override Expression ConvertResult (ResolveContext ec, Binary b)
1914 b.left = EmptyCast.Create (b.left, left);
1915 } else if (right != null) {
1916 b.right = EmptyCast.Create (b.right, right);
1919 TypeSpec r_type = ReturnType;
1920 Expression left_arg, right_arg;
1921 if (r_type == null) {
1924 right_arg = b.right;
1925 r_type = b.left.Type;
1929 r_type = b.right.Type;
1933 right_arg = b.right;
1936 return new PointerArithmetic (b.oper, left_arg, right_arg, r_type, b.loc).Resolve (ec);
1941 public enum Operator {
1942 Multiply = 0 | ArithmeticMask,
1943 Division = 1 | ArithmeticMask,
1944 Modulus = 2 | ArithmeticMask,
1945 Addition = 3 | ArithmeticMask | AdditionMask,
1946 Subtraction = 4 | ArithmeticMask | SubtractionMask,
1948 LeftShift = 5 | ShiftMask,
1949 RightShift = 6 | ShiftMask,
1951 LessThan = 7 | ComparisonMask | RelationalMask,
1952 GreaterThan = 8 | ComparisonMask | RelationalMask,
1953 LessThanOrEqual = 9 | ComparisonMask | RelationalMask,
1954 GreaterThanOrEqual = 10 | ComparisonMask | RelationalMask,
1955 Equality = 11 | ComparisonMask | EqualityMask,
1956 Inequality = 12 | ComparisonMask | EqualityMask,
1958 BitwiseAnd = 13 | BitwiseMask,
1959 ExclusiveOr = 14 | BitwiseMask,
1960 BitwiseOr = 15 | BitwiseMask,
1962 LogicalAnd = 16 | LogicalMask,
1963 LogicalOr = 17 | LogicalMask,
1968 ValuesOnlyMask = ArithmeticMask - 1,
1969 ArithmeticMask = 1 << 5,
1971 ComparisonMask = 1 << 7,
1972 EqualityMask = 1 << 8,
1973 BitwiseMask = 1 << 9,
1974 LogicalMask = 1 << 10,
1975 AdditionMask = 1 << 11,
1976 SubtractionMask = 1 << 12,
1977 RelationalMask = 1 << 13
1980 readonly Operator oper;
1981 protected Expression left, right;
1982 readonly bool is_compound;
1983 Expression enum_conversion;
1985 static PredefinedOperator[] standard_operators;
1986 static PredefinedOperator[] equality_operators;
1987 static PredefinedOperator[] pointer_operators;
1989 public Binary (Operator oper, Expression left, Expression right, bool isCompound, Location loc)
1990 : this (oper, left, right, loc)
1992 this.is_compound = isCompound;
1995 public Binary (Operator oper, Expression left, Expression right, Location loc)
2003 public Operator Oper {
2010 /// Returns a stringified representation of the Operator
2012 string OperName (Operator oper)
2016 case Operator.Multiply:
2019 case Operator.Division:
2022 case Operator.Modulus:
2025 case Operator.Addition:
2028 case Operator.Subtraction:
2031 case Operator.LeftShift:
2034 case Operator.RightShift:
2037 case Operator.LessThan:
2040 case Operator.GreaterThan:
2043 case Operator.LessThanOrEqual:
2046 case Operator.GreaterThanOrEqual:
2049 case Operator.Equality:
2052 case Operator.Inequality:
2055 case Operator.BitwiseAnd:
2058 case Operator.BitwiseOr:
2061 case Operator.ExclusiveOr:
2064 case Operator.LogicalOr:
2067 case Operator.LogicalAnd:
2071 s = oper.ToString ();
2081 public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, Operator oper, Location loc)
2083 new Binary (oper, left, right, loc).Error_OperatorCannotBeApplied (ec, left, right);
2086 public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, string oper, Location loc)
2089 l = TypeManager.CSharpName (left.Type);
2090 r = TypeManager.CSharpName (right.Type);
2092 ec.Report.Error (19, loc, "Operator `{0}' cannot be applied to operands of type `{1}' and `{2}'",
2096 protected void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right)
2098 Error_OperatorCannotBeApplied (ec, left, right, OperName (oper), loc);
2102 // Converts operator to System.Linq.Expressions.ExpressionType enum name
2104 string GetOperatorExpressionTypeName ()
2107 case Operator.Addition:
2108 return is_compound ? "AddAssign" : "Add";
2109 case Operator.BitwiseAnd:
2110 return is_compound ? "AndAssign" : "And";
2111 case Operator.BitwiseOr:
2112 return is_compound ? "OrAssign" : "Or";
2113 case Operator.Division:
2114 return is_compound ? "DivideAssign" : "Divide";
2115 case Operator.ExclusiveOr:
2116 return is_compound ? "ExclusiveOrAssign" : "ExclusiveOr";
2117 case Operator.Equality:
2119 case Operator.GreaterThan:
2120 return "GreaterThan";
2121 case Operator.GreaterThanOrEqual:
2122 return "GreaterThanOrEqual";
2123 case Operator.Inequality:
2125 case Operator.LeftShift:
2126 return is_compound ? "LeftShiftAssign" : "LeftShift";
2127 case Operator.LessThan:
2129 case Operator.LessThanOrEqual:
2130 return "LessThanOrEqual";
2131 case Operator.LogicalAnd:
2133 case Operator.LogicalOr:
2135 case Operator.Modulus:
2136 return is_compound ? "ModuloAssign" : "Modulo";
2137 case Operator.Multiply:
2138 return is_compound ? "MultiplyAssign" : "Multiply";
2139 case Operator.RightShift:
2140 return is_compound ? "RightShiftAssign" : "RightShift";
2141 case Operator.Subtraction:
2142 return is_compound ? "SubtractAssign" : "Subtract";
2144 throw new NotImplementedException ("Unknown expression type operator " + oper.ToString ());
2148 static CSharp.Operator.OpType ConvertBinaryToUserOperator (Operator op)
2151 case Operator.Addition:
2152 return CSharp.Operator.OpType.Addition;
2153 case Operator.BitwiseAnd:
2154 case Operator.LogicalAnd:
2155 return CSharp.Operator.OpType.BitwiseAnd;
2156 case Operator.BitwiseOr:
2157 case Operator.LogicalOr:
2158 return CSharp.Operator.OpType.BitwiseOr;
2159 case Operator.Division:
2160 return CSharp.Operator.OpType.Division;
2161 case Operator.Equality:
2162 return CSharp.Operator.OpType.Equality;
2163 case Operator.ExclusiveOr:
2164 return CSharp.Operator.OpType.ExclusiveOr;
2165 case Operator.GreaterThan:
2166 return CSharp.Operator.OpType.GreaterThan;
2167 case Operator.GreaterThanOrEqual:
2168 return CSharp.Operator.OpType.GreaterThanOrEqual;
2169 case Operator.Inequality:
2170 return CSharp.Operator.OpType.Inequality;
2171 case Operator.LeftShift:
2172 return CSharp.Operator.OpType.LeftShift;
2173 case Operator.LessThan:
2174 return CSharp.Operator.OpType.LessThan;
2175 case Operator.LessThanOrEqual:
2176 return CSharp.Operator.OpType.LessThanOrEqual;
2177 case Operator.Modulus:
2178 return CSharp.Operator.OpType.Modulus;
2179 case Operator.Multiply:
2180 return CSharp.Operator.OpType.Multiply;
2181 case Operator.RightShift:
2182 return CSharp.Operator.OpType.RightShift;
2183 case Operator.Subtraction:
2184 return CSharp.Operator.OpType.Subtraction;
2186 throw new InternalErrorException (op.ToString ());
2190 public static void EmitOperatorOpcode (EmitContext ec, Operator oper, TypeSpec l)
2195 case Operator.Multiply:
2196 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2197 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2198 opcode = OpCodes.Mul_Ovf;
2199 else if (!IsFloat (l))
2200 opcode = OpCodes.Mul_Ovf_Un;
2202 opcode = OpCodes.Mul;
2204 opcode = OpCodes.Mul;
2208 case Operator.Division:
2210 opcode = OpCodes.Div_Un;
2212 opcode = OpCodes.Div;
2215 case Operator.Modulus:
2217 opcode = OpCodes.Rem_Un;
2219 opcode = OpCodes.Rem;
2222 case Operator.Addition:
2223 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2224 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2225 opcode = OpCodes.Add_Ovf;
2226 else if (!IsFloat (l))
2227 opcode = OpCodes.Add_Ovf_Un;
2229 opcode = OpCodes.Add;
2231 opcode = OpCodes.Add;
2234 case Operator.Subtraction:
2235 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2236 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2237 opcode = OpCodes.Sub_Ovf;
2238 else if (!IsFloat (l))
2239 opcode = OpCodes.Sub_Ovf_Un;
2241 opcode = OpCodes.Sub;
2243 opcode = OpCodes.Sub;
2246 case Operator.RightShift:
2248 opcode = OpCodes.Shr_Un;
2250 opcode = OpCodes.Shr;
2253 case Operator.LeftShift:
2254 opcode = OpCodes.Shl;
2257 case Operator.Equality:
2258 opcode = OpCodes.Ceq;
2261 case Operator.Inequality:
2262 ec.Emit (OpCodes.Ceq);
2263 ec.Emit (OpCodes.Ldc_I4_0);
2265 opcode = OpCodes.Ceq;
2268 case Operator.LessThan:
2270 opcode = OpCodes.Clt_Un;
2272 opcode = OpCodes.Clt;
2275 case Operator.GreaterThan:
2277 opcode = OpCodes.Cgt_Un;
2279 opcode = OpCodes.Cgt;
2282 case Operator.LessThanOrEqual:
2283 if (IsUnsigned (l) || IsFloat (l))
2284 ec.Emit (OpCodes.Cgt_Un);
2286 ec.Emit (OpCodes.Cgt);
2287 ec.Emit (OpCodes.Ldc_I4_0);
2289 opcode = OpCodes.Ceq;
2292 case Operator.GreaterThanOrEqual:
2293 if (IsUnsigned (l) || IsFloat (l))
2294 ec.Emit (OpCodes.Clt_Un);
2296 ec.Emit (OpCodes.Clt);
2298 ec.Emit (OpCodes.Ldc_I4_0);
2300 opcode = OpCodes.Ceq;
2303 case Operator.BitwiseOr:
2304 opcode = OpCodes.Or;
2307 case Operator.BitwiseAnd:
2308 opcode = OpCodes.And;
2311 case Operator.ExclusiveOr:
2312 opcode = OpCodes.Xor;
2316 throw new InternalErrorException (oper.ToString ());
2322 static bool IsUnsigned (TypeSpec t)
2327 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2328 t == TypeManager.ushort_type || t == TypeManager.byte_type);
2331 static bool IsFloat (TypeSpec t)
2333 return t == TypeManager.float_type || t == TypeManager.double_type;
2336 public static void Reset ()
2338 equality_operators = pointer_operators = standard_operators = null;
2341 Expression ResolveOperator (ResolveContext ec)
2343 TypeSpec l = left.Type;
2344 TypeSpec r = right.Type;
2346 bool primitives_only = false;
2348 if (standard_operators == null)
2349 CreateStandardOperatorsTable ();
2352 // Handles predefined primitive types
2354 if (TypeManager.IsPrimitiveType (l) && TypeManager.IsPrimitiveType (r)) {
2355 if ((oper & Operator.ShiftMask) == 0) {
2356 if (l != TypeManager.bool_type && !DoBinaryOperatorPromotion (ec))
2359 primitives_only = true;
2363 if (l.IsPointer || r.IsPointer)
2364 return ResolveOperatorPointer (ec, l, r);
2367 bool lenum = TypeManager.IsEnumType (l);
2368 bool renum = TypeManager.IsEnumType (r);
2369 if (lenum || renum) {
2370 expr = ResolveOperatorEnum (ec, lenum, renum, l, r);
2372 // TODO: Can this be ambiguous
2378 if ((oper == Operator.Addition || oper == Operator.Subtraction) && (l.IsDelegate || r.IsDelegate)) {
2380 expr = ResolveOperatorDelegate (ec, l, r);
2382 // TODO: Can this be ambiguous
2388 expr = ResolveUserOperator (ec, l, r);
2392 // Predefined reference types equality
2393 if ((oper & Operator.EqualityMask) != 0) {
2394 expr = ResolveOperatorEquality (ec, l, r);
2400 return ResolveOperatorPredefined (ec, standard_operators, primitives_only, null);
2403 // at least one of 'left' or 'right' is an enumeration constant (EnumConstant or SideEffectConstant or ...)
2404 // if 'left' is not an enumeration constant, create one from the type of 'right'
2405 Constant EnumLiftUp (ResolveContext ec, Constant left, Constant right, Location loc)
2408 case Operator.BitwiseOr:
2409 case Operator.BitwiseAnd:
2410 case Operator.ExclusiveOr:
2411 case Operator.Equality:
2412 case Operator.Inequality:
2413 case Operator.LessThan:
2414 case Operator.LessThanOrEqual:
2415 case Operator.GreaterThan:
2416 case Operator.GreaterThanOrEqual:
2417 if (TypeManager.IsEnumType (left.Type))
2420 if (left.IsZeroInteger)
2421 return left.TryReduce (ec, right.Type, loc);
2425 case Operator.Addition:
2426 case Operator.Subtraction:
2429 case Operator.Multiply:
2430 case Operator.Division:
2431 case Operator.Modulus:
2432 case Operator.LeftShift:
2433 case Operator.RightShift:
2434 if (TypeManager.IsEnumType (right.Type) || TypeManager.IsEnumType (left.Type))
2438 Error_OperatorCannotBeApplied (ec, this.left, this.right);
2443 // The `|' operator used on types which were extended is dangerous
2445 void CheckBitwiseOrOnSignExtended (ResolveContext ec)
2447 OpcodeCast lcast = left as OpcodeCast;
2448 if (lcast != null) {
2449 if (IsUnsigned (lcast.UnderlyingType))
2453 OpcodeCast rcast = right as OpcodeCast;
2454 if (rcast != null) {
2455 if (IsUnsigned (rcast.UnderlyingType))
2459 if (lcast == null && rcast == null)
2462 // FIXME: consider constants
2464 ec.Report.Warning (675, 3, loc,
2465 "The operator `|' used on the sign-extended type `{0}'. Consider casting to a smaller unsigned type first",
2466 TypeManager.CSharpName (lcast != null ? lcast.UnderlyingType : rcast.UnderlyingType));
2469 static void CreatePointerOperatorsTable ()
2471 var temp = new List<PredefinedPointerOperator> ();
2474 // Pointer arithmetic:
2476 // T* operator + (T* x, int y); T* operator - (T* x, int y);
2477 // T* operator + (T* x, uint y); T* operator - (T* x, uint y);
2478 // T* operator + (T* x, long y); T* operator - (T* x, long y);
2479 // T* operator + (T* x, ulong y); T* operator - (T* x, ulong y);
2481 temp.Add (new PredefinedPointerOperator (null, TypeManager.int32_type, Operator.AdditionMask | Operator.SubtractionMask));
2482 temp.Add (new PredefinedPointerOperator (null, TypeManager.uint32_type, Operator.AdditionMask | Operator.SubtractionMask));
2483 temp.Add (new PredefinedPointerOperator (null, TypeManager.int64_type, Operator.AdditionMask | Operator.SubtractionMask));
2484 temp.Add (new PredefinedPointerOperator (null, TypeManager.uint64_type, Operator.AdditionMask | Operator.SubtractionMask));
2487 // T* operator + (int y, T* x);
2488 // T* operator + (uint y, T *x);
2489 // T* operator + (long y, T *x);
2490 // T* operator + (ulong y, T *x);
2492 temp.Add (new PredefinedPointerOperator (TypeManager.int32_type, null, Operator.AdditionMask, null));
2493 temp.Add (new PredefinedPointerOperator (TypeManager.uint32_type, null, Operator.AdditionMask, null));
2494 temp.Add (new PredefinedPointerOperator (TypeManager.int64_type, null, Operator.AdditionMask, null));
2495 temp.Add (new PredefinedPointerOperator (TypeManager.uint64_type, null, Operator.AdditionMask, null));
2498 // long operator - (T* x, T *y)
2500 temp.Add (new PredefinedPointerOperator (null, Operator.SubtractionMask, TypeManager.int64_type));
2502 pointer_operators = temp.ToArray ();
2505 static void CreateStandardOperatorsTable ()
2507 var temp = new List<PredefinedOperator> ();
2508 TypeSpec bool_type = TypeManager.bool_type;
2510 temp.Add (new PredefinedOperator (TypeManager.int32_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2511 temp.Add (new PredefinedOperator (TypeManager.uint32_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2512 temp.Add (new PredefinedOperator (TypeManager.int64_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2513 temp.Add (new PredefinedOperator (TypeManager.uint64_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2514 temp.Add (new PredefinedOperator (TypeManager.float_type, Operator.ArithmeticMask));
2515 temp.Add (new PredefinedOperator (TypeManager.double_type, Operator.ArithmeticMask));
2516 temp.Add (new PredefinedOperator (TypeManager.decimal_type, Operator.ArithmeticMask));
2518 temp.Add (new PredefinedOperator (TypeManager.int32_type, Operator.ComparisonMask, bool_type));
2519 temp.Add (new PredefinedOperator (TypeManager.uint32_type, Operator.ComparisonMask, bool_type));
2520 temp.Add (new PredefinedOperator (TypeManager.int64_type, Operator.ComparisonMask, bool_type));
2521 temp.Add (new PredefinedOperator (TypeManager.uint64_type, Operator.ComparisonMask, bool_type));
2522 temp.Add (new PredefinedOperator (TypeManager.float_type, Operator.ComparisonMask, bool_type));
2523 temp.Add (new PredefinedOperator (TypeManager.double_type, Operator.ComparisonMask, bool_type));
2524 temp.Add (new PredefinedOperator (TypeManager.decimal_type, Operator.ComparisonMask, bool_type));
2526 temp.Add (new PredefinedStringOperator (TypeManager.string_type, Operator.AdditionMask));
2527 temp.Add (new PredefinedStringOperator (TypeManager.string_type, TypeManager.object_type, Operator.AdditionMask));
2528 temp.Add (new PredefinedStringOperator (TypeManager.object_type, TypeManager.string_type, Operator.AdditionMask));
2530 temp.Add (new PredefinedOperator (bool_type,
2531 Operator.BitwiseMask | Operator.LogicalMask | Operator.EqualityMask, bool_type));
2533 temp.Add (new PredefinedShiftOperator (TypeManager.int32_type, Operator.ShiftMask));
2534 temp.Add (new PredefinedShiftOperator (TypeManager.uint32_type, Operator.ShiftMask));
2535 temp.Add (new PredefinedShiftOperator (TypeManager.int64_type, Operator.ShiftMask));
2536 temp.Add (new PredefinedShiftOperator (TypeManager.uint64_type, Operator.ShiftMask));
2538 standard_operators = temp.ToArray ();
2540 var equality = new List<PredefinedOperator> () {
2541 new PredefinedEqualityOperator (TypeManager.string_type, bool_type),
2542 new PredefinedEqualityOperator (TypeManager.delegate_type, bool_type),
2543 new PredefinedOperator (bool_type, Operator.EqualityMask, bool_type)
2546 equality_operators = equality.ToArray ();
2550 // Rules used during binary numeric promotion
2552 static bool DoNumericPromotion (ResolveContext rc, ref Expression prim_expr, ref Expression second_expr, TypeSpec type)
2557 Constant c = prim_expr as Constant;
2559 temp = c.ConvertImplicitly (rc, type);
2566 if (type == TypeManager.uint32_type) {
2567 etype = prim_expr.Type;
2568 if (etype == TypeManager.int32_type || etype == TypeManager.short_type || etype == TypeManager.sbyte_type) {
2569 type = TypeManager.int64_type;
2571 if (type != second_expr.Type) {
2572 c = second_expr as Constant;
2574 temp = c.ConvertImplicitly (rc, type);
2576 temp = Convert.ImplicitNumericConversion (second_expr, type);
2582 } else if (type == TypeManager.uint64_type) {
2584 // A compile-time error occurs if the other operand is of type sbyte, short, int, or long
2586 if (type == TypeManager.int32_type || type == TypeManager.int64_type ||
2587 type == TypeManager.short_type || type == TypeManager.sbyte_type)
2591 temp = Convert.ImplicitNumericConversion (prim_expr, type);
2600 // 7.2.6.2 Binary numeric promotions
2602 public bool DoBinaryOperatorPromotion (ResolveContext ec)
2604 TypeSpec ltype = left.Type;
2605 TypeSpec rtype = right.Type;
2608 foreach (TypeSpec t in ConstantFold.BinaryPromotionsTypes) {
2610 return t == rtype || DoNumericPromotion (ec, ref right, ref left, t);
2613 return t == ltype || DoNumericPromotion (ec, ref left, ref right, t);
2616 TypeSpec int32 = TypeManager.int32_type;
2617 if (ltype != int32) {
2618 Constant c = left as Constant;
2620 temp = c.ConvertImplicitly (ec, int32);
2622 temp = Convert.ImplicitNumericConversion (left, int32);
2629 if (rtype != int32) {
2630 Constant c = right as Constant;
2632 temp = c.ConvertImplicitly (ec, int32);
2634 temp = Convert.ImplicitNumericConversion (right, int32);
2644 protected override Expression DoResolve (ResolveContext ec)
2649 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2650 left = ((ParenthesizedExpression) left).Expr;
2651 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2655 if (left.eclass == ExprClass.Type) {
2656 ec.Report.Error (75, loc, "To cast a negative value, you must enclose the value in parentheses");
2660 left = left.Resolve (ec);
2665 Constant lc = left as Constant;
2667 if (lc != null && lc.Type == TypeManager.bool_type &&
2668 ((oper == Operator.LogicalAnd && lc.IsDefaultValue) ||
2669 (oper == Operator.LogicalOr && !lc.IsDefaultValue))) {
2671 // FIXME: resolve right expression as unreachable
2672 // right.Resolve (ec);
2674 ec.Report.Warning (429, 4, loc, "Unreachable expression code detected");
2678 right = right.Resolve (ec);
2682 eclass = ExprClass.Value;
2683 Constant rc = right as Constant;
2685 // The conversion rules are ignored in enum context but why
2686 if (!ec.HasSet (ResolveContext.Options.EnumScope) && lc != null && rc != null && (TypeManager.IsEnumType (left.Type) || TypeManager.IsEnumType (right.Type))) {
2687 lc = EnumLiftUp (ec, lc, rc, loc);
2689 rc = EnumLiftUp (ec, rc, lc, loc);
2692 if (rc != null && lc != null) {
2693 int prev_e = ec.Report.Errors;
2694 Expression e = ConstantFold.BinaryFold (ec, oper, lc, rc, loc);
2698 if (e != null || ec.Report.Errors != prev_e)
2702 // Comparison warnings
2703 if ((oper & Operator.ComparisonMask) != 0) {
2704 if (left.Equals (right)) {
2705 ec.Report.Warning (1718, 3, loc, "A comparison made to same variable. Did you mean to compare something else?");
2707 CheckUselessComparison (ec, lc, right.Type);
2708 CheckUselessComparison (ec, rc, left.Type);
2711 if (left.Type == InternalType.Dynamic || right.Type == InternalType.Dynamic) {
2712 Arguments args = new Arguments (2);
2713 args.Add (new Argument (left));
2714 args.Add (new Argument (right));
2715 return new DynamicExpressionStatement (this, args, loc).Resolve (ec);
2718 if (RootContext.Version >= LanguageVersion.ISO_2 &&
2719 ((TypeManager.IsNullableType (left.Type) && (right is NullLiteral || TypeManager.IsNullableType (right.Type) || TypeManager.IsValueType (right.Type))) ||
2720 (TypeManager.IsValueType (left.Type) && right is NullLiteral) ||
2721 (TypeManager.IsNullableType (right.Type) && (left is NullLiteral || TypeManager.IsNullableType (left.Type) || TypeManager.IsValueType (left.Type))) ||
2722 (TypeManager.IsValueType (right.Type) && left is NullLiteral)))
2723 return new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
2725 return DoResolveCore (ec, left, right);
2728 protected Expression DoResolveCore (ResolveContext ec, Expression left_orig, Expression right_orig)
2730 Expression expr = ResolveOperator (ec);
2732 Error_OperatorCannotBeApplied (ec, left_orig, right_orig);
2734 if (left == null || right == null)
2735 throw new InternalErrorException ("Invalid conversion");
2737 if (oper == Operator.BitwiseOr)
2738 CheckBitwiseOrOnSignExtended (ec);
2743 public override SLE.Expression MakeExpression (BuilderContext ctx)
2745 var le = left.MakeExpression (ctx);
2746 var re = right.MakeExpression (ctx);
2747 bool is_checked = ctx.HasSet (BuilderContext.Options.CheckedScope);
2750 case Operator.Addition:
2751 return is_checked ? SLE.Expression.AddChecked (le, re) : SLE.Expression.Add (le, re);
2752 case Operator.BitwiseAnd:
2753 return SLE.Expression.And (le, re);
2754 case Operator.BitwiseOr:
2755 return SLE.Expression.Or (le, re);
2756 case Operator.Division:
2757 return SLE.Expression.Divide (le, re);
2758 case Operator.Equality:
2759 return SLE.Expression.Equal (le, re);
2760 case Operator.ExclusiveOr:
2761 return SLE.Expression.ExclusiveOr (le, re);
2762 case Operator.GreaterThan:
2763 return SLE.Expression.GreaterThan (le, re);
2764 case Operator.GreaterThanOrEqual:
2765 return SLE.Expression.GreaterThanOrEqual (le, re);
2766 case Operator.Inequality:
2767 return SLE.Expression.NotEqual (le, re);
2768 case Operator.LeftShift:
2769 return SLE.Expression.LeftShift (le, re);
2770 case Operator.LessThan:
2771 return SLE.Expression.LessThan (le, re);
2772 case Operator.LessThanOrEqual:
2773 return SLE.Expression.LessThanOrEqual (le, re);
2774 case Operator.LogicalAnd:
2775 return SLE.Expression.AndAlso (le, re);
2776 case Operator.LogicalOr:
2777 return SLE.Expression.OrElse (le, re);
2778 case Operator.Modulus:
2779 return SLE.Expression.Modulo (le, re);
2780 case Operator.Multiply:
2781 return is_checked ? SLE.Expression.MultiplyChecked (le, re) : SLE.Expression.Multiply (le, re);
2782 case Operator.RightShift:
2783 return SLE.Expression.RightShift (le, re);
2784 case Operator.Subtraction:
2785 return is_checked ? SLE.Expression.SubtractChecked (le, re) : SLE.Expression.Subtract (le, re);
2787 throw new NotImplementedException (oper.ToString ());
2792 // D operator + (D x, D y)
2793 // D operator - (D x, D y)
2795 Expression ResolveOperatorDelegate (ResolveContext ec, TypeSpec l, TypeSpec r)
2797 if (l != r && !TypeSpecComparer.Variant.IsEqual (r, l)) {
2799 if (right.eclass == ExprClass.MethodGroup || r == InternalType.AnonymousMethod || r == InternalType.Null) {
2800 tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2805 } else if (left.eclass == ExprClass.MethodGroup || (l == InternalType.AnonymousMethod)) {
2806 tmp = Convert.ImplicitConversionRequired (ec, left, r, loc);
2817 Arguments args = new Arguments (2);
2818 args.Add (new Argument (left));
2819 args.Add (new Argument (right));
2821 if (oper == Operator.Addition) {
2822 if (TypeManager.delegate_combine_delegate_delegate == null) {
2823 TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
2824 TypeManager.delegate_type, "Combine", loc, TypeManager.delegate_type, TypeManager.delegate_type);
2827 method = TypeManager.delegate_combine_delegate_delegate;
2828 } else if (oper == Operator.Subtraction) {
2829 if (TypeManager.delegate_remove_delegate_delegate == null) {
2830 TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
2831 TypeManager.delegate_type, "Remove", loc, TypeManager.delegate_type, TypeManager.delegate_type);
2834 method = TypeManager.delegate_remove_delegate_delegate;
2836 return new EmptyExpression (TypeManager.decimal_type);
2839 MethodGroupExpr mg = MethodGroupExpr.CreatePredefined (method, TypeManager.delegate_type, loc);
2840 Expression expr = new UserOperatorCall (mg.BestCandidate, args, CreateExpressionTree, loc);
2841 return new ClassCast (expr, l);
2845 // Enumeration operators
2847 Expression ResolveOperatorEnum (ResolveContext ec, bool lenum, bool renum, TypeSpec ltype, TypeSpec rtype)
2850 // bool operator == (E x, E y);
2851 // bool operator != (E x, E y);
2852 // bool operator < (E x, E y);
2853 // bool operator > (E x, E y);
2854 // bool operator <= (E x, E y);
2855 // bool operator >= (E x, E y);
2857 // E operator & (E x, E y);
2858 // E operator | (E x, E y);
2859 // E operator ^ (E x, E y);
2861 // U operator - (E e, E f)
2862 // E operator - (E e, U x)
2864 // E operator + (U x, E e)
2865 // E operator + (E e, U x)
2867 if (!((oper & (Operator.ComparisonMask | Operator.BitwiseMask)) != 0 ||
2868 (oper == Operator.Subtraction && lenum) ||
2869 (oper == Operator.Addition && (lenum != renum || type != null)))) // type != null for lifted null
2872 Expression ltemp = left;
2873 Expression rtemp = right;
2874 TypeSpec underlying_type;
2877 if ((oper & (Operator.ComparisonMask | Operator.BitwiseMask)) != 0) {
2879 expr = Convert.ImplicitConversion (ec, left, rtype, loc);
2885 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
2893 if (ltype == rtype) {
2894 underlying_type = EnumSpec.GetUnderlyingType (ltype);
2896 if (left is Constant)
2897 left = ((Constant) left).ConvertExplicitly (false, underlying_type).Resolve (ec);
2899 left = EmptyCast.Create (left, underlying_type);
2901 if (right is Constant)
2902 right = ((Constant) right).ConvertExplicitly (false, underlying_type).Resolve (ec);
2904 right = EmptyCast.Create (right, underlying_type);
2906 underlying_type = EnumSpec.GetUnderlyingType (ltype);
2908 if (oper != Operator.Subtraction && oper != Operator.Addition) {
2909 Constant c = right as Constant;
2910 if (c == null || !c.IsDefaultValue)
2913 if (!Convert.ImplicitStandardConversionExists (right, underlying_type))
2916 right = Convert.ImplicitConversionStandard (ec, right, underlying_type, right.Location);
2919 if (left is Constant)
2920 left = ((Constant) left).ConvertExplicitly (false, underlying_type).Resolve (ec);
2922 left = EmptyCast.Create (left, underlying_type);
2925 underlying_type = EnumSpec.GetUnderlyingType (rtype);
2927 if (oper != Operator.Addition) {
2928 Constant c = left as Constant;
2929 if (c == null || !c.IsDefaultValue)
2932 if (!Convert.ImplicitStandardConversionExists (left, underlying_type))
2935 left = Convert.ImplicitConversionStandard (ec, left, underlying_type, left.Location);
2938 if (right is Constant)
2939 right = ((Constant) right).ConvertExplicitly (false, underlying_type).Resolve (ec);
2941 right = EmptyCast.Create (right, underlying_type);
2948 // C# specification uses explicit cast syntax which means binary promotion
2949 // should happen, however it seems that csc does not do that
2951 if (!DoBinaryOperatorPromotion (ec)) {
2957 TypeSpec res_type = null;
2958 if ((oper & Operator.BitwiseMask) != 0 || oper == Operator.Subtraction || oper == Operator.Addition) {
2959 TypeSpec promoted_type = lenum ? left.Type : right.Type;
2960 enum_conversion = Convert.ExplicitNumericConversion (
2961 new EmptyExpression (promoted_type), underlying_type);
2963 if (oper == Operator.Subtraction && renum && lenum)
2964 res_type = underlying_type;
2965 else if (oper == Operator.Addition && renum)
2971 expr = ResolveOperatorPredefined (ec, standard_operators, true, res_type);
2972 if (!is_compound || expr == null)
2980 // If the return type of the selected operator is implicitly convertible to the type of x
2982 if (Convert.ImplicitConversionExists (ec, expr, ltype))
2986 // Otherwise, if the selected operator is a predefined operator, if the return type of the
2987 // selected operator is explicitly convertible to the type of x, and if y is implicitly
2988 // convertible to the type of x or the operator is a shift operator, then the operation
2989 // is evaluated as x = (T)(x op y), where T is the type of x
2991 expr = Convert.ExplicitConversion (ec, expr, ltype, loc);
2995 if (Convert.ImplicitConversionExists (ec, ltemp, ltype))
3002 // 7.9.6 Reference type equality operators
3004 Expression ResolveOperatorEquality (ResolveContext ec, TypeSpec l, TypeSpec r)
3007 type = TypeManager.bool_type;
3010 // a, Both operands are reference-type values or the value null
3011 // b, One operand is a value of type T where T is a type-parameter and
3012 // the other operand is the value null. Furthermore T does not have the
3013 // value type constraint
3015 // LAMESPEC: Very confusing details in the specification, basically any
3016 // reference like type-parameter is allowed
3018 var tparam_l = l as TypeParameterSpec;
3019 var tparam_r = r as TypeParameterSpec;
3020 if (tparam_l != null) {
3021 if (right is NullLiteral && !tparam_l.HasSpecialStruct) {
3022 left = new BoxedCast (left, TypeManager.object_type);
3026 if (!tparam_l.IsReferenceType)
3029 l = tparam_l.GetEffectiveBase ();
3030 left = new BoxedCast (left, l);
3031 } else if (left is NullLiteral && tparam_r == null) {
3032 if (!TypeManager.IsReferenceType (r) || r.Kind == MemberKind.InternalCompilerType)
3038 if (tparam_r != null) {
3039 if (left is NullLiteral && !tparam_r.HasSpecialStruct) {
3040 right = new BoxedCast (right, TypeManager.object_type);
3044 if (!tparam_r.IsReferenceType)
3047 r = tparam_r.GetEffectiveBase ();
3048 right = new BoxedCast (right, r);
3049 } else if (right is NullLiteral) {
3050 if (!TypeManager.IsReferenceType (l) || l.Kind == MemberKind.InternalCompilerType)
3057 // LAMESPEC: method groups can be compared when they convert to other side delegate
3060 if (right.eclass == ExprClass.MethodGroup) {
3061 result = Convert.ImplicitConversion (ec, right, l, loc);
3067 } else if (r.IsDelegate && l != r) {
3070 } else if (left.eclass == ExprClass.MethodGroup && r.IsDelegate) {
3071 result = Convert.ImplicitConversionRequired (ec, left, r, loc);
3080 // bool operator != (string a, string b)
3081 // bool operator == (string a, string b)
3083 // bool operator != (Delegate a, Delegate b)
3084 // bool operator == (Delegate a, Delegate b)
3086 // bool operator != (bool a, bool b)
3087 // bool operator == (bool a, bool b)
3089 // LAMESPEC: Reference equality comparison can apply to value types when
3090 // they implement an implicit conversion to any of types above.
3092 if (r != TypeManager.object_type && l != TypeManager.object_type) {
3093 result = ResolveOperatorPredefined (ec, equality_operators, false, null);
3099 // bool operator != (object a, object b)
3100 // bool operator == (object a, object b)
3102 // An explicit reference conversion exists from the
3103 // type of either operand to the type of the other operand.
3106 // Optimize common path
3108 return l.Kind == MemberKind.InternalCompilerType || l.Kind == MemberKind.Struct ? null : this;
3111 if (!Convert.ExplicitReferenceConversionExists (l, r) &&
3112 !Convert.ExplicitReferenceConversionExists (r, l))
3115 // Reject allowed explicit conversions like int->object
3116 if (!TypeManager.IsReferenceType (l) || !TypeManager.IsReferenceType (r))
3119 if (l == TypeManager.string_type || l == TypeManager.delegate_type || MemberCache.GetUserOperator (l, CSharp.Operator.OpType.Equality, false) != null)
3120 ec.Report.Warning (253, 2, loc,
3121 "Possible unintended reference comparison. Consider casting the right side expression to type `{0}' to get value comparison",
3122 l.GetSignatureForError ());
3124 if (r == TypeManager.string_type || r == TypeManager.delegate_type || MemberCache.GetUserOperator (r, CSharp.Operator.OpType.Equality, false) != null)
3125 ec.Report.Warning (252, 2, loc,
3126 "Possible unintended reference comparison. Consider casting the left side expression to type `{0}' to get value comparison",
3127 r.GetSignatureForError ());
3133 Expression ResolveOperatorPointer (ResolveContext ec, TypeSpec l, TypeSpec r)
3136 // bool operator == (void* x, void* y);
3137 // bool operator != (void* x, void* y);
3138 // bool operator < (void* x, void* y);
3139 // bool operator > (void* x, void* y);
3140 // bool operator <= (void* x, void* y);
3141 // bool operator >= (void* x, void* y);
3143 if ((oper & Operator.ComparisonMask) != 0) {
3146 temp = Convert.ImplicitConversion (ec, left, r, left.Location);
3153 temp = Convert.ImplicitConversion (ec, right, l, right.Location);
3159 type = TypeManager.bool_type;
3163 if (pointer_operators == null)
3164 CreatePointerOperatorsTable ();
3166 return ResolveOperatorPredefined (ec, pointer_operators, false, null);
3170 // Build-in operators method overloading
3172 protected virtual Expression ResolveOperatorPredefined (ResolveContext ec, PredefinedOperator [] operators, bool primitives_only, TypeSpec enum_type)
3174 PredefinedOperator best_operator = null;
3175 TypeSpec l = left.Type;
3176 TypeSpec r = right.Type;
3177 Operator oper_mask = oper & ~Operator.ValuesOnlyMask;
3179 foreach (PredefinedOperator po in operators) {
3180 if ((po.OperatorsMask & oper_mask) == 0)
3183 if (primitives_only) {
3184 if (!po.IsPrimitiveApplicable (l, r))
3187 if (!po.IsApplicable (ec, left, right))
3191 if (best_operator == null) {
3193 if (primitives_only)
3199 best_operator = po.ResolveBetterOperator (ec, best_operator);
3201 if (best_operator == null) {
3202 ec.Report.Error (34, loc, "Operator `{0}' is ambiguous on operands of type `{1}' and `{2}'",
3203 OperName (oper), TypeManager.CSharpName (l), TypeManager.CSharpName (r));
3210 if (best_operator == null)
3213 Expression expr = best_operator.ConvertResult (ec, this);
3216 // Optimize &/&& constant expressions with 0 value
3218 if (oper == Operator.BitwiseAnd || oper == Operator.LogicalAnd) {
3219 Constant rc = right as Constant;
3220 Constant lc = left as Constant;
3221 if ((lc != null && lc.IsDefaultValue) || (rc != null && rc.IsDefaultValue)) {
3223 // The result is a constant with side-effect
3225 Constant side_effect = rc == null ?
3226 new SideEffectConstant (lc, right, loc) :
3227 new SideEffectConstant (rc, left, loc);
3229 return ReducedExpression.Create (side_effect.Resolve (ec), expr);
3233 if (enum_type == null)
3237 // HACK: required by enum_conversion
3239 expr.Type = enum_type;
3240 return EmptyCast.Create (expr, enum_type);
3244 // Performs user-operator overloading
3246 protected virtual Expression ResolveUserOperator (ResolveContext ec, TypeSpec l, TypeSpec r)
3248 var op = ConvertBinaryToUserOperator (oper);
3249 IList<MemberSpec> left_operators = MemberCache.GetUserOperator (l, op, false);
3250 IList<MemberSpec> right_operators = null;
3253 right_operators = MemberCache.GetUserOperator (r, op, false);
3254 if (right_operators == null && left_operators == null)
3256 } else if (left_operators == null) {
3260 Arguments args = new Arguments (2);
3261 Argument larg = new Argument (left);
3263 Argument rarg = new Argument (right);
3267 // User-defined operator implementations always take precedence
3268 // over predefined operator implementations
3270 if (left_operators != null && right_operators != null) {
3271 left_operators = CombineUserOperators (left_operators, right_operators);
3272 } else if (right_operators != null) {
3273 left_operators = right_operators;
3276 var res = new OverloadResolver (left_operators, OverloadResolver.Restrictions.ProbingOnly, loc);
3278 var oper_method = res.ResolveOperator (ec, ref args);
3279 if (oper_method == null)
3282 Expression oper_expr;
3284 // TODO: CreateExpressionTree is allocated every time
3285 if ((oper & Operator.LogicalMask) != 0) {
3286 oper_expr = new ConditionalLogicalOperator (oper_method, args, CreateExpressionTree,
3287 oper == Operator.LogicalAnd, loc).Resolve (ec);
3289 oper_expr = new UserOperatorCall (oper_method, args, CreateExpressionTree, loc);
3298 // Merge two sets of user operators into one, they are mostly distinguish
3299 // expect when they share base type and it contains an operator
3301 static IList<MemberSpec> CombineUserOperators (IList<MemberSpec> left, IList<MemberSpec> right)
3303 var combined = new List<MemberSpec> (left.Count + right.Count);
3304 combined.AddRange (left);
3305 foreach (var r in right) {
3307 foreach (var l in left) {
3308 if (l.DeclaringType == r.DeclaringType) {
3321 public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
3326 private void CheckUselessComparison (ResolveContext ec, Constant c, TypeSpec type)
3328 if (c == null || !IsTypeIntegral (type)
3329 || c is StringConstant
3330 || c is BoolConstant
3331 || c is FloatConstant
3332 || c is DoubleConstant
3333 || c is DecimalConstant
3339 if (c is ULongConstant) {
3340 ulong uvalue = ((ULongConstant) c).Value;
3341 if (uvalue > long.MaxValue) {
3342 if (type == TypeManager.byte_type ||
3343 type == TypeManager.sbyte_type ||
3344 type == TypeManager.short_type ||
3345 type == TypeManager.ushort_type ||
3346 type == TypeManager.int32_type ||
3347 type == TypeManager.uint32_type ||
3348 type == TypeManager.int64_type ||
3349 type == TypeManager.char_type)
3350 WarnUselessComparison (ec, type);
3353 value = (long) uvalue;
3355 else if (c is ByteConstant)
3356 value = ((ByteConstant) c).Value;
3357 else if (c is SByteConstant)
3358 value = ((SByteConstant) c).Value;
3359 else if (c is ShortConstant)
3360 value = ((ShortConstant) c).Value;
3361 else if (c is UShortConstant)
3362 value = ((UShortConstant) c).Value;
3363 else if (c is IntConstant)
3364 value = ((IntConstant) c).Value;
3365 else if (c is UIntConstant)
3366 value = ((UIntConstant) c).Value;
3367 else if (c is LongConstant)
3368 value = ((LongConstant) c).Value;
3369 else if (c is CharConstant)
3370 value = ((CharConstant)c).Value;
3375 if (IsValueOutOfRange (value, type))
3376 WarnUselessComparison (ec, type);
3379 static bool IsValueOutOfRange (long value, TypeSpec type)
3381 if (IsTypeUnsigned (type) && value < 0)
3383 return type == TypeManager.sbyte_type && (value >= 0x80 || value < -0x80) ||
3384 type == TypeManager.byte_type && value >= 0x100 ||
3385 type == TypeManager.short_type && (value >= 0x8000 || value < -0x8000) ||
3386 type == TypeManager.ushort_type && value >= 0x10000 ||
3387 type == TypeManager.int32_type && (value >= 0x80000000 || value < -0x80000000) ||
3388 type == TypeManager.uint32_type && value >= 0x100000000;
3391 private static bool IsTypeIntegral (TypeSpec type)
3393 return type == TypeManager.uint64_type ||
3394 type == TypeManager.int64_type ||
3395 type == TypeManager.uint32_type ||
3396 type == TypeManager.int32_type ||
3397 type == TypeManager.ushort_type ||
3398 type == TypeManager.short_type ||
3399 type == TypeManager.sbyte_type ||
3400 type == TypeManager.byte_type ||
3401 type == TypeManager.char_type;
3404 private static bool IsTypeUnsigned (TypeSpec type)
3406 return type == TypeManager.uint64_type ||
3407 type == TypeManager.uint32_type ||
3408 type == TypeManager.ushort_type ||
3409 type == TypeManager.byte_type ||
3410 type == TypeManager.char_type;
3413 private void WarnUselessComparison (ResolveContext ec, TypeSpec type)
3415 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}'",
3416 TypeManager.CSharpName (type));
3420 /// EmitBranchable is called from Statement.EmitBoolExpression in the
3421 /// context of a conditional bool expression. This function will return
3422 /// false if it is was possible to use EmitBranchable, or true if it was.
3424 /// The expression's code is generated, and we will generate a branch to `target'
3425 /// if the resulting expression value is equal to isTrue
3427 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
3430 // This is more complicated than it looks, but its just to avoid
3431 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
3432 // but on top of that we want for == and != to use a special path
3433 // if we are comparing against null
3435 if ((oper & Operator.EqualityMask) != 0 && (left is Constant || right is Constant)) {
3436 bool my_on_true = oper == Operator.Inequality ? on_true : !on_true;
3439 // put the constant on the rhs, for simplicity
3441 if (left is Constant) {
3442 Expression swap = right;
3448 // brtrue/brfalse works with native int only
3450 if (((Constant) right).IsZeroInteger && right.Type != TypeManager.int64_type && right.Type != TypeManager.uint64_type) {
3451 left.EmitBranchable (ec, target, my_on_true);
3454 if (right.Type == TypeManager.bool_type) {
3455 // right is a boolean, and it's not 'false' => it is 'true'
3456 left.EmitBranchable (ec, target, !my_on_true);
3460 } else if (oper == Operator.LogicalAnd) {
3463 Label tests_end = ec.DefineLabel ();
3465 left.EmitBranchable (ec, tests_end, false);
3466 right.EmitBranchable (ec, target, true);
3467 ec.MarkLabel (tests_end);
3470 // This optimizes code like this
3471 // if (true && i > 4)
3473 if (!(left is Constant))
3474 left.EmitBranchable (ec, target, false);
3476 if (!(right is Constant))
3477 right.EmitBranchable (ec, target, false);
3482 } else if (oper == Operator.LogicalOr){
3484 left.EmitBranchable (ec, target, true);
3485 right.EmitBranchable (ec, target, true);
3488 Label tests_end = ec.DefineLabel ();
3489 left.EmitBranchable (ec, tests_end, true);
3490 right.EmitBranchable (ec, target, false);
3491 ec.MarkLabel (tests_end);
3496 } else if ((oper & Operator.ComparisonMask) == 0) {
3497 base.EmitBranchable (ec, target, on_true);
3504 TypeSpec t = left.Type;
3505 bool is_float = IsFloat (t);
3506 bool is_unsigned = is_float || IsUnsigned (t);
3509 case Operator.Equality:
3511 ec.Emit (OpCodes.Beq, target);
3513 ec.Emit (OpCodes.Bne_Un, target);
3516 case Operator.Inequality:
3518 ec.Emit (OpCodes.Bne_Un, target);
3520 ec.Emit (OpCodes.Beq, target);
3523 case Operator.LessThan:
3525 if (is_unsigned && !is_float)
3526 ec.Emit (OpCodes.Blt_Un, target);
3528 ec.Emit (OpCodes.Blt, target);
3531 ec.Emit (OpCodes.Bge_Un, target);
3533 ec.Emit (OpCodes.Bge, target);
3536 case Operator.GreaterThan:
3538 if (is_unsigned && !is_float)
3539 ec.Emit (OpCodes.Bgt_Un, target);
3541 ec.Emit (OpCodes.Bgt, target);
3544 ec.Emit (OpCodes.Ble_Un, target);
3546 ec.Emit (OpCodes.Ble, target);
3549 case Operator.LessThanOrEqual:
3551 if (is_unsigned && !is_float)
3552 ec.Emit (OpCodes.Ble_Un, target);
3554 ec.Emit (OpCodes.Ble, target);
3557 ec.Emit (OpCodes.Bgt_Un, target);
3559 ec.Emit (OpCodes.Bgt, target);
3563 case Operator.GreaterThanOrEqual:
3565 if (is_unsigned && !is_float)
3566 ec.Emit (OpCodes.Bge_Un, target);
3568 ec.Emit (OpCodes.Bge, target);
3571 ec.Emit (OpCodes.Blt_Un, target);
3573 ec.Emit (OpCodes.Blt, target);
3576 throw new InternalErrorException (oper.ToString ());
3580 public override void Emit (EmitContext ec)
3582 EmitOperator (ec, left.Type);
3585 protected virtual void EmitOperator (EmitContext ec, TypeSpec l)
3588 // Handle short-circuit operators differently
3591 if ((oper & Operator.LogicalMask) != 0) {
3592 Label load_result = ec.DefineLabel ();
3593 Label end = ec.DefineLabel ();
3595 bool is_or = oper == Operator.LogicalOr;
3596 left.EmitBranchable (ec, load_result, is_or);
3598 ec.Emit (OpCodes.Br_S, end);
3600 ec.MarkLabel (load_result);
3601 ec.Emit (is_or ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
3607 // Optimize zero-based operations which cannot be optimized at expression level
3609 if (oper == Operator.Subtraction) {
3610 var lc = left as IntegralConstant;
3611 if (lc != null && lc.IsDefaultValue) {
3613 ec.Emit (OpCodes.Neg);
3620 EmitOperatorOpcode (ec, oper, l);
3623 // Nullable enum could require underlying type cast and we cannot simply wrap binary
3624 // expression because that would wrap lifted binary operation
3626 if (enum_conversion != null)
3627 enum_conversion.Emit (ec);
3630 public override void EmitSideEffect (EmitContext ec)
3632 if ((oper & Operator.LogicalMask) != 0 ||
3633 (ec.HasSet (EmitContext.Options.CheckedScope) && (oper == Operator.Multiply || oper == Operator.Addition || oper == Operator.Subtraction))) {
3634 base.EmitSideEffect (ec);
3636 left.EmitSideEffect (ec);
3637 right.EmitSideEffect (ec);
3641 protected override void CloneTo (CloneContext clonectx, Expression t)
3643 Binary target = (Binary) t;
3645 target.left = left.Clone (clonectx);
3646 target.right = right.Clone (clonectx);
3649 public Expression CreateCallSiteBinder (ResolveContext ec, Arguments args)
3651 Arguments binder_args = new Arguments (4);
3653 MemberAccess sle = new MemberAccess (new MemberAccess (
3654 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Linq", loc), "Expressions", loc);
3656 CSharpBinderFlags flags = 0;
3657 if (ec.HasSet (ResolveContext.Options.CheckedScope))
3658 flags = CSharpBinderFlags.CheckedContext;
3660 if ((oper & Operator.LogicalMask) != 0)
3661 flags |= CSharpBinderFlags.BinaryOperationLogical;
3663 binder_args.Add (new Argument (new EnumConstant (new IntLiteral ((int) flags, loc), TypeManager.binder_flags)));
3664 binder_args.Add (new Argument (new MemberAccess (new MemberAccess (sle, "ExpressionType", loc), GetOperatorExpressionTypeName (), loc)));
3665 binder_args.Add (new Argument (new TypeOf (new TypeExpression (ec.CurrentType, loc), loc)));
3666 binder_args.Add (new Argument (new ImplicitlyTypedArrayCreation (args.CreateDynamicBinderArguments (ec), loc)));
3668 return new Invocation (DynamicExpressionStatement.GetBinder ("BinaryOperation", loc), binder_args);
3671 public override Expression CreateExpressionTree (ResolveContext ec)
3673 return CreateExpressionTree (ec, null);
3676 Expression CreateExpressionTree (ResolveContext ec, Expression method)
3679 bool lift_arg = false;
3682 case Operator.Addition:
3683 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
3684 method_name = "AddChecked";
3686 method_name = "Add";
3688 case Operator.BitwiseAnd:
3689 method_name = "And";
3691 case Operator.BitwiseOr:
3694 case Operator.Division:
3695 method_name = "Divide";
3697 case Operator.Equality:
3698 method_name = "Equal";
3701 case Operator.ExclusiveOr:
3702 method_name = "ExclusiveOr";
3704 case Operator.GreaterThan:
3705 method_name = "GreaterThan";
3708 case Operator.GreaterThanOrEqual:
3709 method_name = "GreaterThanOrEqual";
3712 case Operator.Inequality:
3713 method_name = "NotEqual";
3716 case Operator.LeftShift:
3717 method_name = "LeftShift";
3719 case Operator.LessThan:
3720 method_name = "LessThan";
3723 case Operator.LessThanOrEqual:
3724 method_name = "LessThanOrEqual";
3727 case Operator.LogicalAnd:
3728 method_name = "AndAlso";
3730 case Operator.LogicalOr:
3731 method_name = "OrElse";
3733 case Operator.Modulus:
3734 method_name = "Modulo";
3736 case Operator.Multiply:
3737 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
3738 method_name = "MultiplyChecked";
3740 method_name = "Multiply";
3742 case Operator.RightShift:
3743 method_name = "RightShift";
3745 case Operator.Subtraction:
3746 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
3747 method_name = "SubtractChecked";
3749 method_name = "Subtract";
3753 throw new InternalErrorException ("Unknown expression tree binary operator " + oper);
3756 Arguments args = new Arguments (2);
3757 args.Add (new Argument (left.CreateExpressionTree (ec)));
3758 args.Add (new Argument (right.CreateExpressionTree (ec)));
3759 if (method != null) {
3761 args.Add (new Argument (new BoolConstant (false, loc)));
3763 args.Add (new Argument (method));
3766 return CreateExpressionFactoryCall (ec, method_name, args);
3771 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3772 // b, c, d... may be strings or objects.
3774 public class StringConcat : Expression {
3775 Arguments arguments;
3776 static IList<MemberSpec> concat_members;
3778 public StringConcat (Expression left, Expression right, Location loc)
3781 type = TypeManager.string_type;
3782 eclass = ExprClass.Value;
3784 arguments = new Arguments (2);
3787 public static StringConcat Create (ResolveContext rc, Expression left, Expression right, Location loc)
3789 if (left.eclass == ExprClass.Unresolved || right.eclass == ExprClass.Unresolved)
3790 throw new ArgumentException ();
3792 var s = new StringConcat (left, right, loc);
3793 s.Append (rc, left);
3794 s.Append (rc, right);
3798 public override Expression CreateExpressionTree (ResolveContext ec)
3800 Argument arg = arguments [0];
3801 return CreateExpressionAddCall (ec, arg, arg.CreateExpressionTree (ec), 1);
3805 // Creates nested calls tree from an array of arguments used for IL emit
3807 Expression CreateExpressionAddCall (ResolveContext ec, Argument left, Expression left_etree, int pos)
3809 Arguments concat_args = new Arguments (2);
3810 Arguments add_args = new Arguments (3);
3812 concat_args.Add (left);
3813 add_args.Add (new Argument (left_etree));
3815 concat_args.Add (arguments [pos]);
3816 add_args.Add (new Argument (arguments [pos].CreateExpressionTree (ec)));
3818 var methods = CreateConcatMethodCandidates ();
3819 if (methods == null)
3822 var res = new OverloadResolver (methods, OverloadResolver.Restrictions.NoBaseMembers, loc);
3823 var method = res.ResolveMember<MethodSpec> (ec, ref concat_args);
3827 add_args.Add (new Argument (new TypeOfMethod (method, loc)));
3829 Expression expr = CreateExpressionFactoryCall (ec, "Add", add_args);
3830 if (++pos == arguments.Count)
3833 left = new Argument (new EmptyExpression (method.ReturnType));
3834 return CreateExpressionAddCall (ec, left, expr, pos);
3837 protected override Expression DoResolve (ResolveContext ec)
3842 void Append (ResolveContext rc, Expression operand)
3847 StringConstant sc = operand as StringConstant;
3849 if (arguments.Count != 0) {
3850 Argument last_argument = arguments [arguments.Count - 1];
3851 StringConstant last_expr_constant = last_argument.Expr as StringConstant;
3852 if (last_expr_constant != null) {
3853 last_argument.Expr = new StringConstant (
3854 last_expr_constant.Value + sc.Value, sc.Location).Resolve (rc);
3860 // Multiple (3+) concatenation are resolved as multiple StringConcat instances
3862 StringConcat concat_oper = operand as StringConcat;
3863 if (concat_oper != null) {
3864 arguments.AddRange (concat_oper.arguments);
3869 arguments.Add (new Argument (operand));
3872 IList<MemberSpec> CreateConcatMethodCandidates ()
3874 if (concat_members == null) {
3875 concat_members = MemberCache.FindMembers (type, "Concat", true);
3878 return concat_members;
3881 public override void Emit (EmitContext ec)
3883 var members = CreateConcatMethodCandidates ();
3884 var res = new OverloadResolver (members, OverloadResolver.Restrictions.NoBaseMembers, loc);
3885 var method = res.ResolveMember<MethodSpec> (new ResolveContext (ec.MemberContext), ref arguments);
3887 Invocation.EmitCall (ec, null, method, arguments, loc);
3890 public override SLE.Expression MakeExpression (BuilderContext ctx)
3892 if (arguments.Count != 2)
3893 throw new NotImplementedException ("arguments.Count != 2");
3895 var concat = typeof (string).GetMethod ("Concat", new[] { typeof (object), typeof (object) });
3896 return SLE.Expression.Add (arguments[0].Expr.MakeExpression (ctx), arguments[1].Expr.MakeExpression (ctx), concat);
3899 public static void Reset ()
3901 concat_members = null;
3906 // User-defined conditional logical operator
3908 public class ConditionalLogicalOperator : UserOperatorCall {
3909 readonly bool is_and;
3910 Expression oper_expr;
3912 public ConditionalLogicalOperator (MethodSpec oper, Arguments arguments, Func<ResolveContext, Expression, Expression> expr_tree, bool is_and, Location loc)
3913 : base (oper, arguments, expr_tree, loc)
3915 this.is_and = is_and;
3916 eclass = ExprClass.Unresolved;
3919 protected override Expression DoResolve (ResolveContext ec)
3921 AParametersCollection pd = oper.Parameters;
3922 if (!TypeSpecComparer.IsEqual (type, pd.Types[0]) || !TypeSpecComparer.IsEqual (type, pd.Types[1])) {
3923 ec.Report.Error (217, loc,
3924 "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",
3925 oper.GetSignatureForError ());
3929 Expression left_dup = new EmptyExpression (type);
3930 Expression op_true = GetOperatorTrue (ec, left_dup, loc);
3931 Expression op_false = GetOperatorFalse (ec, left_dup, loc);
3932 if (op_true == null || op_false == null) {
3933 ec.Report.Error (218, loc,
3934 "The type `{0}' must have operator `true' and operator `false' defined when `{1}' is used as a short circuit operator",
3935 TypeManager.CSharpName (type), oper.GetSignatureForError ());
3939 oper_expr = is_and ? op_false : op_true;
3940 eclass = ExprClass.Value;
3944 public override void Emit (EmitContext ec)
3946 Label end_target = ec.DefineLabel ();
3949 // Emit and duplicate left argument
3951 arguments [0].Expr.Emit (ec);
3952 ec.Emit (OpCodes.Dup);
3953 arguments.RemoveAt (0);
3955 oper_expr.EmitBranchable (ec, end_target, true);
3957 ec.MarkLabel (end_target);
3961 public class PointerArithmetic : Expression {
3962 Expression left, right;
3966 // We assume that `l' is always a pointer
3968 public PointerArithmetic (Binary.Operator op, Expression l, Expression r, TypeSpec t, Location loc)
3977 public override Expression CreateExpressionTree (ResolveContext ec)
3979 Error_PointerInsideExpressionTree (ec);
3983 protected override Expression DoResolve (ResolveContext ec)
3985 eclass = ExprClass.Variable;
3987 if (left.Type == TypeManager.void_ptr_type) {
3988 ec.Report.Error (242, loc, "The operation in question is undefined on void pointers");
3995 public override void Emit (EmitContext ec)
3997 TypeSpec op_type = left.Type;
3999 // It must be either array or fixed buffer
4001 if (TypeManager.HasElementType (op_type)) {
4002 element = TypeManager.GetElementType (op_type);
4004 FieldExpr fe = left as FieldExpr;
4006 element = ((FixedFieldSpec) (fe.Spec)).ElementType;
4011 int size = GetTypeSize (element);
4012 TypeSpec rtype = right.Type;
4014 if ((op & Binary.Operator.SubtractionMask) != 0 && rtype.IsPointer){
4016 // handle (pointer - pointer)
4020 ec.Emit (OpCodes.Sub);
4024 ec.Emit (OpCodes.Sizeof, element);
4027 ec.Emit (OpCodes.Div);
4029 ec.Emit (OpCodes.Conv_I8);
4032 // handle + and - on (pointer op int)
4034 Constant left_const = left as Constant;
4035 if (left_const != null) {
4037 // Optimize ((T*)null) pointer operations
4039 if (left_const.IsDefaultValue) {
4040 left = EmptyExpression.Null;
4048 var right_const = right as Constant;
4049 if (right_const != null) {
4051 // Optimize 0-based arithmetic
4053 if (right_const.IsDefaultValue)
4057 right = new IntConstant (size, right.Location);
4059 right = new SizeOf (new TypeExpression (element, right.Location), right.Location);
4061 // TODO: Should be the checks resolve context sensitive?
4062 ResolveContext rc = new ResolveContext (ec.MemberContext, ResolveContext.Options.UnsafeScope);
4063 right = new Binary (Binary.Operator.Multiply, right, right_const, loc).Resolve (rc);
4069 if (rtype == TypeManager.sbyte_type || rtype == TypeManager.byte_type ||
4070 rtype == TypeManager.short_type || rtype == TypeManager.ushort_type) {
4071 ec.Emit (OpCodes.Conv_I);
4072 } else if (rtype == TypeManager.uint32_type) {
4073 ec.Emit (OpCodes.Conv_U);
4076 if (right_const == null && size != 1){
4078 ec.Emit (OpCodes.Sizeof, element);
4081 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
4082 ec.Emit (OpCodes.Conv_I8);
4084 Binary.EmitOperatorOpcode (ec, Binary.Operator.Multiply, rtype);
4087 if (left_const == null) {
4088 if (rtype == TypeManager.int64_type)
4089 ec.Emit (OpCodes.Conv_I);
4090 else if (rtype == TypeManager.uint64_type)
4091 ec.Emit (OpCodes.Conv_U);
4093 Binary.EmitOperatorOpcode (ec, op, op_type);
4100 // A boolean-expression is an expression that yields a result
4103 public class BooleanExpression : ShimExpression
4105 public BooleanExpression (Expression expr)
4108 this.loc = expr.Location;
4111 public override Expression CreateExpressionTree (ResolveContext ec)
4113 // TODO: We should emit IsTrue (v4) instead of direct user operator
4114 // call but that would break csc compatibility
4115 return base.CreateExpressionTree (ec);
4118 protected override Expression DoResolve (ResolveContext ec)
4120 // A boolean-expression is required to be of a type
4121 // that can be implicitly converted to bool or of
4122 // a type that implements operator true
4124 expr = expr.Resolve (ec);
4128 Assign ass = expr as Assign;
4129 if (ass != null && ass.Source is Constant) {
4130 ec.Report.Warning (665, 3, loc,
4131 "Assignment in conditional expression is always constant. Did you mean to use `==' instead ?");
4134 if (expr.Type == TypeManager.bool_type)
4137 if (expr.Type == InternalType.Dynamic) {
4138 Arguments args = new Arguments (1);
4139 args.Add (new Argument (expr));
4140 return new DynamicUnaryConversion ("IsTrue", args, loc).Resolve (ec);
4143 type = TypeManager.bool_type;
4144 Expression converted = Convert.ImplicitConversion (ec, expr, type, loc);
4145 if (converted != null)
4149 // If no implicit conversion to bool exists, try using `operator true'
4151 converted = GetOperatorTrue (ec, expr, loc);
4152 if (converted == null) {
4153 expr.Error_ValueCannotBeConverted (ec, loc, type, false);
4162 /// Implements the ternary conditional operator (?:)
4164 public class Conditional : Expression {
4165 Expression expr, true_expr, false_expr;
4167 public Conditional (BooleanExpression expr, Expression true_expr, Expression false_expr, Location loc)
4170 this.true_expr = true_expr;
4171 this.false_expr = false_expr;
4175 public Expression Expr {
4181 public Expression TrueExpr {
4187 public Expression FalseExpr {
4193 public override Expression CreateExpressionTree (ResolveContext ec)
4195 Arguments args = new Arguments (3);
4196 args.Add (new Argument (expr.CreateExpressionTree (ec)));
4197 args.Add (new Argument (true_expr.CreateExpressionTree (ec)));
4198 args.Add (new Argument (false_expr.CreateExpressionTree (ec)));
4199 return CreateExpressionFactoryCall (ec, "Condition", args);
4202 protected override Expression DoResolve (ResolveContext ec)
4204 expr = expr.Resolve (ec);
4205 true_expr = true_expr.Resolve (ec);
4206 false_expr = false_expr.Resolve (ec);
4208 if (true_expr == null || false_expr == null || expr == null)
4211 eclass = ExprClass.Value;
4212 TypeSpec true_type = true_expr.Type;
4213 TypeSpec false_type = false_expr.Type;
4217 // First, if an implicit conversion exists from true_expr
4218 // to false_expr, then the result type is of type false_expr.Type
4220 if (!TypeSpecComparer.IsEqual (true_type, false_type)) {
4221 Expression conv = Convert.ImplicitConversion (ec, true_expr, false_type, loc);
4224 // Check if both can convert implicitly to each other's type
4226 if (true_type != InternalType.Dynamic) {
4229 if (false_type != InternalType.Dynamic && Convert.ImplicitConversion (ec, false_expr, true_type, loc) != null) {
4230 ec.Report.Error (172, true_expr.Location,
4231 "Type of conditional expression cannot be determined as `{0}' and `{1}' convert implicitly to each other",
4232 TypeManager.CSharpName (true_type), TypeManager.CSharpName (false_type));
4238 } else if ((conv = Convert.ImplicitConversion (ec, false_expr, true_type, loc)) != null) {
4241 ec.Report.Error (173, true_expr.Location,
4242 "Type of conditional expression cannot be determined because there is no implicit conversion between `{0}' and `{1}'",
4243 TypeManager.CSharpName (true_type), TypeManager.CSharpName (false_type));
4248 // Dead code optimalization
4249 Constant c = expr as Constant;
4251 bool is_false = c.IsDefaultValue;
4252 ec.Report.Warning (429, 4, is_false ? true_expr.Location : false_expr.Location, "Unreachable expression code detected");
4253 return ReducedExpression.Create (is_false ? false_expr : true_expr, this).Resolve (ec);
4259 public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
4264 public override void Emit (EmitContext ec)
4266 Label false_target = ec.DefineLabel ();
4267 Label end_target = ec.DefineLabel ();
4269 expr.EmitBranchable (ec, false_target, false);
4270 true_expr.Emit (ec);
4272 if (type.IsInterface) {
4273 LocalBuilder temp = ec.GetTemporaryLocal (type);
4274 ec.Emit (OpCodes.Stloc, temp);
4275 ec.Emit (OpCodes.Ldloc, temp);
4276 ec.FreeTemporaryLocal (temp, type);
4279 ec.Emit (OpCodes.Br, end_target);
4280 ec.MarkLabel (false_target);
4281 false_expr.Emit (ec);
4282 ec.MarkLabel (end_target);
4285 protected override void CloneTo (CloneContext clonectx, Expression t)
4287 Conditional target = (Conditional) t;
4289 target.expr = expr.Clone (clonectx);
4290 target.true_expr = true_expr.Clone (clonectx);
4291 target.false_expr = false_expr.Clone (clonectx);
4295 public abstract class VariableReference : Expression, IAssignMethod, IMemoryLocation, IVariableReference {
4296 LocalTemporary temp;
4299 public abstract HoistedVariable GetHoistedVariable (AnonymousExpression ae);
4300 public abstract bool IsFixed { get; }
4301 public abstract bool IsRef { get; }
4302 public abstract string Name { get; }
4303 public abstract void SetHasAddressTaken ();
4306 // Variable IL data, it has to be protected to encapsulate hoisted variables
4308 protected abstract ILocalVariable Variable { get; }
4311 // Variable flow-analysis data
4313 public abstract VariableInfo VariableInfo { get; }
4316 public virtual void AddressOf (EmitContext ec, AddressOp mode)
4318 HoistedVariable hv = GetHoistedVariable (ec);
4320 hv.AddressOf (ec, mode);
4324 Variable.EmitAddressOf (ec);
4327 public HoistedVariable GetHoistedVariable (ResolveContext rc)
4329 return GetHoistedVariable (rc.CurrentAnonymousMethod);
4332 public HoistedVariable GetHoistedVariable (EmitContext ec)
4334 return GetHoistedVariable (ec.CurrentAnonymousMethod);
4337 public override string GetSignatureForError ()
4342 public override void Emit (EmitContext ec)
4347 public override void EmitSideEffect (EmitContext ec)
4353 // This method is used by parameters that are references, that are
4354 // being passed as references: we only want to pass the pointer (that
4355 // is already stored in the parameter, not the address of the pointer,
4356 // and not the value of the variable).
4358 public void EmitLoad (EmitContext ec)
4363 public void Emit (EmitContext ec, bool leave_copy)
4365 Report.Debug (64, "VARIABLE EMIT", this, Variable, type, IsRef, loc);
4367 HoistedVariable hv = GetHoistedVariable (ec);
4369 hv.Emit (ec, leave_copy);
4377 // If we are a reference, we loaded on the stack a pointer
4378 // Now lets load the real value
4380 ec.EmitLoadFromPtr (type);
4384 ec.Emit (OpCodes.Dup);
4387 temp = new LocalTemporary (Type);
4393 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy,
4394 bool prepare_for_load)
4396 HoistedVariable hv = GetHoistedVariable (ec);
4398 hv.EmitAssign (ec, source, leave_copy, prepare_for_load);
4402 New n_source = source as New;
4403 if (n_source != null) {
4404 if (!n_source.Emit (ec, this)) {
4408 ec.EmitLoadFromPtr (type);
4420 ec.Emit (OpCodes.Dup);
4422 temp = new LocalTemporary (Type);
4428 ec.EmitStoreFromPtr (type);
4430 Variable.EmitAssign (ec);
4438 public bool IsHoisted {
4439 get { return GetHoistedVariable ((AnonymousExpression) null) != null; }
4446 public class LocalVariableReference : VariableReference {
4447 readonly string name;
4449 public LocalInfo local_info;
4452 public LocalVariableReference (Block block, string name, Location l)
4460 // Setting `is_readonly' to false will allow you to create a writable
4461 // reference to a read-only variable. This is used by foreach and using.
4463 public LocalVariableReference (Block block, string name, Location l,
4464 LocalInfo local_info, bool is_readonly)
4465 : this (block, name, l)
4467 this.local_info = local_info;
4468 this.is_readonly = is_readonly;
4471 public override VariableInfo VariableInfo {
4472 get { return local_info.VariableInfo; }
4475 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
4477 return local_info.HoistedVariant;
4481 // A local variable is always fixed
4483 public override bool IsFixed {
4484 get { return true; }
4487 public override bool IsRef {
4488 get { return false; }
4491 public bool IsReadOnly {
4492 get { return is_readonly; }
4495 public override string Name {
4496 get { return name; }
4499 public bool VerifyAssigned (ResolveContext ec)
4501 VariableInfo variable_info = local_info.VariableInfo;
4502 return variable_info == null || variable_info.IsAssigned (ec, loc);
4505 void ResolveLocalInfo ()
4507 if (local_info == null) {
4508 local_info = Block.GetLocalInfo (Name);
4509 type = local_info.VariableType;
4510 is_readonly = local_info.ReadOnly;
4514 public override void SetHasAddressTaken ()
4516 local_info.AddressTaken = true;
4519 public override Expression CreateExpressionTree (ResolveContext ec)
4521 HoistedVariable hv = GetHoistedVariable (ec);
4523 return hv.CreateExpressionTree ();
4525 Arguments arg = new Arguments (1);
4526 arg.Add (new Argument (this));
4527 return CreateExpressionFactoryCall (ec, "Constant", arg);
4530 Expression DoResolveBase (ResolveContext ec)
4532 Expression e = Block.GetConstantExpression (Name);
4534 return e.Resolve (ec);
4536 VerifyAssigned (ec);
4539 // If we are referencing a variable from the external block
4540 // flag it for capturing
4542 if (ec.MustCaptureVariable (local_info)) {
4543 if (local_info.AddressTaken)
4544 AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, this, loc);
4546 if (ec.IsVariableCapturingRequired) {
4547 AnonymousMethodStorey storey = local_info.Block.Explicit.CreateAnonymousMethodStorey (ec);
4548 storey.CaptureLocalVariable (ec, local_info);
4552 eclass = ExprClass.Variable;
4553 type = local_info.VariableType;
4557 protected override Expression DoResolve (ResolveContext ec)
4559 ResolveLocalInfo ();
4560 local_info.Used = true;
4562 if (type == null && local_info.Type is VarExpr) {
4563 local_info.VariableType = TypeManager.object_type;
4564 Error_VariableIsUsedBeforeItIsDeclared (ec.Report, Name);
4568 return DoResolveBase (ec);
4571 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
4573 ResolveLocalInfo ();
4576 if (right_side == EmptyExpression.OutAccess.Instance)
4577 local_info.Used = true;
4579 // Infer implicitly typed local variable
4581 VarExpr ve = local_info.Type as VarExpr;
4583 if (!ve.InferType (ec, right_side))
4585 type = local_info.VariableType = ve.Type;
4592 if (right_side == EmptyExpression.OutAccess.Instance) {
4593 code = 1657; msg = "Cannot pass `{0}' as a ref or out argument because it is a `{1}'";
4594 } else if (right_side == EmptyExpression.LValueMemberAccess) {
4595 code = 1654; msg = "Cannot assign to members of `{0}' because it is a `{1}'";
4596 } else if (right_side == EmptyExpression.LValueMemberOutAccess) {
4597 code = 1655; msg = "Cannot pass members of `{0}' as ref or out arguments because it is a `{1}'";
4598 } else if (right_side == EmptyExpression.UnaryAddress) {
4599 code = 459; msg = "Cannot take the address of {1} `{0}'";
4601 code = 1656; msg = "Cannot assign to `{0}' because it is a `{1}'";
4603 ec.Report.Error (code, loc, msg, Name, local_info.GetReadOnlyContext ());
4604 } else if (VariableInfo != null) {
4605 VariableInfo.SetAssigned (ec);
4608 return DoResolveBase (ec);
4611 public override int GetHashCode ()
4613 return Name.GetHashCode ();
4616 public override bool Equals (object obj)
4618 LocalVariableReference lvr = obj as LocalVariableReference;
4622 return Name == lvr.Name && Block == lvr.Block;
4625 protected override ILocalVariable Variable {
4626 get { return local_info; }
4629 public override string ToString ()
4631 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
4634 protected override void CloneTo (CloneContext clonectx, Expression t)
4636 LocalVariableReference target = (LocalVariableReference) t;
4638 target.Block = clonectx.LookupBlock (Block);
4639 if (local_info != null)
4640 target.local_info = clonectx.LookupVariable (local_info);
4645 /// This represents a reference to a parameter in the intermediate
4648 public class ParameterReference : VariableReference {
4649 readonly ToplevelParameterInfo pi;
4651 public ParameterReference (ToplevelParameterInfo pi, Location loc)
4657 public override bool IsRef {
4658 get { return (pi.Parameter.ModFlags & Parameter.Modifier.ISBYREF) != 0; }
4661 bool HasOutModifier {
4662 get { return pi.Parameter.ModFlags == Parameter.Modifier.OUT; }
4665 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
4667 return pi.Parameter.HoistedVariant;
4671 // A ref or out parameter is classified as a moveable variable, even
4672 // if the argument given for the parameter is a fixed variable
4674 public override bool IsFixed {
4675 get { return !IsRef; }
4678 public override string Name {
4679 get { return Parameter.Name; }
4682 public Parameter Parameter {
4683 get { return pi.Parameter; }
4686 public override VariableInfo VariableInfo {
4687 get { return pi.VariableInfo; }
4690 protected override ILocalVariable Variable {
4691 get { return Parameter; }
4694 public bool IsAssigned (ResolveContext ec, Location loc)
4696 // HACK: Variables are not captured in probing mode
4697 if (ec.IsInProbingMode)
4700 if (!ec.DoFlowAnalysis || !HasOutModifier || ec.CurrentBranching.IsAssigned (VariableInfo))
4703 ec.Report.Error (269, loc, "Use of unassigned out parameter `{0}'", Name);
4707 public override void SetHasAddressTaken ()
4709 Parameter.HasAddressTaken = true;
4712 void SetAssigned (ResolveContext ec)
4714 if (HasOutModifier && ec.DoFlowAnalysis)
4715 ec.CurrentBranching.SetAssigned (VariableInfo);
4718 bool DoResolveBase (ResolveContext ec)
4720 type = pi.ParameterType;
4721 eclass = ExprClass.Variable;
4723 AnonymousExpression am = ec.CurrentAnonymousMethod;
4727 Block b = ec.CurrentBlock;
4730 IParameterData[] p = b.Toplevel.Parameters.FixedParameters;
4731 for (int i = 0; i < p.Length; ++i) {
4732 if (p [i] != Parameter)
4736 // Don't capture local parameters
4738 if (b == ec.CurrentBlock.Toplevel && !am.IsIterator)
4742 ec.Report.Error (1628, loc,
4743 "Parameter `{0}' cannot be used inside `{1}' when using `ref' or `out' modifier",
4744 Name, am.ContainerType);
4747 if (pi.Parameter.HasAddressTaken)
4748 AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, this, loc);
4750 if (ec.IsVariableCapturingRequired && !b.Toplevel.IsExpressionTree) {
4751 AnonymousMethodStorey storey = pi.Block.CreateAnonymousMethodStorey (ec);
4752 storey.CaptureParameter (ec, this);
4764 public override int GetHashCode ()
4766 return Name.GetHashCode ();
4769 public override bool Equals (object obj)
4771 ParameterReference pr = obj as ParameterReference;
4775 return Name == pr.Name;
4778 public override void AddressOf (EmitContext ec, AddressOp mode)
4781 // ParameterReferences might already be a reference
4788 base.AddressOf (ec, mode);
4791 protected override void CloneTo (CloneContext clonectx, Expression target)
4796 public override Expression CreateExpressionTree (ResolveContext ec)
4798 HoistedVariable hv = GetHoistedVariable (ec);
4800 return hv.CreateExpressionTree ();
4802 return Parameter.ExpressionTreeVariableReference ();
4806 // Notice that for ref/out parameters, the type exposed is not the
4807 // same type exposed externally.
4810 // externally we expose "int&"
4811 // here we expose "int".
4813 // We record this in "is_ref". This means that the type system can treat
4814 // the type as it is expected, but when we generate the code, we generate
4815 // the alternate kind of code.
4817 protected override Expression DoResolve (ResolveContext ec)
4819 if (!DoResolveBase (ec))
4822 // HACK: Variables are not captured in probing mode
4823 if (ec.IsInProbingMode)
4826 if (HasOutModifier && ec.DoFlowAnalysis &&
4827 (!ec.OmitStructFlowAnalysis || !VariableInfo.TypeInfo.IsStruct) && !IsAssigned (ec, loc))
4833 override public Expression DoResolveLValue (ResolveContext ec, Expression right_side)
4835 if (!DoResolveBase (ec))
4842 static public void EmitLdArg (EmitContext ec, int x)
4845 case 0: ec.Emit (OpCodes.Ldarg_0); break;
4846 case 1: ec.Emit (OpCodes.Ldarg_1); break;
4847 case 2: ec.Emit (OpCodes.Ldarg_2); break;
4848 case 3: ec.Emit (OpCodes.Ldarg_3); break;
4850 if (x > byte.MaxValue)
4851 ec.Emit (OpCodes.Ldarg, x);
4853 ec.Emit (OpCodes.Ldarg_S, (byte) x);
4860 /// Invocation of methods or delegates.
4862 public class Invocation : ExpressionStatement
4864 protected Arguments arguments;
4865 protected Expression expr;
4866 protected MethodGroupExpr mg;
4868 public Invocation (Expression expr, Arguments arguments)
4871 this.arguments = arguments;
4873 loc = expr.Location;
4877 public Arguments Arguments {
4883 public Expression Expression {
4890 protected override void CloneTo (CloneContext clonectx, Expression t)
4892 Invocation target = (Invocation) t;
4894 if (arguments != null)
4895 target.arguments = arguments.Clone (clonectx);
4897 target.expr = expr.Clone (clonectx);
4901 public override Expression CreateExpressionTree (ResolveContext ec)
4903 Expression instance = mg.IsInstance ?
4904 mg.InstanceExpression.CreateExpressionTree (ec) :
4905 new NullLiteral (loc);
4907 var args = Arguments.CreateForExpressionTree (ec, arguments,
4909 mg.CreateExpressionTree (ec));
4911 return CreateExpressionFactoryCall (ec, "Call", args);
4914 protected override Expression DoResolve (ResolveContext ec)
4916 Expression member_expr;
4917 var atn = expr as ATypeNameExpression;
4919 member_expr = atn.LookupNameExpression (ec, true, true);
4920 if (member_expr != null)
4921 member_expr = member_expr.Resolve (ec);
4923 member_expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4926 if (member_expr == null)
4930 // Next, evaluate all the expressions in the argument list
4932 bool dynamic_arg = false;
4933 if (arguments != null)
4934 arguments.Resolve (ec, out dynamic_arg);
4936 TypeSpec expr_type = member_expr.Type;
4937 mg = member_expr as MethodGroupExpr;
4939 bool dynamic_member = expr_type == InternalType.Dynamic;
4941 if (!dynamic_member) {
4942 Expression invoke = null;
4945 if (expr_type != null && TypeManager.IsDelegateType (expr_type)) {
4946 invoke = new DelegateInvocation (member_expr, arguments, loc);
4947 invoke = invoke.Resolve (ec);
4948 if (invoke == null || !dynamic_arg)
4951 MemberExpr me = member_expr as MemberExpr;
4953 member_expr.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup, loc);
4957 ec.Report.Error (1955, loc, "The member `{0}' cannot be used as method or delegate",
4958 member_expr.GetSignatureForError ());
4963 if (invoke == null) {
4964 mg = DoResolveOverload (ec);
4970 if (dynamic_arg || dynamic_member)
4971 return DoResolveDynamic (ec, member_expr);
4973 var method = mg.BestCandidate;
4974 if (method != null) {
4975 type = method.ReturnType;
4978 if (arguments == null && method.DeclaringType == TypeManager.object_type && method.Name == Destructor.MetadataName) {
4980 ec.Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
4982 ec.Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
4986 IsSpecialMethodInvocation (ec, method, loc);
4988 if (mg.InstanceExpression != null)
4989 mg.InstanceExpression.CheckMarshalByRefAccess (ec);
4991 eclass = ExprClass.Value;
4995 Expression DoResolveDynamic (ResolveContext ec, Expression memberExpr)
4998 DynamicMemberBinder dmb = memberExpr as DynamicMemberBinder;
5000 args = dmb.Arguments;
5001 if (arguments != null)
5002 args.AddRange (arguments);
5003 } else if (mg == null) {
5004 if (arguments == null)
5005 args = new Arguments (1);
5009 args.Insert (0, new Argument (memberExpr));
5013 ec.Report.Error (1971, loc,
5014 "The base call to method `{0}' cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access",
5019 if (arguments == null)
5020 args = new Arguments (1);
5024 MemberAccess ma = expr as MemberAccess;
5026 var left_type = ma.LeftExpression as TypeExpr;
5027 if (left_type != null) {
5028 args.Insert (0, new Argument (new TypeOf (left_type, loc).Resolve (ec), Argument.AType.DynamicTypeName));
5030 args.Insert (0, new Argument (ma.LeftExpression.Resolve (ec)));
5032 } else { // is SimpleName
5034 args.Insert (0, new Argument (new TypeOf (new TypeExpression (ec.CurrentType, loc), loc).Resolve (ec), Argument.AType.DynamicTypeName));
5036 args.Insert (0, new Argument (new This (loc).Resolve (ec)));
5041 return new DynamicInvocation (expr as ATypeNameExpression, args, loc).Resolve (ec);
5044 protected virtual MethodGroupExpr DoResolveOverload (ResolveContext ec)
5046 return mg.OverloadResolve (ec, ref arguments, null, OverloadResolver.Restrictions.None);
5049 static Type[] GetVarargsTypes (MethodSpec mb, Arguments arguments)
5051 AParametersCollection pd = mb.Parameters;
5053 Argument a = arguments[pd.Count - 1];
5054 Arglist list = (Arglist) a.Expr;
5056 return list.ArgumentTypes;
5060 // If a member is a method or event, or if it is a constant, field or property of either a delegate type
5061 // or the type dynamic, then the member is invocable
5063 public static bool IsMemberInvocable (MemberSpec member)
5065 switch (member.Kind) {
5066 case MemberKind.Event:
5068 case MemberKind.Field:
5069 case MemberKind.Property:
5070 var m = member as IInterfaceMemberSpec;
5071 return m.MemberType.IsDelegate || m.MemberType == InternalType.Dynamic;
5077 public static bool IsSpecialMethodInvocation (ResolveContext ec, MethodSpec method, Location loc)
5079 if (!method.IsReservedMethod)
5082 if (ec.HasSet (ResolveContext.Options.InvokeSpecialName) || ec.CurrentMemberDefinition.IsCompilerGenerated)
5085 ec.Report.SymbolRelatedToPreviousError (method);
5086 ec.Report.Error (571, loc, "`{0}': cannot explicitly call operator or accessor",
5087 method.GetSignatureForError ());
5093 // Used to decide whether call or callvirt is needed
5095 static bool IsVirtualCallRequired (Expression instance, MethodSpec method)
5098 // There are 2 scenarious where we emit callvirt
5100 // Case 1: A method is virtual and it's not used to call base
5101 // Case 2: A method instance expression can be null. In this casen callvirt ensures
5102 // correct NRE exception when the method is called
5104 var decl_type = method.DeclaringType;
5105 if (decl_type.IsStruct || decl_type.IsEnum)
5108 if (instance is BaseThis)
5112 // It's non-virtual and will never be null
5114 if (!method.IsVirtual && (instance is This || instance is New || instance is ArrayCreation || instance is DelegateCreation || instance is TypeOf))
5121 /// is_base tells whether we want to force the use of the `call'
5122 /// opcode instead of using callvirt. Call is required to call
5123 /// a specific method, while callvirt will always use the most
5124 /// recent method in the vtable.
5126 /// is_static tells whether this is an invocation on a static method
5128 /// instance_expr is an expression that represents the instance
5129 /// it must be non-null if is_static is false.
5131 /// method is the method to invoke.
5133 /// Arguments is the list of arguments to pass to the method or constructor.
5135 public static void EmitCall (EmitContext ec, Expression instance_expr,
5136 MethodSpec method, Arguments Arguments, Location loc)
5138 EmitCall (ec, instance_expr, method, Arguments, loc, false, false);
5141 // `dup_args' leaves an extra copy of the arguments on the stack
5142 // `omit_args' does not leave any arguments at all.
5143 // So, basically, you could make one call with `dup_args' set to true,
5144 // and then another with `omit_args' set to true, and the two calls
5145 // would have the same set of arguments. However, each argument would
5146 // only have been evaluated once.
5147 public static void EmitCall (EmitContext ec, Expression instance_expr,
5148 MethodSpec method, Arguments Arguments, Location loc,
5149 bool dup_args, bool omit_args)
5151 LocalTemporary this_arg = null;
5153 // Speed up the check by not doing it on not allowed targets
5154 if (method.ReturnType == TypeManager.void_type && method.IsConditionallyExcluded (loc))
5158 TypeSpec iexpr_type;
5160 if (method.IsStatic) {
5162 call_op = OpCodes.Call;
5164 iexpr_type = instance_expr.Type;
5166 if (IsVirtualCallRequired (instance_expr, method)) {
5167 call_op = OpCodes.Callvirt;
5169 call_op = OpCodes.Call;
5173 // If this is ourselves, push "this"
5176 TypeSpec t = iexpr_type;
5179 // Push the instance expression
5181 if ((iexpr_type.IsStruct && (call_op == OpCodes.Callvirt || (call_op == OpCodes.Call && method.DeclaringType == iexpr_type))) ||
5182 iexpr_type.IsGenericParameter || TypeManager.IsNullableType (method.DeclaringType)) {
5184 // If the expression implements IMemoryLocation, then
5185 // we can optimize and use AddressOf on the
5188 // If not we have to use some temporary storage for
5190 var iml = instance_expr as IMemoryLocation;
5192 iml.AddressOf (ec, AddressOp.LoadStore);
5194 LocalTemporary temp = new LocalTemporary (iexpr_type);
5195 instance_expr.Emit (ec);
5197 temp.AddressOf (ec, AddressOp.Load);
5200 // avoid the overhead of doing this all the time.
5202 t = ReferenceContainer.MakeType (iexpr_type);
5203 } else if (iexpr_type.IsEnum || iexpr_type.IsStruct) {
5204 instance_expr.Emit (ec);
5205 ec.Emit (OpCodes.Box, iexpr_type);
5206 t = iexpr_type = TypeManager.object_type;
5208 instance_expr.Emit (ec);
5212 ec.Emit (OpCodes.Dup);
5213 if (Arguments != null && Arguments.Count != 0) {
5214 this_arg = new LocalTemporary (t);
5215 this_arg.Store (ec);
5221 if (!omit_args && Arguments != null)
5222 Arguments.Emit (ec, dup_args, this_arg);
5224 if (call_op == OpCodes.Callvirt && (iexpr_type.IsGenericParameter || iexpr_type.IsStruct)) {
5225 ec.Emit (OpCodes.Constrained, iexpr_type);
5228 if (method.Parameters.HasArglist) {
5229 Type[] varargs_types = GetVarargsTypes (method, Arguments);
5230 ec.Emit (call_op, method, varargs_types);
5237 // and DoFoo is not virtual, you can omit the callvirt,
5238 // because you don't need the null checking behavior.
5240 ec.Emit (call_op, method);
5243 public override void Emit (EmitContext ec)
5245 mg.EmitCall (ec, arguments);
5248 public override void EmitStatement (EmitContext ec)
5253 // Pop the return value if there is one
5255 if (type != TypeManager.void_type)
5256 ec.Emit (OpCodes.Pop);
5259 public override SLE.Expression MakeExpression (BuilderContext ctx)
5261 return MakeExpression (ctx, mg.InstanceExpression, mg.BestCandidate, arguments);
5264 public static SLE.Expression MakeExpression (BuilderContext ctx, Expression instance, MethodSpec mi, Arguments args)
5266 var instance_expr = instance == null ? null : instance.MakeExpression (ctx);
5267 return SLE.Expression.Call (instance_expr, (MethodInfo) mi.GetMetaInfo (), Arguments.MakeExpression (args, ctx));
5272 /// Implements the new expression
5274 public class New : ExpressionStatement, IMemoryLocation {
5275 protected Arguments Arguments;
5278 // During bootstrap, it contains the RequestedType,
5279 // but if `type' is not null, it *might* contain a NewDelegate
5280 // (because of field multi-initialization)
5282 protected Expression RequestedType;
5284 protected MethodSpec method;
5286 public New (Expression requested_type, Arguments arguments, Location l)
5288 RequestedType = requested_type;
5289 Arguments = arguments;
5294 /// Converts complex core type syntax like 'new int ()' to simple constant
5296 public static Constant Constantify (TypeSpec t)
5298 if (t == TypeManager.int32_type)
5299 return new IntConstant (0, Location.Null);
5300 if (t == TypeManager.uint32_type)
5301 return new UIntConstant (0, Location.Null);
5302 if (t == TypeManager.int64_type)
5303 return new LongConstant (0, Location.Null);
5304 if (t == TypeManager.uint64_type)
5305 return new ULongConstant (0, Location.Null);
5306 if (t == TypeManager.float_type)
5307 return new FloatConstant (0, Location.Null);
5308 if (t == TypeManager.double_type)
5309 return new DoubleConstant (0, Location.Null);
5310 if (t == TypeManager.short_type)
5311 return new ShortConstant (0, Location.Null);
5312 if (t == TypeManager.ushort_type)
5313 return new UShortConstant (0, Location.Null);
5314 if (t == TypeManager.sbyte_type)
5315 return new SByteConstant (0, Location.Null);
5316 if (t == TypeManager.byte_type)
5317 return new ByteConstant (0, Location.Null);
5318 if (t == TypeManager.char_type)
5319 return new CharConstant ('\0', Location.Null);
5320 if (t == TypeManager.bool_type)
5321 return new BoolConstant (false, Location.Null);
5322 if (t == TypeManager.decimal_type)
5323 return new DecimalConstant (0, Location.Null);
5324 if (TypeManager.IsEnumType (t))
5325 return new EnumConstant (Constantify (EnumSpec.GetUnderlyingType (t)), t);
5326 if (TypeManager.IsNullableType (t))
5327 return Nullable.LiftedNull.Create (t, Location.Null);
5333 // Checks whether the type is an interface that has the
5334 // [ComImport, CoClass] attributes and must be treated
5337 public Expression CheckComImport (ResolveContext ec)
5339 if (!type.IsInterface)
5343 // Turn the call into:
5344 // (the-interface-stated) (new class-referenced-in-coclassattribute ())
5346 var real_class = type.MemberDefinition.GetAttributeCoClass ();
5347 if (real_class == null)
5350 New proxy = new New (new TypeExpression (real_class, loc), Arguments, loc);
5351 Cast cast = new Cast (new TypeExpression (type, loc), proxy, loc);
5352 return cast.Resolve (ec);
5355 public override Expression CreateExpressionTree (ResolveContext ec)
5358 if (method == null) {
5359 args = new Arguments (1);
5360 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
5362 args = Arguments.CreateForExpressionTree (ec,
5363 Arguments, new TypeOfMethod (method, loc));
5366 return CreateExpressionFactoryCall (ec, "New", args);
5369 protected override Expression DoResolve (ResolveContext ec)
5371 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec, false);
5376 eclass = ExprClass.Value;
5378 if (type.IsPointer) {
5379 ec.Report.Error (1919, loc, "Unsafe type `{0}' cannot be used in an object creation expression",
5380 TypeManager.CSharpName (type));
5384 if (Arguments == null) {
5385 Constant c = Constantify (type);
5387 return ReducedExpression.Create (c.Resolve (ec), this);
5390 if (TypeManager.IsDelegateType (type)) {
5391 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5394 var tparam = type as TypeParameterSpec;
5395 if (tparam != null) {
5396 if (!tparam.HasSpecialConstructor && !tparam.HasSpecialStruct) {
5397 ec.Report.Error (304, loc,
5398 "Cannot create an instance of the variable type `{0}' because it does not have the new() constraint",
5399 TypeManager.CSharpName (type));
5402 if ((Arguments != null) && (Arguments.Count != 0)) {
5403 ec.Report.Error (417, loc,
5404 "`{0}': cannot provide arguments when creating an instance of a variable type",
5405 TypeManager.CSharpName (type));
5408 if (TypeManager.activator_create_instance == null) {
5409 TypeSpec activator_type = TypeManager.CoreLookupType (ec.Compiler, "System", "Activator", MemberKind.Class, true);
5410 if (activator_type != null) {
5411 TypeManager.activator_create_instance = TypeManager.GetPredefinedMethod (
5412 activator_type, MemberFilter.Method ("CreateInstance", 1, ParametersCompiled.EmptyReadOnlyParameters, null), loc);
5419 if (type.IsStatic) {
5420 ec.Report.SymbolRelatedToPreviousError (type);
5421 ec.Report.Error (712, loc, "Cannot create an instance of the static class `{0}'", TypeManager.CSharpName (type));
5425 if (type.IsInterface || type.IsAbstract){
5426 if (!TypeManager.IsGenericType (type)) {
5427 RequestedType = CheckComImport (ec);
5428 if (RequestedType != null)
5429 return RequestedType;
5432 ec.Report.SymbolRelatedToPreviousError (type);
5433 ec.Report.Error (144, loc, "Cannot create an instance of the abstract class or interface `{0}'", TypeManager.CSharpName (type));
5438 // Any struct always defines parameterless constructor
5440 if (type.IsStruct && Arguments == null)
5444 if (Arguments != null) {
5445 Arguments.Resolve (ec, out dynamic);
5450 method = ConstructorLookup (ec, type, ref Arguments, loc);
5453 Arguments.Insert (0, new Argument (new TypeOf (texpr, loc).Resolve (ec), Argument.AType.DynamicTypeName));
5454 return new DynamicConstructorBinder (type, Arguments, loc).Resolve (ec);
5460 bool DoEmitTypeParameter (EmitContext ec)
5462 var ctor_factory = TypeManager.activator_create_instance.MakeGenericMethod (type);
5463 var tparam = (TypeParameterSpec) type;
5465 if (tparam.IsReferenceType) {
5466 ec.Emit (OpCodes.Call, ctor_factory);
5470 // Allow DoEmit() to be called multiple times.
5471 // We need to create a new LocalTemporary each time since
5472 // you can't share LocalBuilders among ILGeneators.
5473 LocalTemporary temp = new LocalTemporary (type);
5475 Label label_activator = ec.DefineLabel ();
5476 Label label_end = ec.DefineLabel ();
5478 temp.AddressOf (ec, AddressOp.Store);
5479 ec.Emit (OpCodes.Initobj, type);
5482 ec.Emit (OpCodes.Box, type);
5483 ec.Emit (OpCodes.Brfalse, label_activator);
5485 temp.AddressOf (ec, AddressOp.Store);
5486 ec.Emit (OpCodes.Initobj, type);
5488 ec.Emit (OpCodes.Br_S, label_end);
5490 ec.MarkLabel (label_activator);
5492 ec.Emit (OpCodes.Call, ctor_factory);
5493 ec.MarkLabel (label_end);
5498 // This Emit can be invoked in two contexts:
5499 // * As a mechanism that will leave a value on the stack (new object)
5500 // * As one that wont (init struct)
5502 // If we are dealing with a ValueType, we have a few
5503 // situations to deal with:
5505 // * The target is a ValueType, and we have been provided
5506 // the instance (this is easy, we are being assigned).
5508 // * The target of New is being passed as an argument,
5509 // to a boxing operation or a function that takes a
5512 // In this case, we need to create a temporary variable
5513 // that is the argument of New.
5515 // Returns whether a value is left on the stack
5517 // *** Implementation note ***
5519 // To benefit from this optimization, each assignable expression
5520 // has to manually cast to New and call this Emit.
5522 // TODO: It's worth to implement it for arrays and fields
5524 public virtual bool Emit (EmitContext ec, IMemoryLocation target)
5526 bool is_value_type = TypeManager.IsValueType (type);
5527 VariableReference vr = target as VariableReference;
5529 if (target != null && is_value_type && (vr != null || method == null)) {
5530 target.AddressOf (ec, AddressOp.Store);
5531 } else if (vr != null && vr.IsRef) {
5535 if (Arguments != null)
5536 Arguments.Emit (ec);
5538 if (is_value_type) {
5539 if (method == null) {
5540 ec.Emit (OpCodes.Initobj, type);
5545 ec.Emit (OpCodes.Call, method);
5550 if (type is TypeParameterSpec)
5551 return DoEmitTypeParameter (ec);
5553 ec.Emit (OpCodes.Newobj, method);
5557 public override void Emit (EmitContext ec)
5559 LocalTemporary v = null;
5560 if (method == null && TypeManager.IsValueType (type)) {
5561 // TODO: Use temporary variable from pool
5562 v = new LocalTemporary (type);
5569 public override void EmitStatement (EmitContext ec)
5571 LocalTemporary v = null;
5572 if (method == null && TypeManager.IsValueType (type)) {
5573 // TODO: Use temporary variable from pool
5574 v = new LocalTemporary (type);
5578 ec.Emit (OpCodes.Pop);
5581 public virtual bool HasInitializer {
5587 public void AddressOf (EmitContext ec, AddressOp mode)
5589 EmitAddressOf (ec, mode);
5592 protected virtual IMemoryLocation EmitAddressOf (EmitContext ec, AddressOp mode)
5594 LocalTemporary value_target = new LocalTemporary (type);
5596 if (type is TypeParameterSpec) {
5597 DoEmitTypeParameter (ec);
5598 value_target.Store (ec);
5599 value_target.AddressOf (ec, mode);
5600 return value_target;
5603 if (!TypeManager.IsStruct (type)){
5605 // We throw an exception. So far, I believe we only need to support
5607 // foreach (int j in new StructType ())
5610 throw new Exception ("AddressOf should not be used for classes");
5613 value_target.AddressOf (ec, AddressOp.Store);
5615 if (method == null) {
5616 ec.Emit (OpCodes.Initobj, type);
5618 if (Arguments != null)
5619 Arguments.Emit (ec);
5621 ec.Emit (OpCodes.Call, method);
5624 value_target.AddressOf (ec, mode);
5625 return value_target;
5628 protected override void CloneTo (CloneContext clonectx, Expression t)
5630 New target = (New) t;
5632 target.RequestedType = RequestedType.Clone (clonectx);
5633 if (Arguments != null){
5634 target.Arguments = Arguments.Clone (clonectx);
5638 public override SLE.Expression MakeExpression (BuilderContext ctx)
5640 return SLE.Expression.New ((ConstructorInfo) method.GetMetaInfo (), Arguments.MakeExpression (Arguments, ctx));
5644 public class ArrayInitializer : Expression
5646 List<Expression> elements;
5648 public ArrayInitializer (List<Expression> init, Location loc)
5654 public ArrayInitializer (int count, Location loc)
5656 elements = new List<Expression> (count);
5660 public ArrayInitializer (Location loc)
5665 public void Add (Expression expr)
5667 elements.Add (expr);
5670 public override Expression CreateExpressionTree (ResolveContext ec)
5672 throw new NotSupportedException ("ET");
5675 protected override void CloneTo (CloneContext clonectx, Expression t)
5677 var target = (ArrayInitializer) t;
5679 target.elements = new List<Expression> (elements.Count);
5680 foreach (var element in elements)
5681 target.elements.Add (element.Clone (clonectx));
5685 get { return elements.Count; }
5688 protected override Expression DoResolve (ResolveContext rc)
5690 var current_field = rc.CurrentMemberDefinition as FieldBase;
5691 return new ArrayCreation (new TypeExpression (current_field.MemberType, current_field.Location), this).Resolve (rc);
5694 public override void Emit (EmitContext ec)
5696 throw new InternalErrorException ("Missing Resolve call");
5699 public Expression this [int index] {
5700 get { return elements [index]; }
5705 /// 14.5.10.2: Represents an array creation expression.
5709 /// There are two possible scenarios here: one is an array creation
5710 /// expression that specifies the dimensions and optionally the
5711 /// initialization data and the other which does not need dimensions
5712 /// specified but where initialization data is mandatory.
5714 public class ArrayCreation : Expression
5716 FullNamedExpression requested_base_type;
5717 ArrayInitializer initializers;
5720 // The list of Argument types.
5721 // This is used to construct the `newarray' or constructor signature
5723 protected List<Expression> arguments;
5725 protected TypeSpec array_element_type;
5726 int num_arguments = 0;
5727 protected int dimensions;
5728 protected readonly ComposedTypeSpecifier rank;
5729 Expression first_emit;
5730 LocalTemporary first_emit_temp;
5732 protected List<Expression> array_data;
5734 Dictionary<int, int> bounds;
5736 // The number of constants in array initializers
5737 int const_initializers_count;
5738 bool only_constant_initializers;
5740 public ArrayCreation (FullNamedExpression requested_base_type, List<Expression> exprs, ComposedTypeSpecifier rank, ArrayInitializer initializers, Location l)
5741 : this (requested_base_type, rank, initializers, l)
5743 arguments = new List<Expression> (exprs);
5744 num_arguments = arguments.Count;
5748 // For expressions like int[] foo = new int[] { 1, 2, 3 };
5750 public ArrayCreation (FullNamedExpression requested_base_type, ComposedTypeSpecifier rank, ArrayInitializer initializers, Location loc)
5752 this.requested_base_type = requested_base_type;
5754 this.initializers = initializers;
5758 num_arguments = rank.Dimension;
5762 // For compiler generated single dimensional arrays only
5764 public ArrayCreation (FullNamedExpression requested_base_type, ArrayInitializer initializers, Location loc)
5765 : this (requested_base_type, ComposedTypeSpecifier.SingleDimension, initializers, loc)
5770 // For expressions like int[] foo = { 1, 2, 3 };
5772 public ArrayCreation (FullNamedExpression requested_base_type, ArrayInitializer initializers)
5773 : this (requested_base_type, null, initializers, initializers.Location)
5777 protected override void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
5779 ec.Report.Error (248, loc, "Cannot create an array with a negative size");
5782 bool CheckIndices (ResolveContext ec, ArrayInitializer probe, int idx, bool specified_dims, int child_bounds)
5784 if (initializers != null && bounds == null) {
5786 // We use this to store all the date values in the order in which we
5787 // will need to store them in the byte blob later
5789 array_data = new List<Expression> ();
5790 bounds = new Dictionary<int, int> ();
5793 if (specified_dims) {
5794 Expression a = arguments [idx];
5799 a = ConvertExpressionToArrayIndex (ec, a);
5805 if (initializers != null) {
5806 Constant c = a as Constant;
5807 if (c == null && a is ArrayIndexCast)
5808 c = ((ArrayIndexCast) a).Child as Constant;
5811 ec.Report.Error (150, a.Location, "A constant value is expected");
5817 value = System.Convert.ToInt32 (c.GetValue ());
5819 ec.Report.Error (150, a.Location, "A constant value is expected");
5823 // TODO: probe.Count does not fit ulong in
5824 if (value != probe.Count) {
5825 ec.Report.Error (847, loc, "An array initializer of length `{0}' was expected", value.ToString ());
5829 bounds[idx] = value;
5833 if (initializers == null)
5836 only_constant_initializers = true;
5837 for (int i = 0; i < probe.Count; ++i) {
5839 if (o is ArrayInitializer) {
5840 var sub_probe = o as ArrayInitializer;
5841 if (idx + 1 >= dimensions){
5842 ec.Report.Error (623, loc, "Array initializers can only be used in a variable or field initializer. Try using a new expression instead");
5846 bool ret = CheckIndices (ec, sub_probe, idx + 1, specified_dims, child_bounds - 1);
5849 } else if (child_bounds > 1) {
5850 ec.Report.Error (846, o.Location, "A nested array initializer was expected");
5852 Expression element = ResolveArrayElement (ec, o);
5853 if (element == null)
5856 // Initializers with the default values can be ignored
5857 Constant c = element as Constant;
5859 if (!c.IsDefaultInitializer (array_element_type)) {
5860 ++const_initializers_count;
5863 only_constant_initializers = false;
5866 array_data.Add (element);
5873 public override Expression CreateExpressionTree (ResolveContext ec)
5877 if (array_data == null) {
5878 args = new Arguments (arguments.Count + 1);
5879 args.Add (new Argument (new TypeOf (new TypeExpression (array_element_type, loc), loc)));
5880 foreach (Expression a in arguments)
5881 args.Add (new Argument (a.CreateExpressionTree (ec)));
5883 return CreateExpressionFactoryCall (ec, "NewArrayBounds", args);
5886 if (dimensions > 1) {
5887 ec.Report.Error (838, loc, "An expression tree cannot contain a multidimensional array initializer");
5891 args = new Arguments (array_data == null ? 1 : array_data.Count + 1);
5892 args.Add (new Argument (new TypeOf (new TypeExpression (array_element_type, loc), loc)));
5893 if (array_data != null) {
5894 for (int i = 0; i < array_data.Count; ++i) {
5895 Expression e = array_data [i];
5896 args.Add (new Argument (e.CreateExpressionTree (ec)));
5900 return CreateExpressionFactoryCall (ec, "NewArrayInit", args);
5903 public void UpdateIndices ()
5906 for (var probe = initializers; probe != null;) {
5907 if (probe.Count > 0 && probe [0] is ArrayInitializer) {
5908 Expression e = new IntConstant (probe.Count, Location.Null);
5911 bounds [i++] = probe.Count;
5913 probe = (ArrayInitializer) probe[0];
5916 Expression e = new IntConstant (probe.Count, Location.Null);
5919 bounds [i++] = probe.Count;
5925 protected virtual Expression ResolveArrayElement (ResolveContext ec, Expression element)
5927 element = element.Resolve (ec);
5928 if (element == null)
5931 if (element is CompoundAssign.TargetExpression) {
5932 if (first_emit != null)
5933 throw new InternalErrorException ("Can only handle one mutator at a time");
5934 first_emit = element;
5935 element = first_emit_temp = new LocalTemporary (element.Type);
5938 return Convert.ImplicitConversionRequired (
5939 ec, element, array_element_type, loc);
5942 protected bool ResolveInitializers (ResolveContext ec)
5944 if (arguments != null) {
5946 for (int i = 0; i < arguments.Count; ++i) {
5947 res &= CheckIndices (ec, initializers, i, true, dimensions);
5948 if (initializers != null)
5955 arguments = new List<Expression> ();
5957 if (!CheckIndices (ec, initializers, 0, false, dimensions))
5966 // Resolved the type of the array
5968 bool ResolveArrayType (ResolveContext ec)
5970 if (requested_base_type is VarExpr) {
5971 ec.Report.Error (820, loc, "An implicitly typed local variable declarator cannot use an array initializer");
5978 FullNamedExpression array_type_expr;
5979 if (num_arguments > 0) {
5980 array_type_expr = new ComposedCast (requested_base_type, rank);
5982 array_type_expr = requested_base_type;
5985 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec, false);
5986 if (array_type_expr == null)
5989 type = array_type_expr.Type;
5990 var ac = type as ArrayContainer;
5992 ec.Report.Error (622, loc, "Can only use array initializer expressions to assign to array types. Try using a new expression instead");
5996 array_element_type = ac.Element;
5997 dimensions = ac.Rank;
6002 protected override Expression DoResolve (ResolveContext ec)
6007 if (!ResolveArrayType (ec))
6011 // validate the initializers and fill in any missing bits
6013 if (!ResolveInitializers (ec))
6016 eclass = ExprClass.Value;
6020 byte [] MakeByteBlob ()
6025 int count = array_data.Count;
6027 TypeSpec element_type = array_element_type;
6028 if (TypeManager.IsEnumType (element_type))
6029 element_type = EnumSpec.GetUnderlyingType (element_type);
6031 factor = GetTypeSize (element_type);
6033 throw new Exception ("unrecognized type in MakeByteBlob: " + element_type);
6035 data = new byte [(count * factor + 3) & ~3];
6038 for (int i = 0; i < count; ++i) {
6039 object v = array_data [i];
6041 if (v is EnumConstant)
6042 v = ((EnumConstant) v).Child;
6044 if (v is Constant && !(v is StringConstant))
6045 v = ((Constant) v).GetValue ();
6051 if (element_type == TypeManager.int64_type){
6052 if (!(v is Expression)){
6053 long val = (long) v;
6055 for (int j = 0; j < factor; ++j) {
6056 data [idx + j] = (byte) (val & 0xFF);
6060 } else if (element_type == TypeManager.uint64_type){
6061 if (!(v is Expression)){
6062 ulong val = (ulong) v;
6064 for (int j = 0; j < factor; ++j) {
6065 data [idx + j] = (byte) (val & 0xFF);
6069 } else if (element_type == TypeManager.float_type) {
6070 if (!(v is Expression)){
6071 element = BitConverter.GetBytes ((float) v);
6073 for (int j = 0; j < factor; ++j)
6074 data [idx + j] = element [j];
6075 if (!BitConverter.IsLittleEndian)
6076 System.Array.Reverse (data, idx, 4);
6078 } else if (element_type == TypeManager.double_type) {
6079 if (!(v is Expression)){
6080 element = BitConverter.GetBytes ((double) v);
6082 for (int j = 0; j < factor; ++j)
6083 data [idx + j] = element [j];
6085 // FIXME: Handle the ARM float format.
6086 if (!BitConverter.IsLittleEndian)
6087 System.Array.Reverse (data, idx, 8);
6089 } else if (element_type == TypeManager.char_type){
6090 if (!(v is Expression)){
6091 int val = (int) ((char) v);
6093 data [idx] = (byte) (val & 0xff);
6094 data [idx+1] = (byte) (val >> 8);
6096 } else if (element_type == TypeManager.short_type){
6097 if (!(v is Expression)){
6098 int val = (int) ((short) v);
6100 data [idx] = (byte) (val & 0xff);
6101 data [idx+1] = (byte) (val >> 8);
6103 } else if (element_type == TypeManager.ushort_type){
6104 if (!(v is Expression)){
6105 int val = (int) ((ushort) v);
6107 data [idx] = (byte) (val & 0xff);
6108 data [idx+1] = (byte) (val >> 8);
6110 } else if (element_type == TypeManager.int32_type) {
6111 if (!(v is Expression)){
6114 data [idx] = (byte) (val & 0xff);
6115 data [idx+1] = (byte) ((val >> 8) & 0xff);
6116 data [idx+2] = (byte) ((val >> 16) & 0xff);
6117 data [idx+3] = (byte) (val >> 24);
6119 } else if (element_type == TypeManager.uint32_type) {
6120 if (!(v is Expression)){
6121 uint val = (uint) v;
6123 data [idx] = (byte) (val & 0xff);
6124 data [idx+1] = (byte) ((val >> 8) & 0xff);
6125 data [idx+2] = (byte) ((val >> 16) & 0xff);
6126 data [idx+3] = (byte) (val >> 24);
6128 } else if (element_type == TypeManager.sbyte_type) {
6129 if (!(v is Expression)){
6130 sbyte val = (sbyte) v;
6131 data [idx] = (byte) val;
6133 } else if (element_type == TypeManager.byte_type) {
6134 if (!(v is Expression)){
6135 byte val = (byte) v;
6136 data [idx] = (byte) val;
6138 } else if (element_type == TypeManager.bool_type) {
6139 if (!(v is Expression)){
6140 bool val = (bool) v;
6141 data [idx] = (byte) (val ? 1 : 0);
6143 } else if (element_type == TypeManager.decimal_type){
6144 if (!(v is Expression)){
6145 int [] bits = Decimal.GetBits ((decimal) v);
6148 // FIXME: For some reason, this doesn't work on the MS runtime.
6149 int [] nbits = new int [4];
6150 nbits [0] = bits [3];
6151 nbits [1] = bits [2];
6152 nbits [2] = bits [0];
6153 nbits [3] = bits [1];
6155 for (int j = 0; j < 4; j++){
6156 data [p++] = (byte) (nbits [j] & 0xff);
6157 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6158 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6159 data [p++] = (byte) (nbits [j] >> 24);
6163 throw new Exception ("Unrecognized type in MakeByteBlob: " + element_type);
6173 public override SLE.Expression MakeExpression (BuilderContext ctx)
6175 var initializers = new SLE.Expression [array_data.Count];
6176 for (var i = 0; i < initializers.Length; i++) {
6177 if (array_data [i] == null)
6178 initializers [i] = SLE.Expression.Default (array_element_type.GetMetaInfo ());
6180 initializers [i] = array_data [i].MakeExpression (ctx);
6183 return SLE.Expression.NewArrayInit (array_element_type.GetMetaInfo (), initializers);
6187 // Emits the initializers for the array
6189 void EmitStaticInitializers (EmitContext ec)
6191 // FIXME: This should go to Resolve !
6192 if (TypeManager.void_initializearray_array_fieldhandle == null) {
6193 TypeManager.void_initializearray_array_fieldhandle = TypeManager.GetPredefinedMethod (
6194 TypeManager.runtime_helpers_type, "InitializeArray", loc,
6195 TypeManager.array_type, TypeManager.runtime_field_handle_type);
6196 if (TypeManager.void_initializearray_array_fieldhandle == null)
6201 // First, the static data
6205 byte [] data = MakeByteBlob ();
6207 fb = RootContext.MakeStaticData (data);
6209 ec.Emit (OpCodes.Dup);
6210 ec.Emit (OpCodes.Ldtoken, fb);
6211 ec.Emit (OpCodes.Call, TypeManager.void_initializearray_array_fieldhandle);
6215 // Emits pieces of the array that can not be computed at compile
6216 // time (variables and string locations).
6218 // This always expect the top value on the stack to be the array
6220 void EmitDynamicInitializers (EmitContext ec, bool emitConstants)
6222 int dims = bounds.Count;
6223 var current_pos = new int [dims];
6225 for (int i = 0; i < array_data.Count; i++){
6227 Expression e = array_data [i];
6228 var c = e as Constant;
6230 // Constant can be initialized via StaticInitializer
6231 if (c == null || (c != null && emitConstants && !c.IsDefaultInitializer (array_element_type))) {
6232 TypeSpec etype = e.Type;
6234 ec.Emit (OpCodes.Dup);
6236 for (int idx = 0; idx < dims; idx++)
6237 ec.EmitInt (current_pos [idx]);
6240 // If we are dealing with a struct, get the
6241 // address of it, so we can store it.
6243 if ((dims == 1) && TypeManager.IsStruct (etype) &&
6244 (!TypeManager.IsBuiltinOrEnum (etype) ||
6245 etype == TypeManager.decimal_type)) {
6247 ec.Emit (OpCodes.Ldelema, etype);
6252 ec.EmitArrayStore ((ArrayContainer) type);
6258 for (int j = dims - 1; j >= 0; j--){
6260 if (current_pos [j] < bounds [j])
6262 current_pos [j] = 0;
6267 public override void Emit (EmitContext ec)
6269 if (first_emit != null) {
6270 first_emit.Emit (ec);
6271 first_emit_temp.Store (ec);
6274 foreach (Expression e in arguments)
6277 ec.EmitArrayNew ((ArrayContainer) type);
6279 if (initializers == null)
6282 // Emit static initializer for arrays which have contain more than 2 items and
6283 // the static initializer will initialize at least 25% of array values or there
6284 // is more than 10 items to be initialized
6285 // NOTE: const_initializers_count does not contain default constant values.
6286 if (const_initializers_count > 2 && (array_data.Count > 10 || const_initializers_count * 4 > (array_data.Count)) &&
6287 (TypeManager.IsPrimitiveType (array_element_type) || TypeManager.IsEnumType (array_element_type))) {
6288 EmitStaticInitializers (ec);
6290 if (!only_constant_initializers)
6291 EmitDynamicInitializers (ec, false);
6293 EmitDynamicInitializers (ec, true);
6296 if (first_emit_temp != null)
6297 first_emit_temp.Release (ec);
6300 public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
6302 // no multi dimensional or jagged arrays
6303 if (arguments.Count != 1 || array_element_type.IsArray) {
6304 base.EncodeAttributeValue (rc, enc, targetType);
6308 // No array covariance, except for array -> object
6309 if (type != targetType) {
6310 if (targetType != TypeManager.object_type) {
6311 base.EncodeAttributeValue (rc, enc, targetType);
6315 if (enc.Encode (type) == AttributeEncoder.EncodedTypeProperties.DynamicType) {
6316 Attribute.Error_AttributeArgumentIsDynamic (rc, loc);
6321 // Single dimensional array of 0 size
6322 if (array_data == null) {
6323 IntConstant ic = arguments[0] as IntConstant;
6324 if (ic == null || !ic.IsDefaultValue) {
6325 base.EncodeAttributeValue (rc, enc, targetType);
6327 enc.Stream.Write (0);
6333 enc.Stream.Write ((int) array_data.Count);
6334 foreach (var element in array_data) {
6335 element.EncodeAttributeValue (rc, enc, array_element_type);
6339 protected override void CloneTo (CloneContext clonectx, Expression t)
6341 ArrayCreation target = (ArrayCreation) t;
6343 if (requested_base_type != null)
6344 target.requested_base_type = (FullNamedExpression)requested_base_type.Clone (clonectx);
6346 if (arguments != null){
6347 target.arguments = new List<Expression> (arguments.Count);
6348 foreach (Expression e in arguments)
6349 target.arguments.Add (e.Clone (clonectx));
6352 if (initializers != null)
6353 target.initializers = (ArrayInitializer) initializers.Clone (clonectx);
6358 // Represents an implicitly typed array epxression
6360 class ImplicitlyTypedArrayCreation : ArrayCreation
6362 TypeInferenceContext best_type_inference;
6364 public ImplicitlyTypedArrayCreation (ComposedTypeSpecifier rank, ArrayInitializer initializers, Location loc)
6365 : base (null, rank, initializers, loc)
6369 public ImplicitlyTypedArrayCreation (ArrayInitializer initializers, Location loc)
6370 : base (null, initializers, loc)
6374 protected override Expression DoResolve (ResolveContext ec)
6379 dimensions = rank.Dimension;
6381 best_type_inference = new TypeInferenceContext ();
6383 if (!ResolveInitializers (ec))
6386 best_type_inference.FixAllTypes (ec);
6387 array_element_type = best_type_inference.InferredTypeArguments[0];
6388 best_type_inference = null;
6390 if (array_element_type == null || array_element_type == InternalType.MethodGroup || array_element_type == InternalType.AnonymousMethod ||
6391 arguments.Count != rank.Dimension) {
6392 ec.Report.Error (826, loc,
6393 "The type of an implicitly typed array cannot be inferred from the initializer. Try specifying array type explicitly");
6398 // At this point we found common base type for all initializer elements
6399 // but we have to be sure that all static initializer elements are of
6402 UnifyInitializerElement (ec);
6404 type = ArrayContainer.MakeType (array_element_type, dimensions);
6405 eclass = ExprClass.Value;
6410 // Converts static initializer only
6412 void UnifyInitializerElement (ResolveContext ec)
6414 for (int i = 0; i < array_data.Count; ++i) {
6415 Expression e = array_data[i];
6417 array_data [i] = Convert.ImplicitConversion (ec, e, array_element_type, Location.Null);
6421 protected override Expression ResolveArrayElement (ResolveContext ec, Expression element)
6423 element = element.Resolve (ec);
6424 if (element != null)
6425 best_type_inference.AddCommonTypeBound (element.Type);
6431 public sealed class CompilerGeneratedThis : This
6433 public static This Instance = new CompilerGeneratedThis ();
6435 private CompilerGeneratedThis ()
6436 : base (Location.Null)
6440 public CompilerGeneratedThis (TypeSpec type, Location loc)
6446 protected override Expression DoResolve (ResolveContext ec)
6448 eclass = ExprClass.Variable;
6450 type = ec.CurrentType;
6455 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
6462 /// Represents the `this' construct
6465 public class This : VariableReference
6467 sealed class ThisVariable : ILocalVariable
6469 public static readonly ILocalVariable Instance = new ThisVariable ();
6471 public void Emit (EmitContext ec)
6473 ec.Emit (OpCodes.Ldarg_0);
6476 public void EmitAssign (EmitContext ec)
6478 throw new InvalidOperationException ();
6481 public void EmitAddressOf (EmitContext ec)
6483 ec.Emit (OpCodes.Ldarg_0);
6487 VariableInfo variable_info;
6489 public This (Location loc)
6496 public override string Name {
6497 get { return "this"; }
6500 public override bool IsRef {
6501 get { return type.IsStruct; }
6504 protected override ILocalVariable Variable {
6505 get { return ThisVariable.Instance; }
6508 public override VariableInfo VariableInfo {
6509 get { return variable_info; }
6512 public override bool IsFixed {
6513 get { return false; }
6518 protected virtual void Error_ThisNotAvailable (ResolveContext ec)
6520 if (ec.IsStatic && !ec.HasSet (ResolveContext.Options.ConstantScope)) {
6521 ec.Report.Error (26, loc, "Keyword `this' is not valid in a static property, static method, or static field initializer");
6522 } else if (ec.CurrentAnonymousMethod != null) {
6523 ec.Report.Error (1673, loc,
6524 "Anonymous methods inside structs cannot access instance members of `this'. " +
6525 "Consider copying `this' to a local variable outside the anonymous method and using the local instead");
6527 ec.Report.Error (27, loc, "Keyword `this' is not available in the current context");
6531 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
6536 AnonymousMethodStorey storey = ae.Storey;
6537 while (storey != null) {
6538 AnonymousMethodStorey temp = storey.Parent as AnonymousMethodStorey;
6540 return storey.HoistedThis;
6548 public static bool IsThisAvailable (ResolveContext ec, bool ignoreAnonymous)
6550 if (ec.IsStatic || ec.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.BaseInitializer | ResolveContext.Options.ConstantScope))
6553 if (ignoreAnonymous || ec.CurrentAnonymousMethod == null)
6556 if (TypeManager.IsStruct (ec.CurrentType) && ec.CurrentIterator == null)
6562 public virtual void ResolveBase (ResolveContext ec)
6564 if (!IsThisAvailable (ec, false)) {
6565 Error_ThisNotAvailable (ec);
6568 var block = ec.CurrentBlock;
6569 if (block != null) {
6570 if (block.Toplevel.ThisVariable != null)
6571 variable_info = block.Toplevel.ThisVariable.VariableInfo;
6573 AnonymousExpression am = ec.CurrentAnonymousMethod;
6574 if (am != null && ec.IsVariableCapturingRequired) {
6575 am.SetHasThisAccess ();
6579 eclass = ExprClass.Variable;
6580 type = ec.CurrentType;
6584 // Called from Invocation to check if the invocation is correct
6586 public override void CheckMarshalByRefAccess (ResolveContext ec)
6588 if ((variable_info != null) && !(TypeManager.IsStruct (type) && ec.OmitStructFlowAnalysis) &&
6589 !variable_info.IsAssigned (ec)) {
6590 ec.Report.Error (188, loc,
6591 "The `this' object cannot be used before all of its fields are assigned to");
6592 variable_info.SetAssigned (ec);
6596 public override Expression CreateExpressionTree (ResolveContext ec)
6598 Arguments args = new Arguments (1);
6599 args.Add (new Argument (this));
6601 // Use typeless constant for ldarg.0 to save some
6602 // space and avoid problems with anonymous stories
6603 return CreateExpressionFactoryCall (ec, "Constant", args);
6606 protected override Expression DoResolve (ResolveContext ec)
6612 override public Expression DoResolveLValue (ResolveContext ec, Expression right_side)
6616 if (variable_info != null)
6617 variable_info.SetAssigned (ec);
6619 if (ec.CurrentType.IsClass){
6620 if (right_side == EmptyExpression.UnaryAddress)
6621 ec.Report.Error (459, loc, "Cannot take the address of `this' because it is read-only");
6622 else if (right_side == EmptyExpression.OutAccess.Instance)
6623 ec.Report.Error (1605, loc, "Cannot pass `this' as a ref or out argument because it is read-only");
6625 ec.Report.Error (1604, loc, "Cannot assign to `this' because it is read-only");
6631 public override int GetHashCode()
6633 throw new NotImplementedException ();
6636 public override bool Equals (object obj)
6638 This t = obj as This;
6645 protected override void CloneTo (CloneContext clonectx, Expression t)
6650 public override void SetHasAddressTaken ()
6657 /// Represents the `__arglist' construct
6659 public class ArglistAccess : Expression
6661 public ArglistAccess (Location loc)
6666 public override Expression CreateExpressionTree (ResolveContext ec)
6668 throw new NotSupportedException ("ET");
6671 protected override Expression DoResolve (ResolveContext ec)
6673 eclass = ExprClass.Variable;
6674 type = TypeManager.runtime_argument_handle_type;
6676 if (ec.HasSet (ResolveContext.Options.FieldInitializerScope) || !ec.CurrentBlock.Toplevel.Parameters.HasArglist) {
6677 ec.Report.Error (190, loc,
6678 "The __arglist construct is valid only within a variable argument method");
6684 public override void Emit (EmitContext ec)
6686 ec.Emit (OpCodes.Arglist);
6689 protected override void CloneTo (CloneContext clonectx, Expression target)
6696 /// Represents the `__arglist (....)' construct
6698 public class Arglist : Expression
6700 Arguments Arguments;
6702 public Arglist (Location loc)
6707 public Arglist (Arguments args, Location l)
6713 public Type[] ArgumentTypes {
6715 if (Arguments == null)
6716 return System.Type.EmptyTypes;
6718 var retval = new Type [Arguments.Count];
6719 for (int i = 0; i < retval.Length; i++)
6720 retval[i] = Arguments[i].Expr.Type.GetMetaInfo ();
6726 public override Expression CreateExpressionTree (ResolveContext ec)
6728 ec.Report.Error (1952, loc, "An expression tree cannot contain a method with variable arguments");
6732 protected override Expression DoResolve (ResolveContext ec)
6734 eclass = ExprClass.Variable;
6735 type = InternalType.Arglist;
6736 if (Arguments != null) {
6737 bool dynamic; // Can be ignored as there is always only 1 overload
6738 Arguments.Resolve (ec, out dynamic);
6744 public override void Emit (EmitContext ec)
6746 if (Arguments != null)
6747 Arguments.Emit (ec);
6750 protected override void CloneTo (CloneContext clonectx, Expression t)
6752 Arglist target = (Arglist) t;
6754 if (Arguments != null)
6755 target.Arguments = Arguments.Clone (clonectx);
6760 /// Implements the typeof operator
6762 public class TypeOf : Expression {
6763 FullNamedExpression QueriedType;
6766 public TypeOf (FullNamedExpression queried_type, Location l)
6768 QueriedType = queried_type;
6773 public TypeSpec TypeArgument {
6779 public FullNamedExpression TypeExpression {
6787 public override Expression CreateExpressionTree (ResolveContext ec)
6789 Arguments args = new Arguments (2);
6790 args.Add (new Argument (this));
6791 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
6792 return CreateExpressionFactoryCall (ec, "Constant", args);
6795 protected override Expression DoResolve (ResolveContext ec)
6797 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
6801 typearg = texpr.Type;
6803 if (typearg == TypeManager.void_type && !(QueriedType is TypeExpression)) {
6804 ec.Report.Error (673, loc, "System.Void cannot be used from C#. Use typeof (void) to get the void type object");
6805 } else if (typearg.IsPointer && !ec.IsUnsafe){
6806 UnsafeError (ec, loc);
6807 } else if (texpr is DynamicTypeExpr) {
6808 ec.Report.Error (1962, QueriedType.Location,
6809 "The typeof operator cannot be used on the dynamic type");
6812 type = TypeManager.type_type;
6813 QueriedType = texpr;
6815 return DoResolveBase ();
6818 protected Expression DoResolveBase ()
6820 if (TypeManager.system_type_get_type_from_handle == null) {
6821 TypeManager.system_type_get_type_from_handle = TypeManager.GetPredefinedMethod (
6822 TypeManager.type_type, "GetTypeFromHandle", loc, TypeManager.runtime_handle_type);
6825 // Even though what is returned is a type object, it's treated as a value by the compiler.
6826 // In particular, 'typeof (Foo).X' is something totally different from 'Foo.X'.
6827 eclass = ExprClass.Value;
6831 static bool ContainsDynamicType (TypeSpec type)
6833 if (type == InternalType.Dynamic)
6836 var element_container = type as ElementTypeSpec;
6837 if (element_container != null)
6838 return ContainsDynamicType (element_container.Element);
6840 foreach (var t in type.TypeArguments) {
6841 if (ContainsDynamicType (t)) {
6849 static bool ContainsTypeParameter (TypeSpec type)
6851 if (type.Kind == MemberKind.TypeParameter)
6854 var element_container = type as ElementTypeSpec;
6855 if (element_container != null)
6856 return ContainsTypeParameter (element_container.Element);
6858 foreach (var t in type.TypeArguments) {
6859 if (ContainsTypeParameter (t)) {
6867 public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
6869 // Target type is not System.Type therefore must be object
6870 // and we need to use different encoding sequence
6871 if (targetType != type)
6874 if (!(QueriedType is GenericOpenTypeExpr)) {
6876 while (gt != null) {
6877 if (ContainsTypeParameter (gt)) {
6878 rc.Compiler.Report.Error (416, loc, "`{0}': an attribute argument cannot use type parameters",
6879 typearg.GetSignatureForError ());
6883 gt = gt.DeclaringType;
6886 if (ContainsDynamicType (typearg)) {
6887 Attribute.Error_AttributeArgumentIsDynamic (rc, loc);
6892 enc.EncodeTypeName (typearg);
6895 public override void Emit (EmitContext ec)
6897 ec.Emit (OpCodes.Ldtoken, typearg);
6898 ec.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6901 protected override void CloneTo (CloneContext clonectx, Expression t)
6903 TypeOf target = (TypeOf) t;
6904 if (QueriedType != null)
6905 target.QueriedType = (FullNamedExpression) QueriedType.Clone (clonectx);
6909 class TypeOfMethod : TypeOfMember<MethodSpec>
6911 public TypeOfMethod (MethodSpec method, Location loc)
6912 : base (method, loc)
6916 protected override Expression DoResolve (ResolveContext ec)
6918 if (member.IsConstructor) {
6919 type = TypeManager.ctorinfo_type;
6921 type = TypeManager.ctorinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", "ConstructorInfo", MemberKind.Class, true);
6923 type = TypeManager.methodinfo_type;
6925 type = TypeManager.methodinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", "MethodInfo", MemberKind.Class, true);
6928 return base.DoResolve (ec);
6931 public override void Emit (EmitContext ec)
6933 ec.Emit (OpCodes.Ldtoken, member);
6936 ec.Emit (OpCodes.Castclass, type);
6939 protected override string GetMethodName {
6940 get { return "GetMethodFromHandle"; }
6943 protected override string RuntimeHandleName {
6944 get { return "RuntimeMethodHandle"; }
6947 protected override MethodSpec TypeFromHandle {
6949 return TypeManager.methodbase_get_type_from_handle;
6952 TypeManager.methodbase_get_type_from_handle = value;
6956 protected override MethodSpec TypeFromHandleGeneric {
6958 return TypeManager.methodbase_get_type_from_handle_generic;
6961 TypeManager.methodbase_get_type_from_handle_generic = value;
6965 protected override string TypeName {
6966 get { return "MethodBase"; }
6970 abstract class TypeOfMember<T> : Expression where T : MemberSpec
6972 protected readonly T member;
6974 protected TypeOfMember (T member, Location loc)
6976 this.member = member;
6980 public override Expression CreateExpressionTree (ResolveContext ec)
6982 Arguments args = new Arguments (2);
6983 args.Add (new Argument (this));
6984 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
6985 return CreateExpressionFactoryCall (ec, "Constant", args);
6988 protected override Expression DoResolve (ResolveContext ec)
6990 bool is_generic = member.DeclaringType.IsGenericOrParentIsGeneric;
6991 var mi = is_generic ? TypeFromHandleGeneric : TypeFromHandle;
6994 TypeSpec t = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", TypeName, MemberKind.Class, true);
6995 TypeSpec handle_type = TypeManager.CoreLookupType (ec.Compiler, "System", RuntimeHandleName, MemberKind.Struct, true);
6997 if (t == null || handle_type == null)
7000 mi = TypeManager.GetPredefinedMethod (t, GetMethodName, loc,
7002 new TypeSpec[] { handle_type, TypeManager.runtime_handle_type } :
7003 new TypeSpec[] { handle_type } );
7006 TypeFromHandleGeneric = mi;
7008 TypeFromHandle = mi;
7011 eclass = ExprClass.Value;
7015 public override void Emit (EmitContext ec)
7017 bool is_generic = member.DeclaringType.IsGenericOrParentIsGeneric;
7020 mi = TypeFromHandleGeneric;
7021 ec.Emit (OpCodes.Ldtoken, member.DeclaringType);
7023 mi = TypeFromHandle;
7026 ec.Emit (OpCodes.Call, mi);
7029 protected abstract string GetMethodName { get; }
7030 protected abstract string RuntimeHandleName { get; }
7031 protected abstract MethodSpec TypeFromHandle { get; set; }
7032 protected abstract MethodSpec TypeFromHandleGeneric { get; set; }
7033 protected abstract string TypeName { get; }
7036 class TypeOfField : TypeOfMember<FieldSpec>
7038 public TypeOfField (FieldSpec field, Location loc)
7043 protected override Expression DoResolve (ResolveContext ec)
7045 if (TypeManager.fieldinfo_type == null)
7046 TypeManager.fieldinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", TypeName, MemberKind.Class, true);
7048 type = TypeManager.fieldinfo_type;
7049 return base.DoResolve (ec);
7052 public override void Emit (EmitContext ec)
7054 ec.Emit (OpCodes.Ldtoken, member);
7058 protected override string GetMethodName {
7059 get { return "GetFieldFromHandle"; }
7062 protected override string RuntimeHandleName {
7063 get { return "RuntimeFieldHandle"; }
7066 protected override MethodSpec TypeFromHandle {
7068 return TypeManager.fieldinfo_get_field_from_handle;
7071 TypeManager.fieldinfo_get_field_from_handle = value;
7075 protected override MethodSpec TypeFromHandleGeneric {
7077 return TypeManager.fieldinfo_get_field_from_handle_generic;
7080 TypeManager.fieldinfo_get_field_from_handle_generic = value;
7084 protected override string TypeName {
7085 get { return "FieldInfo"; }
7090 /// Implements the sizeof expression
7092 public class SizeOf : Expression {
7093 readonly Expression QueriedType;
7094 TypeSpec type_queried;
7096 public SizeOf (Expression queried_type, Location l)
7098 this.QueriedType = queried_type;
7102 public override Expression CreateExpressionTree (ResolveContext ec)
7104 Error_PointerInsideExpressionTree (ec);
7108 protected override Expression DoResolve (ResolveContext ec)
7110 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
7114 type_queried = texpr.Type;
7115 if (TypeManager.IsEnumType (type_queried))
7116 type_queried = EnumSpec.GetUnderlyingType (type_queried);
7118 int size_of = GetTypeSize (type_queried);
7120 return new IntConstant (size_of, loc).Resolve (ec);
7123 if (!TypeManager.VerifyUnmanaged (ec.Compiler, type_queried, loc)){
7128 ec.Report.Error (233, loc,
7129 "`{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)",
7130 TypeManager.CSharpName (type_queried));
7133 type = TypeManager.int32_type;
7134 eclass = ExprClass.Value;
7138 public override void Emit (EmitContext ec)
7140 ec.Emit (OpCodes.Sizeof, type_queried);
7143 protected override void CloneTo (CloneContext clonectx, Expression t)
7149 /// Implements the qualified-alias-member (::) expression.
7151 public class QualifiedAliasMember : MemberAccess
7153 readonly string alias;
7154 public static readonly string GlobalAlias = "global";
7156 public QualifiedAliasMember (string alias, string identifier, Location l)
7157 : base (null, identifier, l)
7162 public QualifiedAliasMember (string alias, string identifier, TypeArguments targs, Location l)
7163 : base (null, identifier, targs, l)
7168 public QualifiedAliasMember (string alias, string identifier, int arity, Location l)
7169 : base (null, identifier, arity, l)
7174 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
7176 if (alias == GlobalAlias) {
7177 expr = GlobalRootNamespace.Instance;
7178 return base.ResolveAsTypeStep (ec, silent);
7181 int errors = ec.Compiler.Report.Errors;
7182 expr = ec.LookupNamespaceAlias (alias);
7184 if (errors == ec.Compiler.Report.Errors)
7185 ec.Compiler.Report.Error (432, loc, "Alias `{0}' not found", alias);
7189 FullNamedExpression fne = base.ResolveAsTypeStep (ec, silent);
7193 if (expr.eclass == ExprClass.Type) {
7195 ec.Compiler.Report.Error (431, loc,
7196 "Alias `{0}' cannot be used with '::' since it denotes a type. Consider replacing '::' with '.'", alias);
7204 protected override Expression DoResolve (ResolveContext ec)
7206 return ResolveAsTypeStep (ec, false);
7209 protected override void Error_IdentifierNotFound (IMemberContext rc, TypeSpec expr_type, string identifier)
7211 rc.Compiler.Report.Error (687, loc,
7212 "A namespace alias qualifier `{0}' did not resolve to a namespace or a type",
7213 GetSignatureForError ());
7216 public override string GetSignatureForError ()
7219 if (targs != null) {
7220 name = Name + "<" + targs.GetSignatureForError () + ">";
7223 return alias + "::" + name;
7226 public override Expression LookupNameExpression (ResolveContext rc, bool readMode, bool invocableOnly)
7228 return DoResolve (rc);
7231 protected override void CloneTo (CloneContext clonectx, Expression t)
7238 /// Implements the member access expression
7240 public class MemberAccess : ATypeNameExpression
7242 protected Expression expr;
7244 public MemberAccess (Expression expr, string id)
7245 : base (id, expr.Location)
7250 public MemberAccess (Expression expr, string identifier, Location loc)
7251 : base (identifier, loc)
7256 public MemberAccess (Expression expr, string identifier, TypeArguments args, Location loc)
7257 : base (identifier, args, loc)
7262 public MemberAccess (Expression expr, string identifier, int arity, Location loc)
7263 : base (identifier, arity, loc)
7268 public Expression LeftExpression {
7274 protected override Expression DoResolve (ResolveContext ec)
7276 return DoResolveName (ec, null);
7279 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
7281 return DoResolveName (ec, right_side);
7284 Expression DoResolveName (ResolveContext rc, Expression right_side)
7286 Expression e = LookupNameExpression (rc, right_side == null, false);
7290 if (right_side != null) {
7291 if (e is TypeExpr) {
7292 e.Error_UnexpectedKind (rc, ResolveFlags.VariableOrValue, loc);
7296 e = e.ResolveLValue (rc, right_side);
7298 e = e.Resolve (rc, ResolveFlags.VariableOrValue | ResolveFlags.Type);
7304 public override Expression LookupNameExpression (ResolveContext rc, bool readMode, bool invocableOnly)
7306 var sn = expr as SimpleName;
7307 const ResolveFlags flags = ResolveFlags.VariableOrValue | ResolveFlags.Type;
7310 // Resolve the expression with flow analysis turned off, we'll do the definite
7311 // assignment checks later. This is because we don't know yet what the expression
7312 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7313 // definite assignment check on the actual field and not on the whole struct.
7315 using (rc.Set (ResolveContext.Options.OmitStructFlowAnalysis)) {
7317 expr = sn.LookupNameExpression (rc, true, false);
7319 // Call resolve on expression which does have type set as we need expression type
7320 // TODO: I should probably ensure that the type is always set and leave resolve for the final
7321 if (expr is VariableReference || expr is ConstantExpr || expr is Linq.TransparentMemberAccess) {
7322 using (rc.With (ResolveContext.Options.DoFlowAnalysis, false)) {
7323 expr = expr.Resolve (rc);
7325 } else if (expr is TypeParameterExpr) {
7326 expr.Error_UnexpectedKind (rc, flags, expr.Location);
7330 expr = expr.Resolve (rc, flags);
7337 Namespace ns = expr as Namespace;
7339 FullNamedExpression retval = ns.Lookup (rc.Compiler, Name, Arity, loc);
7341 if (retval == null) {
7342 ns.Error_NamespaceDoesNotExist (loc, Name, Arity, rc);
7346 if (HasTypeArguments)
7347 return new GenericTypeExpr (retval.Type, targs, loc);
7353 TypeSpec expr_type = expr.Type;
7354 if (expr_type == InternalType.Dynamic) {
7355 me = expr as MemberExpr;
7357 me.ResolveInstanceExpression (rc);
7359 Arguments args = new Arguments (1);
7360 args.Add (new Argument (expr));
7361 return new DynamicMemberBinder (Name, args, loc);
7364 const MemberKind dot_kinds = MemberKind.Class | MemberKind.Struct | MemberKind.Delegate | MemberKind.Enum |
7365 MemberKind.Interface | MemberKind.TypeParameter | MemberKind.ArrayType;
7367 if ((expr_type.Kind & dot_kinds) == 0 || expr_type == TypeManager.void_type) {
7368 if (expr_type == InternalType.Null && rc.Compiler.IsRuntimeBinder)
7369 rc.Report.Error (Report.RuntimeErrorId, loc, "Cannot perform member binding on `null' value");
7371 Unary.Error_OperatorCannotBeApplied (rc, loc, ".", expr_type);
7375 var current_type = rc.CurrentType;
7376 var lookup_arity = Arity;
7377 bool errorMode = false;
7378 Expression member_lookup;
7380 member_lookup = MemberLookup (errorMode ? null : rc, current_type, expr_type, Name, lookup_arity, invocableOnly, loc);
7381 if (member_lookup == null) {
7383 // Try to look for extension method when member lookup failed
7385 if (MethodGroupExpr.IsExtensionMethodArgument (expr)) {
7386 NamespaceEntry scope = null;
7387 var methods = rc.LookupExtensionMethod (expr_type, Name, lookup_arity, ref scope);
7388 if (methods != null) {
7389 var emg = new ExtensionMethodGroupExpr (methods, scope, expr, loc);
7390 if (HasTypeArguments) {
7391 if (!targs.Resolve (rc))
7394 emg.SetTypeArguments (rc, targs);
7397 // TODO: Should it really skip the checks bellow
7398 return emg.Resolve (rc);
7404 if (member_lookup == null) {
7405 if (expr is TypeExpr)
7406 base.Error_TypeDoesNotContainDefinition (rc, expr_type, Name);
7408 Error_TypeDoesNotContainDefinition (rc, expr_type, Name);
7413 if (member_lookup is MethodGroupExpr) {
7414 // Leave it to overload resolution to report correct error
7416 // TODO: rc.SymbolRelatedToPreviousError
7417 ErrorIsInaccesible (rc, member_lookup.GetSignatureForError (), loc);
7422 if (member_lookup != null)
7425 current_type = null;
7427 invocableOnly = false;
7431 TypeExpr texpr = member_lookup as TypeExpr;
7432 if (texpr != null) {
7433 if (!(expr is TypeExpr)) {
7434 me = expr as MemberExpr;
7435 if (me == null || me.ProbeIdenticalTypeName (rc, expr, sn) == expr) {
7436 rc.Report.Error (572, loc, "`{0}': cannot reference a type through an expression; try `{1}' instead",
7437 Name, member_lookup.GetSignatureForError ());
7442 if (!texpr.Type.IsAccessible (rc.CurrentType)) {
7443 rc.Report.SymbolRelatedToPreviousError (member_lookup.Type);
7444 ErrorIsInaccesible (rc, member_lookup.Type.GetSignatureForError (), loc);
7448 if (HasTypeArguments) {
7449 return new GenericTypeExpr (member_lookup.Type, targs, loc);
7452 return member_lookup;
7455 me = member_lookup as MemberExpr;
7457 if (sn != null && me.IsStatic)
7458 expr = me.ProbeIdenticalTypeName (rc, expr, sn);
7460 me = me.ResolveMemberAccess (rc, expr, sn);
7463 if (!targs.Resolve (rc))
7466 me.SetTypeArguments (rc, targs);
7469 if (sn != null && (!TypeManager.IsValueType (expr_type) || me is PropertyExpr)) {
7470 if (me.IsInstance) {
7471 LocalVariableReference var = expr as LocalVariableReference;
7472 if (var != null && !var.VerifyAssigned (rc))
7480 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
7482 return ResolveNamespaceOrType (ec, silent);
7485 public FullNamedExpression ResolveNamespaceOrType (IMemberContext rc, bool silent)
7487 FullNamedExpression expr_resolved = expr.ResolveAsTypeStep (rc, silent);
7489 if (expr_resolved == null)
7492 Namespace ns = expr_resolved as Namespace;
7494 FullNamedExpression retval = ns.Lookup (rc.Compiler, Name, Arity, loc);
7496 if (retval == null) {
7498 ns.Error_NamespaceDoesNotExist (loc, Name, Arity, rc);
7499 } else if (HasTypeArguments) {
7500 retval = new GenericTypeExpr (retval.Type, targs, loc).ResolveAsTypeStep (rc, silent);
7506 TypeExpr tnew_expr = expr_resolved.ResolveAsTypeTerminal (rc, false);
7507 if (tnew_expr == null)
7510 TypeSpec expr_type = tnew_expr.Type;
7511 if (TypeManager.IsGenericParameter (expr_type)) {
7512 rc.Compiler.Report.Error (704, loc, "A nested type cannot be specified through a type parameter `{0}'",
7513 tnew_expr.GetSignatureForError ());
7517 var nested = MemberCache.FindNestedType (expr_type, Name, Arity);
7518 if (nested == null) {
7522 Error_IdentifierNotFound (rc, expr_type, Name);
7526 if (!nested.IsAccessible (rc.CurrentType ?? InternalType.FakeInternalType)) {
7527 ErrorIsInaccesible (rc, nested.GetSignatureForError (), loc);
7532 if (HasTypeArguments) {
7533 texpr = new GenericTypeExpr (nested, targs, loc);
7535 texpr = new GenericOpenTypeExpr (nested, loc);
7538 texpr = new TypeExpression (nested, loc);
7541 return texpr.ResolveAsTypeStep (rc, false);
7544 protected virtual void Error_IdentifierNotFound (IMemberContext rc, TypeSpec expr_type, string identifier)
7546 var nested = MemberCache.FindNestedType (expr_type, Name, -System.Math.Max (1, Arity));
7548 if (nested != null) {
7549 Error_TypeArgumentsCannotBeUsed (rc.Compiler.Report, expr.Location, nested, Arity);
7553 var any_other_member = MemberLookup (null, rc.CurrentType, expr_type, Name, 0, false, loc);
7554 if (any_other_member != null) {
7555 any_other_member.Error_UnexpectedKind (rc.Compiler.Report, null, "type", loc);
7559 rc.Compiler.Report.Error (426, loc, "The nested type `{0}' does not exist in the type `{1}'",
7560 Name, expr_type.GetSignatureForError ());
7563 protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
7565 if (RootContext.Version > LanguageVersion.ISO_2 && !ec.Compiler.IsRuntimeBinder && MethodGroupExpr.IsExtensionMethodArgument (expr)) {
7566 ec.Report.Error (1061, loc,
7567 "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?)",
7568 type.GetSignatureForError (), name);
7572 base.Error_TypeDoesNotContainDefinition (ec, type, name);
7575 public override string GetSignatureForError ()
7577 return expr.GetSignatureForError () + "." + base.GetSignatureForError ();
7580 protected override void CloneTo (CloneContext clonectx, Expression t)
7582 MemberAccess target = (MemberAccess) t;
7584 target.expr = expr.Clone (clonectx);
7589 /// Implements checked expressions
7591 public class CheckedExpr : Expression {
7593 public Expression Expr;
7595 public CheckedExpr (Expression e, Location l)
7601 public override Expression CreateExpressionTree (ResolveContext ec)
7603 using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
7604 return Expr.CreateExpressionTree (ec);
7607 protected override Expression DoResolve (ResolveContext ec)
7609 using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
7610 Expr = Expr.Resolve (ec);
7615 if (Expr is Constant || Expr is MethodGroupExpr || Expr is AnonymousMethodExpression || Expr is DefaultValueExpression)
7618 eclass = Expr.eclass;
7623 public override void Emit (EmitContext ec)
7625 using (ec.With (EmitContext.Options.AllCheckStateFlags, true))
7629 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
7631 using (ec.With (EmitContext.Options.AllCheckStateFlags, true))
7632 Expr.EmitBranchable (ec, target, on_true);
7635 public override SLE.Expression MakeExpression (BuilderContext ctx)
7637 using (ctx.With (BuilderContext.Options.AllCheckStateFlags, true)) {
7638 return Expr.MakeExpression (ctx);
7642 protected override void CloneTo (CloneContext clonectx, Expression t)
7644 CheckedExpr target = (CheckedExpr) t;
7646 target.Expr = Expr.Clone (clonectx);
7651 /// Implements the unchecked expression
7653 public class UnCheckedExpr : Expression {
7655 public Expression Expr;
7657 public UnCheckedExpr (Expression e, Location l)
7663 public override Expression CreateExpressionTree (ResolveContext ec)
7665 using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
7666 return Expr.CreateExpressionTree (ec);
7669 protected override Expression DoResolve (ResolveContext ec)
7671 using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
7672 Expr = Expr.Resolve (ec);
7677 if (Expr is Constant || Expr is MethodGroupExpr || Expr is AnonymousMethodExpression || Expr is DefaultValueExpression)
7680 eclass = Expr.eclass;
7685 public override void Emit (EmitContext ec)
7687 using (ec.With (EmitContext.Options.AllCheckStateFlags, false))
7691 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
7693 using (ec.With (EmitContext.Options.AllCheckStateFlags, false))
7694 Expr.EmitBranchable (ec, target, on_true);
7697 protected override void CloneTo (CloneContext clonectx, Expression t)
7699 UnCheckedExpr target = (UnCheckedExpr) t;
7701 target.Expr = Expr.Clone (clonectx);
7706 /// An Element Access expression.
7708 /// During semantic analysis these are transformed into
7709 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7711 public class ElementAccess : Expression {
7712 public Arguments Arguments;
7713 public Expression Expr;
7715 public ElementAccess (Expression e, Arguments args, Location loc)
7719 this.Arguments = args;
7723 // We perform some simple tests, and then to "split" the emit and store
7724 // code we create an instance of a different class, and return that.
7726 Expression CreateAccessExpression (ResolveContext ec)
7729 return (new ArrayAccess (this, loc));
7732 return MakePointerAccess (ec, type);
7734 FieldExpr fe = Expr as FieldExpr;
7736 var ff = fe.Spec as FixedFieldSpec;
7738 return MakePointerAccess (ec, ff.ElementType);
7742 var indexers = MemberCache.FindMembers (type, MemberCache.IndexerNameAlias, false);
7743 if (indexers != null || type == InternalType.Dynamic) {
7744 return new IndexerExpr (indexers, this);
7747 ec.Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
7748 type.GetSignatureForError ());
7752 public override Expression CreateExpressionTree (ResolveContext ec)
7754 Arguments args = Arguments.CreateForExpressionTree (ec, Arguments,
7755 Expr.CreateExpressionTree (ec));
7757 return CreateExpressionFactoryCall (ec, "ArrayIndex", args);
7760 Expression MakePointerAccess (ResolveContext ec, TypeSpec type)
7762 if (Arguments.Count != 1){
7763 ec.Report.Error (196, loc, "A pointer must be indexed by only one value");
7767 if (Arguments [0] is NamedArgument)
7768 Error_NamedArgument ((NamedArgument) Arguments[0], ec.Report);
7770 Expression p = new PointerArithmetic (Binary.Operator.Addition, Expr, Arguments [0].Expr.Resolve (ec), type, loc);
7771 return new Indirection (p, loc);
7774 protected override Expression DoResolve (ResolveContext ec)
7776 Expr = Expr.Resolve (ec);
7782 // TODO: Create 1 result for Resolve and ResolveLValue ?
7783 var res = CreateAccessExpression (ec);
7787 return res.Resolve (ec);
7790 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
7792 Expr = Expr.Resolve (ec);
7798 var res = CreateAccessExpression (ec);
7802 return res.ResolveLValue (ec, right_side);
7805 public override void Emit (EmitContext ec)
7807 throw new Exception ("Should never be reached");
7810 public static void Error_NamedArgument (NamedArgument na, Report Report)
7812 Report.Error (1742, na.Location, "An element access expression cannot use named argument");
7815 public override string GetSignatureForError ()
7817 return Expr.GetSignatureForError ();
7820 protected override void CloneTo (CloneContext clonectx, Expression t)
7822 ElementAccess target = (ElementAccess) t;
7824 target.Expr = Expr.Clone (clonectx);
7825 if (Arguments != null)
7826 target.Arguments = Arguments.Clone (clonectx);
7831 /// Implements array access
7833 public class ArrayAccess : Expression, IDynamicAssign, IMemoryLocation {
7835 // Points to our "data" repository
7839 LocalTemporary temp;
7843 public ArrayAccess (ElementAccess ea_data, Location l)
7849 public override Expression CreateExpressionTree (ResolveContext ec)
7851 return ea.CreateExpressionTree (ec);
7854 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
7856 return DoResolve (ec);
7859 protected override Expression DoResolve (ResolveContext ec)
7861 // dynamic is used per argument in ConvertExpressionToArrayIndex case
7863 ea.Arguments.Resolve (ec, out dynamic);
7865 var ac = ea.Expr.Type as ArrayContainer;
7866 int rank = ea.Arguments.Count;
7867 if (ac.Rank != rank) {
7868 ec.Report.Error (22, ea.Location, "Wrong number of indexes `{0}' inside [], expected `{1}'",
7869 rank.ToString (), ac.Rank.ToString ());
7874 if (type.IsPointer && !ec.IsUnsafe) {
7875 UnsafeError (ec, ea.Location);
7878 foreach (Argument a in ea.Arguments) {
7879 if (a is NamedArgument)
7880 ElementAccess.Error_NamedArgument ((NamedArgument) a, ec.Report);
7882 a.Expr = ConvertExpressionToArrayIndex (ec, a.Expr);
7885 eclass = ExprClass.Variable;
7890 protected override void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
7892 ec.Report.Warning (251, 2, loc, "Indexing an array with a negative index (array indices always start at zero)");
7896 // Load the array arguments into the stack.
7898 void LoadArrayAndArguments (EmitContext ec)
7902 for (int i = 0; i < ea.Arguments.Count; ++i) {
7903 ea.Arguments [i].Emit (ec);
7907 public void Emit (EmitContext ec, bool leave_copy)
7909 var ac = ea.Expr.Type as ArrayContainer;
7912 ec.EmitLoadFromPtr (type);
7914 LoadArrayAndArguments (ec);
7915 ec.EmitArrayLoad (ac);
7919 ec.Emit (OpCodes.Dup);
7920 temp = new LocalTemporary (this.type);
7925 public override void Emit (EmitContext ec)
7930 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
7932 var ac = (ArrayContainer) ea.Expr.Type;
7933 TypeSpec t = source.Type;
7934 prepared = prepare_for_load;
7937 AddressOf (ec, AddressOp.LoadStore);
7938 ec.Emit (OpCodes.Dup);
7940 LoadArrayAndArguments (ec);
7943 // If we are dealing with a struct, get the
7944 // address of it, so we can store it.
7946 // The stobj opcode used by value types will need
7947 // an address on the stack, not really an array/array
7950 if (ac.Rank == 1 && TypeManager.IsStruct (t) &&
7951 (!TypeManager.IsBuiltinOrEnum (t) ||
7952 t == TypeManager.decimal_type)) {
7954 ec.Emit (OpCodes.Ldelema, t);
7960 ec.Emit (OpCodes.Dup);
7961 temp = new LocalTemporary (this.type);
7966 ec.EmitStoreFromPtr (t);
7968 ec.EmitArrayStore (ac);
7977 public void EmitNew (EmitContext ec, New source, bool leave_copy)
7979 if (!source.Emit (ec, this)) {
7981 throw new NotImplementedException ();
7986 throw new NotImplementedException ();
7989 public void AddressOf (EmitContext ec, AddressOp mode)
7991 var ac = (ArrayContainer) ea.Expr.Type;
7993 LoadArrayAndArguments (ec);
7994 ec.EmitArrayAddress (ac);
7997 public SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
8000 return SLE.Expression.ArrayAccess (
8001 ea.Expr.MakeExpression (ctx),
8002 Arguments.MakeExpression (ea.Arguments, ctx));
8004 throw new NotImplementedException ();
8008 public override SLE.Expression MakeExpression (BuilderContext ctx)
8010 return SLE.Expression.ArrayIndex (
8011 ea.Expr.MakeExpression (ctx),
8012 Arguments.MakeExpression (ea.Arguments, ctx));
8017 // Indexer access expression
8019 class IndexerExpr : PropertyOrIndexerExpr<IndexerSpec>, OverloadResolver.IBaseMembersProvider
8021 LocalTemporary prepared_value;
8022 IList<MemberSpec> indexers;
8023 Arguments arguments;
8025 public IndexerExpr (IList<MemberSpec> indexers, ElementAccess ea)
8026 : base (ea.Location)
8028 this.indexers = indexers;
8029 this.InstanceExpression = ea.Expr;
8030 this.arguments = ea.Arguments;
8034 protected override TypeSpec DeclaringType {
8036 return best_candidate.DeclaringType;
8040 public override bool IsInstance {
8046 public override bool IsStatic {
8052 public override string Name {
8060 public override Expression CreateExpressionTree (ResolveContext ec)
8062 Arguments args = Arguments.CreateForExpressionTree (ec, arguments,
8063 InstanceExpression.CreateExpressionTree (ec),
8064 new TypeOfMethod (Getter, loc));
8066 return CreateExpressionFactoryCall (ec, "Call", args);
8069 public override void Emit (EmitContext ec, bool leave_copy)
8072 prepared_value.Emit (ec);
8074 Invocation.EmitCall (ec, InstanceExpression, Getter, arguments, loc, false, false);
8078 ec.Emit (OpCodes.Dup);
8079 temp = new LocalTemporary (Type);
8084 public override void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8086 prepared = prepare_for_load;
8087 Expression value = source;
8090 Invocation.EmitCall (ec, InstanceExpression, Getter,
8091 arguments, loc, true, false);
8093 prepared_value = new LocalTemporary (type);
8094 prepared_value.Store (ec);
8096 prepared_value.Release (ec);
8099 ec.Emit (OpCodes.Dup);
8100 temp = new LocalTemporary (Type);
8103 } else if (leave_copy) {
8104 temp = new LocalTemporary (Type);
8111 arguments.Add (new Argument (value));
8113 Invocation.EmitCall (ec, InstanceExpression, Setter, arguments, loc, false, prepared);
8121 public override string GetSignatureForError ()
8123 return best_candidate.GetSignatureForError ();
8126 public override SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
8128 var value = new[] { source.MakeExpression (ctx) };
8129 var args = Arguments.MakeExpression (arguments, ctx).Concat (value);
8131 return SLE.Expression.Block (
8132 SLE.Expression.Call (InstanceExpression.MakeExpression (ctx), (MethodInfo) Setter.GetMetaInfo (), args),
8135 return args.First ();
8139 public override SLE.Expression MakeExpression (BuilderContext ctx)
8141 var args = Arguments.MakeExpression (arguments, ctx);
8142 return SLE.Expression.Call (InstanceExpression.MakeExpression (ctx), (MethodInfo) Getter.GetMetaInfo (), args);
8145 protected override Expression OverloadResolve (ResolveContext rc, Expression right_side)
8147 if (best_candidate != null)
8150 eclass = ExprClass.IndexerAccess;
8153 arguments.Resolve (rc, out dynamic);
8155 if (indexers == null && InstanceExpression.Type == InternalType.Dynamic) {
8158 var res = new OverloadResolver (indexers, OverloadResolver.Restrictions.None, loc);
8159 res.BaseMembersProvider = this;
8161 // TODO: Do I need 2 argument sets?
8162 best_candidate = res.ResolveMember<IndexerSpec> (rc, ref arguments);
8163 if (best_candidate != null)
8164 type = best_candidate.MemberType;
8165 else if (!res.BestCandidateIsDynamic)
8170 // It has dynamic arguments
8173 Arguments args = new Arguments (arguments.Count + 1);
8175 rc.Report.Error (1972, loc,
8176 "The indexer base access cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access");
8178 args.Add (new Argument (InstanceExpression));
8180 args.AddRange (arguments);
8182 best_candidate = null;
8183 return new DynamicIndexBinder (args, loc);
8186 ResolveInstanceExpression (rc);
8187 CheckProtectedMemberAccess (rc, best_candidate);
8191 protected override void CloneTo (CloneContext clonectx, Expression t)
8193 IndexerExpr target = (IndexerExpr) t;
8195 if (arguments != null)
8196 target.arguments = arguments.Clone (clonectx);
8199 public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
8201 Error_TypeArgumentsCannotBeUsed (ec.Report, "indexer", GetSignatureForError (), loc);
8204 #region IBaseMembersProvider Members
8206 IList<MemberSpec> OverloadResolver.IBaseMembersProvider.GetBaseMembers (TypeSpec baseType)
8208 return baseType == null ? null : MemberCache.FindMembers (baseType, MemberCache.IndexerNameAlias, false);
8211 MethodGroupExpr OverloadResolver.IBaseMembersProvider.LookupExtensionMethod (ResolveContext rc)
8220 // A base access expression
8222 public class BaseThis : This
8224 public BaseThis (Location loc)
8229 public BaseThis (TypeSpec type, Location loc)
8233 eclass = ExprClass.Variable;
8238 public override string Name {
8246 public override Expression CreateExpressionTree (ResolveContext ec)
8248 ec.Report.Error (831, loc, "An expression tree may not contain a base access");
8249 return base.CreateExpressionTree (ec);
8252 public override void Emit (EmitContext ec)
8256 if (ec.CurrentType.IsStruct) {
8257 ec.Emit (OpCodes.Ldobj, ec.CurrentType);
8258 ec.Emit (OpCodes.Box, ec.CurrentType);
8262 protected override void Error_ThisNotAvailable (ResolveContext ec)
8265 ec.Report.Error (1511, loc, "Keyword `base' is not available in a static method");
8267 ec.Report.Error (1512, loc, "Keyword `base' is not available in the current context");
8271 public override void ResolveBase (ResolveContext ec)
8273 base.ResolveBase (ec);
8274 type = ec.CurrentType.BaseType;
8279 /// This class exists solely to pass the Type around and to be a dummy
8280 /// that can be passed to the conversion functions (this is used by
8281 /// foreach implementation to typecast the object return value from
8282 /// get_Current into the proper type. All code has been generated and
8283 /// we only care about the side effect conversions to be performed
8285 /// This is also now used as a placeholder where a no-action expression
8286 /// is needed (the `New' class).
8288 public class EmptyExpression : Expression {
8289 public static readonly Expression Null = new EmptyExpression ();
8291 public class OutAccess : EmptyExpression
8293 public static readonly OutAccess Instance = new OutAccess ();
8295 public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
8297 rc.Report.Error (206, right_side.Location,
8298 "A property, indexer or dynamic member access may not be passed as `ref' or `out' parameter");
8304 public static readonly EmptyExpression LValueMemberAccess = new EmptyExpression ();
8305 public static readonly EmptyExpression LValueMemberOutAccess = new EmptyExpression ();
8306 public static readonly EmptyExpression UnaryAddress = new EmptyExpression ();
8307 public static readonly EmptyExpression EventAddition = new EmptyExpression ();
8308 public static readonly EmptyExpression EventSubtraction = new EmptyExpression ();
8309 public static readonly EmptyExpression MissingValue = new EmptyExpression (InternalType.FakeInternalType);
8311 static EmptyExpression temp = new EmptyExpression ();
8312 public static EmptyExpression Grab ()
8314 EmptyExpression retval = temp == null ? new EmptyExpression () : temp;
8319 public static void Release (EmptyExpression e)
8326 // FIXME: Don't set to object
8327 type = TypeManager.object_type;
8328 eclass = ExprClass.Value;
8329 loc = Location.Null;
8332 public EmptyExpression (TypeSpec t)
8335 eclass = ExprClass.Value;
8336 loc = Location.Null;
8339 public override Expression CreateExpressionTree (ResolveContext ec)
8341 throw new NotSupportedException ("ET");
8344 protected override Expression DoResolve (ResolveContext ec)
8349 public override void Emit (EmitContext ec)
8351 // nothing, as we only exist to not do anything.
8354 public override void EmitSideEffect (EmitContext ec)
8359 // This is just because we might want to reuse this bad boy
8360 // instead of creating gazillions of EmptyExpressions.
8361 // (CanImplicitConversion uses it)
8363 public void SetType (TypeSpec t)
8370 // Empty statement expression
8372 public sealed class EmptyExpressionStatement : ExpressionStatement
8374 public static readonly EmptyExpressionStatement Instance = new EmptyExpressionStatement ();
8376 private EmptyExpressionStatement ()
8378 loc = Location.Null;
8381 public override Expression CreateExpressionTree (ResolveContext ec)
8386 public override void EmitStatement (EmitContext ec)
8391 protected override Expression DoResolve (ResolveContext ec)
8393 eclass = ExprClass.Value;
8394 type = TypeManager.object_type;
8398 public override void Emit (EmitContext ec)
8404 public class UserCast : Expression {
8408 public UserCast (MethodSpec method, Expression source, Location l)
8410 this.method = method;
8411 this.source = source;
8412 type = method.ReturnType;
8416 public Expression Source {
8422 public override Expression CreateExpressionTree (ResolveContext ec)
8424 Arguments args = new Arguments (3);
8425 args.Add (new Argument (source.CreateExpressionTree (ec)));
8426 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
8427 args.Add (new Argument (new TypeOfMethod (method, loc)));
8428 return CreateExpressionFactoryCall (ec, "Convert", args);
8431 protected override Expression DoResolve (ResolveContext ec)
8433 ObsoleteAttribute oa = method.GetAttributeObsolete ();
8435 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
8437 eclass = ExprClass.Value;
8441 public override void Emit (EmitContext ec)
8444 ec.Emit (OpCodes.Call, method);
8447 public override string GetSignatureForError ()
8449 return TypeManager.CSharpSignature (method);
8452 public override SLE.Expression MakeExpression (BuilderContext ctx)
8454 return SLE.Expression.Convert (source.MakeExpression (ctx), type.GetMetaInfo (), (MethodInfo) method.GetMetaInfo ());
8459 // Holds additional type specifiers like ?, *, []
8461 public class ComposedTypeSpecifier
8463 public static readonly ComposedTypeSpecifier SingleDimension = new ComposedTypeSpecifier (1, Location.Null);
8465 public readonly int Dimension;
8466 public readonly Location Location;
8468 public ComposedTypeSpecifier (int specifier, Location loc)
8470 this.Dimension = specifier;
8471 this.Location = loc;
8475 public bool IsNullable {
8477 return Dimension == -1;
8481 public bool IsPointer {
8483 return Dimension == -2;
8487 public ComposedTypeSpecifier Next { get; set; }
8491 public static ComposedTypeSpecifier CreateArrayDimension (int dimension, Location loc)
8493 return new ComposedTypeSpecifier (dimension, loc);
8496 public static ComposedTypeSpecifier CreateNullable (Location loc)
8498 return new ComposedTypeSpecifier (-1, loc);
8501 public static ComposedTypeSpecifier CreatePointer (Location loc)
8503 return new ComposedTypeSpecifier (-2, loc);
8506 public string GetSignatureForError ()
8511 ArrayContainer.GetPostfixSignature (Dimension);
8513 return Next != null ? s + Next.GetSignatureForError () : s;
8518 // This class is used to "construct" the type during a typecast
8519 // operation. Since the Type.GetType class in .NET can parse
8520 // the type specification, we just use this to construct the type
8521 // one bit at a time.
8523 public class ComposedCast : TypeExpr {
8524 FullNamedExpression left;
8525 ComposedTypeSpecifier spec;
8527 public ComposedCast (FullNamedExpression left, ComposedTypeSpecifier spec)
8530 throw new ArgumentNullException ("spec");
8534 this.loc = spec.Location;
8537 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
8539 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec, false);
8544 eclass = ExprClass.Type;
8546 var single_spec = spec;
8548 if (single_spec.IsNullable) {
8549 lexpr = new Nullable.NullableType (lexpr, loc);
8550 lexpr = lexpr.ResolveAsTypeTerminal (ec, false);
8554 single_spec = single_spec.Next;
8555 } else if (single_spec.IsPointer) {
8556 if (!TypeManager.VerifyUnmanaged (ec.Compiler, type, loc))
8560 UnsafeError (ec.Compiler.Report, loc);
8564 type = PointerContainer.MakeType (type);
8565 single_spec = single_spec.Next;
8566 } while (single_spec != null && single_spec.IsPointer);
8569 if (single_spec != null && single_spec.Dimension > 0) {
8570 if (TypeManager.IsSpecialType (type)) {
8571 ec.Compiler.Report.Error (611, loc, "Array elements cannot be of type `{0}'", type.GetSignatureForError ());
8572 } else if (type.IsStatic) {
8573 ec.Compiler.Report.SymbolRelatedToPreviousError (type);
8574 ec.Compiler.Report.Error (719, loc, "Array elements cannot be of static type `{0}'",
8575 type.GetSignatureForError ());
8577 MakeArray (single_spec);
8584 void MakeArray (ComposedTypeSpecifier spec)
8586 if (spec.Next != null)
8587 MakeArray (spec.Next);
8589 type = ArrayContainer.MakeType (type, spec.Dimension);
8592 public override string GetSignatureForError ()
8594 return left.GetSignatureForError () + spec.GetSignatureForError ();
8598 public class FixedBufferPtr : Expression {
8601 public FixedBufferPtr (Expression array, TypeSpec array_type, Location l)
8606 type = PointerContainer.MakeType (array_type);
8607 eclass = ExprClass.Value;
8610 public override Expression CreateExpressionTree (ResolveContext ec)
8612 Error_PointerInsideExpressionTree (ec);
8616 public override void Emit(EmitContext ec)
8621 protected override Expression DoResolve (ResolveContext ec)
8624 // We are born fully resolved
8632 // This class is used to represent the address of an array, used
8633 // only by the Fixed statement, this generates "&a [0]" construct
8634 // for fixed (char *pa = a)
8636 public class ArrayPtr : FixedBufferPtr {
8637 TypeSpec array_type;
8639 public ArrayPtr (Expression array, TypeSpec array_type, Location l):
8640 base (array, array_type, l)
8642 this.array_type = array_type;
8645 public override void Emit (EmitContext ec)
8650 ec.Emit (OpCodes.Ldelema, array_type);
8655 // Encapsulates a conversion rules required for array indexes
8657 public class ArrayIndexCast : TypeCast
8659 public ArrayIndexCast (Expression expr)
8660 : base (expr, TypeManager.int32_type)
8662 if (expr.Type == TypeManager.int32_type)
8663 throw new ArgumentException ("unnecessary array index conversion");
8666 public override Expression CreateExpressionTree (ResolveContext ec)
8668 using (ec.Set (ResolveContext.Options.CheckedScope)) {
8669 return base.CreateExpressionTree (ec);
8673 public override void Emit (EmitContext ec)
8677 var expr_type = child.Type;
8679 if (expr_type == TypeManager.uint32_type)
8680 ec.Emit (OpCodes.Conv_U);
8681 else if (expr_type == TypeManager.int64_type)
8682 ec.Emit (OpCodes.Conv_Ovf_I);
8683 else if (expr_type == TypeManager.uint64_type)
8684 ec.Emit (OpCodes.Conv_Ovf_I_Un);
8686 throw new InternalErrorException ("Cannot emit cast to unknown array element type", type);
8691 // Implements the `stackalloc' keyword
8693 public class StackAlloc : Expression {
8698 public StackAlloc (Expression type, Expression count, Location l)
8705 public override Expression CreateExpressionTree (ResolveContext ec)
8707 throw new NotSupportedException ("ET");
8710 protected override Expression DoResolve (ResolveContext ec)
8712 count = count.Resolve (ec);
8716 if (count.Type != TypeManager.uint32_type){
8717 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8722 Constant c = count as Constant;
8723 if (c != null && c.IsNegative) {
8724 ec.Report.Error (247, loc, "Cannot use a negative size with stackalloc");
8727 if (ec.HasAny (ResolveContext.Options.CatchScope | ResolveContext.Options.FinallyScope)) {
8728 ec.Report.Error (255, loc, "Cannot use stackalloc in finally or catch");
8731 TypeExpr texpr = t.ResolveAsTypeTerminal (ec, false);
8737 if (!TypeManager.VerifyUnmanaged (ec.Compiler, otype, loc))
8740 type = PointerContainer.MakeType (otype);
8741 eclass = ExprClass.Value;
8746 public override void Emit (EmitContext ec)
8748 int size = GetTypeSize (otype);
8753 ec.Emit (OpCodes.Sizeof, otype);
8757 ec.Emit (OpCodes.Mul_Ovf_Un);
8758 ec.Emit (OpCodes.Localloc);
8761 protected override void CloneTo (CloneContext clonectx, Expression t)
8763 StackAlloc target = (StackAlloc) t;
8764 target.count = count.Clone (clonectx);
8765 target.t = t.Clone (clonectx);
8770 // An object initializer expression
8772 public class ElementInitializer : Assign
8774 public readonly string Name;
8776 public ElementInitializer (string name, Expression initializer, Location loc)
8777 : base (null, initializer, loc)
8782 protected override void CloneTo (CloneContext clonectx, Expression t)
8784 ElementInitializer target = (ElementInitializer) t;
8785 target.source = source.Clone (clonectx);
8788 public override Expression CreateExpressionTree (ResolveContext ec)
8790 Arguments args = new Arguments (2);
8791 FieldExpr fe = target as FieldExpr;
8793 args.Add (new Argument (fe.CreateTypeOfExpression ()));
8795 args.Add (new Argument (((PropertyExpr)target).CreateSetterTypeOfExpression ()));
8797 args.Add (new Argument (source.CreateExpressionTree (ec)));
8798 return CreateExpressionFactoryCall (ec,
8799 source is CollectionOrObjectInitializers ? "ListBind" : "Bind",
8803 protected override Expression DoResolve (ResolveContext ec)
8806 return EmptyExpressionStatement.Instance;
8808 var t = ec.CurrentInitializerVariable.Type;
8809 if (t == InternalType.Dynamic) {
8810 Arguments args = new Arguments (1);
8811 args.Add (new Argument (ec.CurrentInitializerVariable));
8812 target = new DynamicMemberBinder (Name, args, loc);
8815 var member = MemberLookup (ec, ec.CurrentType, t, Name, 0, false, loc);
8816 if (member == null) {
8817 member = Expression.MemberLookup (null, ec.CurrentType, t, Name, 0, false, loc);
8819 if (member != null) {
8820 // TODO: ec.Report.SymbolRelatedToPreviousError (member);
8821 ErrorIsInaccesible (ec, member.GetSignatureForError (), loc);
8826 if (member == null) {
8827 Error_TypeDoesNotContainDefinition (ec, loc, t, Name);
8831 if (!(member is PropertyExpr || member is FieldExpr)) {
8832 ec.Report.Error (1913, loc,
8833 "Member `{0}' cannot be initialized. An object initializer may only be used for fields, or properties",
8834 member.GetSignatureForError ());
8839 var me = member as MemberExpr;
8841 ec.Report.Error (1914, loc,
8842 "Static field or property `{0}' cannot be assigned in an object initializer",
8843 me.GetSignatureForError ());
8847 me.InstanceExpression = ec.CurrentInitializerVariable;
8850 if (source is CollectionOrObjectInitializers) {
8851 Expression previous = ec.CurrentInitializerVariable;
8852 ec.CurrentInitializerVariable = target;
8853 source = source.Resolve (ec);
8854 ec.CurrentInitializerVariable = previous;
8858 eclass = source.eclass;
8863 return base.DoResolve (ec);
8866 public override void EmitStatement (EmitContext ec)
8868 if (source is CollectionOrObjectInitializers)
8871 base.EmitStatement (ec);
8876 // A collection initializer expression
8878 class CollectionElementInitializer : Invocation
8880 public class ElementInitializerArgument : Argument
8882 public ElementInitializerArgument (Expression e)
8888 sealed class AddMemberAccess : MemberAccess
8890 public AddMemberAccess (Expression expr, Location loc)
8891 : base (expr, "Add", loc)
8895 protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
8897 if (TypeManager.HasElementType (type))
8900 base.Error_TypeDoesNotContainDefinition (ec, type, name);
8904 public CollectionElementInitializer (Expression argument)
8905 : base (null, new Arguments (1))
8907 base.arguments.Add (new ElementInitializerArgument (argument));
8908 this.loc = argument.Location;
8911 public CollectionElementInitializer (List<Expression> arguments, Location loc)
8912 : base (null, new Arguments (arguments.Count))
8914 foreach (Expression e in arguments)
8915 base.arguments.Add (new ElementInitializerArgument (e));
8920 public override Expression CreateExpressionTree (ResolveContext ec)
8922 Arguments args = new Arguments (2);
8923 args.Add (new Argument (mg.CreateExpressionTree (ec)));
8925 var expr_initializers = new ArrayInitializer (arguments.Count, loc);
8926 foreach (Argument a in arguments)
8927 expr_initializers.Add (a.CreateExpressionTree (ec));
8929 args.Add (new Argument (new ArrayCreation (
8930 CreateExpressionTypeExpression (ec, loc), expr_initializers, loc)));
8931 return CreateExpressionFactoryCall (ec, "ElementInit", args);
8934 protected override void CloneTo (CloneContext clonectx, Expression t)
8936 CollectionElementInitializer target = (CollectionElementInitializer) t;
8937 if (arguments != null)
8938 target.arguments = arguments.Clone (clonectx);
8941 protected override Expression DoResolve (ResolveContext ec)
8943 base.expr = new AddMemberAccess (ec.CurrentInitializerVariable, loc);
8945 return base.DoResolve (ec);
8950 // A block of object or collection initializers
8952 public class CollectionOrObjectInitializers : ExpressionStatement
8954 IList<Expression> initializers;
8955 bool is_collection_initialization;
8957 public static readonly CollectionOrObjectInitializers Empty =
8958 new CollectionOrObjectInitializers (Array.AsReadOnly (new Expression [0]), Location.Null);
8960 public CollectionOrObjectInitializers (IList<Expression> initializers, Location loc)
8962 this.initializers = initializers;
8966 public bool IsEmpty {
8968 return initializers.Count == 0;
8972 public bool IsCollectionInitializer {
8974 return is_collection_initialization;
8978 protected override void CloneTo (CloneContext clonectx, Expression target)
8980 CollectionOrObjectInitializers t = (CollectionOrObjectInitializers) target;
8982 t.initializers = new List<Expression> (initializers.Count);
8983 foreach (var e in initializers)
8984 t.initializers.Add (e.Clone (clonectx));
8987 public override Expression CreateExpressionTree (ResolveContext ec)
8989 var expr_initializers = new ArrayInitializer (initializers.Count, loc);
8990 foreach (Expression e in initializers) {
8991 Expression expr = e.CreateExpressionTree (ec);
8993 expr_initializers.Add (expr);
8996 return new ImplicitlyTypedArrayCreation (expr_initializers, loc);
8999 protected override Expression DoResolve (ResolveContext ec)
9001 List<string> element_names = null;
9002 for (int i = 0; i < initializers.Count; ++i) {
9003 Expression initializer = initializers [i];
9004 ElementInitializer element_initializer = initializer as ElementInitializer;
9007 if (element_initializer != null) {
9008 element_names = new List<string> (initializers.Count);
9009 element_names.Add (element_initializer.Name);
9010 } else if (initializer is CompletingExpression){
9011 initializer.Resolve (ec);
9012 throw new InternalErrorException ("This line should never be reached");
9014 if (!ec.CurrentInitializerVariable.Type.ImplementsInterface (TypeManager.ienumerable_type)) {
9015 ec.Report.Error (1922, loc, "A field or property `{0}' cannot be initialized with a collection " +
9016 "object initializer because type `{1}' does not implement `{2}' interface",
9017 ec.CurrentInitializerVariable.GetSignatureForError (),
9018 TypeManager.CSharpName (ec.CurrentInitializerVariable.Type),
9019 TypeManager.CSharpName (TypeManager.ienumerable_type));
9022 is_collection_initialization = true;
9025 if (is_collection_initialization != (element_initializer == null)) {
9026 ec.Report.Error (747, initializer.Location, "Inconsistent `{0}' member declaration",
9027 is_collection_initialization ? "collection initializer" : "object initializer");
9031 if (!is_collection_initialization) {
9032 if (element_names.Contains (element_initializer.Name)) {
9033 ec.Report.Error (1912, element_initializer.Location,
9034 "An object initializer includes more than one member `{0}' initialization",
9035 element_initializer.Name);
9037 element_names.Add (element_initializer.Name);
9042 Expression e = initializer.Resolve (ec);
9043 if (e == EmptyExpressionStatement.Instance)
9044 initializers.RemoveAt (i--);
9046 initializers [i] = e;
9049 type = ec.CurrentInitializerVariable.Type;
9050 if (is_collection_initialization) {
9051 if (TypeManager.HasElementType (type)) {
9052 ec.Report.Error (1925, loc, "Cannot initialize object of type `{0}' with a collection initializer",
9053 TypeManager.CSharpName (type));
9057 eclass = ExprClass.Variable;
9061 public override void Emit (EmitContext ec)
9066 public override void EmitStatement (EmitContext ec)
9068 foreach (ExpressionStatement e in initializers)
9069 e.EmitStatement (ec);
9074 // New expression with element/object initializers
9076 public class NewInitialize : New
9079 // This class serves as a proxy for variable initializer target instances.
9080 // A real variable is assigned later when we resolve left side of an
9083 sealed class InitializerTargetExpression : Expression, IMemoryLocation
9085 NewInitialize new_instance;
9087 public InitializerTargetExpression (NewInitialize newInstance)
9089 this.type = newInstance.type;
9090 this.loc = newInstance.loc;
9091 this.eclass = newInstance.eclass;
9092 this.new_instance = newInstance;
9095 public override Expression CreateExpressionTree (ResolveContext ec)
9097 // Should not be reached
9098 throw new NotSupportedException ("ET");
9101 protected override Expression DoResolve (ResolveContext ec)
9106 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
9111 public override void Emit (EmitContext ec)
9113 Expression e = (Expression) new_instance.instance;
9117 #region IMemoryLocation Members
9119 public void AddressOf (EmitContext ec, AddressOp mode)
9121 new_instance.instance.AddressOf (ec, mode);
9127 CollectionOrObjectInitializers initializers;
9128 IMemoryLocation instance;
9130 public NewInitialize (FullNamedExpression requested_type, Arguments arguments, CollectionOrObjectInitializers initializers, Location l)
9131 : base (requested_type, arguments, l)
9133 this.initializers = initializers;
9136 protected override IMemoryLocation EmitAddressOf (EmitContext ec, AddressOp Mode)
9138 instance = base.EmitAddressOf (ec, Mode);
9140 if (!initializers.IsEmpty)
9141 initializers.Emit (ec);
9146 protected override void CloneTo (CloneContext clonectx, Expression t)
9148 base.CloneTo (clonectx, t);
9150 NewInitialize target = (NewInitialize) t;
9151 target.initializers = (CollectionOrObjectInitializers) initializers.Clone (clonectx);
9154 public override Expression CreateExpressionTree (ResolveContext ec)
9156 Arguments args = new Arguments (2);
9157 args.Add (new Argument (base.CreateExpressionTree (ec)));
9158 if (!initializers.IsEmpty)
9159 args.Add (new Argument (initializers.CreateExpressionTree (ec)));
9161 return CreateExpressionFactoryCall (ec,
9162 initializers.IsCollectionInitializer ? "ListInit" : "MemberInit",
9166 protected override Expression DoResolve (ResolveContext ec)
9168 Expression e = base.DoResolve (ec);
9172 Expression previous = ec.CurrentInitializerVariable;
9173 ec.CurrentInitializerVariable = new InitializerTargetExpression (this);
9174 initializers.Resolve (ec);
9175 ec.CurrentInitializerVariable = previous;
9179 public override bool Emit (EmitContext ec, IMemoryLocation target)
9181 bool left_on_stack = base.Emit (ec, target);
9183 if (initializers.IsEmpty)
9184 return left_on_stack;
9186 LocalTemporary temp = target as LocalTemporary;
9188 if (!left_on_stack) {
9189 VariableReference vr = target as VariableReference;
9191 // FIXME: This still does not work correctly for pre-set variables
9192 if (vr != null && vr.IsRef)
9193 target.AddressOf (ec, AddressOp.Load);
9195 ((Expression) target).Emit (ec);
9196 left_on_stack = true;
9199 temp = new LocalTemporary (type);
9206 initializers.Emit (ec);
9208 if (left_on_stack) {
9213 return left_on_stack;
9216 public override bool HasInitializer {
9218 return !initializers.IsEmpty;
9223 public class NewAnonymousType : New
9225 static readonly AnonymousTypeParameter[] EmptyParameters = new AnonymousTypeParameter[0];
9227 List<AnonymousTypeParameter> parameters;
9228 readonly TypeContainer parent;
9229 AnonymousTypeClass anonymous_type;
9231 public NewAnonymousType (List<AnonymousTypeParameter> parameters, TypeContainer parent, Location loc)
9232 : base (null, null, loc)
9234 this.parameters = parameters;
9235 this.parent = parent;
9238 protected override void CloneTo (CloneContext clonectx, Expression target)
9240 if (parameters == null)
9243 NewAnonymousType t = (NewAnonymousType) target;
9244 t.parameters = new List<AnonymousTypeParameter> (parameters.Count);
9245 foreach (AnonymousTypeParameter atp in parameters)
9246 t.parameters.Add ((AnonymousTypeParameter) atp.Clone (clonectx));
9249 AnonymousTypeClass CreateAnonymousType (ResolveContext ec, IList<AnonymousTypeParameter> parameters)
9251 AnonymousTypeClass type = parent.Module.Compiled.GetAnonymousType (parameters);
9255 type = AnonymousTypeClass.Create (ec.Compiler, parent, parameters, loc);
9261 type.ResolveTypeParameters ();
9264 if (ec.Report.Errors == 0)
9267 parent.Module.Compiled.AddAnonymousType (type);
9271 public override Expression CreateExpressionTree (ResolveContext ec)
9273 if (parameters == null)
9274 return base.CreateExpressionTree (ec);
9276 var init = new ArrayInitializer (parameters.Count, loc);
9277 foreach (Property p in anonymous_type.Properties)
9278 init.Add (new TypeOfMethod (MemberCache.GetMember (type, p.Get.Spec), loc));
9280 var ctor_args = new ArrayInitializer (Arguments.Count, loc);
9281 foreach (Argument a in Arguments)
9282 ctor_args.Add (a.CreateExpressionTree (ec));
9284 Arguments args = new Arguments (3);
9285 args.Add (new Argument (new TypeOfMethod (method, loc)));
9286 args.Add (new Argument (new ArrayCreation (TypeManager.expression_type_expr, ctor_args, loc)));
9287 args.Add (new Argument (new ImplicitlyTypedArrayCreation (init, loc)));
9289 return CreateExpressionFactoryCall (ec, "New", args);
9292 protected override Expression DoResolve (ResolveContext ec)
9294 if (ec.HasSet (ResolveContext.Options.ConstantScope)) {
9295 ec.Report.Error (836, loc, "Anonymous types cannot be used in this expression");
9299 if (parameters == null) {
9300 anonymous_type = CreateAnonymousType (ec, EmptyParameters);
9301 RequestedType = new TypeExpression (anonymous_type.Definition, loc);
9302 return base.DoResolve (ec);
9306 Arguments = new Arguments (parameters.Count);
9307 TypeExpression [] t_args = new TypeExpression [parameters.Count];
9308 for (int i = 0; i < parameters.Count; ++i) {
9309 Expression e = ((AnonymousTypeParameter) parameters [i]).Resolve (ec);
9315 Arguments.Add (new Argument (e));
9316 t_args [i] = new TypeExpression (e.Type, e.Location);
9322 anonymous_type = CreateAnonymousType (ec, parameters);
9323 if (anonymous_type == null)
9326 RequestedType = new GenericTypeExpr (anonymous_type.Definition, new TypeArguments (t_args), loc);
9327 return base.DoResolve (ec);
9331 public class AnonymousTypeParameter : ShimExpression
9333 public readonly string Name;
9335 public AnonymousTypeParameter (Expression initializer, string name, Location loc)
9336 : base (initializer)
9342 public AnonymousTypeParameter (Parameter parameter)
9343 : base (new SimpleName (parameter.Name, parameter.Location))
9345 this.Name = parameter.Name;
9346 this.loc = parameter.Location;
9349 public override bool Equals (object o)
9351 AnonymousTypeParameter other = o as AnonymousTypeParameter;
9352 return other != null && Name == other.Name;
9355 public override int GetHashCode ()
9357 return Name.GetHashCode ();
9360 protected override Expression DoResolve (ResolveContext ec)
9362 Expression e = expr.Resolve (ec);
9366 if (e.eclass == ExprClass.MethodGroup) {
9367 Error_InvalidInitializer (ec, e.ExprClassName);
9372 if (type == TypeManager.void_type || type == InternalType.Null ||
9373 type == InternalType.AnonymousMethod || type.IsPointer) {
9374 Error_InvalidInitializer (ec, e.GetSignatureForError ());
9381 protected virtual void Error_InvalidInitializer (ResolveContext ec, string initializer)
9383 ec.Report.Error (828, loc, "An anonymous type property `{0}' cannot be initialized with `{1}'",