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);
1538 } else if (expr.Type == InternalType.Dynamic) {
1539 if (type != InternalType.Dynamic) {
1540 Arguments arg = new Arguments (1);
1541 arg.Add (new Argument (expr));
1542 return new DynamicConversion (type, CSharpBinderFlags.ConvertExplicit, arg, loc).Resolve (ec);
1548 var res = Convert.ExplicitConversion (ec, expr, type, loc);
1550 return EmptyCast.Create (res, type);
1555 protected override void CloneTo (CloneContext clonectx, Expression t)
1557 Cast target = (Cast) t;
1559 target.target_type = target_type.Clone (clonectx);
1560 target.expr = expr.Clone (clonectx);
1564 public class ImplicitCast : ShimExpression
1568 public ImplicitCast (Expression expr, TypeSpec target, bool arrayAccess)
1571 this.loc = expr.Location;
1573 this.arrayAccess = arrayAccess;
1576 protected override Expression DoResolve (ResolveContext ec)
1578 expr = expr.Resolve (ec);
1583 expr = ConvertExpressionToArrayIndex (ec, expr);
1585 expr = Convert.ImplicitConversionRequired (ec, expr, type, loc);
1592 // C# 2.0 Default value expression
1594 public class DefaultValueExpression : Expression
1598 public DefaultValueExpression (Expression expr, Location loc)
1604 public override Expression CreateExpressionTree (ResolveContext ec)
1606 Arguments args = new Arguments (2);
1607 args.Add (new Argument (this));
1608 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
1609 return CreateExpressionFactoryCall (ec, "Constant", args);
1612 protected override Expression DoResolve (ResolveContext ec)
1614 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
1620 if (type.IsStatic) {
1621 ec.Report.Error (-244, loc, "The `default value' operator cannot be applied to an operand of a static type");
1625 return new NullLiteral (Location).ConvertImplicitly (ec, type);
1627 if (TypeManager.IsReferenceType (type))
1628 return new NullConstant (type, loc);
1630 Constant c = New.Constantify (type);
1632 return c.Resolve (ec);
1634 eclass = ExprClass.Variable;
1638 public override void Emit (EmitContext ec)
1640 LocalTemporary temp_storage = new LocalTemporary(type);
1642 temp_storage.AddressOf(ec, AddressOp.LoadStore);
1643 ec.Emit(OpCodes.Initobj, type);
1644 temp_storage.Emit(ec);
1647 protected override void CloneTo (CloneContext clonectx, Expression t)
1649 DefaultValueExpression target = (DefaultValueExpression) t;
1651 target.expr = expr.Clone (clonectx);
1656 /// Binary operators
1658 public class Binary : Expression, IDynamicBinder
1660 protected class PredefinedOperator {
1661 protected readonly TypeSpec left;
1662 protected readonly TypeSpec right;
1663 public readonly Operator OperatorsMask;
1664 public TypeSpec ReturnType;
1666 public PredefinedOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
1667 : this (ltype, rtype, op_mask, ltype)
1671 public PredefinedOperator (TypeSpec type, Operator op_mask, TypeSpec return_type)
1672 : this (type, type, op_mask, return_type)
1676 public PredefinedOperator (TypeSpec type, Operator op_mask)
1677 : this (type, type, op_mask, type)
1681 public PredefinedOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask, TypeSpec return_type)
1683 if ((op_mask & Operator.ValuesOnlyMask) != 0)
1684 throw new InternalErrorException ("Only masked values can be used");
1688 this.OperatorsMask = op_mask;
1689 this.ReturnType = return_type;
1692 public virtual Expression ConvertResult (ResolveContext ec, Binary b)
1694 b.type = ReturnType;
1696 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1697 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
1700 // A user operators does not support multiple user conversions, but decimal type
1701 // is considered to be predefined type therefore we apply predefined operators rules
1702 // and then look for decimal user-operator implementation
1704 if (left == TypeManager.decimal_type)
1705 return b.ResolveUserOperator (ec, b.left.Type, b.right.Type);
1707 var c = b.right as Constant;
1709 if (c.IsDefaultValue && (b.oper == Operator.Addition || b.oper == Operator.BitwiseOr || b.oper == Operator.Subtraction))
1710 return ReducedExpression.Create (b.left, b).Resolve (ec);
1711 if ((b.oper == Operator.Multiply || b.oper == Operator.Division) && c.IsOneInteger)
1712 return ReducedExpression.Create (b.left, b).Resolve (ec);
1716 c = b.left as Constant;
1718 if (c.IsDefaultValue && (b.oper == Operator.Addition || b.oper == Operator.BitwiseOr))
1719 return ReducedExpression.Create (b.right, b).Resolve (ec);
1720 if (b.oper == Operator.Multiply && c.IsOneInteger)
1721 return ReducedExpression.Create (b.right, b).Resolve (ec);
1728 public bool IsPrimitiveApplicable (TypeSpec ltype, TypeSpec rtype)
1731 // We are dealing with primitive types only
1733 return left == ltype && ltype == rtype;
1736 public virtual bool IsApplicable (ResolveContext ec, Expression lexpr, Expression rexpr)
1739 if (left == lexpr.Type && right == rexpr.Type)
1742 return Convert.ImplicitConversionExists (ec, lexpr, left) &&
1743 Convert.ImplicitConversionExists (ec, rexpr, right);
1746 public PredefinedOperator ResolveBetterOperator (ResolveContext ec, PredefinedOperator best_operator)
1749 if (left != null && best_operator.left != null) {
1750 result = OverloadResolver.BetterTypeConversion (ec, best_operator.left, left);
1754 // When second argument is same as the first one, the result is same
1756 if (right != null && (left != right || best_operator.left != best_operator.right)) {
1757 result |= OverloadResolver.BetterTypeConversion (ec, best_operator.right, right);
1760 if (result == 0 || result > 2)
1763 return result == 1 ? best_operator : this;
1767 class PredefinedStringOperator : PredefinedOperator {
1768 public PredefinedStringOperator (TypeSpec type, Operator op_mask)
1769 : base (type, op_mask, type)
1771 ReturnType = TypeManager.string_type;
1774 public PredefinedStringOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
1775 : base (ltype, rtype, op_mask)
1777 ReturnType = TypeManager.string_type;
1780 public override Expression ConvertResult (ResolveContext ec, Binary b)
1783 // Use original expression for nullable arguments
1785 Nullable.Unwrap unwrap = b.left as Nullable.Unwrap;
1787 b.left = unwrap.Original;
1789 unwrap = b.right as Nullable.Unwrap;
1791 b.right = unwrap.Original;
1793 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1794 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
1797 // Start a new concat expression using converted expression
1799 return StringConcat.Create (ec, b.left, b.right, b.loc);
1803 class PredefinedShiftOperator : PredefinedOperator {
1804 public PredefinedShiftOperator (TypeSpec ltype, Operator op_mask) :
1805 base (ltype, TypeManager.int32_type, op_mask)
1809 public override Expression ConvertResult (ResolveContext ec, Binary b)
1811 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1813 Expression expr_tree_expr = Convert.ImplicitConversion (ec, b.right, TypeManager.int32_type, b.right.Location);
1815 int right_mask = left == TypeManager.int32_type || left == TypeManager.uint32_type ? 0x1f : 0x3f;
1818 // b = b.left >> b.right & (0x1f|0x3f)
1820 b.right = new Binary (Operator.BitwiseAnd,
1821 b.right, new IntConstant (right_mask, b.right.Location), b.loc).Resolve (ec);
1824 // Expression tree representation does not use & mask
1826 b.right = ReducedExpression.Create (b.right, expr_tree_expr).Resolve (ec);
1827 b.type = ReturnType;
1830 // Optimize shift by 0
1832 var c = b.right as Constant;
1833 if (c != null && c.IsDefaultValue)
1834 return ReducedExpression.Create (b.left, b).Resolve (ec);
1840 class PredefinedEqualityOperator : PredefinedOperator
1842 MethodSpec equal_method, inequal_method;
1844 public PredefinedEqualityOperator (TypeSpec arg, TypeSpec retType)
1845 : base (arg, arg, Operator.EqualityMask, retType)
1849 public override Expression ConvertResult (ResolveContext ec, Binary b)
1851 b.type = ReturnType;
1853 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1854 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
1856 Arguments args = new Arguments (2);
1857 args.Add (new Argument (b.left));
1858 args.Add (new Argument (b.right));
1861 if (b.oper == Operator.Equality) {
1862 if (equal_method == null) {
1863 equal_method = TypeManager.GetPredefinedMethod (left,
1864 new MemberFilter (CSharp.Operator.GetMetadataName (CSharp.Operator.OpType.Equality), 0, MemberKind.Operator, null, ReturnType), b.loc);
1867 method = equal_method;
1869 if (inequal_method == null) {
1870 inequal_method = TypeManager.GetPredefinedMethod (left,
1871 new MemberFilter (CSharp.Operator.GetMetadataName (CSharp.Operator.OpType.Inequality), 0, MemberKind.Operator, null, ReturnType), b.loc);
1874 method = inequal_method;
1877 return new UserOperatorCall (method, args, b.CreateExpressionTree, b.loc);
1881 class PredefinedPointerOperator : PredefinedOperator
1883 public PredefinedPointerOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
1884 : base (ltype, rtype, op_mask)
1888 public PredefinedPointerOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask, TypeSpec retType)
1889 : base (ltype, rtype, op_mask, retType)
1893 public PredefinedPointerOperator (TypeSpec type, Operator op_mask, TypeSpec return_type)
1894 : base (type, op_mask, return_type)
1898 public override bool IsApplicable (ResolveContext ec, Expression lexpr, Expression rexpr)
1901 if (!lexpr.Type.IsPointer)
1904 if (!Convert.ImplicitConversionExists (ec, lexpr, left))
1908 if (right == null) {
1909 if (!rexpr.Type.IsPointer)
1912 if (!Convert.ImplicitConversionExists (ec, rexpr, right))
1919 public override Expression ConvertResult (ResolveContext ec, Binary b)
1922 b.left = EmptyCast.Create (b.left, left);
1923 } else if (right != null) {
1924 b.right = EmptyCast.Create (b.right, right);
1927 TypeSpec r_type = ReturnType;
1928 Expression left_arg, right_arg;
1929 if (r_type == null) {
1932 right_arg = b.right;
1933 r_type = b.left.Type;
1937 r_type = b.right.Type;
1941 right_arg = b.right;
1944 return new PointerArithmetic (b.oper, left_arg, right_arg, r_type, b.loc).Resolve (ec);
1949 public enum Operator {
1950 Multiply = 0 | ArithmeticMask,
1951 Division = 1 | ArithmeticMask,
1952 Modulus = 2 | ArithmeticMask,
1953 Addition = 3 | ArithmeticMask | AdditionMask,
1954 Subtraction = 4 | ArithmeticMask | SubtractionMask,
1956 LeftShift = 5 | ShiftMask,
1957 RightShift = 6 | ShiftMask,
1959 LessThan = 7 | ComparisonMask | RelationalMask,
1960 GreaterThan = 8 | ComparisonMask | RelationalMask,
1961 LessThanOrEqual = 9 | ComparisonMask | RelationalMask,
1962 GreaterThanOrEqual = 10 | ComparisonMask | RelationalMask,
1963 Equality = 11 | ComparisonMask | EqualityMask,
1964 Inequality = 12 | ComparisonMask | EqualityMask,
1966 BitwiseAnd = 13 | BitwiseMask,
1967 ExclusiveOr = 14 | BitwiseMask,
1968 BitwiseOr = 15 | BitwiseMask,
1970 LogicalAnd = 16 | LogicalMask,
1971 LogicalOr = 17 | LogicalMask,
1976 ValuesOnlyMask = ArithmeticMask - 1,
1977 ArithmeticMask = 1 << 5,
1979 ComparisonMask = 1 << 7,
1980 EqualityMask = 1 << 8,
1981 BitwiseMask = 1 << 9,
1982 LogicalMask = 1 << 10,
1983 AdditionMask = 1 << 11,
1984 SubtractionMask = 1 << 12,
1985 RelationalMask = 1 << 13
1988 readonly Operator oper;
1989 protected Expression left, right;
1990 readonly bool is_compound;
1991 Expression enum_conversion;
1993 static PredefinedOperator[] standard_operators;
1994 static PredefinedOperator[] equality_operators;
1995 static PredefinedOperator[] pointer_operators;
1997 public Binary (Operator oper, Expression left, Expression right, bool isCompound, Location loc)
1998 : this (oper, left, right, loc)
2000 this.is_compound = isCompound;
2003 public Binary (Operator oper, Expression left, Expression right, Location loc)
2011 public Operator Oper {
2018 /// Returns a stringified representation of the Operator
2020 string OperName (Operator oper)
2024 case Operator.Multiply:
2027 case Operator.Division:
2030 case Operator.Modulus:
2033 case Operator.Addition:
2036 case Operator.Subtraction:
2039 case Operator.LeftShift:
2042 case Operator.RightShift:
2045 case Operator.LessThan:
2048 case Operator.GreaterThan:
2051 case Operator.LessThanOrEqual:
2054 case Operator.GreaterThanOrEqual:
2057 case Operator.Equality:
2060 case Operator.Inequality:
2063 case Operator.BitwiseAnd:
2066 case Operator.BitwiseOr:
2069 case Operator.ExclusiveOr:
2072 case Operator.LogicalOr:
2075 case Operator.LogicalAnd:
2079 s = oper.ToString ();
2089 public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, Operator oper, Location loc)
2091 new Binary (oper, left, right, loc).Error_OperatorCannotBeApplied (ec, left, right);
2094 public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, string oper, Location loc)
2097 l = TypeManager.CSharpName (left.Type);
2098 r = TypeManager.CSharpName (right.Type);
2100 ec.Report.Error (19, loc, "Operator `{0}' cannot be applied to operands of type `{1}' and `{2}'",
2104 protected void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right)
2106 Error_OperatorCannotBeApplied (ec, left, right, OperName (oper), loc);
2110 // Converts operator to System.Linq.Expressions.ExpressionType enum name
2112 string GetOperatorExpressionTypeName ()
2115 case Operator.Addition:
2116 return is_compound ? "AddAssign" : "Add";
2117 case Operator.BitwiseAnd:
2118 return is_compound ? "AndAssign" : "And";
2119 case Operator.BitwiseOr:
2120 return is_compound ? "OrAssign" : "Or";
2121 case Operator.Division:
2122 return is_compound ? "DivideAssign" : "Divide";
2123 case Operator.ExclusiveOr:
2124 return is_compound ? "ExclusiveOrAssign" : "ExclusiveOr";
2125 case Operator.Equality:
2127 case Operator.GreaterThan:
2128 return "GreaterThan";
2129 case Operator.GreaterThanOrEqual:
2130 return "GreaterThanOrEqual";
2131 case Operator.Inequality:
2133 case Operator.LeftShift:
2134 return is_compound ? "LeftShiftAssign" : "LeftShift";
2135 case Operator.LessThan:
2137 case Operator.LessThanOrEqual:
2138 return "LessThanOrEqual";
2139 case Operator.LogicalAnd:
2141 case Operator.LogicalOr:
2143 case Operator.Modulus:
2144 return is_compound ? "ModuloAssign" : "Modulo";
2145 case Operator.Multiply:
2146 return is_compound ? "MultiplyAssign" : "Multiply";
2147 case Operator.RightShift:
2148 return is_compound ? "RightShiftAssign" : "RightShift";
2149 case Operator.Subtraction:
2150 return is_compound ? "SubtractAssign" : "Subtract";
2152 throw new NotImplementedException ("Unknown expression type operator " + oper.ToString ());
2156 static CSharp.Operator.OpType ConvertBinaryToUserOperator (Operator op)
2159 case Operator.Addition:
2160 return CSharp.Operator.OpType.Addition;
2161 case Operator.BitwiseAnd:
2162 case Operator.LogicalAnd:
2163 return CSharp.Operator.OpType.BitwiseAnd;
2164 case Operator.BitwiseOr:
2165 case Operator.LogicalOr:
2166 return CSharp.Operator.OpType.BitwiseOr;
2167 case Operator.Division:
2168 return CSharp.Operator.OpType.Division;
2169 case Operator.Equality:
2170 return CSharp.Operator.OpType.Equality;
2171 case Operator.ExclusiveOr:
2172 return CSharp.Operator.OpType.ExclusiveOr;
2173 case Operator.GreaterThan:
2174 return CSharp.Operator.OpType.GreaterThan;
2175 case Operator.GreaterThanOrEqual:
2176 return CSharp.Operator.OpType.GreaterThanOrEqual;
2177 case Operator.Inequality:
2178 return CSharp.Operator.OpType.Inequality;
2179 case Operator.LeftShift:
2180 return CSharp.Operator.OpType.LeftShift;
2181 case Operator.LessThan:
2182 return CSharp.Operator.OpType.LessThan;
2183 case Operator.LessThanOrEqual:
2184 return CSharp.Operator.OpType.LessThanOrEqual;
2185 case Operator.Modulus:
2186 return CSharp.Operator.OpType.Modulus;
2187 case Operator.Multiply:
2188 return CSharp.Operator.OpType.Multiply;
2189 case Operator.RightShift:
2190 return CSharp.Operator.OpType.RightShift;
2191 case Operator.Subtraction:
2192 return CSharp.Operator.OpType.Subtraction;
2194 throw new InternalErrorException (op.ToString ());
2198 public static void EmitOperatorOpcode (EmitContext ec, Operator oper, TypeSpec l)
2203 case Operator.Multiply:
2204 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2205 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2206 opcode = OpCodes.Mul_Ovf;
2207 else if (!IsFloat (l))
2208 opcode = OpCodes.Mul_Ovf_Un;
2210 opcode = OpCodes.Mul;
2212 opcode = OpCodes.Mul;
2216 case Operator.Division:
2218 opcode = OpCodes.Div_Un;
2220 opcode = OpCodes.Div;
2223 case Operator.Modulus:
2225 opcode = OpCodes.Rem_Un;
2227 opcode = OpCodes.Rem;
2230 case Operator.Addition:
2231 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2232 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2233 opcode = OpCodes.Add_Ovf;
2234 else if (!IsFloat (l))
2235 opcode = OpCodes.Add_Ovf_Un;
2237 opcode = OpCodes.Add;
2239 opcode = OpCodes.Add;
2242 case Operator.Subtraction:
2243 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2244 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2245 opcode = OpCodes.Sub_Ovf;
2246 else if (!IsFloat (l))
2247 opcode = OpCodes.Sub_Ovf_Un;
2249 opcode = OpCodes.Sub;
2251 opcode = OpCodes.Sub;
2254 case Operator.RightShift:
2256 opcode = OpCodes.Shr_Un;
2258 opcode = OpCodes.Shr;
2261 case Operator.LeftShift:
2262 opcode = OpCodes.Shl;
2265 case Operator.Equality:
2266 opcode = OpCodes.Ceq;
2269 case Operator.Inequality:
2270 ec.Emit (OpCodes.Ceq);
2271 ec.Emit (OpCodes.Ldc_I4_0);
2273 opcode = OpCodes.Ceq;
2276 case Operator.LessThan:
2278 opcode = OpCodes.Clt_Un;
2280 opcode = OpCodes.Clt;
2283 case Operator.GreaterThan:
2285 opcode = OpCodes.Cgt_Un;
2287 opcode = OpCodes.Cgt;
2290 case Operator.LessThanOrEqual:
2291 if (IsUnsigned (l) || IsFloat (l))
2292 ec.Emit (OpCodes.Cgt_Un);
2294 ec.Emit (OpCodes.Cgt);
2295 ec.Emit (OpCodes.Ldc_I4_0);
2297 opcode = OpCodes.Ceq;
2300 case Operator.GreaterThanOrEqual:
2301 if (IsUnsigned (l) || IsFloat (l))
2302 ec.Emit (OpCodes.Clt_Un);
2304 ec.Emit (OpCodes.Clt);
2306 ec.Emit (OpCodes.Ldc_I4_0);
2308 opcode = OpCodes.Ceq;
2311 case Operator.BitwiseOr:
2312 opcode = OpCodes.Or;
2315 case Operator.BitwiseAnd:
2316 opcode = OpCodes.And;
2319 case Operator.ExclusiveOr:
2320 opcode = OpCodes.Xor;
2324 throw new InternalErrorException (oper.ToString ());
2330 static bool IsUnsigned (TypeSpec t)
2335 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2336 t == TypeManager.ushort_type || t == TypeManager.byte_type);
2339 static bool IsFloat (TypeSpec t)
2341 return t == TypeManager.float_type || t == TypeManager.double_type;
2344 public static void Reset ()
2346 equality_operators = pointer_operators = standard_operators = null;
2349 Expression ResolveOperator (ResolveContext ec)
2351 TypeSpec l = left.Type;
2352 TypeSpec r = right.Type;
2354 bool primitives_only = false;
2356 if (standard_operators == null)
2357 CreateStandardOperatorsTable ();
2360 // Handles predefined primitive types
2362 if (TypeManager.IsPrimitiveType (l) && TypeManager.IsPrimitiveType (r)) {
2363 if ((oper & Operator.ShiftMask) == 0) {
2364 if (l != TypeManager.bool_type && !DoBinaryOperatorPromotion (ec))
2367 primitives_only = true;
2371 if (l.IsPointer || r.IsPointer)
2372 return ResolveOperatorPointer (ec, l, r);
2375 bool lenum = TypeManager.IsEnumType (l);
2376 bool renum = TypeManager.IsEnumType (r);
2377 if (lenum || renum) {
2378 expr = ResolveOperatorEnum (ec, lenum, renum, l, r);
2380 // TODO: Can this be ambiguous
2386 if ((oper == Operator.Addition || oper == Operator.Subtraction) && (l.IsDelegate || r.IsDelegate)) {
2388 expr = ResolveOperatorDelegate (ec, l, r);
2390 // TODO: Can this be ambiguous
2396 expr = ResolveUserOperator (ec, l, r);
2400 // Predefined reference types equality
2401 if ((oper & Operator.EqualityMask) != 0) {
2402 expr = ResolveOperatorEquality (ec, l, r);
2408 return ResolveOperatorPredefined (ec, standard_operators, primitives_only, null);
2411 // at least one of 'left' or 'right' is an enumeration constant (EnumConstant or SideEffectConstant or ...)
2412 // if 'left' is not an enumeration constant, create one from the type of 'right'
2413 Constant EnumLiftUp (ResolveContext ec, Constant left, Constant right, Location loc)
2416 case Operator.BitwiseOr:
2417 case Operator.BitwiseAnd:
2418 case Operator.ExclusiveOr:
2419 case Operator.Equality:
2420 case Operator.Inequality:
2421 case Operator.LessThan:
2422 case Operator.LessThanOrEqual:
2423 case Operator.GreaterThan:
2424 case Operator.GreaterThanOrEqual:
2425 if (TypeManager.IsEnumType (left.Type))
2428 if (left.IsZeroInteger)
2429 return left.TryReduce (ec, right.Type, loc);
2433 case Operator.Addition:
2434 case Operator.Subtraction:
2437 case Operator.Multiply:
2438 case Operator.Division:
2439 case Operator.Modulus:
2440 case Operator.LeftShift:
2441 case Operator.RightShift:
2442 if (TypeManager.IsEnumType (right.Type) || TypeManager.IsEnumType (left.Type))
2446 Error_OperatorCannotBeApplied (ec, this.left, this.right);
2451 // The `|' operator used on types which were extended is dangerous
2453 void CheckBitwiseOrOnSignExtended (ResolveContext ec)
2455 OpcodeCast lcast = left as OpcodeCast;
2456 if (lcast != null) {
2457 if (IsUnsigned (lcast.UnderlyingType))
2461 OpcodeCast rcast = right as OpcodeCast;
2462 if (rcast != null) {
2463 if (IsUnsigned (rcast.UnderlyingType))
2467 if (lcast == null && rcast == null)
2470 // FIXME: consider constants
2472 ec.Report.Warning (675, 3, loc,
2473 "The operator `|' used on the sign-extended type `{0}'. Consider casting to a smaller unsigned type first",
2474 TypeManager.CSharpName (lcast != null ? lcast.UnderlyingType : rcast.UnderlyingType));
2477 static void CreatePointerOperatorsTable ()
2479 var temp = new List<PredefinedPointerOperator> ();
2482 // Pointer arithmetic:
2484 // T* operator + (T* x, int y); T* operator - (T* x, int y);
2485 // T* operator + (T* x, uint y); T* operator - (T* x, uint y);
2486 // T* operator + (T* x, long y); T* operator - (T* x, long y);
2487 // T* operator + (T* x, ulong y); T* operator - (T* x, ulong y);
2489 temp.Add (new PredefinedPointerOperator (null, TypeManager.int32_type, Operator.AdditionMask | Operator.SubtractionMask));
2490 temp.Add (new PredefinedPointerOperator (null, TypeManager.uint32_type, Operator.AdditionMask | Operator.SubtractionMask));
2491 temp.Add (new PredefinedPointerOperator (null, TypeManager.int64_type, Operator.AdditionMask | Operator.SubtractionMask));
2492 temp.Add (new PredefinedPointerOperator (null, TypeManager.uint64_type, Operator.AdditionMask | Operator.SubtractionMask));
2495 // T* operator + (int y, T* x);
2496 // T* operator + (uint y, T *x);
2497 // T* operator + (long y, T *x);
2498 // T* operator + (ulong y, T *x);
2500 temp.Add (new PredefinedPointerOperator (TypeManager.int32_type, null, Operator.AdditionMask, null));
2501 temp.Add (new PredefinedPointerOperator (TypeManager.uint32_type, null, Operator.AdditionMask, null));
2502 temp.Add (new PredefinedPointerOperator (TypeManager.int64_type, null, Operator.AdditionMask, null));
2503 temp.Add (new PredefinedPointerOperator (TypeManager.uint64_type, null, Operator.AdditionMask, null));
2506 // long operator - (T* x, T *y)
2508 temp.Add (new PredefinedPointerOperator (null, Operator.SubtractionMask, TypeManager.int64_type));
2510 pointer_operators = temp.ToArray ();
2513 static void CreateStandardOperatorsTable ()
2515 var temp = new List<PredefinedOperator> ();
2516 TypeSpec bool_type = TypeManager.bool_type;
2518 temp.Add (new PredefinedOperator (TypeManager.int32_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2519 temp.Add (new PredefinedOperator (TypeManager.uint32_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2520 temp.Add (new PredefinedOperator (TypeManager.int64_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2521 temp.Add (new PredefinedOperator (TypeManager.uint64_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2522 temp.Add (new PredefinedOperator (TypeManager.float_type, Operator.ArithmeticMask));
2523 temp.Add (new PredefinedOperator (TypeManager.double_type, Operator.ArithmeticMask));
2524 temp.Add (new PredefinedOperator (TypeManager.decimal_type, Operator.ArithmeticMask));
2526 temp.Add (new PredefinedOperator (TypeManager.int32_type, Operator.ComparisonMask, bool_type));
2527 temp.Add (new PredefinedOperator (TypeManager.uint32_type, Operator.ComparisonMask, bool_type));
2528 temp.Add (new PredefinedOperator (TypeManager.int64_type, Operator.ComparisonMask, bool_type));
2529 temp.Add (new PredefinedOperator (TypeManager.uint64_type, Operator.ComparisonMask, bool_type));
2530 temp.Add (new PredefinedOperator (TypeManager.float_type, Operator.ComparisonMask, bool_type));
2531 temp.Add (new PredefinedOperator (TypeManager.double_type, Operator.ComparisonMask, bool_type));
2532 temp.Add (new PredefinedOperator (TypeManager.decimal_type, Operator.ComparisonMask, bool_type));
2534 temp.Add (new PredefinedStringOperator (TypeManager.string_type, Operator.AdditionMask));
2535 temp.Add (new PredefinedStringOperator (TypeManager.string_type, TypeManager.object_type, Operator.AdditionMask));
2536 temp.Add (new PredefinedStringOperator (TypeManager.object_type, TypeManager.string_type, Operator.AdditionMask));
2538 temp.Add (new PredefinedOperator (bool_type,
2539 Operator.BitwiseMask | Operator.LogicalMask | Operator.EqualityMask, bool_type));
2541 temp.Add (new PredefinedShiftOperator (TypeManager.int32_type, Operator.ShiftMask));
2542 temp.Add (new PredefinedShiftOperator (TypeManager.uint32_type, Operator.ShiftMask));
2543 temp.Add (new PredefinedShiftOperator (TypeManager.int64_type, Operator.ShiftMask));
2544 temp.Add (new PredefinedShiftOperator (TypeManager.uint64_type, Operator.ShiftMask));
2546 standard_operators = temp.ToArray ();
2548 var equality = new List<PredefinedOperator> () {
2549 new PredefinedEqualityOperator (TypeManager.string_type, bool_type),
2550 new PredefinedEqualityOperator (TypeManager.delegate_type, bool_type),
2551 new PredefinedOperator (bool_type, Operator.EqualityMask, bool_type)
2554 equality_operators = equality.ToArray ();
2558 // Rules used during binary numeric promotion
2560 static bool DoNumericPromotion (ResolveContext rc, ref Expression prim_expr, ref Expression second_expr, TypeSpec type)
2565 Constant c = prim_expr as Constant;
2567 temp = c.ConvertImplicitly (rc, type);
2574 if (type == TypeManager.uint32_type) {
2575 etype = prim_expr.Type;
2576 if (etype == TypeManager.int32_type || etype == TypeManager.short_type || etype == TypeManager.sbyte_type) {
2577 type = TypeManager.int64_type;
2579 if (type != second_expr.Type) {
2580 c = second_expr as Constant;
2582 temp = c.ConvertImplicitly (rc, type);
2584 temp = Convert.ImplicitNumericConversion (second_expr, type);
2590 } else if (type == TypeManager.uint64_type) {
2592 // A compile-time error occurs if the other operand is of type sbyte, short, int, or long
2594 if (type == TypeManager.int32_type || type == TypeManager.int64_type ||
2595 type == TypeManager.short_type || type == TypeManager.sbyte_type)
2599 temp = Convert.ImplicitNumericConversion (prim_expr, type);
2608 // 7.2.6.2 Binary numeric promotions
2610 public bool DoBinaryOperatorPromotion (ResolveContext ec)
2612 TypeSpec ltype = left.Type;
2613 TypeSpec rtype = right.Type;
2616 foreach (TypeSpec t in ConstantFold.BinaryPromotionsTypes) {
2618 return t == rtype || DoNumericPromotion (ec, ref right, ref left, t);
2621 return t == ltype || DoNumericPromotion (ec, ref left, ref right, t);
2624 TypeSpec int32 = TypeManager.int32_type;
2625 if (ltype != int32) {
2626 Constant c = left as Constant;
2628 temp = c.ConvertImplicitly (ec, int32);
2630 temp = Convert.ImplicitNumericConversion (left, int32);
2637 if (rtype != int32) {
2638 Constant c = right as Constant;
2640 temp = c.ConvertImplicitly (ec, int32);
2642 temp = Convert.ImplicitNumericConversion (right, int32);
2652 protected override Expression DoResolve (ResolveContext ec)
2657 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2658 left = ((ParenthesizedExpression) left).Expr;
2659 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2663 if (left.eclass == ExprClass.Type) {
2664 ec.Report.Error (75, loc, "To cast a negative value, you must enclose the value in parentheses");
2668 left = left.Resolve (ec);
2673 Constant lc = left as Constant;
2675 if (lc != null && lc.Type == TypeManager.bool_type &&
2676 ((oper == Operator.LogicalAnd && lc.IsDefaultValue) ||
2677 (oper == Operator.LogicalOr && !lc.IsDefaultValue))) {
2679 // FIXME: resolve right expression as unreachable
2680 // right.Resolve (ec);
2682 ec.Report.Warning (429, 4, loc, "Unreachable expression code detected");
2686 right = right.Resolve (ec);
2690 eclass = ExprClass.Value;
2691 Constant rc = right as Constant;
2693 // The conversion rules are ignored in enum context but why
2694 if (!ec.HasSet (ResolveContext.Options.EnumScope) && lc != null && rc != null && (TypeManager.IsEnumType (left.Type) || TypeManager.IsEnumType (right.Type))) {
2695 lc = EnumLiftUp (ec, lc, rc, loc);
2697 rc = EnumLiftUp (ec, rc, lc, loc);
2700 if (rc != null && lc != null) {
2701 int prev_e = ec.Report.Errors;
2702 Expression e = ConstantFold.BinaryFold (ec, oper, lc, rc, loc);
2706 if (e != null || ec.Report.Errors != prev_e)
2710 // Comparison warnings
2711 if ((oper & Operator.ComparisonMask) != 0) {
2712 if (left.Equals (right)) {
2713 ec.Report.Warning (1718, 3, loc, "A comparison made to same variable. Did you mean to compare something else?");
2715 CheckUselessComparison (ec, lc, right.Type);
2716 CheckUselessComparison (ec, rc, left.Type);
2719 if (left.Type == InternalType.Dynamic || right.Type == InternalType.Dynamic) {
2720 Arguments args = new Arguments (2);
2721 args.Add (new Argument (left));
2722 args.Add (new Argument (right));
2723 return new DynamicExpressionStatement (this, args, loc).Resolve (ec);
2726 if (RootContext.Version >= LanguageVersion.ISO_2 &&
2727 ((TypeManager.IsNullableType (left.Type) && (right is NullLiteral || TypeManager.IsNullableType (right.Type) || TypeManager.IsValueType (right.Type))) ||
2728 (TypeManager.IsValueType (left.Type) && right is NullLiteral) ||
2729 (TypeManager.IsNullableType (right.Type) && (left is NullLiteral || TypeManager.IsNullableType (left.Type) || TypeManager.IsValueType (left.Type))) ||
2730 (TypeManager.IsValueType (right.Type) && left is NullLiteral)))
2731 return new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
2733 return DoResolveCore (ec, left, right);
2736 protected Expression DoResolveCore (ResolveContext ec, Expression left_orig, Expression right_orig)
2738 Expression expr = ResolveOperator (ec);
2740 Error_OperatorCannotBeApplied (ec, left_orig, right_orig);
2742 if (left == null || right == null)
2743 throw new InternalErrorException ("Invalid conversion");
2745 if (oper == Operator.BitwiseOr)
2746 CheckBitwiseOrOnSignExtended (ec);
2751 public override SLE.Expression MakeExpression (BuilderContext ctx)
2753 var le = left.MakeExpression (ctx);
2754 var re = right.MakeExpression (ctx);
2755 bool is_checked = ctx.HasSet (BuilderContext.Options.CheckedScope);
2758 case Operator.Addition:
2759 return is_checked ? SLE.Expression.AddChecked (le, re) : SLE.Expression.Add (le, re);
2760 case Operator.BitwiseAnd:
2761 return SLE.Expression.And (le, re);
2762 case Operator.BitwiseOr:
2763 return SLE.Expression.Or (le, re);
2764 case Operator.Division:
2765 return SLE.Expression.Divide (le, re);
2766 case Operator.Equality:
2767 return SLE.Expression.Equal (le, re);
2768 case Operator.ExclusiveOr:
2769 return SLE.Expression.ExclusiveOr (le, re);
2770 case Operator.GreaterThan:
2771 return SLE.Expression.GreaterThan (le, re);
2772 case Operator.GreaterThanOrEqual:
2773 return SLE.Expression.GreaterThanOrEqual (le, re);
2774 case Operator.Inequality:
2775 return SLE.Expression.NotEqual (le, re);
2776 case Operator.LeftShift:
2777 return SLE.Expression.LeftShift (le, re);
2778 case Operator.LessThan:
2779 return SLE.Expression.LessThan (le, re);
2780 case Operator.LessThanOrEqual:
2781 return SLE.Expression.LessThanOrEqual (le, re);
2782 case Operator.LogicalAnd:
2783 return SLE.Expression.AndAlso (le, re);
2784 case Operator.LogicalOr:
2785 return SLE.Expression.OrElse (le, re);
2786 case Operator.Modulus:
2787 return SLE.Expression.Modulo (le, re);
2788 case Operator.Multiply:
2789 return is_checked ? SLE.Expression.MultiplyChecked (le, re) : SLE.Expression.Multiply (le, re);
2790 case Operator.RightShift:
2791 return SLE.Expression.RightShift (le, re);
2792 case Operator.Subtraction:
2793 return is_checked ? SLE.Expression.SubtractChecked (le, re) : SLE.Expression.Subtract (le, re);
2795 throw new NotImplementedException (oper.ToString ());
2800 // D operator + (D x, D y)
2801 // D operator - (D x, D y)
2803 Expression ResolveOperatorDelegate (ResolveContext ec, TypeSpec l, TypeSpec r)
2805 if (l != r && !TypeSpecComparer.Variant.IsEqual (r, l)) {
2807 if (right.eclass == ExprClass.MethodGroup || r == InternalType.AnonymousMethod || r == InternalType.Null) {
2808 tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2813 } else if (left.eclass == ExprClass.MethodGroup || (l == InternalType.AnonymousMethod)) {
2814 tmp = Convert.ImplicitConversionRequired (ec, left, r, loc);
2825 Arguments args = new Arguments (2);
2826 args.Add (new Argument (left));
2827 args.Add (new Argument (right));
2829 if (oper == Operator.Addition) {
2830 if (TypeManager.delegate_combine_delegate_delegate == null) {
2831 TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
2832 TypeManager.delegate_type, "Combine", loc, TypeManager.delegate_type, TypeManager.delegate_type);
2835 method = TypeManager.delegate_combine_delegate_delegate;
2836 } else if (oper == Operator.Subtraction) {
2837 if (TypeManager.delegate_remove_delegate_delegate == null) {
2838 TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
2839 TypeManager.delegate_type, "Remove", loc, TypeManager.delegate_type, TypeManager.delegate_type);
2842 method = TypeManager.delegate_remove_delegate_delegate;
2844 return new EmptyExpression (TypeManager.decimal_type);
2847 MethodGroupExpr mg = MethodGroupExpr.CreatePredefined (method, TypeManager.delegate_type, loc);
2848 Expression expr = new UserOperatorCall (mg.BestCandidate, args, CreateExpressionTree, loc);
2849 return new ClassCast (expr, l);
2853 // Enumeration operators
2855 Expression ResolveOperatorEnum (ResolveContext ec, bool lenum, bool renum, TypeSpec ltype, TypeSpec rtype)
2858 // bool operator == (E x, E y);
2859 // bool operator != (E x, E y);
2860 // bool operator < (E x, E y);
2861 // bool operator > (E x, E y);
2862 // bool operator <= (E x, E y);
2863 // bool operator >= (E x, E y);
2865 // E operator & (E x, E y);
2866 // E operator | (E x, E y);
2867 // E operator ^ (E x, E y);
2869 // U operator - (E e, E f)
2870 // E operator - (E e, U x)
2872 // E operator + (U x, E e)
2873 // E operator + (E e, U x)
2875 if (!((oper & (Operator.ComparisonMask | Operator.BitwiseMask)) != 0 ||
2876 (oper == Operator.Subtraction && lenum) ||
2877 (oper == Operator.Addition && (lenum != renum || type != null)))) // type != null for lifted null
2880 Expression ltemp = left;
2881 Expression rtemp = right;
2882 TypeSpec underlying_type;
2885 if ((oper & (Operator.ComparisonMask | Operator.BitwiseMask)) != 0) {
2887 expr = Convert.ImplicitConversion (ec, left, rtype, loc);
2893 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
2901 if (ltype == rtype) {
2902 underlying_type = EnumSpec.GetUnderlyingType (ltype);
2904 if (left is Constant)
2905 left = ((Constant) left).ConvertExplicitly (false, underlying_type).Resolve (ec);
2907 left = EmptyCast.Create (left, underlying_type);
2909 if (right is Constant)
2910 right = ((Constant) right).ConvertExplicitly (false, underlying_type).Resolve (ec);
2912 right = EmptyCast.Create (right, underlying_type);
2914 underlying_type = EnumSpec.GetUnderlyingType (ltype);
2916 if (oper != Operator.Subtraction && oper != Operator.Addition) {
2917 Constant c = right as Constant;
2918 if (c == null || !c.IsDefaultValue)
2921 if (!Convert.ImplicitStandardConversionExists (right, underlying_type))
2924 right = Convert.ImplicitConversionStandard (ec, right, underlying_type, right.Location);
2927 if (left is Constant)
2928 left = ((Constant) left).ConvertExplicitly (false, underlying_type).Resolve (ec);
2930 left = EmptyCast.Create (left, underlying_type);
2933 underlying_type = EnumSpec.GetUnderlyingType (rtype);
2935 if (oper != Operator.Addition) {
2936 Constant c = left as Constant;
2937 if (c == null || !c.IsDefaultValue)
2940 if (!Convert.ImplicitStandardConversionExists (left, underlying_type))
2943 left = Convert.ImplicitConversionStandard (ec, left, underlying_type, left.Location);
2946 if (right is Constant)
2947 right = ((Constant) right).ConvertExplicitly (false, underlying_type).Resolve (ec);
2949 right = EmptyCast.Create (right, underlying_type);
2956 // C# specification uses explicit cast syntax which means binary promotion
2957 // should happen, however it seems that csc does not do that
2959 if (!DoBinaryOperatorPromotion (ec)) {
2965 TypeSpec res_type = null;
2966 if ((oper & Operator.BitwiseMask) != 0 || oper == Operator.Subtraction || oper == Operator.Addition) {
2967 TypeSpec promoted_type = lenum ? left.Type : right.Type;
2968 enum_conversion = Convert.ExplicitNumericConversion (
2969 new EmptyExpression (promoted_type), underlying_type);
2971 if (oper == Operator.Subtraction && renum && lenum)
2972 res_type = underlying_type;
2973 else if (oper == Operator.Addition && renum)
2979 expr = ResolveOperatorPredefined (ec, standard_operators, true, res_type);
2980 if (!is_compound || expr == null)
2988 // If the return type of the selected operator is implicitly convertible to the type of x
2990 if (Convert.ImplicitConversionExists (ec, expr, ltype))
2994 // Otherwise, if the selected operator is a predefined operator, if the return type of the
2995 // selected operator is explicitly convertible to the type of x, and if y is implicitly
2996 // convertible to the type of x or the operator is a shift operator, then the operation
2997 // is evaluated as x = (T)(x op y), where T is the type of x
2999 expr = Convert.ExplicitConversion (ec, expr, ltype, loc);
3003 if (Convert.ImplicitConversionExists (ec, ltemp, ltype))
3010 // 7.9.6 Reference type equality operators
3012 Expression ResolveOperatorEquality (ResolveContext ec, TypeSpec l, TypeSpec r)
3015 type = TypeManager.bool_type;
3018 // a, Both operands are reference-type values or the value null
3019 // b, One operand is a value of type T where T is a type-parameter and
3020 // the other operand is the value null. Furthermore T does not have the
3021 // value type constraint
3023 // LAMESPEC: Very confusing details in the specification, basically any
3024 // reference like type-parameter is allowed
3026 var tparam_l = l as TypeParameterSpec;
3027 var tparam_r = r as TypeParameterSpec;
3028 if (tparam_l != null) {
3029 if (right is NullLiteral && !tparam_l.HasSpecialStruct) {
3030 left = new BoxedCast (left, TypeManager.object_type);
3034 if (!tparam_l.IsReferenceType)
3037 l = tparam_l.GetEffectiveBase ();
3038 left = new BoxedCast (left, l);
3039 } else if (left is NullLiteral && tparam_r == null) {
3040 if (!TypeManager.IsReferenceType (r) || r.Kind == MemberKind.InternalCompilerType)
3046 if (tparam_r != null) {
3047 if (left is NullLiteral && !tparam_r.HasSpecialStruct) {
3048 right = new BoxedCast (right, TypeManager.object_type);
3052 if (!tparam_r.IsReferenceType)
3055 r = tparam_r.GetEffectiveBase ();
3056 right = new BoxedCast (right, r);
3057 } else if (right is NullLiteral) {
3058 if (!TypeManager.IsReferenceType (l) || l.Kind == MemberKind.InternalCompilerType)
3065 // LAMESPEC: method groups can be compared when they convert to other side delegate
3068 if (right.eclass == ExprClass.MethodGroup) {
3069 result = Convert.ImplicitConversion (ec, right, l, loc);
3075 } else if (r.IsDelegate && l != r) {
3078 } else if (left.eclass == ExprClass.MethodGroup && r.IsDelegate) {
3079 result = Convert.ImplicitConversionRequired (ec, left, r, loc);
3088 // bool operator != (string a, string b)
3089 // bool operator == (string a, string b)
3091 // bool operator != (Delegate a, Delegate b)
3092 // bool operator == (Delegate a, Delegate b)
3094 // bool operator != (bool a, bool b)
3095 // bool operator == (bool a, bool b)
3097 // LAMESPEC: Reference equality comparison can apply to value types when
3098 // they implement an implicit conversion to any of types above.
3100 if (r != TypeManager.object_type && l != TypeManager.object_type) {
3101 result = ResolveOperatorPredefined (ec, equality_operators, false, null);
3107 // bool operator != (object a, object b)
3108 // bool operator == (object a, object b)
3110 // An explicit reference conversion exists from the
3111 // type of either operand to the type of the other operand.
3114 // Optimize common path
3116 return l.Kind == MemberKind.InternalCompilerType || l.Kind == MemberKind.Struct ? null : this;
3119 if (!Convert.ExplicitReferenceConversionExists (l, r) &&
3120 !Convert.ExplicitReferenceConversionExists (r, l))
3123 // Reject allowed explicit conversions like int->object
3124 if (!TypeManager.IsReferenceType (l) || !TypeManager.IsReferenceType (r))
3127 if (l == TypeManager.string_type || l == TypeManager.delegate_type || MemberCache.GetUserOperator (l, CSharp.Operator.OpType.Equality, false) != null)
3128 ec.Report.Warning (253, 2, loc,
3129 "Possible unintended reference comparison. Consider casting the right side expression to type `{0}' to get value comparison",
3130 l.GetSignatureForError ());
3132 if (r == TypeManager.string_type || r == TypeManager.delegate_type || MemberCache.GetUserOperator (r, CSharp.Operator.OpType.Equality, false) != null)
3133 ec.Report.Warning (252, 2, loc,
3134 "Possible unintended reference comparison. Consider casting the left side expression to type `{0}' to get value comparison",
3135 r.GetSignatureForError ());
3141 Expression ResolveOperatorPointer (ResolveContext ec, TypeSpec l, TypeSpec r)
3144 // bool operator == (void* x, void* y);
3145 // bool operator != (void* x, void* y);
3146 // bool operator < (void* x, void* y);
3147 // bool operator > (void* x, void* y);
3148 // bool operator <= (void* x, void* y);
3149 // bool operator >= (void* x, void* y);
3151 if ((oper & Operator.ComparisonMask) != 0) {
3154 temp = Convert.ImplicitConversion (ec, left, r, left.Location);
3161 temp = Convert.ImplicitConversion (ec, right, l, right.Location);
3167 type = TypeManager.bool_type;
3171 if (pointer_operators == null)
3172 CreatePointerOperatorsTable ();
3174 return ResolveOperatorPredefined (ec, pointer_operators, false, null);
3178 // Build-in operators method overloading
3180 protected virtual Expression ResolveOperatorPredefined (ResolveContext ec, PredefinedOperator [] operators, bool primitives_only, TypeSpec enum_type)
3182 PredefinedOperator best_operator = null;
3183 TypeSpec l = left.Type;
3184 TypeSpec r = right.Type;
3185 Operator oper_mask = oper & ~Operator.ValuesOnlyMask;
3187 foreach (PredefinedOperator po in operators) {
3188 if ((po.OperatorsMask & oper_mask) == 0)
3191 if (primitives_only) {
3192 if (!po.IsPrimitiveApplicable (l, r))
3195 if (!po.IsApplicable (ec, left, right))
3199 if (best_operator == null) {
3201 if (primitives_only)
3207 best_operator = po.ResolveBetterOperator (ec, best_operator);
3209 if (best_operator == null) {
3210 ec.Report.Error (34, loc, "Operator `{0}' is ambiguous on operands of type `{1}' and `{2}'",
3211 OperName (oper), TypeManager.CSharpName (l), TypeManager.CSharpName (r));
3218 if (best_operator == null)
3221 Expression expr = best_operator.ConvertResult (ec, this);
3224 // Optimize &/&& constant expressions with 0 value
3226 if (oper == Operator.BitwiseAnd || oper == Operator.LogicalAnd) {
3227 Constant rc = right as Constant;
3228 Constant lc = left as Constant;
3229 if ((lc != null && lc.IsDefaultValue) || (rc != null && rc.IsDefaultValue)) {
3231 // The result is a constant with side-effect
3233 Constant side_effect = rc == null ?
3234 new SideEffectConstant (lc, right, loc) :
3235 new SideEffectConstant (rc, left, loc);
3237 return ReducedExpression.Create (side_effect.Resolve (ec), expr);
3241 if (enum_type == null)
3245 // HACK: required by enum_conversion
3247 expr.Type = enum_type;
3248 return EmptyCast.Create (expr, enum_type);
3252 // Performs user-operator overloading
3254 protected virtual Expression ResolveUserOperator (ResolveContext ec, TypeSpec l, TypeSpec r)
3256 var op = ConvertBinaryToUserOperator (oper);
3257 IList<MemberSpec> left_operators = MemberCache.GetUserOperator (l, op, false);
3258 IList<MemberSpec> right_operators = null;
3261 right_operators = MemberCache.GetUserOperator (r, op, false);
3262 if (right_operators == null && left_operators == null)
3264 } else if (left_operators == null) {
3268 Arguments args = new Arguments (2);
3269 Argument larg = new Argument (left);
3271 Argument rarg = new Argument (right);
3275 // User-defined operator implementations always take precedence
3276 // over predefined operator implementations
3278 if (left_operators != null && right_operators != null) {
3279 left_operators = CombineUserOperators (left_operators, right_operators);
3280 } else if (right_operators != null) {
3281 left_operators = right_operators;
3284 var res = new OverloadResolver (left_operators, OverloadResolver.Restrictions.ProbingOnly, loc);
3286 var oper_method = res.ResolveOperator (ec, ref args);
3287 if (oper_method == null)
3290 Expression oper_expr;
3292 // TODO: CreateExpressionTree is allocated every time
3293 if ((oper & Operator.LogicalMask) != 0) {
3294 oper_expr = new ConditionalLogicalOperator (oper_method, args, CreateExpressionTree,
3295 oper == Operator.LogicalAnd, loc).Resolve (ec);
3297 oper_expr = new UserOperatorCall (oper_method, args, CreateExpressionTree, loc);
3306 // Merge two sets of user operators into one, they are mostly distinguish
3307 // expect when they share base type and it contains an operator
3309 static IList<MemberSpec> CombineUserOperators (IList<MemberSpec> left, IList<MemberSpec> right)
3311 var combined = new List<MemberSpec> (left.Count + right.Count);
3312 combined.AddRange (left);
3313 foreach (var r in right) {
3315 foreach (var l in left) {
3316 if (l.DeclaringType == r.DeclaringType) {
3329 public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
3334 private void CheckUselessComparison (ResolveContext ec, Constant c, TypeSpec type)
3336 if (c == null || !IsTypeIntegral (type)
3337 || c is StringConstant
3338 || c is BoolConstant
3339 || c is FloatConstant
3340 || c is DoubleConstant
3341 || c is DecimalConstant
3347 if (c is ULongConstant) {
3348 ulong uvalue = ((ULongConstant) c).Value;
3349 if (uvalue > long.MaxValue) {
3350 if (type == TypeManager.byte_type ||
3351 type == TypeManager.sbyte_type ||
3352 type == TypeManager.short_type ||
3353 type == TypeManager.ushort_type ||
3354 type == TypeManager.int32_type ||
3355 type == TypeManager.uint32_type ||
3356 type == TypeManager.int64_type ||
3357 type == TypeManager.char_type)
3358 WarnUselessComparison (ec, type);
3361 value = (long) uvalue;
3363 else if (c is ByteConstant)
3364 value = ((ByteConstant) c).Value;
3365 else if (c is SByteConstant)
3366 value = ((SByteConstant) c).Value;
3367 else if (c is ShortConstant)
3368 value = ((ShortConstant) c).Value;
3369 else if (c is UShortConstant)
3370 value = ((UShortConstant) c).Value;
3371 else if (c is IntConstant)
3372 value = ((IntConstant) c).Value;
3373 else if (c is UIntConstant)
3374 value = ((UIntConstant) c).Value;
3375 else if (c is LongConstant)
3376 value = ((LongConstant) c).Value;
3377 else if (c is CharConstant)
3378 value = ((CharConstant)c).Value;
3383 if (IsValueOutOfRange (value, type))
3384 WarnUselessComparison (ec, type);
3387 static bool IsValueOutOfRange (long value, TypeSpec type)
3389 if (IsTypeUnsigned (type) && value < 0)
3391 return type == TypeManager.sbyte_type && (value >= 0x80 || value < -0x80) ||
3392 type == TypeManager.byte_type && value >= 0x100 ||
3393 type == TypeManager.short_type && (value >= 0x8000 || value < -0x8000) ||
3394 type == TypeManager.ushort_type && value >= 0x10000 ||
3395 type == TypeManager.int32_type && (value >= 0x80000000 || value < -0x80000000) ||
3396 type == TypeManager.uint32_type && value >= 0x100000000;
3399 private static bool IsTypeIntegral (TypeSpec type)
3401 return type == TypeManager.uint64_type ||
3402 type == TypeManager.int64_type ||
3403 type == TypeManager.uint32_type ||
3404 type == TypeManager.int32_type ||
3405 type == TypeManager.ushort_type ||
3406 type == TypeManager.short_type ||
3407 type == TypeManager.sbyte_type ||
3408 type == TypeManager.byte_type ||
3409 type == TypeManager.char_type;
3412 private static bool IsTypeUnsigned (TypeSpec type)
3414 return type == TypeManager.uint64_type ||
3415 type == TypeManager.uint32_type ||
3416 type == TypeManager.ushort_type ||
3417 type == TypeManager.byte_type ||
3418 type == TypeManager.char_type;
3421 private void WarnUselessComparison (ResolveContext ec, TypeSpec type)
3423 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}'",
3424 TypeManager.CSharpName (type));
3428 /// EmitBranchable is called from Statement.EmitBoolExpression in the
3429 /// context of a conditional bool expression. This function will return
3430 /// false if it is was possible to use EmitBranchable, or true if it was.
3432 /// The expression's code is generated, and we will generate a branch to `target'
3433 /// if the resulting expression value is equal to isTrue
3435 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
3438 // This is more complicated than it looks, but its just to avoid
3439 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
3440 // but on top of that we want for == and != to use a special path
3441 // if we are comparing against null
3443 if ((oper & Operator.EqualityMask) != 0 && (left is Constant || right is Constant)) {
3444 bool my_on_true = oper == Operator.Inequality ? on_true : !on_true;
3447 // put the constant on the rhs, for simplicity
3449 if (left is Constant) {
3450 Expression swap = right;
3456 // brtrue/brfalse works with native int only
3458 if (((Constant) right).IsZeroInteger && right.Type != TypeManager.int64_type && right.Type != TypeManager.uint64_type) {
3459 left.EmitBranchable (ec, target, my_on_true);
3462 if (right.Type == TypeManager.bool_type) {
3463 // right is a boolean, and it's not 'false' => it is 'true'
3464 left.EmitBranchable (ec, target, !my_on_true);
3468 } else if (oper == Operator.LogicalAnd) {
3471 Label tests_end = ec.DefineLabel ();
3473 left.EmitBranchable (ec, tests_end, false);
3474 right.EmitBranchable (ec, target, true);
3475 ec.MarkLabel (tests_end);
3478 // This optimizes code like this
3479 // if (true && i > 4)
3481 if (!(left is Constant))
3482 left.EmitBranchable (ec, target, false);
3484 if (!(right is Constant))
3485 right.EmitBranchable (ec, target, false);
3490 } else if (oper == Operator.LogicalOr){
3492 left.EmitBranchable (ec, target, true);
3493 right.EmitBranchable (ec, target, true);
3496 Label tests_end = ec.DefineLabel ();
3497 left.EmitBranchable (ec, tests_end, true);
3498 right.EmitBranchable (ec, target, false);
3499 ec.MarkLabel (tests_end);
3504 } else if ((oper & Operator.ComparisonMask) == 0) {
3505 base.EmitBranchable (ec, target, on_true);
3512 TypeSpec t = left.Type;
3513 bool is_float = IsFloat (t);
3514 bool is_unsigned = is_float || IsUnsigned (t);
3517 case Operator.Equality:
3519 ec.Emit (OpCodes.Beq, target);
3521 ec.Emit (OpCodes.Bne_Un, target);
3524 case Operator.Inequality:
3526 ec.Emit (OpCodes.Bne_Un, target);
3528 ec.Emit (OpCodes.Beq, target);
3531 case Operator.LessThan:
3533 if (is_unsigned && !is_float)
3534 ec.Emit (OpCodes.Blt_Un, target);
3536 ec.Emit (OpCodes.Blt, target);
3539 ec.Emit (OpCodes.Bge_Un, target);
3541 ec.Emit (OpCodes.Bge, target);
3544 case Operator.GreaterThan:
3546 if (is_unsigned && !is_float)
3547 ec.Emit (OpCodes.Bgt_Un, target);
3549 ec.Emit (OpCodes.Bgt, target);
3552 ec.Emit (OpCodes.Ble_Un, target);
3554 ec.Emit (OpCodes.Ble, target);
3557 case Operator.LessThanOrEqual:
3559 if (is_unsigned && !is_float)
3560 ec.Emit (OpCodes.Ble_Un, target);
3562 ec.Emit (OpCodes.Ble, target);
3565 ec.Emit (OpCodes.Bgt_Un, target);
3567 ec.Emit (OpCodes.Bgt, target);
3571 case Operator.GreaterThanOrEqual:
3573 if (is_unsigned && !is_float)
3574 ec.Emit (OpCodes.Bge_Un, target);
3576 ec.Emit (OpCodes.Bge, target);
3579 ec.Emit (OpCodes.Blt_Un, target);
3581 ec.Emit (OpCodes.Blt, target);
3584 throw new InternalErrorException (oper.ToString ());
3588 public override void Emit (EmitContext ec)
3590 EmitOperator (ec, left.Type);
3593 protected virtual void EmitOperator (EmitContext ec, TypeSpec l)
3596 // Handle short-circuit operators differently
3599 if ((oper & Operator.LogicalMask) != 0) {
3600 Label load_result = ec.DefineLabel ();
3601 Label end = ec.DefineLabel ();
3603 bool is_or = oper == Operator.LogicalOr;
3604 left.EmitBranchable (ec, load_result, is_or);
3606 ec.Emit (OpCodes.Br_S, end);
3608 ec.MarkLabel (load_result);
3609 ec.Emit (is_or ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
3615 // Optimize zero-based operations which cannot be optimized at expression level
3617 if (oper == Operator.Subtraction) {
3618 var lc = left as IntegralConstant;
3619 if (lc != null && lc.IsDefaultValue) {
3621 ec.Emit (OpCodes.Neg);
3628 EmitOperatorOpcode (ec, oper, l);
3631 // Nullable enum could require underlying type cast and we cannot simply wrap binary
3632 // expression because that would wrap lifted binary operation
3634 if (enum_conversion != null)
3635 enum_conversion.Emit (ec);
3638 public override void EmitSideEffect (EmitContext ec)
3640 if ((oper & Operator.LogicalMask) != 0 ||
3641 (ec.HasSet (EmitContext.Options.CheckedScope) && (oper == Operator.Multiply || oper == Operator.Addition || oper == Operator.Subtraction))) {
3642 base.EmitSideEffect (ec);
3644 left.EmitSideEffect (ec);
3645 right.EmitSideEffect (ec);
3649 protected override void CloneTo (CloneContext clonectx, Expression t)
3651 Binary target = (Binary) t;
3653 target.left = left.Clone (clonectx);
3654 target.right = right.Clone (clonectx);
3657 public Expression CreateCallSiteBinder (ResolveContext ec, Arguments args)
3659 Arguments binder_args = new Arguments (4);
3661 MemberAccess sle = new MemberAccess (new MemberAccess (
3662 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Linq", loc), "Expressions", loc);
3664 CSharpBinderFlags flags = 0;
3665 if (ec.HasSet (ResolveContext.Options.CheckedScope))
3666 flags = CSharpBinderFlags.CheckedContext;
3668 if ((oper & Operator.LogicalMask) != 0)
3669 flags |= CSharpBinderFlags.BinaryOperationLogical;
3671 binder_args.Add (new Argument (new EnumConstant (new IntLiteral ((int) flags, loc), TypeManager.binder_flags)));
3672 binder_args.Add (new Argument (new MemberAccess (new MemberAccess (sle, "ExpressionType", loc), GetOperatorExpressionTypeName (), loc)));
3673 binder_args.Add (new Argument (new TypeOf (new TypeExpression (ec.CurrentType, loc), loc)));
3674 binder_args.Add (new Argument (new ImplicitlyTypedArrayCreation (args.CreateDynamicBinderArguments (ec), loc)));
3676 return new Invocation (DynamicExpressionStatement.GetBinder ("BinaryOperation", loc), binder_args);
3679 public override Expression CreateExpressionTree (ResolveContext ec)
3681 return CreateExpressionTree (ec, null);
3684 Expression CreateExpressionTree (ResolveContext ec, Expression method)
3687 bool lift_arg = false;
3690 case Operator.Addition:
3691 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
3692 method_name = "AddChecked";
3694 method_name = "Add";
3696 case Operator.BitwiseAnd:
3697 method_name = "And";
3699 case Operator.BitwiseOr:
3702 case Operator.Division:
3703 method_name = "Divide";
3705 case Operator.Equality:
3706 method_name = "Equal";
3709 case Operator.ExclusiveOr:
3710 method_name = "ExclusiveOr";
3712 case Operator.GreaterThan:
3713 method_name = "GreaterThan";
3716 case Operator.GreaterThanOrEqual:
3717 method_name = "GreaterThanOrEqual";
3720 case Operator.Inequality:
3721 method_name = "NotEqual";
3724 case Operator.LeftShift:
3725 method_name = "LeftShift";
3727 case Operator.LessThan:
3728 method_name = "LessThan";
3731 case Operator.LessThanOrEqual:
3732 method_name = "LessThanOrEqual";
3735 case Operator.LogicalAnd:
3736 method_name = "AndAlso";
3738 case Operator.LogicalOr:
3739 method_name = "OrElse";
3741 case Operator.Modulus:
3742 method_name = "Modulo";
3744 case Operator.Multiply:
3745 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
3746 method_name = "MultiplyChecked";
3748 method_name = "Multiply";
3750 case Operator.RightShift:
3751 method_name = "RightShift";
3753 case Operator.Subtraction:
3754 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
3755 method_name = "SubtractChecked";
3757 method_name = "Subtract";
3761 throw new InternalErrorException ("Unknown expression tree binary operator " + oper);
3764 Arguments args = new Arguments (2);
3765 args.Add (new Argument (left.CreateExpressionTree (ec)));
3766 args.Add (new Argument (right.CreateExpressionTree (ec)));
3767 if (method != null) {
3769 args.Add (new Argument (new BoolConstant (false, loc)));
3771 args.Add (new Argument (method));
3774 return CreateExpressionFactoryCall (ec, method_name, args);
3779 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3780 // b, c, d... may be strings or objects.
3782 public class StringConcat : Expression {
3783 Arguments arguments;
3784 static IList<MemberSpec> concat_members;
3786 public StringConcat (Expression left, Expression right, Location loc)
3789 type = TypeManager.string_type;
3790 eclass = ExprClass.Value;
3792 arguments = new Arguments (2);
3795 public static StringConcat Create (ResolveContext rc, Expression left, Expression right, Location loc)
3797 if (left.eclass == ExprClass.Unresolved || right.eclass == ExprClass.Unresolved)
3798 throw new ArgumentException ();
3800 var s = new StringConcat (left, right, loc);
3801 s.Append (rc, left);
3802 s.Append (rc, right);
3806 public override Expression CreateExpressionTree (ResolveContext ec)
3808 Argument arg = arguments [0];
3809 return CreateExpressionAddCall (ec, arg, arg.CreateExpressionTree (ec), 1);
3813 // Creates nested calls tree from an array of arguments used for IL emit
3815 Expression CreateExpressionAddCall (ResolveContext ec, Argument left, Expression left_etree, int pos)
3817 Arguments concat_args = new Arguments (2);
3818 Arguments add_args = new Arguments (3);
3820 concat_args.Add (left);
3821 add_args.Add (new Argument (left_etree));
3823 concat_args.Add (arguments [pos]);
3824 add_args.Add (new Argument (arguments [pos].CreateExpressionTree (ec)));
3826 var methods = CreateConcatMethodCandidates ();
3827 if (methods == null)
3830 var res = new OverloadResolver (methods, OverloadResolver.Restrictions.NoBaseMembers, loc);
3831 var method = res.ResolveMember<MethodSpec> (ec, ref concat_args);
3835 add_args.Add (new Argument (new TypeOfMethod (method, loc)));
3837 Expression expr = CreateExpressionFactoryCall (ec, "Add", add_args);
3838 if (++pos == arguments.Count)
3841 left = new Argument (new EmptyExpression (method.ReturnType));
3842 return CreateExpressionAddCall (ec, left, expr, pos);
3845 protected override Expression DoResolve (ResolveContext ec)
3850 void Append (ResolveContext rc, Expression operand)
3855 StringConstant sc = operand as StringConstant;
3857 if (arguments.Count != 0) {
3858 Argument last_argument = arguments [arguments.Count - 1];
3859 StringConstant last_expr_constant = last_argument.Expr as StringConstant;
3860 if (last_expr_constant != null) {
3861 last_argument.Expr = new StringConstant (
3862 last_expr_constant.Value + sc.Value, sc.Location).Resolve (rc);
3868 // Multiple (3+) concatenation are resolved as multiple StringConcat instances
3870 StringConcat concat_oper = operand as StringConcat;
3871 if (concat_oper != null) {
3872 arguments.AddRange (concat_oper.arguments);
3877 arguments.Add (new Argument (operand));
3880 IList<MemberSpec> CreateConcatMethodCandidates ()
3882 if (concat_members == null) {
3883 concat_members = MemberCache.FindMembers (type, "Concat", true);
3886 return concat_members;
3889 public override void Emit (EmitContext ec)
3891 var members = CreateConcatMethodCandidates ();
3892 var res = new OverloadResolver (members, OverloadResolver.Restrictions.NoBaseMembers, loc);
3893 var method = res.ResolveMember<MethodSpec> (new ResolveContext (ec.MemberContext), ref arguments);
3895 Invocation.EmitCall (ec, null, method, arguments, loc);
3898 public override SLE.Expression MakeExpression (BuilderContext ctx)
3900 if (arguments.Count != 2)
3901 throw new NotImplementedException ("arguments.Count != 2");
3903 var concat = typeof (string).GetMethod ("Concat", new[] { typeof (object), typeof (object) });
3904 return SLE.Expression.Add (arguments[0].Expr.MakeExpression (ctx), arguments[1].Expr.MakeExpression (ctx), concat);
3907 public static void Reset ()
3909 concat_members = null;
3914 // User-defined conditional logical operator
3916 public class ConditionalLogicalOperator : UserOperatorCall {
3917 readonly bool is_and;
3918 Expression oper_expr;
3920 public ConditionalLogicalOperator (MethodSpec oper, Arguments arguments, Func<ResolveContext, Expression, Expression> expr_tree, bool is_and, Location loc)
3921 : base (oper, arguments, expr_tree, loc)
3923 this.is_and = is_and;
3924 eclass = ExprClass.Unresolved;
3927 protected override Expression DoResolve (ResolveContext ec)
3929 AParametersCollection pd = oper.Parameters;
3930 if (!TypeSpecComparer.IsEqual (type, pd.Types[0]) || !TypeSpecComparer.IsEqual (type, pd.Types[1])) {
3931 ec.Report.Error (217, loc,
3932 "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",
3933 oper.GetSignatureForError ());
3937 Expression left_dup = new EmptyExpression (type);
3938 Expression op_true = GetOperatorTrue (ec, left_dup, loc);
3939 Expression op_false = GetOperatorFalse (ec, left_dup, loc);
3940 if (op_true == null || op_false == null) {
3941 ec.Report.Error (218, loc,
3942 "The type `{0}' must have operator `true' and operator `false' defined when `{1}' is used as a short circuit operator",
3943 TypeManager.CSharpName (type), oper.GetSignatureForError ());
3947 oper_expr = is_and ? op_false : op_true;
3948 eclass = ExprClass.Value;
3952 public override void Emit (EmitContext ec)
3954 Label end_target = ec.DefineLabel ();
3957 // Emit and duplicate left argument
3959 arguments [0].Expr.Emit (ec);
3960 ec.Emit (OpCodes.Dup);
3961 arguments.RemoveAt (0);
3963 oper_expr.EmitBranchable (ec, end_target, true);
3965 ec.MarkLabel (end_target);
3969 public class PointerArithmetic : Expression {
3970 Expression left, right;
3974 // We assume that `l' is always a pointer
3976 public PointerArithmetic (Binary.Operator op, Expression l, Expression r, TypeSpec t, Location loc)
3985 public override Expression CreateExpressionTree (ResolveContext ec)
3987 Error_PointerInsideExpressionTree (ec);
3991 protected override Expression DoResolve (ResolveContext ec)
3993 eclass = ExprClass.Variable;
3995 if (left.Type == TypeManager.void_ptr_type) {
3996 ec.Report.Error (242, loc, "The operation in question is undefined on void pointers");
4003 public override void Emit (EmitContext ec)
4005 TypeSpec op_type = left.Type;
4007 // It must be either array or fixed buffer
4009 if (TypeManager.HasElementType (op_type)) {
4010 element = TypeManager.GetElementType (op_type);
4012 FieldExpr fe = left as FieldExpr;
4014 element = ((FixedFieldSpec) (fe.Spec)).ElementType;
4019 int size = GetTypeSize (element);
4020 TypeSpec rtype = right.Type;
4022 if ((op & Binary.Operator.SubtractionMask) != 0 && rtype.IsPointer){
4024 // handle (pointer - pointer)
4028 ec.Emit (OpCodes.Sub);
4032 ec.Emit (OpCodes.Sizeof, element);
4035 ec.Emit (OpCodes.Div);
4037 ec.Emit (OpCodes.Conv_I8);
4040 // handle + and - on (pointer op int)
4042 Constant left_const = left as Constant;
4043 if (left_const != null) {
4045 // Optimize ((T*)null) pointer operations
4047 if (left_const.IsDefaultValue) {
4048 left = EmptyExpression.Null;
4056 var right_const = right as Constant;
4057 if (right_const != null) {
4059 // Optimize 0-based arithmetic
4061 if (right_const.IsDefaultValue)
4065 right = new IntConstant (size, right.Location);
4067 right = new SizeOf (new TypeExpression (element, right.Location), right.Location);
4069 // TODO: Should be the checks resolve context sensitive?
4070 ResolveContext rc = new ResolveContext (ec.MemberContext, ResolveContext.Options.UnsafeScope);
4071 right = new Binary (Binary.Operator.Multiply, right, right_const, loc).Resolve (rc);
4077 if (rtype == TypeManager.sbyte_type || rtype == TypeManager.byte_type ||
4078 rtype == TypeManager.short_type || rtype == TypeManager.ushort_type) {
4079 ec.Emit (OpCodes.Conv_I);
4080 } else if (rtype == TypeManager.uint32_type) {
4081 ec.Emit (OpCodes.Conv_U);
4084 if (right_const == null && size != 1){
4086 ec.Emit (OpCodes.Sizeof, element);
4089 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
4090 ec.Emit (OpCodes.Conv_I8);
4092 Binary.EmitOperatorOpcode (ec, Binary.Operator.Multiply, rtype);
4095 if (left_const == null) {
4096 if (rtype == TypeManager.int64_type)
4097 ec.Emit (OpCodes.Conv_I);
4098 else if (rtype == TypeManager.uint64_type)
4099 ec.Emit (OpCodes.Conv_U);
4101 Binary.EmitOperatorOpcode (ec, op, op_type);
4108 // A boolean-expression is an expression that yields a result
4111 public class BooleanExpression : ShimExpression
4113 public BooleanExpression (Expression expr)
4116 this.loc = expr.Location;
4119 public override Expression CreateExpressionTree (ResolveContext ec)
4121 // TODO: We should emit IsTrue (v4) instead of direct user operator
4122 // call but that would break csc compatibility
4123 return base.CreateExpressionTree (ec);
4126 protected override Expression DoResolve (ResolveContext ec)
4128 // A boolean-expression is required to be of a type
4129 // that can be implicitly converted to bool or of
4130 // a type that implements operator true
4132 expr = expr.Resolve (ec);
4136 Assign ass = expr as Assign;
4137 if (ass != null && ass.Source is Constant) {
4138 ec.Report.Warning (665, 3, loc,
4139 "Assignment in conditional expression is always constant. Did you mean to use `==' instead ?");
4142 if (expr.Type == TypeManager.bool_type)
4145 if (expr.Type == InternalType.Dynamic) {
4146 Arguments args = new Arguments (1);
4147 args.Add (new Argument (expr));
4148 return new DynamicUnaryConversion ("IsTrue", args, loc).Resolve (ec);
4151 type = TypeManager.bool_type;
4152 Expression converted = Convert.ImplicitConversion (ec, expr, type, loc);
4153 if (converted != null)
4157 // If no implicit conversion to bool exists, try using `operator true'
4159 converted = GetOperatorTrue (ec, expr, loc);
4160 if (converted == null) {
4161 expr.Error_ValueCannotBeConverted (ec, loc, type, false);
4170 /// Implements the ternary conditional operator (?:)
4172 public class Conditional : Expression {
4173 Expression expr, true_expr, false_expr;
4175 public Conditional (BooleanExpression expr, Expression true_expr, Expression false_expr, Location loc)
4178 this.true_expr = true_expr;
4179 this.false_expr = false_expr;
4183 public Expression Expr {
4189 public Expression TrueExpr {
4195 public Expression FalseExpr {
4201 public override Expression CreateExpressionTree (ResolveContext ec)
4203 Arguments args = new Arguments (3);
4204 args.Add (new Argument (expr.CreateExpressionTree (ec)));
4205 args.Add (new Argument (true_expr.CreateExpressionTree (ec)));
4206 args.Add (new Argument (false_expr.CreateExpressionTree (ec)));
4207 return CreateExpressionFactoryCall (ec, "Condition", args);
4210 protected override Expression DoResolve (ResolveContext ec)
4212 expr = expr.Resolve (ec);
4213 true_expr = true_expr.Resolve (ec);
4214 false_expr = false_expr.Resolve (ec);
4216 if (true_expr == null || false_expr == null || expr == null)
4219 eclass = ExprClass.Value;
4220 TypeSpec true_type = true_expr.Type;
4221 TypeSpec false_type = false_expr.Type;
4225 // First, if an implicit conversion exists from true_expr
4226 // to false_expr, then the result type is of type false_expr.Type
4228 if (!TypeSpecComparer.IsEqual (true_type, false_type)) {
4229 Expression conv = Convert.ImplicitConversion (ec, true_expr, false_type, loc);
4232 // Check if both can convert implicitly to each other's type
4234 if (true_type != InternalType.Dynamic) {
4237 if (false_type != InternalType.Dynamic && Convert.ImplicitConversion (ec, false_expr, true_type, loc) != null) {
4238 ec.Report.Error (172, true_expr.Location,
4239 "Type of conditional expression cannot be determined as `{0}' and `{1}' convert implicitly to each other",
4240 TypeManager.CSharpName (true_type), TypeManager.CSharpName (false_type));
4246 } else if ((conv = Convert.ImplicitConversion (ec, false_expr, true_type, loc)) != null) {
4249 ec.Report.Error (173, true_expr.Location,
4250 "Type of conditional expression cannot be determined because there is no implicit conversion between `{0}' and `{1}'",
4251 TypeManager.CSharpName (true_type), TypeManager.CSharpName (false_type));
4256 // Dead code optimalization
4257 Constant c = expr as Constant;
4259 bool is_false = c.IsDefaultValue;
4260 ec.Report.Warning (429, 4, is_false ? true_expr.Location : false_expr.Location, "Unreachable expression code detected");
4261 return ReducedExpression.Create (is_false ? false_expr : true_expr, this).Resolve (ec);
4267 public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
4272 public override void Emit (EmitContext ec)
4274 Label false_target = ec.DefineLabel ();
4275 Label end_target = ec.DefineLabel ();
4277 expr.EmitBranchable (ec, false_target, false);
4278 true_expr.Emit (ec);
4280 if (type.IsInterface) {
4281 LocalBuilder temp = ec.GetTemporaryLocal (type);
4282 ec.Emit (OpCodes.Stloc, temp);
4283 ec.Emit (OpCodes.Ldloc, temp);
4284 ec.FreeTemporaryLocal (temp, type);
4287 ec.Emit (OpCodes.Br, end_target);
4288 ec.MarkLabel (false_target);
4289 false_expr.Emit (ec);
4290 ec.MarkLabel (end_target);
4293 protected override void CloneTo (CloneContext clonectx, Expression t)
4295 Conditional target = (Conditional) t;
4297 target.expr = expr.Clone (clonectx);
4298 target.true_expr = true_expr.Clone (clonectx);
4299 target.false_expr = false_expr.Clone (clonectx);
4303 public abstract class VariableReference : Expression, IAssignMethod, IMemoryLocation, IVariableReference {
4304 LocalTemporary temp;
4307 public abstract HoistedVariable GetHoistedVariable (AnonymousExpression ae);
4308 public abstract bool IsFixed { get; }
4309 public abstract bool IsRef { get; }
4310 public abstract string Name { get; }
4311 public abstract void SetHasAddressTaken ();
4314 // Variable IL data, it has to be protected to encapsulate hoisted variables
4316 protected abstract ILocalVariable Variable { get; }
4319 // Variable flow-analysis data
4321 public abstract VariableInfo VariableInfo { get; }
4324 public virtual void AddressOf (EmitContext ec, AddressOp mode)
4326 HoistedVariable hv = GetHoistedVariable (ec);
4328 hv.AddressOf (ec, mode);
4332 Variable.EmitAddressOf (ec);
4335 public HoistedVariable GetHoistedVariable (ResolveContext rc)
4337 return GetHoistedVariable (rc.CurrentAnonymousMethod);
4340 public HoistedVariable GetHoistedVariable (EmitContext ec)
4342 return GetHoistedVariable (ec.CurrentAnonymousMethod);
4345 public override string GetSignatureForError ()
4350 public override void Emit (EmitContext ec)
4355 public override void EmitSideEffect (EmitContext ec)
4361 // This method is used by parameters that are references, that are
4362 // being passed as references: we only want to pass the pointer (that
4363 // is already stored in the parameter, not the address of the pointer,
4364 // and not the value of the variable).
4366 public void EmitLoad (EmitContext ec)
4371 public void Emit (EmitContext ec, bool leave_copy)
4373 Report.Debug (64, "VARIABLE EMIT", this, Variable, type, IsRef, loc);
4375 HoistedVariable hv = GetHoistedVariable (ec);
4377 hv.Emit (ec, leave_copy);
4385 // If we are a reference, we loaded on the stack a pointer
4386 // Now lets load the real value
4388 ec.EmitLoadFromPtr (type);
4392 ec.Emit (OpCodes.Dup);
4395 temp = new LocalTemporary (Type);
4401 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy,
4402 bool prepare_for_load)
4404 HoistedVariable hv = GetHoistedVariable (ec);
4406 hv.EmitAssign (ec, source, leave_copy, prepare_for_load);
4410 New n_source = source as New;
4411 if (n_source != null) {
4412 if (!n_source.Emit (ec, this)) {
4416 ec.EmitLoadFromPtr (type);
4428 ec.Emit (OpCodes.Dup);
4430 temp = new LocalTemporary (Type);
4436 ec.EmitStoreFromPtr (type);
4438 Variable.EmitAssign (ec);
4446 public bool IsHoisted {
4447 get { return GetHoistedVariable ((AnonymousExpression) null) != null; }
4454 public class LocalVariableReference : VariableReference {
4455 readonly string name;
4457 public LocalInfo local_info;
4460 public LocalVariableReference (Block block, string name, Location l)
4468 // Setting `is_readonly' to false will allow you to create a writable
4469 // reference to a read-only variable. This is used by foreach and using.
4471 public LocalVariableReference (Block block, string name, Location l,
4472 LocalInfo local_info, bool is_readonly)
4473 : this (block, name, l)
4475 this.local_info = local_info;
4476 this.is_readonly = is_readonly;
4479 public override VariableInfo VariableInfo {
4480 get { return local_info.VariableInfo; }
4483 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
4485 return local_info.HoistedVariant;
4489 // A local variable is always fixed
4491 public override bool IsFixed {
4492 get { return true; }
4495 public override bool IsRef {
4496 get { return false; }
4499 public bool IsReadOnly {
4500 get { return is_readonly; }
4503 public override string Name {
4504 get { return name; }
4507 public bool VerifyAssigned (ResolveContext ec)
4509 VariableInfo variable_info = local_info.VariableInfo;
4510 return variable_info == null || variable_info.IsAssigned (ec, loc);
4513 void ResolveLocalInfo ()
4515 if (local_info == null) {
4516 local_info = Block.GetLocalInfo (Name);
4517 type = local_info.VariableType;
4518 is_readonly = local_info.ReadOnly;
4522 public override void SetHasAddressTaken ()
4524 local_info.AddressTaken = true;
4527 public override Expression CreateExpressionTree (ResolveContext ec)
4529 HoistedVariable hv = GetHoistedVariable (ec);
4531 return hv.CreateExpressionTree ();
4533 Arguments arg = new Arguments (1);
4534 arg.Add (new Argument (this));
4535 return CreateExpressionFactoryCall (ec, "Constant", arg);
4538 Expression DoResolveBase (ResolveContext ec)
4540 Expression e = Block.GetConstantExpression (Name);
4542 return e.Resolve (ec);
4544 VerifyAssigned (ec);
4547 // If we are referencing a variable from the external block
4548 // flag it for capturing
4550 if (ec.MustCaptureVariable (local_info)) {
4551 if (local_info.AddressTaken)
4552 AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, this, loc);
4554 if (ec.IsVariableCapturingRequired) {
4555 AnonymousMethodStorey storey = local_info.Block.Explicit.CreateAnonymousMethodStorey (ec);
4556 storey.CaptureLocalVariable (ec, local_info);
4560 eclass = ExprClass.Variable;
4561 type = local_info.VariableType;
4565 protected override Expression DoResolve (ResolveContext ec)
4567 ResolveLocalInfo ();
4568 local_info.Used = true;
4570 if (type == null && local_info.Type is VarExpr) {
4571 local_info.VariableType = TypeManager.object_type;
4572 Error_VariableIsUsedBeforeItIsDeclared (ec.Report, Name);
4576 return DoResolveBase (ec);
4579 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
4581 ResolveLocalInfo ();
4584 if (right_side == EmptyExpression.OutAccess.Instance)
4585 local_info.Used = true;
4587 // Infer implicitly typed local variable
4589 VarExpr ve = local_info.Type as VarExpr;
4591 if (!ve.InferType (ec, right_side))
4593 type = local_info.VariableType = ve.Type;
4600 if (right_side == EmptyExpression.OutAccess.Instance) {
4601 code = 1657; msg = "Cannot pass `{0}' as a ref or out argument because it is a `{1}'";
4602 } else if (right_side == EmptyExpression.LValueMemberAccess) {
4603 code = 1654; msg = "Cannot assign to members of `{0}' because it is a `{1}'";
4604 } else if (right_side == EmptyExpression.LValueMemberOutAccess) {
4605 code = 1655; msg = "Cannot pass members of `{0}' as ref or out arguments because it is a `{1}'";
4606 } else if (right_side == EmptyExpression.UnaryAddress) {
4607 code = 459; msg = "Cannot take the address of {1} `{0}'";
4609 code = 1656; msg = "Cannot assign to `{0}' because it is a `{1}'";
4611 ec.Report.Error (code, loc, msg, Name, local_info.GetReadOnlyContext ());
4612 } else if (VariableInfo != null) {
4613 VariableInfo.SetAssigned (ec);
4616 return DoResolveBase (ec);
4619 public override int GetHashCode ()
4621 return Name.GetHashCode ();
4624 public override bool Equals (object obj)
4626 LocalVariableReference lvr = obj as LocalVariableReference;
4630 return Name == lvr.Name && Block == lvr.Block;
4633 protected override ILocalVariable Variable {
4634 get { return local_info; }
4637 public override string ToString ()
4639 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
4642 protected override void CloneTo (CloneContext clonectx, Expression t)
4644 LocalVariableReference target = (LocalVariableReference) t;
4646 target.Block = clonectx.LookupBlock (Block);
4647 if (local_info != null)
4648 target.local_info = clonectx.LookupVariable (local_info);
4653 /// This represents a reference to a parameter in the intermediate
4656 public class ParameterReference : VariableReference {
4657 readonly ToplevelParameterInfo pi;
4659 public ParameterReference (ToplevelParameterInfo pi, Location loc)
4665 public override bool IsRef {
4666 get { return (pi.Parameter.ModFlags & Parameter.Modifier.ISBYREF) != 0; }
4669 bool HasOutModifier {
4670 get { return pi.Parameter.ModFlags == Parameter.Modifier.OUT; }
4673 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
4675 return pi.Parameter.HoistedVariant;
4679 // A ref or out parameter is classified as a moveable variable, even
4680 // if the argument given for the parameter is a fixed variable
4682 public override bool IsFixed {
4683 get { return !IsRef; }
4686 public override string Name {
4687 get { return Parameter.Name; }
4690 public Parameter Parameter {
4691 get { return pi.Parameter; }
4694 public override VariableInfo VariableInfo {
4695 get { return pi.VariableInfo; }
4698 protected override ILocalVariable Variable {
4699 get { return Parameter; }
4702 public bool IsAssigned (ResolveContext ec, Location loc)
4704 // HACK: Variables are not captured in probing mode
4705 if (ec.IsInProbingMode)
4708 if (!ec.DoFlowAnalysis || !HasOutModifier || ec.CurrentBranching.IsAssigned (VariableInfo))
4711 ec.Report.Error (269, loc, "Use of unassigned out parameter `{0}'", Name);
4715 public override void SetHasAddressTaken ()
4717 Parameter.HasAddressTaken = true;
4720 void SetAssigned (ResolveContext ec)
4722 if (HasOutModifier && ec.DoFlowAnalysis)
4723 ec.CurrentBranching.SetAssigned (VariableInfo);
4726 bool DoResolveBase (ResolveContext ec)
4728 type = pi.ParameterType;
4729 eclass = ExprClass.Variable;
4731 AnonymousExpression am = ec.CurrentAnonymousMethod;
4735 Block b = ec.CurrentBlock;
4738 IParameterData[] p = b.Toplevel.Parameters.FixedParameters;
4739 for (int i = 0; i < p.Length; ++i) {
4740 if (p [i] != Parameter)
4744 // Don't capture local parameters
4746 if (b == ec.CurrentBlock.Toplevel && !am.IsIterator)
4750 ec.Report.Error (1628, loc,
4751 "Parameter `{0}' cannot be used inside `{1}' when using `ref' or `out' modifier",
4752 Name, am.ContainerType);
4755 if (pi.Parameter.HasAddressTaken)
4756 AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, this, loc);
4758 if (ec.IsVariableCapturingRequired && !b.Toplevel.IsExpressionTree) {
4759 AnonymousMethodStorey storey = pi.Block.CreateAnonymousMethodStorey (ec);
4760 storey.CaptureParameter (ec, this);
4772 public override int GetHashCode ()
4774 return Name.GetHashCode ();
4777 public override bool Equals (object obj)
4779 ParameterReference pr = obj as ParameterReference;
4783 return Name == pr.Name;
4786 public override void AddressOf (EmitContext ec, AddressOp mode)
4789 // ParameterReferences might already be a reference
4796 base.AddressOf (ec, mode);
4799 protected override void CloneTo (CloneContext clonectx, Expression target)
4804 public override Expression CreateExpressionTree (ResolveContext ec)
4806 HoistedVariable hv = GetHoistedVariable (ec);
4808 return hv.CreateExpressionTree ();
4810 return Parameter.ExpressionTreeVariableReference ();
4814 // Notice that for ref/out parameters, the type exposed is not the
4815 // same type exposed externally.
4818 // externally we expose "int&"
4819 // here we expose "int".
4821 // We record this in "is_ref". This means that the type system can treat
4822 // the type as it is expected, but when we generate the code, we generate
4823 // the alternate kind of code.
4825 protected override Expression DoResolve (ResolveContext ec)
4827 if (!DoResolveBase (ec))
4830 // HACK: Variables are not captured in probing mode
4831 if (ec.IsInProbingMode)
4834 if (HasOutModifier && ec.DoFlowAnalysis &&
4835 (!ec.OmitStructFlowAnalysis || !VariableInfo.TypeInfo.IsStruct) && !IsAssigned (ec, loc))
4841 override public Expression DoResolveLValue (ResolveContext ec, Expression right_side)
4843 if (!DoResolveBase (ec))
4850 static public void EmitLdArg (EmitContext ec, int x)
4853 case 0: ec.Emit (OpCodes.Ldarg_0); break;
4854 case 1: ec.Emit (OpCodes.Ldarg_1); break;
4855 case 2: ec.Emit (OpCodes.Ldarg_2); break;
4856 case 3: ec.Emit (OpCodes.Ldarg_3); break;
4858 if (x > byte.MaxValue)
4859 ec.Emit (OpCodes.Ldarg, x);
4861 ec.Emit (OpCodes.Ldarg_S, (byte) x);
4868 /// Invocation of methods or delegates.
4870 public class Invocation : ExpressionStatement
4872 protected Arguments arguments;
4873 protected Expression expr;
4874 protected MethodGroupExpr mg;
4876 public Invocation (Expression expr, Arguments arguments)
4879 this.arguments = arguments;
4881 loc = expr.Location;
4885 public Arguments Arguments {
4891 public Expression Expression {
4898 protected override void CloneTo (CloneContext clonectx, Expression t)
4900 Invocation target = (Invocation) t;
4902 if (arguments != null)
4903 target.arguments = arguments.Clone (clonectx);
4905 target.expr = expr.Clone (clonectx);
4909 public override Expression CreateExpressionTree (ResolveContext ec)
4911 Expression instance = mg.IsInstance ?
4912 mg.InstanceExpression.CreateExpressionTree (ec) :
4913 new NullLiteral (loc);
4915 var args = Arguments.CreateForExpressionTree (ec, arguments,
4917 mg.CreateExpressionTree (ec));
4919 return CreateExpressionFactoryCall (ec, "Call", args);
4922 protected override Expression DoResolve (ResolveContext ec)
4924 Expression member_expr;
4925 var atn = expr as ATypeNameExpression;
4927 member_expr = atn.LookupNameExpression (ec, true, true);
4928 if (member_expr != null)
4929 member_expr = member_expr.Resolve (ec);
4931 member_expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4934 if (member_expr == null)
4938 // Next, evaluate all the expressions in the argument list
4940 bool dynamic_arg = false;
4941 if (arguments != null)
4942 arguments.Resolve (ec, out dynamic_arg);
4944 TypeSpec expr_type = member_expr.Type;
4945 mg = member_expr as MethodGroupExpr;
4947 bool dynamic_member = expr_type == InternalType.Dynamic;
4949 if (!dynamic_member) {
4950 Expression invoke = null;
4953 if (expr_type != null && TypeManager.IsDelegateType (expr_type)) {
4954 invoke = new DelegateInvocation (member_expr, arguments, loc);
4955 invoke = invoke.Resolve (ec);
4956 if (invoke == null || !dynamic_arg)
4959 MemberExpr me = member_expr as MemberExpr;
4961 member_expr.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup, loc);
4965 ec.Report.Error (1955, loc, "The member `{0}' cannot be used as method or delegate",
4966 member_expr.GetSignatureForError ());
4971 if (invoke == null) {
4972 mg = DoResolveOverload (ec);
4978 if (dynamic_arg || dynamic_member)
4979 return DoResolveDynamic (ec, member_expr);
4981 var method = mg.BestCandidate;
4982 if (method != null) {
4983 type = method.ReturnType;
4986 if (arguments == null && method.DeclaringType == TypeManager.object_type && method.Name == Destructor.MetadataName) {
4988 ec.Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
4990 ec.Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
4994 IsSpecialMethodInvocation (ec, method, loc);
4996 if (mg.InstanceExpression != null)
4997 mg.InstanceExpression.CheckMarshalByRefAccess (ec);
4999 eclass = ExprClass.Value;
5003 Expression DoResolveDynamic (ResolveContext ec, Expression memberExpr)
5006 DynamicMemberBinder dmb = memberExpr as DynamicMemberBinder;
5008 args = dmb.Arguments;
5009 if (arguments != null)
5010 args.AddRange (arguments);
5011 } else if (mg == null) {
5012 if (arguments == null)
5013 args = new Arguments (1);
5017 args.Insert (0, new Argument (memberExpr));
5021 ec.Report.Error (1971, loc,
5022 "The base call to method `{0}' cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access",
5027 if (arguments == null)
5028 args = new Arguments (1);
5032 MemberAccess ma = expr as MemberAccess;
5034 var left_type = ma.LeftExpression as TypeExpr;
5035 if (left_type != null) {
5036 args.Insert (0, new Argument (new TypeOf (left_type, loc).Resolve (ec), Argument.AType.DynamicTypeName));
5038 args.Insert (0, new Argument (ma.LeftExpression.Resolve (ec)));
5040 } else { // is SimpleName
5042 args.Insert (0, new Argument (new TypeOf (new TypeExpression (ec.CurrentType, loc), loc).Resolve (ec), Argument.AType.DynamicTypeName));
5044 args.Insert (0, new Argument (new This (loc).Resolve (ec)));
5049 return new DynamicInvocation (expr as ATypeNameExpression, args, loc).Resolve (ec);
5052 protected virtual MethodGroupExpr DoResolveOverload (ResolveContext ec)
5054 return mg.OverloadResolve (ec, ref arguments, null, OverloadResolver.Restrictions.None);
5057 static Type[] GetVarargsTypes (MethodSpec mb, Arguments arguments)
5059 AParametersCollection pd = mb.Parameters;
5061 Argument a = arguments[pd.Count - 1];
5062 Arglist list = (Arglist) a.Expr;
5064 return list.ArgumentTypes;
5068 // If a member is a method or event, or if it is a constant, field or property of either a delegate type
5069 // or the type dynamic, then the member is invocable
5071 public static bool IsMemberInvocable (MemberSpec member)
5073 switch (member.Kind) {
5074 case MemberKind.Event:
5076 case MemberKind.Field:
5077 case MemberKind.Property:
5078 var m = member as IInterfaceMemberSpec;
5079 return m.MemberType.IsDelegate || m.MemberType == InternalType.Dynamic;
5085 public static bool IsSpecialMethodInvocation (ResolveContext ec, MethodSpec method, Location loc)
5087 if (!method.IsReservedMethod)
5090 if (ec.HasSet (ResolveContext.Options.InvokeSpecialName) || ec.CurrentMemberDefinition.IsCompilerGenerated)
5093 ec.Report.SymbolRelatedToPreviousError (method);
5094 ec.Report.Error (571, loc, "`{0}': cannot explicitly call operator or accessor",
5095 method.GetSignatureForError ());
5101 // Used to decide whether call or callvirt is needed
5103 static bool IsVirtualCallRequired (Expression instance, MethodSpec method)
5106 // There are 2 scenarious where we emit callvirt
5108 // Case 1: A method is virtual and it's not used to call base
5109 // Case 2: A method instance expression can be null. In this casen callvirt ensures
5110 // correct NRE exception when the method is called
5112 var decl_type = method.DeclaringType;
5113 if (decl_type.IsStruct || decl_type.IsEnum)
5116 if (instance is BaseThis)
5120 // It's non-virtual and will never be null
5122 if (!method.IsVirtual && (instance is This || instance is New || instance is ArrayCreation || instance is DelegateCreation || instance is TypeOf))
5129 /// is_base tells whether we want to force the use of the `call'
5130 /// opcode instead of using callvirt. Call is required to call
5131 /// a specific method, while callvirt will always use the most
5132 /// recent method in the vtable.
5134 /// is_static tells whether this is an invocation on a static method
5136 /// instance_expr is an expression that represents the instance
5137 /// it must be non-null if is_static is false.
5139 /// method is the method to invoke.
5141 /// Arguments is the list of arguments to pass to the method or constructor.
5143 public static void EmitCall (EmitContext ec, Expression instance_expr,
5144 MethodSpec method, Arguments Arguments, Location loc)
5146 EmitCall (ec, instance_expr, method, Arguments, loc, false, false);
5149 // `dup_args' leaves an extra copy of the arguments on the stack
5150 // `omit_args' does not leave any arguments at all.
5151 // So, basically, you could make one call with `dup_args' set to true,
5152 // and then another with `omit_args' set to true, and the two calls
5153 // would have the same set of arguments. However, each argument would
5154 // only have been evaluated once.
5155 public static void EmitCall (EmitContext ec, Expression instance_expr,
5156 MethodSpec method, Arguments Arguments, Location loc,
5157 bool dup_args, bool omit_args)
5159 LocalTemporary this_arg = null;
5161 // Speed up the check by not doing it on not allowed targets
5162 if (method.ReturnType == TypeManager.void_type && method.IsConditionallyExcluded (loc))
5166 TypeSpec iexpr_type;
5168 if (method.IsStatic) {
5170 call_op = OpCodes.Call;
5172 iexpr_type = instance_expr.Type;
5174 if (IsVirtualCallRequired (instance_expr, method)) {
5175 call_op = OpCodes.Callvirt;
5177 call_op = OpCodes.Call;
5181 // If this is ourselves, push "this"
5184 TypeSpec t = iexpr_type;
5187 // Push the instance expression
5189 if ((iexpr_type.IsStruct && (call_op == OpCodes.Callvirt || (call_op == OpCodes.Call && method.DeclaringType == iexpr_type))) ||
5190 iexpr_type.IsGenericParameter || TypeManager.IsNullableType (method.DeclaringType)) {
5192 // If the expression implements IMemoryLocation, then
5193 // we can optimize and use AddressOf on the
5196 // If not we have to use some temporary storage for
5198 var iml = instance_expr as IMemoryLocation;
5200 iml.AddressOf (ec, AddressOp.LoadStore);
5202 LocalTemporary temp = new LocalTemporary (iexpr_type);
5203 instance_expr.Emit (ec);
5205 temp.AddressOf (ec, AddressOp.Load);
5208 // avoid the overhead of doing this all the time.
5210 t = ReferenceContainer.MakeType (iexpr_type);
5211 } else if (iexpr_type.IsEnum || iexpr_type.IsStruct) {
5212 instance_expr.Emit (ec);
5213 ec.Emit (OpCodes.Box, iexpr_type);
5214 t = iexpr_type = TypeManager.object_type;
5216 instance_expr.Emit (ec);
5220 ec.Emit (OpCodes.Dup);
5221 if (Arguments != null && Arguments.Count != 0) {
5222 this_arg = new LocalTemporary (t);
5223 this_arg.Store (ec);
5229 if (!omit_args && Arguments != null)
5230 Arguments.Emit (ec, dup_args, this_arg);
5232 if (call_op == OpCodes.Callvirt && (iexpr_type.IsGenericParameter || iexpr_type.IsStruct)) {
5233 ec.Emit (OpCodes.Constrained, iexpr_type);
5236 if (method.Parameters.HasArglist) {
5237 Type[] varargs_types = GetVarargsTypes (method, Arguments);
5238 ec.Emit (call_op, method, varargs_types);
5245 // and DoFoo is not virtual, you can omit the callvirt,
5246 // because you don't need the null checking behavior.
5248 ec.Emit (call_op, method);
5251 public override void Emit (EmitContext ec)
5253 mg.EmitCall (ec, arguments);
5256 public override void EmitStatement (EmitContext ec)
5261 // Pop the return value if there is one
5263 if (type != TypeManager.void_type)
5264 ec.Emit (OpCodes.Pop);
5267 public override SLE.Expression MakeExpression (BuilderContext ctx)
5269 return MakeExpression (ctx, mg.InstanceExpression, mg.BestCandidate, arguments);
5272 public static SLE.Expression MakeExpression (BuilderContext ctx, Expression instance, MethodSpec mi, Arguments args)
5274 var instance_expr = instance == null ? null : instance.MakeExpression (ctx);
5275 return SLE.Expression.Call (instance_expr, (MethodInfo) mi.GetMetaInfo (), Arguments.MakeExpression (args, ctx));
5280 /// Implements the new expression
5282 public class New : ExpressionStatement, IMemoryLocation {
5283 protected Arguments Arguments;
5286 // During bootstrap, it contains the RequestedType,
5287 // but if `type' is not null, it *might* contain a NewDelegate
5288 // (because of field multi-initialization)
5290 protected Expression RequestedType;
5292 protected MethodSpec method;
5294 public New (Expression requested_type, Arguments arguments, Location l)
5296 RequestedType = requested_type;
5297 Arguments = arguments;
5302 /// Converts complex core type syntax like 'new int ()' to simple constant
5304 public static Constant Constantify (TypeSpec t)
5306 if (t == TypeManager.int32_type)
5307 return new IntConstant (0, Location.Null);
5308 if (t == TypeManager.uint32_type)
5309 return new UIntConstant (0, Location.Null);
5310 if (t == TypeManager.int64_type)
5311 return new LongConstant (0, Location.Null);
5312 if (t == TypeManager.uint64_type)
5313 return new ULongConstant (0, Location.Null);
5314 if (t == TypeManager.float_type)
5315 return new FloatConstant (0, Location.Null);
5316 if (t == TypeManager.double_type)
5317 return new DoubleConstant (0, Location.Null);
5318 if (t == TypeManager.short_type)
5319 return new ShortConstant (0, Location.Null);
5320 if (t == TypeManager.ushort_type)
5321 return new UShortConstant (0, Location.Null);
5322 if (t == TypeManager.sbyte_type)
5323 return new SByteConstant (0, Location.Null);
5324 if (t == TypeManager.byte_type)
5325 return new ByteConstant (0, Location.Null);
5326 if (t == TypeManager.char_type)
5327 return new CharConstant ('\0', Location.Null);
5328 if (t == TypeManager.bool_type)
5329 return new BoolConstant (false, Location.Null);
5330 if (t == TypeManager.decimal_type)
5331 return new DecimalConstant (0, Location.Null);
5332 if (TypeManager.IsEnumType (t))
5333 return new EnumConstant (Constantify (EnumSpec.GetUnderlyingType (t)), t);
5334 if (TypeManager.IsNullableType (t))
5335 return Nullable.LiftedNull.Create (t, Location.Null);
5341 // Checks whether the type is an interface that has the
5342 // [ComImport, CoClass] attributes and must be treated
5345 public Expression CheckComImport (ResolveContext ec)
5347 if (!type.IsInterface)
5351 // Turn the call into:
5352 // (the-interface-stated) (new class-referenced-in-coclassattribute ())
5354 var real_class = type.MemberDefinition.GetAttributeCoClass ();
5355 if (real_class == null)
5358 New proxy = new New (new TypeExpression (real_class, loc), Arguments, loc);
5359 Cast cast = new Cast (new TypeExpression (type, loc), proxy, loc);
5360 return cast.Resolve (ec);
5363 public override Expression CreateExpressionTree (ResolveContext ec)
5366 if (method == null) {
5367 args = new Arguments (1);
5368 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
5370 args = Arguments.CreateForExpressionTree (ec,
5371 Arguments, new TypeOfMethod (method, loc));
5374 return CreateExpressionFactoryCall (ec, "New", args);
5377 protected override Expression DoResolve (ResolveContext ec)
5379 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec, false);
5384 eclass = ExprClass.Value;
5386 if (type.IsPointer) {
5387 ec.Report.Error (1919, loc, "Unsafe type `{0}' cannot be used in an object creation expression",
5388 TypeManager.CSharpName (type));
5392 if (Arguments == null) {
5393 Constant c = Constantify (type);
5395 return ReducedExpression.Create (c.Resolve (ec), this);
5398 if (TypeManager.IsDelegateType (type)) {
5399 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5402 var tparam = type as TypeParameterSpec;
5403 if (tparam != null) {
5404 if (!tparam.HasSpecialConstructor && !tparam.HasSpecialStruct) {
5405 ec.Report.Error (304, loc,
5406 "Cannot create an instance of the variable type `{0}' because it does not have the new() constraint",
5407 TypeManager.CSharpName (type));
5410 if ((Arguments != null) && (Arguments.Count != 0)) {
5411 ec.Report.Error (417, loc,
5412 "`{0}': cannot provide arguments when creating an instance of a variable type",
5413 TypeManager.CSharpName (type));
5416 if (TypeManager.activator_create_instance == null) {
5417 TypeSpec activator_type = TypeManager.CoreLookupType (ec.Compiler, "System", "Activator", MemberKind.Class, true);
5418 if (activator_type != null) {
5419 TypeManager.activator_create_instance = TypeManager.GetPredefinedMethod (
5420 activator_type, MemberFilter.Method ("CreateInstance", 1, ParametersCompiled.EmptyReadOnlyParameters, null), loc);
5427 if (type.IsStatic) {
5428 ec.Report.SymbolRelatedToPreviousError (type);
5429 ec.Report.Error (712, loc, "Cannot create an instance of the static class `{0}'", TypeManager.CSharpName (type));
5433 if (type.IsInterface || type.IsAbstract){
5434 if (!TypeManager.IsGenericType (type)) {
5435 RequestedType = CheckComImport (ec);
5436 if (RequestedType != null)
5437 return RequestedType;
5440 ec.Report.SymbolRelatedToPreviousError (type);
5441 ec.Report.Error (144, loc, "Cannot create an instance of the abstract class or interface `{0}'", TypeManager.CSharpName (type));
5446 // Any struct always defines parameterless constructor
5448 if (type.IsStruct && Arguments == null)
5452 if (Arguments != null) {
5453 Arguments.Resolve (ec, out dynamic);
5458 method = ConstructorLookup (ec, type, ref Arguments, loc);
5461 Arguments.Insert (0, new Argument (new TypeOf (texpr, loc).Resolve (ec), Argument.AType.DynamicTypeName));
5462 return new DynamicConstructorBinder (type, Arguments, loc).Resolve (ec);
5468 bool DoEmitTypeParameter (EmitContext ec)
5470 var ctor_factory = TypeManager.activator_create_instance.MakeGenericMethod (type);
5471 var tparam = (TypeParameterSpec) type;
5473 if (tparam.IsReferenceType) {
5474 ec.Emit (OpCodes.Call, ctor_factory);
5478 // Allow DoEmit() to be called multiple times.
5479 // We need to create a new LocalTemporary each time since
5480 // you can't share LocalBuilders among ILGeneators.
5481 LocalTemporary temp = new LocalTemporary (type);
5483 Label label_activator = ec.DefineLabel ();
5484 Label label_end = ec.DefineLabel ();
5486 temp.AddressOf (ec, AddressOp.Store);
5487 ec.Emit (OpCodes.Initobj, type);
5490 ec.Emit (OpCodes.Box, type);
5491 ec.Emit (OpCodes.Brfalse, label_activator);
5493 temp.AddressOf (ec, AddressOp.Store);
5494 ec.Emit (OpCodes.Initobj, type);
5496 ec.Emit (OpCodes.Br_S, label_end);
5498 ec.MarkLabel (label_activator);
5500 ec.Emit (OpCodes.Call, ctor_factory);
5501 ec.MarkLabel (label_end);
5506 // This Emit can be invoked in two contexts:
5507 // * As a mechanism that will leave a value on the stack (new object)
5508 // * As one that wont (init struct)
5510 // If we are dealing with a ValueType, we have a few
5511 // situations to deal with:
5513 // * The target is a ValueType, and we have been provided
5514 // the instance (this is easy, we are being assigned).
5516 // * The target of New is being passed as an argument,
5517 // to a boxing operation or a function that takes a
5520 // In this case, we need to create a temporary variable
5521 // that is the argument of New.
5523 // Returns whether a value is left on the stack
5525 // *** Implementation note ***
5527 // To benefit from this optimization, each assignable expression
5528 // has to manually cast to New and call this Emit.
5530 // TODO: It's worth to implement it for arrays and fields
5532 public virtual bool Emit (EmitContext ec, IMemoryLocation target)
5534 bool is_value_type = TypeManager.IsValueType (type);
5535 VariableReference vr = target as VariableReference;
5537 if (target != null && is_value_type && (vr != null || method == null)) {
5538 target.AddressOf (ec, AddressOp.Store);
5539 } else if (vr != null && vr.IsRef) {
5543 if (Arguments != null)
5544 Arguments.Emit (ec);
5546 if (is_value_type) {
5547 if (method == null) {
5548 ec.Emit (OpCodes.Initobj, type);
5553 ec.Emit (OpCodes.Call, method);
5558 if (type is TypeParameterSpec)
5559 return DoEmitTypeParameter (ec);
5561 ec.Emit (OpCodes.Newobj, method);
5565 public override void Emit (EmitContext ec)
5567 LocalTemporary v = null;
5568 if (method == null && TypeManager.IsValueType (type)) {
5569 // TODO: Use temporary variable from pool
5570 v = new LocalTemporary (type);
5577 public override void EmitStatement (EmitContext ec)
5579 LocalTemporary v = null;
5580 if (method == null && TypeManager.IsValueType (type)) {
5581 // TODO: Use temporary variable from pool
5582 v = new LocalTemporary (type);
5586 ec.Emit (OpCodes.Pop);
5589 public virtual bool HasInitializer {
5595 public void AddressOf (EmitContext ec, AddressOp mode)
5597 EmitAddressOf (ec, mode);
5600 protected virtual IMemoryLocation EmitAddressOf (EmitContext ec, AddressOp mode)
5602 LocalTemporary value_target = new LocalTemporary (type);
5604 if (type is TypeParameterSpec) {
5605 DoEmitTypeParameter (ec);
5606 value_target.Store (ec);
5607 value_target.AddressOf (ec, mode);
5608 return value_target;
5611 if (!TypeManager.IsStruct (type)){
5613 // We throw an exception. So far, I believe we only need to support
5615 // foreach (int j in new StructType ())
5618 throw new Exception ("AddressOf should not be used for classes");
5621 value_target.AddressOf (ec, AddressOp.Store);
5623 if (method == null) {
5624 ec.Emit (OpCodes.Initobj, type);
5626 if (Arguments != null)
5627 Arguments.Emit (ec);
5629 ec.Emit (OpCodes.Call, method);
5632 value_target.AddressOf (ec, mode);
5633 return value_target;
5636 protected override void CloneTo (CloneContext clonectx, Expression t)
5638 New target = (New) t;
5640 target.RequestedType = RequestedType.Clone (clonectx);
5641 if (Arguments != null){
5642 target.Arguments = Arguments.Clone (clonectx);
5646 public override SLE.Expression MakeExpression (BuilderContext ctx)
5648 return SLE.Expression.New ((ConstructorInfo) method.GetMetaInfo (), Arguments.MakeExpression (Arguments, ctx));
5652 public class ArrayInitializer : Expression
5654 List<Expression> elements;
5656 public ArrayInitializer (List<Expression> init, Location loc)
5662 public ArrayInitializer (int count, Location loc)
5664 elements = new List<Expression> (count);
5668 public ArrayInitializer (Location loc)
5673 public void Add (Expression expr)
5675 elements.Add (expr);
5678 public override Expression CreateExpressionTree (ResolveContext ec)
5680 throw new NotSupportedException ("ET");
5683 protected override void CloneTo (CloneContext clonectx, Expression t)
5685 var target = (ArrayInitializer) t;
5687 target.elements = new List<Expression> (elements.Count);
5688 foreach (var element in elements)
5689 target.elements.Add (element.Clone (clonectx));
5693 get { return elements.Count; }
5696 protected override Expression DoResolve (ResolveContext rc)
5698 var current_field = rc.CurrentMemberDefinition as FieldBase;
5699 return new ArrayCreation (new TypeExpression (current_field.MemberType, current_field.Location), this).Resolve (rc);
5702 public override void Emit (EmitContext ec)
5704 throw new InternalErrorException ("Missing Resolve call");
5707 public Expression this [int index] {
5708 get { return elements [index]; }
5713 /// 14.5.10.2: Represents an array creation expression.
5717 /// There are two possible scenarios here: one is an array creation
5718 /// expression that specifies the dimensions and optionally the
5719 /// initialization data and the other which does not need dimensions
5720 /// specified but where initialization data is mandatory.
5722 public class ArrayCreation : Expression
5724 FullNamedExpression requested_base_type;
5725 ArrayInitializer initializers;
5728 // The list of Argument types.
5729 // This is used to construct the `newarray' or constructor signature
5731 protected List<Expression> arguments;
5733 protected TypeSpec array_element_type;
5734 int num_arguments = 0;
5735 protected int dimensions;
5736 protected readonly ComposedTypeSpecifier rank;
5737 Expression first_emit;
5738 LocalTemporary first_emit_temp;
5740 protected List<Expression> array_data;
5742 Dictionary<int, int> bounds;
5744 // The number of constants in array initializers
5745 int const_initializers_count;
5746 bool only_constant_initializers;
5748 public ArrayCreation (FullNamedExpression requested_base_type, List<Expression> exprs, ComposedTypeSpecifier rank, ArrayInitializer initializers, Location l)
5749 : this (requested_base_type, rank, initializers, l)
5751 arguments = new List<Expression> (exprs);
5752 num_arguments = arguments.Count;
5756 // For expressions like int[] foo = new int[] { 1, 2, 3 };
5758 public ArrayCreation (FullNamedExpression requested_base_type, ComposedTypeSpecifier rank, ArrayInitializer initializers, Location loc)
5760 this.requested_base_type = requested_base_type;
5762 this.initializers = initializers;
5766 num_arguments = rank.Dimension;
5770 // For compiler generated single dimensional arrays only
5772 public ArrayCreation (FullNamedExpression requested_base_type, ArrayInitializer initializers, Location loc)
5773 : this (requested_base_type, ComposedTypeSpecifier.SingleDimension, initializers, loc)
5778 // For expressions like int[] foo = { 1, 2, 3 };
5780 public ArrayCreation (FullNamedExpression requested_base_type, ArrayInitializer initializers)
5781 : this (requested_base_type, null, initializers, initializers.Location)
5785 protected override void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
5787 ec.Report.Error (248, loc, "Cannot create an array with a negative size");
5790 bool CheckIndices (ResolveContext ec, ArrayInitializer probe, int idx, bool specified_dims, int child_bounds)
5792 if (initializers != null && bounds == null) {
5794 // We use this to store all the date values in the order in which we
5795 // will need to store them in the byte blob later
5797 array_data = new List<Expression> ();
5798 bounds = new Dictionary<int, int> ();
5801 if (specified_dims) {
5802 Expression a = arguments [idx];
5807 a = ConvertExpressionToArrayIndex (ec, a);
5813 if (initializers != null) {
5814 Constant c = a as Constant;
5815 if (c == null && a is ArrayIndexCast)
5816 c = ((ArrayIndexCast) a).Child as Constant;
5819 ec.Report.Error (150, a.Location, "A constant value is expected");
5825 value = System.Convert.ToInt32 (c.GetValue ());
5827 ec.Report.Error (150, a.Location, "A constant value is expected");
5831 // TODO: probe.Count does not fit ulong in
5832 if (value != probe.Count) {
5833 ec.Report.Error (847, loc, "An array initializer of length `{0}' was expected", value.ToString ());
5837 bounds[idx] = value;
5841 if (initializers == null)
5844 only_constant_initializers = true;
5845 for (int i = 0; i < probe.Count; ++i) {
5847 if (o is ArrayInitializer) {
5848 var sub_probe = o as ArrayInitializer;
5849 if (idx + 1 >= dimensions){
5850 ec.Report.Error (623, loc, "Array initializers can only be used in a variable or field initializer. Try using a new expression instead");
5854 bool ret = CheckIndices (ec, sub_probe, idx + 1, specified_dims, child_bounds - 1);
5857 } else if (child_bounds > 1) {
5858 ec.Report.Error (846, o.Location, "A nested array initializer was expected");
5860 Expression element = ResolveArrayElement (ec, o);
5861 if (element == null)
5864 // Initializers with the default values can be ignored
5865 Constant c = element as Constant;
5867 if (!c.IsDefaultInitializer (array_element_type)) {
5868 ++const_initializers_count;
5871 only_constant_initializers = false;
5874 array_data.Add (element);
5881 public override Expression CreateExpressionTree (ResolveContext ec)
5885 if (array_data == null) {
5886 args = new Arguments (arguments.Count + 1);
5887 args.Add (new Argument (new TypeOf (new TypeExpression (array_element_type, loc), loc)));
5888 foreach (Expression a in arguments)
5889 args.Add (new Argument (a.CreateExpressionTree (ec)));
5891 return CreateExpressionFactoryCall (ec, "NewArrayBounds", args);
5894 if (dimensions > 1) {
5895 ec.Report.Error (838, loc, "An expression tree cannot contain a multidimensional array initializer");
5899 args = new Arguments (array_data == null ? 1 : array_data.Count + 1);
5900 args.Add (new Argument (new TypeOf (new TypeExpression (array_element_type, loc), loc)));
5901 if (array_data != null) {
5902 for (int i = 0; i < array_data.Count; ++i) {
5903 Expression e = array_data [i];
5904 args.Add (new Argument (e.CreateExpressionTree (ec)));
5908 return CreateExpressionFactoryCall (ec, "NewArrayInit", args);
5911 public void UpdateIndices ()
5914 for (var probe = initializers; probe != null;) {
5915 if (probe.Count > 0 && probe [0] is ArrayInitializer) {
5916 Expression e = new IntConstant (probe.Count, Location.Null);
5919 bounds [i++] = probe.Count;
5921 probe = (ArrayInitializer) probe[0];
5924 Expression e = new IntConstant (probe.Count, Location.Null);
5927 bounds [i++] = probe.Count;
5933 protected virtual Expression ResolveArrayElement (ResolveContext ec, Expression element)
5935 element = element.Resolve (ec);
5936 if (element == null)
5939 if (element is CompoundAssign.TargetExpression) {
5940 if (first_emit != null)
5941 throw new InternalErrorException ("Can only handle one mutator at a time");
5942 first_emit = element;
5943 element = first_emit_temp = new LocalTemporary (element.Type);
5946 return Convert.ImplicitConversionRequired (
5947 ec, element, array_element_type, loc);
5950 protected bool ResolveInitializers (ResolveContext ec)
5952 if (arguments != null) {
5954 for (int i = 0; i < arguments.Count; ++i) {
5955 res &= CheckIndices (ec, initializers, i, true, dimensions);
5956 if (initializers != null)
5963 arguments = new List<Expression> ();
5965 if (!CheckIndices (ec, initializers, 0, false, dimensions))
5974 // Resolved the type of the array
5976 bool ResolveArrayType (ResolveContext ec)
5978 if (requested_base_type is VarExpr) {
5979 ec.Report.Error (820, loc, "An implicitly typed local variable declarator cannot use an array initializer");
5986 FullNamedExpression array_type_expr;
5987 if (num_arguments > 0) {
5988 array_type_expr = new ComposedCast (requested_base_type, rank);
5990 array_type_expr = requested_base_type;
5993 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec, false);
5994 if (array_type_expr == null)
5997 type = array_type_expr.Type;
5998 var ac = type as ArrayContainer;
6000 ec.Report.Error (622, loc, "Can only use array initializer expressions to assign to array types. Try using a new expression instead");
6004 array_element_type = ac.Element;
6005 dimensions = ac.Rank;
6010 protected override Expression DoResolve (ResolveContext ec)
6015 if (!ResolveArrayType (ec))
6019 // validate the initializers and fill in any missing bits
6021 if (!ResolveInitializers (ec))
6024 eclass = ExprClass.Value;
6028 byte [] MakeByteBlob ()
6033 int count = array_data.Count;
6035 TypeSpec element_type = array_element_type;
6036 if (TypeManager.IsEnumType (element_type))
6037 element_type = EnumSpec.GetUnderlyingType (element_type);
6039 factor = GetTypeSize (element_type);
6041 throw new Exception ("unrecognized type in MakeByteBlob: " + element_type);
6043 data = new byte [(count * factor + 3) & ~3];
6046 for (int i = 0; i < count; ++i) {
6047 object v = array_data [i];
6049 if (v is EnumConstant)
6050 v = ((EnumConstant) v).Child;
6052 if (v is Constant && !(v is StringConstant))
6053 v = ((Constant) v).GetValue ();
6059 if (element_type == TypeManager.int64_type){
6060 if (!(v is Expression)){
6061 long val = (long) v;
6063 for (int j = 0; j < factor; ++j) {
6064 data [idx + j] = (byte) (val & 0xFF);
6068 } else if (element_type == TypeManager.uint64_type){
6069 if (!(v is Expression)){
6070 ulong val = (ulong) v;
6072 for (int j = 0; j < factor; ++j) {
6073 data [idx + j] = (byte) (val & 0xFF);
6077 } else if (element_type == TypeManager.float_type) {
6078 if (!(v is Expression)){
6079 element = BitConverter.GetBytes ((float) v);
6081 for (int j = 0; j < factor; ++j)
6082 data [idx + j] = element [j];
6083 if (!BitConverter.IsLittleEndian)
6084 System.Array.Reverse (data, idx, 4);
6086 } else if (element_type == TypeManager.double_type) {
6087 if (!(v is Expression)){
6088 element = BitConverter.GetBytes ((double) v);
6090 for (int j = 0; j < factor; ++j)
6091 data [idx + j] = element [j];
6093 // FIXME: Handle the ARM float format.
6094 if (!BitConverter.IsLittleEndian)
6095 System.Array.Reverse (data, idx, 8);
6097 } else if (element_type == TypeManager.char_type){
6098 if (!(v is Expression)){
6099 int val = (int) ((char) v);
6101 data [idx] = (byte) (val & 0xff);
6102 data [idx+1] = (byte) (val >> 8);
6104 } else if (element_type == TypeManager.short_type){
6105 if (!(v is Expression)){
6106 int val = (int) ((short) v);
6108 data [idx] = (byte) (val & 0xff);
6109 data [idx+1] = (byte) (val >> 8);
6111 } else if (element_type == TypeManager.ushort_type){
6112 if (!(v is Expression)){
6113 int val = (int) ((ushort) v);
6115 data [idx] = (byte) (val & 0xff);
6116 data [idx+1] = (byte) (val >> 8);
6118 } else if (element_type == TypeManager.int32_type) {
6119 if (!(v is Expression)){
6122 data [idx] = (byte) (val & 0xff);
6123 data [idx+1] = (byte) ((val >> 8) & 0xff);
6124 data [idx+2] = (byte) ((val >> 16) & 0xff);
6125 data [idx+3] = (byte) (val >> 24);
6127 } else if (element_type == TypeManager.uint32_type) {
6128 if (!(v is Expression)){
6129 uint val = (uint) v;
6131 data [idx] = (byte) (val & 0xff);
6132 data [idx+1] = (byte) ((val >> 8) & 0xff);
6133 data [idx+2] = (byte) ((val >> 16) & 0xff);
6134 data [idx+3] = (byte) (val >> 24);
6136 } else if (element_type == TypeManager.sbyte_type) {
6137 if (!(v is Expression)){
6138 sbyte val = (sbyte) v;
6139 data [idx] = (byte) val;
6141 } else if (element_type == TypeManager.byte_type) {
6142 if (!(v is Expression)){
6143 byte val = (byte) v;
6144 data [idx] = (byte) val;
6146 } else if (element_type == TypeManager.bool_type) {
6147 if (!(v is Expression)){
6148 bool val = (bool) v;
6149 data [idx] = (byte) (val ? 1 : 0);
6151 } else if (element_type == TypeManager.decimal_type){
6152 if (!(v is Expression)){
6153 int [] bits = Decimal.GetBits ((decimal) v);
6156 // FIXME: For some reason, this doesn't work on the MS runtime.
6157 int [] nbits = new int [4];
6158 nbits [0] = bits [3];
6159 nbits [1] = bits [2];
6160 nbits [2] = bits [0];
6161 nbits [3] = bits [1];
6163 for (int j = 0; j < 4; j++){
6164 data [p++] = (byte) (nbits [j] & 0xff);
6165 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6166 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6167 data [p++] = (byte) (nbits [j] >> 24);
6171 throw new Exception ("Unrecognized type in MakeByteBlob: " + element_type);
6181 public override SLE.Expression MakeExpression (BuilderContext ctx)
6183 var initializers = new SLE.Expression [array_data.Count];
6184 for (var i = 0; i < initializers.Length; i++) {
6185 if (array_data [i] == null)
6186 initializers [i] = SLE.Expression.Default (array_element_type.GetMetaInfo ());
6188 initializers [i] = array_data [i].MakeExpression (ctx);
6191 return SLE.Expression.NewArrayInit (array_element_type.GetMetaInfo (), initializers);
6195 // Emits the initializers for the array
6197 void EmitStaticInitializers (EmitContext ec)
6199 // FIXME: This should go to Resolve !
6200 if (TypeManager.void_initializearray_array_fieldhandle == null) {
6201 TypeManager.void_initializearray_array_fieldhandle = TypeManager.GetPredefinedMethod (
6202 TypeManager.runtime_helpers_type, "InitializeArray", loc,
6203 TypeManager.array_type, TypeManager.runtime_field_handle_type);
6204 if (TypeManager.void_initializearray_array_fieldhandle == null)
6209 // First, the static data
6213 byte [] data = MakeByteBlob ();
6215 fb = RootContext.MakeStaticData (data);
6217 ec.Emit (OpCodes.Dup);
6218 ec.Emit (OpCodes.Ldtoken, fb);
6219 ec.Emit (OpCodes.Call, TypeManager.void_initializearray_array_fieldhandle);
6223 // Emits pieces of the array that can not be computed at compile
6224 // time (variables and string locations).
6226 // This always expect the top value on the stack to be the array
6228 void EmitDynamicInitializers (EmitContext ec, bool emitConstants)
6230 int dims = bounds.Count;
6231 var current_pos = new int [dims];
6233 for (int i = 0; i < array_data.Count; i++){
6235 Expression e = array_data [i];
6236 var c = e as Constant;
6238 // Constant can be initialized via StaticInitializer
6239 if (c == null || (c != null && emitConstants && !c.IsDefaultInitializer (array_element_type))) {
6240 TypeSpec etype = e.Type;
6242 ec.Emit (OpCodes.Dup);
6244 for (int idx = 0; idx < dims; idx++)
6245 ec.EmitInt (current_pos [idx]);
6248 // If we are dealing with a struct, get the
6249 // address of it, so we can store it.
6251 if ((dims == 1) && TypeManager.IsStruct (etype) &&
6252 (!TypeManager.IsBuiltinOrEnum (etype) ||
6253 etype == TypeManager.decimal_type)) {
6255 ec.Emit (OpCodes.Ldelema, etype);
6260 ec.EmitArrayStore ((ArrayContainer) type);
6266 for (int j = dims - 1; j >= 0; j--){
6268 if (current_pos [j] < bounds [j])
6270 current_pos [j] = 0;
6275 public override void Emit (EmitContext ec)
6277 if (first_emit != null) {
6278 first_emit.Emit (ec);
6279 first_emit_temp.Store (ec);
6282 foreach (Expression e in arguments)
6285 ec.EmitArrayNew ((ArrayContainer) type);
6287 if (initializers == null)
6290 // Emit static initializer for arrays which have contain more than 2 items and
6291 // the static initializer will initialize at least 25% of array values.
6292 // NOTE: const_initializers_count does not contain default constant values.
6293 if (const_initializers_count > 2 && const_initializers_count * 4 > (array_data.Count) &&
6294 (TypeManager.IsPrimitiveType (array_element_type) || TypeManager.IsEnumType (array_element_type))) {
6295 EmitStaticInitializers (ec);
6297 if (!only_constant_initializers)
6298 EmitDynamicInitializers (ec, false);
6300 EmitDynamicInitializers (ec, true);
6303 if (first_emit_temp != null)
6304 first_emit_temp.Release (ec);
6307 public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
6309 // no multi dimensional or jagged arrays
6310 if (arguments.Count != 1 || array_element_type.IsArray) {
6311 base.EncodeAttributeValue (rc, enc, targetType);
6315 // No array covariance, except for array -> object
6316 if (type != targetType) {
6317 if (targetType != TypeManager.object_type) {
6318 base.EncodeAttributeValue (rc, enc, targetType);
6322 if (enc.Encode (type) == AttributeEncoder.EncodedTypeProperties.DynamicType) {
6323 Attribute.Error_AttributeArgumentIsDynamic (rc, loc);
6328 // Single dimensional array of 0 size
6329 if (array_data == null) {
6330 IntConstant ic = arguments[0] as IntConstant;
6331 if (ic == null || !ic.IsDefaultValue) {
6332 base.EncodeAttributeValue (rc, enc, targetType);
6334 enc.Stream.Write (0);
6340 enc.Stream.Write ((int) array_data.Count);
6341 foreach (var element in array_data) {
6342 element.EncodeAttributeValue (rc, enc, array_element_type);
6346 protected override void CloneTo (CloneContext clonectx, Expression t)
6348 ArrayCreation target = (ArrayCreation) t;
6350 if (requested_base_type != null)
6351 target.requested_base_type = (FullNamedExpression)requested_base_type.Clone (clonectx);
6353 if (arguments != null){
6354 target.arguments = new List<Expression> (arguments.Count);
6355 foreach (Expression e in arguments)
6356 target.arguments.Add (e.Clone (clonectx));
6359 if (initializers != null)
6360 target.initializers = (ArrayInitializer) initializers.Clone (clonectx);
6365 // Represents an implicitly typed array epxression
6367 class ImplicitlyTypedArrayCreation : ArrayCreation
6369 TypeInferenceContext best_type_inference;
6371 public ImplicitlyTypedArrayCreation (ComposedTypeSpecifier rank, ArrayInitializer initializers, Location loc)
6372 : base (null, rank, initializers, loc)
6376 public ImplicitlyTypedArrayCreation (ArrayInitializer initializers, Location loc)
6377 : base (null, initializers, loc)
6381 protected override Expression DoResolve (ResolveContext ec)
6386 dimensions = rank.Dimension;
6388 best_type_inference = new TypeInferenceContext ();
6390 if (!ResolveInitializers (ec))
6393 best_type_inference.FixAllTypes (ec);
6394 array_element_type = best_type_inference.InferredTypeArguments[0];
6395 best_type_inference = null;
6397 if (array_element_type == null || array_element_type == InternalType.MethodGroup || array_element_type == InternalType.AnonymousMethod ||
6398 arguments.Count != rank.Dimension) {
6399 ec.Report.Error (826, loc,
6400 "The type of an implicitly typed array cannot be inferred from the initializer. Try specifying array type explicitly");
6405 // At this point we found common base type for all initializer elements
6406 // but we have to be sure that all static initializer elements are of
6409 UnifyInitializerElement (ec);
6411 type = ArrayContainer.MakeType (array_element_type, dimensions);
6412 eclass = ExprClass.Value;
6417 // Converts static initializer only
6419 void UnifyInitializerElement (ResolveContext ec)
6421 for (int i = 0; i < array_data.Count; ++i) {
6422 Expression e = array_data[i];
6424 array_data [i] = Convert.ImplicitConversion (ec, e, array_element_type, Location.Null);
6428 protected override Expression ResolveArrayElement (ResolveContext ec, Expression element)
6430 element = element.Resolve (ec);
6431 if (element != null)
6432 best_type_inference.AddCommonTypeBound (element.Type);
6438 public sealed class CompilerGeneratedThis : This
6440 public static This Instance = new CompilerGeneratedThis ();
6442 private CompilerGeneratedThis ()
6443 : base (Location.Null)
6447 public CompilerGeneratedThis (TypeSpec type, Location loc)
6453 protected override Expression DoResolve (ResolveContext ec)
6455 eclass = ExprClass.Variable;
6457 type = ec.CurrentType;
6462 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
6469 /// Represents the `this' construct
6472 public class This : VariableReference
6474 sealed class ThisVariable : ILocalVariable
6476 public static readonly ILocalVariable Instance = new ThisVariable ();
6478 public void Emit (EmitContext ec)
6480 ec.Emit (OpCodes.Ldarg_0);
6483 public void EmitAssign (EmitContext ec)
6485 throw new InvalidOperationException ();
6488 public void EmitAddressOf (EmitContext ec)
6490 ec.Emit (OpCodes.Ldarg_0);
6494 VariableInfo variable_info;
6496 public This (Location loc)
6503 public override string Name {
6504 get { return "this"; }
6507 public override bool IsRef {
6508 get { return type.IsStruct; }
6511 protected override ILocalVariable Variable {
6512 get { return ThisVariable.Instance; }
6515 public override VariableInfo VariableInfo {
6516 get { return variable_info; }
6519 public override bool IsFixed {
6520 get { return false; }
6525 protected virtual void Error_ThisNotAvailable (ResolveContext ec)
6527 if (ec.IsStatic && !ec.HasSet (ResolveContext.Options.ConstantScope)) {
6528 ec.Report.Error (26, loc, "Keyword `this' is not valid in a static property, static method, or static field initializer");
6529 } else if (ec.CurrentAnonymousMethod != null) {
6530 ec.Report.Error (1673, loc,
6531 "Anonymous methods inside structs cannot access instance members of `this'. " +
6532 "Consider copying `this' to a local variable outside the anonymous method and using the local instead");
6534 ec.Report.Error (27, loc, "Keyword `this' is not available in the current context");
6538 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
6543 AnonymousMethodStorey storey = ae.Storey;
6544 while (storey != null) {
6545 AnonymousMethodStorey temp = storey.Parent as AnonymousMethodStorey;
6547 return storey.HoistedThis;
6555 public static bool IsThisAvailable (ResolveContext ec, bool ignoreAnonymous)
6557 if (ec.IsStatic || ec.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.BaseInitializer | ResolveContext.Options.ConstantScope))
6560 if (ignoreAnonymous || ec.CurrentAnonymousMethod == null)
6563 if (TypeManager.IsStruct (ec.CurrentType) && ec.CurrentIterator == null)
6569 public virtual void ResolveBase (ResolveContext ec)
6571 if (!IsThisAvailable (ec, false)) {
6572 Error_ThisNotAvailable (ec);
6575 var block = ec.CurrentBlock;
6576 if (block != null) {
6577 if (block.Toplevel.ThisVariable != null)
6578 variable_info = block.Toplevel.ThisVariable.VariableInfo;
6580 AnonymousExpression am = ec.CurrentAnonymousMethod;
6581 if (am != null && ec.IsVariableCapturingRequired) {
6582 am.SetHasThisAccess ();
6586 eclass = ExprClass.Variable;
6587 type = ec.CurrentType;
6591 // Called from Invocation to check if the invocation is correct
6593 public override void CheckMarshalByRefAccess (ResolveContext ec)
6595 if ((variable_info != null) && !(TypeManager.IsStruct (type) && ec.OmitStructFlowAnalysis) &&
6596 !variable_info.IsAssigned (ec)) {
6597 ec.Report.Error (188, loc,
6598 "The `this' object cannot be used before all of its fields are assigned to");
6599 variable_info.SetAssigned (ec);
6603 public override Expression CreateExpressionTree (ResolveContext ec)
6605 Arguments args = new Arguments (1);
6606 args.Add (new Argument (this));
6608 // Use typeless constant for ldarg.0 to save some
6609 // space and avoid problems with anonymous stories
6610 return CreateExpressionFactoryCall (ec, "Constant", args);
6613 protected override Expression DoResolve (ResolveContext ec)
6619 override public Expression DoResolveLValue (ResolveContext ec, Expression right_side)
6623 if (variable_info != null)
6624 variable_info.SetAssigned (ec);
6626 if (ec.CurrentType.IsClass){
6627 if (right_side == EmptyExpression.UnaryAddress)
6628 ec.Report.Error (459, loc, "Cannot take the address of `this' because it is read-only");
6629 else if (right_side == EmptyExpression.OutAccess.Instance)
6630 ec.Report.Error (1605, loc, "Cannot pass `this' as a ref or out argument because it is read-only");
6632 ec.Report.Error (1604, loc, "Cannot assign to `this' because it is read-only");
6638 public override int GetHashCode()
6640 throw new NotImplementedException ();
6643 public override bool Equals (object obj)
6645 This t = obj as This;
6652 protected override void CloneTo (CloneContext clonectx, Expression t)
6657 public override void SetHasAddressTaken ()
6664 /// Represents the `__arglist' construct
6666 public class ArglistAccess : Expression
6668 public ArglistAccess (Location loc)
6673 public override Expression CreateExpressionTree (ResolveContext ec)
6675 throw new NotSupportedException ("ET");
6678 protected override Expression DoResolve (ResolveContext ec)
6680 eclass = ExprClass.Variable;
6681 type = TypeManager.runtime_argument_handle_type;
6683 if (ec.HasSet (ResolveContext.Options.FieldInitializerScope) || !ec.CurrentBlock.Toplevel.Parameters.HasArglist) {
6684 ec.Report.Error (190, loc,
6685 "The __arglist construct is valid only within a variable argument method");
6691 public override void Emit (EmitContext ec)
6693 ec.Emit (OpCodes.Arglist);
6696 protected override void CloneTo (CloneContext clonectx, Expression target)
6703 /// Represents the `__arglist (....)' construct
6705 public class Arglist : Expression
6707 Arguments Arguments;
6709 public Arglist (Location loc)
6714 public Arglist (Arguments args, Location l)
6720 public Type[] ArgumentTypes {
6722 if (Arguments == null)
6723 return System.Type.EmptyTypes;
6725 var retval = new Type [Arguments.Count];
6726 for (int i = 0; i < retval.Length; i++)
6727 retval[i] = Arguments[i].Expr.Type.GetMetaInfo ();
6733 public override Expression CreateExpressionTree (ResolveContext ec)
6735 ec.Report.Error (1952, loc, "An expression tree cannot contain a method with variable arguments");
6739 protected override Expression DoResolve (ResolveContext ec)
6741 eclass = ExprClass.Variable;
6742 type = InternalType.Arglist;
6743 if (Arguments != null) {
6744 bool dynamic; // Can be ignored as there is always only 1 overload
6745 Arguments.Resolve (ec, out dynamic);
6751 public override void Emit (EmitContext ec)
6753 if (Arguments != null)
6754 Arguments.Emit (ec);
6757 protected override void CloneTo (CloneContext clonectx, Expression t)
6759 Arglist target = (Arglist) t;
6761 if (Arguments != null)
6762 target.Arguments = Arguments.Clone (clonectx);
6767 /// Implements the typeof operator
6769 public class TypeOf : Expression {
6770 FullNamedExpression QueriedType;
6773 public TypeOf (FullNamedExpression queried_type, Location l)
6775 QueriedType = queried_type;
6780 public TypeSpec TypeArgument {
6786 public FullNamedExpression TypeExpression {
6794 public override Expression CreateExpressionTree (ResolveContext ec)
6796 Arguments args = new Arguments (2);
6797 args.Add (new Argument (this));
6798 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
6799 return CreateExpressionFactoryCall (ec, "Constant", args);
6802 protected override Expression DoResolve (ResolveContext ec)
6804 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
6808 typearg = texpr.Type;
6810 if (typearg == TypeManager.void_type && !(QueriedType is TypeExpression)) {
6811 ec.Report.Error (673, loc, "System.Void cannot be used from C#. Use typeof (void) to get the void type object");
6812 } else if (typearg.IsPointer && !ec.IsUnsafe){
6813 UnsafeError (ec, loc);
6814 } else if (texpr is DynamicTypeExpr) {
6815 ec.Report.Error (1962, QueriedType.Location,
6816 "The typeof operator cannot be used on the dynamic type");
6819 type = TypeManager.type_type;
6820 QueriedType = texpr;
6822 return DoResolveBase ();
6825 protected Expression DoResolveBase ()
6827 if (TypeManager.system_type_get_type_from_handle == null) {
6828 TypeManager.system_type_get_type_from_handle = TypeManager.GetPredefinedMethod (
6829 TypeManager.type_type, "GetTypeFromHandle", loc, TypeManager.runtime_handle_type);
6832 // Even though what is returned is a type object, it's treated as a value by the compiler.
6833 // In particular, 'typeof (Foo).X' is something totally different from 'Foo.X'.
6834 eclass = ExprClass.Value;
6838 static bool ContainsDynamicType (TypeSpec type)
6840 if (type == InternalType.Dynamic)
6843 var element_container = type as ElementTypeSpec;
6844 if (element_container != null)
6845 return ContainsDynamicType (element_container.Element);
6847 foreach (var t in type.TypeArguments) {
6848 if (ContainsDynamicType (t)) {
6856 static bool ContainsTypeParameter (TypeSpec type)
6858 if (type.Kind == MemberKind.TypeParameter)
6861 var element_container = type as ElementTypeSpec;
6862 if (element_container != null)
6863 return ContainsTypeParameter (element_container.Element);
6865 foreach (var t in type.TypeArguments) {
6866 if (ContainsTypeParameter (t)) {
6874 public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
6876 // Target type is not System.Type therefore must be object
6877 // and we need to use different encoding sequence
6878 if (targetType != type)
6881 if (!(QueriedType is GenericOpenTypeExpr)) {
6883 while (gt != null) {
6884 if (ContainsTypeParameter (gt)) {
6885 rc.Compiler.Report.Error (416, loc, "`{0}': an attribute argument cannot use type parameters",
6886 typearg.GetSignatureForError ());
6890 gt = gt.DeclaringType;
6893 if (ContainsDynamicType (typearg)) {
6894 Attribute.Error_AttributeArgumentIsDynamic (rc, loc);
6899 enc.EncodeTypeName (typearg);
6902 public override void Emit (EmitContext ec)
6904 ec.Emit (OpCodes.Ldtoken, typearg);
6905 ec.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6908 protected override void CloneTo (CloneContext clonectx, Expression t)
6910 TypeOf target = (TypeOf) t;
6911 if (QueriedType != null)
6912 target.QueriedType = (FullNamedExpression) QueriedType.Clone (clonectx);
6916 class TypeOfMethod : TypeOfMember<MethodSpec>
6918 public TypeOfMethod (MethodSpec method, Location loc)
6919 : base (method, loc)
6923 protected override Expression DoResolve (ResolveContext ec)
6925 if (member.IsConstructor) {
6926 type = TypeManager.ctorinfo_type;
6928 type = TypeManager.ctorinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", "ConstructorInfo", MemberKind.Class, true);
6930 type = TypeManager.methodinfo_type;
6932 type = TypeManager.methodinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", "MethodInfo", MemberKind.Class, true);
6935 return base.DoResolve (ec);
6938 public override void Emit (EmitContext ec)
6940 ec.Emit (OpCodes.Ldtoken, member);
6943 ec.Emit (OpCodes.Castclass, type);
6946 protected override string GetMethodName {
6947 get { return "GetMethodFromHandle"; }
6950 protected override string RuntimeHandleName {
6951 get { return "RuntimeMethodHandle"; }
6954 protected override MethodSpec TypeFromHandle {
6956 return TypeManager.methodbase_get_type_from_handle;
6959 TypeManager.methodbase_get_type_from_handle = value;
6963 protected override MethodSpec TypeFromHandleGeneric {
6965 return TypeManager.methodbase_get_type_from_handle_generic;
6968 TypeManager.methodbase_get_type_from_handle_generic = value;
6972 protected override string TypeName {
6973 get { return "MethodBase"; }
6977 abstract class TypeOfMember<T> : Expression where T : MemberSpec
6979 protected readonly T member;
6981 protected TypeOfMember (T member, Location loc)
6983 this.member = member;
6987 public override Expression CreateExpressionTree (ResolveContext ec)
6989 Arguments args = new Arguments (2);
6990 args.Add (new Argument (this));
6991 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
6992 return CreateExpressionFactoryCall (ec, "Constant", args);
6995 protected override Expression DoResolve (ResolveContext ec)
6997 bool is_generic = member.DeclaringType.IsGenericOrParentIsGeneric;
6998 var mi = is_generic ? TypeFromHandleGeneric : TypeFromHandle;
7001 TypeSpec t = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", TypeName, MemberKind.Class, true);
7002 TypeSpec handle_type = TypeManager.CoreLookupType (ec.Compiler, "System", RuntimeHandleName, MemberKind.Struct, true);
7004 if (t == null || handle_type == null)
7007 mi = TypeManager.GetPredefinedMethod (t, GetMethodName, loc,
7009 new TypeSpec[] { handle_type, TypeManager.runtime_handle_type } :
7010 new TypeSpec[] { handle_type } );
7013 TypeFromHandleGeneric = mi;
7015 TypeFromHandle = mi;
7018 eclass = ExprClass.Value;
7022 public override void Emit (EmitContext ec)
7024 bool is_generic = member.DeclaringType.IsGenericOrParentIsGeneric;
7027 mi = TypeFromHandleGeneric;
7028 ec.Emit (OpCodes.Ldtoken, member.DeclaringType);
7030 mi = TypeFromHandle;
7033 ec.Emit (OpCodes.Call, mi);
7036 protected abstract string GetMethodName { get; }
7037 protected abstract string RuntimeHandleName { get; }
7038 protected abstract MethodSpec TypeFromHandle { get; set; }
7039 protected abstract MethodSpec TypeFromHandleGeneric { get; set; }
7040 protected abstract string TypeName { get; }
7043 class TypeOfField : TypeOfMember<FieldSpec>
7045 public TypeOfField (FieldSpec field, Location loc)
7050 protected override Expression DoResolve (ResolveContext ec)
7052 if (TypeManager.fieldinfo_type == null)
7053 TypeManager.fieldinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", TypeName, MemberKind.Class, true);
7055 type = TypeManager.fieldinfo_type;
7056 return base.DoResolve (ec);
7059 public override void Emit (EmitContext ec)
7061 ec.Emit (OpCodes.Ldtoken, member);
7065 protected override string GetMethodName {
7066 get { return "GetFieldFromHandle"; }
7069 protected override string RuntimeHandleName {
7070 get { return "RuntimeFieldHandle"; }
7073 protected override MethodSpec TypeFromHandle {
7075 return TypeManager.fieldinfo_get_field_from_handle;
7078 TypeManager.fieldinfo_get_field_from_handle = value;
7082 protected override MethodSpec TypeFromHandleGeneric {
7084 return TypeManager.fieldinfo_get_field_from_handle_generic;
7087 TypeManager.fieldinfo_get_field_from_handle_generic = value;
7091 protected override string TypeName {
7092 get { return "FieldInfo"; }
7097 /// Implements the sizeof expression
7099 public class SizeOf : Expression {
7100 readonly Expression QueriedType;
7101 TypeSpec type_queried;
7103 public SizeOf (Expression queried_type, Location l)
7105 this.QueriedType = queried_type;
7109 public override Expression CreateExpressionTree (ResolveContext ec)
7111 Error_PointerInsideExpressionTree (ec);
7115 protected override Expression DoResolve (ResolveContext ec)
7117 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
7121 type_queried = texpr.Type;
7122 if (TypeManager.IsEnumType (type_queried))
7123 type_queried = EnumSpec.GetUnderlyingType (type_queried);
7125 int size_of = GetTypeSize (type_queried);
7127 return new IntConstant (size_of, loc).Resolve (ec);
7130 if (!TypeManager.VerifyUnmanaged (ec.Compiler, type_queried, loc)){
7135 ec.Report.Error (233, loc,
7136 "`{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)",
7137 TypeManager.CSharpName (type_queried));
7140 type = TypeManager.int32_type;
7141 eclass = ExprClass.Value;
7145 public override void Emit (EmitContext ec)
7147 ec.Emit (OpCodes.Sizeof, type_queried);
7150 protected override void CloneTo (CloneContext clonectx, Expression t)
7156 /// Implements the qualified-alias-member (::) expression.
7158 public class QualifiedAliasMember : MemberAccess
7160 readonly string alias;
7161 public static readonly string GlobalAlias = "global";
7163 public QualifiedAliasMember (string alias, string identifier, Location l)
7164 : base (null, identifier, l)
7169 public QualifiedAliasMember (string alias, string identifier, TypeArguments targs, Location l)
7170 : base (null, identifier, targs, l)
7175 public QualifiedAliasMember (string alias, string identifier, int arity, Location l)
7176 : base (null, identifier, arity, l)
7181 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
7183 if (alias == GlobalAlias) {
7184 expr = GlobalRootNamespace.Instance;
7185 return base.ResolveAsTypeStep (ec, silent);
7188 int errors = ec.Compiler.Report.Errors;
7189 expr = ec.LookupNamespaceAlias (alias);
7191 if (errors == ec.Compiler.Report.Errors)
7192 ec.Compiler.Report.Error (432, loc, "Alias `{0}' not found", alias);
7196 FullNamedExpression fne = base.ResolveAsTypeStep (ec, silent);
7200 if (expr.eclass == ExprClass.Type) {
7202 ec.Compiler.Report.Error (431, loc,
7203 "Alias `{0}' cannot be used with '::' since it denotes a type. Consider replacing '::' with '.'", alias);
7211 protected override Expression DoResolve (ResolveContext ec)
7213 return ResolveAsTypeStep (ec, false);
7216 protected override void Error_IdentifierNotFound (IMemberContext rc, TypeSpec expr_type, string identifier)
7218 rc.Compiler.Report.Error (687, loc,
7219 "A namespace alias qualifier `{0}' did not resolve to a namespace or a type",
7220 GetSignatureForError ());
7223 public override string GetSignatureForError ()
7226 if (targs != null) {
7227 name = Name + "<" + targs.GetSignatureForError () + ">";
7230 return alias + "::" + name;
7233 public override Expression LookupNameExpression (ResolveContext rc, bool readMode, bool invocableOnly)
7235 return DoResolve (rc);
7238 protected override void CloneTo (CloneContext clonectx, Expression t)
7245 /// Implements the member access expression
7247 public class MemberAccess : ATypeNameExpression
7249 protected Expression expr;
7251 public MemberAccess (Expression expr, string id)
7252 : base (id, expr.Location)
7257 public MemberAccess (Expression expr, string identifier, Location loc)
7258 : base (identifier, loc)
7263 public MemberAccess (Expression expr, string identifier, TypeArguments args, Location loc)
7264 : base (identifier, args, loc)
7269 public MemberAccess (Expression expr, string identifier, int arity, Location loc)
7270 : base (identifier, arity, loc)
7275 public Expression LeftExpression {
7281 protected override Expression DoResolve (ResolveContext ec)
7283 return DoResolveName (ec, null);
7286 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
7288 return DoResolveName (ec, right_side);
7291 Expression DoResolveName (ResolveContext rc, Expression right_side)
7293 Expression e = LookupNameExpression (rc, right_side == null, false);
7297 if (right_side != null) {
7298 if (e is TypeExpr) {
7299 e.Error_UnexpectedKind (rc, ResolveFlags.VariableOrValue, loc);
7303 e = e.ResolveLValue (rc, right_side);
7305 e = e.Resolve (rc, ResolveFlags.VariableOrValue | ResolveFlags.Type);
7311 public override Expression LookupNameExpression (ResolveContext rc, bool readMode, bool invocableOnly)
7313 var sn = expr as SimpleName;
7314 const ResolveFlags flags = ResolveFlags.VariableOrValue | ResolveFlags.Type;
7317 // Resolve the expression with flow analysis turned off, we'll do the definite
7318 // assignment checks later. This is because we don't know yet what the expression
7319 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7320 // definite assignment check on the actual field and not on the whole struct.
7322 using (rc.Set (ResolveContext.Options.OmitStructFlowAnalysis)) {
7324 expr = sn.LookupNameExpression (rc, true, false);
7326 // Call resolve on expression which does have type set as we need expression type
7327 // TODO: I should probably ensure that the type is always set and leave resolve for the final
7328 if (expr is VariableReference || expr is ConstantExpr || expr is Linq.TransparentMemberAccess) {
7329 using (rc.With (ResolveContext.Options.DoFlowAnalysis, false)) {
7330 expr = expr.Resolve (rc);
7332 } else if (expr is TypeParameterExpr) {
7333 expr.Error_UnexpectedKind (rc, flags, expr.Location);
7337 expr = expr.Resolve (rc, flags);
7344 Namespace ns = expr as Namespace;
7346 FullNamedExpression retval = ns.Lookup (rc.Compiler, Name, Arity, loc);
7348 if (retval == null) {
7349 ns.Error_NamespaceDoesNotExist (loc, Name, Arity, rc);
7353 if (HasTypeArguments)
7354 return new GenericTypeExpr (retval.Type, targs, loc);
7360 TypeSpec expr_type = expr.Type;
7361 if (expr_type == InternalType.Dynamic) {
7362 me = expr as MemberExpr;
7364 me.ResolveInstanceExpression (rc);
7366 Arguments args = new Arguments (1);
7367 args.Add (new Argument (expr));
7368 return new DynamicMemberBinder (Name, args, loc);
7371 const MemberKind dot_kinds = MemberKind.Class | MemberKind.Struct | MemberKind.Delegate | MemberKind.Enum |
7372 MemberKind.Interface | MemberKind.TypeParameter | MemberKind.ArrayType;
7374 if ((expr_type.Kind & dot_kinds) == 0 || expr_type == TypeManager.void_type) {
7375 if (expr_type == InternalType.Null && rc.Compiler.IsRuntimeBinder)
7376 rc.Report.Error (Report.RuntimeErrorId, loc, "Cannot perform member binding on `null' value");
7378 Unary.Error_OperatorCannotBeApplied (rc, loc, ".", expr_type);
7382 var current_type = rc.CurrentType;
7383 var lookup_arity = Arity;
7384 bool errorMode = false;
7385 Expression member_lookup;
7387 member_lookup = MemberLookup (errorMode ? null : rc, current_type, expr_type, Name, lookup_arity, invocableOnly, loc);
7388 if (member_lookup == null) {
7390 // Try to look for extension method when member lookup failed
7392 if (MethodGroupExpr.IsExtensionMethodArgument (expr)) {
7393 NamespaceEntry scope = null;
7394 var methods = rc.LookupExtensionMethod (expr_type, Name, lookup_arity, ref scope);
7395 if (methods != null) {
7396 var emg = new ExtensionMethodGroupExpr (methods, scope, expr, loc);
7397 if (HasTypeArguments) {
7398 if (!targs.Resolve (rc))
7401 emg.SetTypeArguments (rc, targs);
7404 // TODO: Should it really skip the checks bellow
7405 return emg.Resolve (rc);
7411 if (member_lookup == null) {
7412 if (expr is TypeExpr)
7413 base.Error_TypeDoesNotContainDefinition (rc, expr_type, Name);
7415 Error_TypeDoesNotContainDefinition (rc, expr_type, Name);
7420 if (member_lookup is MethodGroupExpr) {
7421 // Leave it to overload resolution to report correct error
7423 // TODO: rc.SymbolRelatedToPreviousError
7424 ErrorIsInaccesible (rc, member_lookup.GetSignatureForError (), loc);
7429 if (member_lookup != null)
7432 current_type = null;
7434 invocableOnly = false;
7438 TypeExpr texpr = member_lookup as TypeExpr;
7439 if (texpr != null) {
7440 if (!(expr is TypeExpr)) {
7441 me = expr as MemberExpr;
7442 if (me == null || me.ProbeIdenticalTypeName (rc, expr, sn) == expr) {
7443 rc.Report.Error (572, loc, "`{0}': cannot reference a type through an expression; try `{1}' instead",
7444 Name, member_lookup.GetSignatureForError ());
7449 if (!texpr.Type.IsAccessible (rc.CurrentType)) {
7450 rc.Report.SymbolRelatedToPreviousError (member_lookup.Type);
7451 ErrorIsInaccesible (rc, member_lookup.Type.GetSignatureForError (), loc);
7455 if (HasTypeArguments) {
7456 return new GenericTypeExpr (member_lookup.Type, targs, loc);
7459 return member_lookup;
7462 me = member_lookup as MemberExpr;
7464 if (sn != null && me.IsStatic)
7465 expr = me.ProbeIdenticalTypeName (rc, expr, sn);
7467 me = me.ResolveMemberAccess (rc, expr, sn);
7470 if (!targs.Resolve (rc))
7473 me.SetTypeArguments (rc, targs);
7476 if (sn != null && (!TypeManager.IsValueType (expr_type) || me is PropertyExpr)) {
7477 if (me.IsInstance) {
7478 LocalVariableReference var = expr as LocalVariableReference;
7479 if (var != null && !var.VerifyAssigned (rc))
7487 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
7489 return ResolveNamespaceOrType (ec, silent);
7492 public FullNamedExpression ResolveNamespaceOrType (IMemberContext rc, bool silent)
7494 FullNamedExpression expr_resolved = expr.ResolveAsTypeStep (rc, silent);
7496 if (expr_resolved == null)
7499 Namespace ns = expr_resolved as Namespace;
7501 FullNamedExpression retval = ns.Lookup (rc.Compiler, Name, Arity, loc);
7503 if (retval == null) {
7505 ns.Error_NamespaceDoesNotExist (loc, Name, Arity, rc);
7506 } else if (HasTypeArguments) {
7507 retval = new GenericTypeExpr (retval.Type, targs, loc).ResolveAsTypeStep (rc, silent);
7513 TypeExpr tnew_expr = expr_resolved.ResolveAsTypeTerminal (rc, false);
7514 if (tnew_expr == null)
7517 TypeSpec expr_type = tnew_expr.Type;
7518 if (TypeManager.IsGenericParameter (expr_type)) {
7519 rc.Compiler.Report.Error (704, loc, "A nested type cannot be specified through a type parameter `{0}'",
7520 tnew_expr.GetSignatureForError ());
7524 var nested = MemberCache.FindNestedType (expr_type, Name, Arity);
7525 if (nested == null) {
7529 Error_IdentifierNotFound (rc, expr_type, Name);
7533 if (!nested.IsAccessible (rc.CurrentType ?? InternalType.FakeInternalType)) {
7534 ErrorIsInaccesible (rc, nested.GetSignatureForError (), loc);
7539 if (HasTypeArguments) {
7540 texpr = new GenericTypeExpr (nested, targs, loc);
7542 texpr = new GenericOpenTypeExpr (nested, loc);
7545 texpr = new TypeExpression (nested, loc);
7548 return texpr.ResolveAsTypeStep (rc, false);
7551 protected virtual void Error_IdentifierNotFound (IMemberContext rc, TypeSpec expr_type, string identifier)
7553 var nested = MemberCache.FindNestedType (expr_type, Name, -System.Math.Max (1, Arity));
7555 if (nested != null) {
7556 Error_TypeArgumentsCannotBeUsed (rc.Compiler.Report, expr.Location, nested, Arity);
7560 var any_other_member = MemberLookup (null, rc.CurrentType, expr_type, Name, 0, false, loc);
7561 if (any_other_member != null) {
7562 any_other_member.Error_UnexpectedKind (rc.Compiler.Report, null, "type", loc);
7566 rc.Compiler.Report.Error (426, loc, "The nested type `{0}' does not exist in the type `{1}'",
7567 Name, expr_type.GetSignatureForError ());
7570 protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
7572 if (RootContext.Version > LanguageVersion.ISO_2 && !ec.Compiler.IsRuntimeBinder && MethodGroupExpr.IsExtensionMethodArgument (expr)) {
7573 ec.Report.Error (1061, loc,
7574 "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?)",
7575 type.GetSignatureForError (), name);
7579 base.Error_TypeDoesNotContainDefinition (ec, type, name);
7582 public override string GetSignatureForError ()
7584 return expr.GetSignatureForError () + "." + base.GetSignatureForError ();
7587 protected override void CloneTo (CloneContext clonectx, Expression t)
7589 MemberAccess target = (MemberAccess) t;
7591 target.expr = expr.Clone (clonectx);
7596 /// Implements checked expressions
7598 public class CheckedExpr : Expression {
7600 public Expression Expr;
7602 public CheckedExpr (Expression e, Location l)
7608 public override Expression CreateExpressionTree (ResolveContext ec)
7610 using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
7611 return Expr.CreateExpressionTree (ec);
7614 protected override Expression DoResolve (ResolveContext ec)
7616 using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
7617 Expr = Expr.Resolve (ec);
7622 if (Expr is Constant || Expr is MethodGroupExpr || Expr is AnonymousMethodExpression || Expr is DefaultValueExpression)
7625 eclass = Expr.eclass;
7630 public override void Emit (EmitContext ec)
7632 using (ec.With (EmitContext.Options.AllCheckStateFlags, true))
7636 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
7638 using (ec.With (EmitContext.Options.AllCheckStateFlags, true))
7639 Expr.EmitBranchable (ec, target, on_true);
7642 public override SLE.Expression MakeExpression (BuilderContext ctx)
7644 using (ctx.With (BuilderContext.Options.AllCheckStateFlags, true)) {
7645 return Expr.MakeExpression (ctx);
7649 protected override void CloneTo (CloneContext clonectx, Expression t)
7651 CheckedExpr target = (CheckedExpr) t;
7653 target.Expr = Expr.Clone (clonectx);
7658 /// Implements the unchecked expression
7660 public class UnCheckedExpr : Expression {
7662 public Expression Expr;
7664 public UnCheckedExpr (Expression e, Location l)
7670 public override Expression CreateExpressionTree (ResolveContext ec)
7672 using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
7673 return Expr.CreateExpressionTree (ec);
7676 protected override Expression DoResolve (ResolveContext ec)
7678 using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
7679 Expr = Expr.Resolve (ec);
7684 if (Expr is Constant || Expr is MethodGroupExpr || Expr is AnonymousMethodExpression || Expr is DefaultValueExpression)
7687 eclass = Expr.eclass;
7692 public override void Emit (EmitContext ec)
7694 using (ec.With (EmitContext.Options.AllCheckStateFlags, false))
7698 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
7700 using (ec.With (EmitContext.Options.AllCheckStateFlags, false))
7701 Expr.EmitBranchable (ec, target, on_true);
7704 protected override void CloneTo (CloneContext clonectx, Expression t)
7706 UnCheckedExpr target = (UnCheckedExpr) t;
7708 target.Expr = Expr.Clone (clonectx);
7713 /// An Element Access expression.
7715 /// During semantic analysis these are transformed into
7716 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7718 public class ElementAccess : Expression {
7719 public Arguments Arguments;
7720 public Expression Expr;
7722 public ElementAccess (Expression e, Arguments args, Location loc)
7726 this.Arguments = args;
7730 // We perform some simple tests, and then to "split" the emit and store
7731 // code we create an instance of a different class, and return that.
7733 Expression CreateAccessExpression (ResolveContext ec)
7736 return (new ArrayAccess (this, loc));
7739 return MakePointerAccess (ec, type);
7741 FieldExpr fe = Expr as FieldExpr;
7743 var ff = fe.Spec as FixedFieldSpec;
7745 return MakePointerAccess (ec, ff.ElementType);
7749 var indexers = MemberCache.FindMembers (type, MemberCache.IndexerNameAlias, false);
7750 if (indexers != null || type == InternalType.Dynamic) {
7751 return new IndexerExpr (indexers, this);
7754 ec.Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
7755 type.GetSignatureForError ());
7759 public override Expression CreateExpressionTree (ResolveContext ec)
7761 Arguments args = Arguments.CreateForExpressionTree (ec, Arguments,
7762 Expr.CreateExpressionTree (ec));
7764 return CreateExpressionFactoryCall (ec, "ArrayIndex", args);
7767 Expression MakePointerAccess (ResolveContext ec, TypeSpec type)
7769 if (Arguments.Count != 1){
7770 ec.Report.Error (196, loc, "A pointer must be indexed by only one value");
7774 if (Arguments [0] is NamedArgument)
7775 Error_NamedArgument ((NamedArgument) Arguments[0], ec.Report);
7777 Expression p = new PointerArithmetic (Binary.Operator.Addition, Expr, Arguments [0].Expr.Resolve (ec), type, loc);
7778 return new Indirection (p, loc);
7781 protected override Expression DoResolve (ResolveContext ec)
7783 Expr = Expr.Resolve (ec);
7789 // TODO: Create 1 result for Resolve and ResolveLValue ?
7790 var res = CreateAccessExpression (ec);
7794 return res.Resolve (ec);
7797 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
7799 Expr = Expr.Resolve (ec);
7805 var res = CreateAccessExpression (ec);
7809 return res.ResolveLValue (ec, right_side);
7812 public override void Emit (EmitContext ec)
7814 throw new Exception ("Should never be reached");
7817 public static void Error_NamedArgument (NamedArgument na, Report Report)
7819 Report.Error (1742, na.Location, "An element access expression cannot use named argument");
7822 public override string GetSignatureForError ()
7824 return Expr.GetSignatureForError ();
7827 protected override void CloneTo (CloneContext clonectx, Expression t)
7829 ElementAccess target = (ElementAccess) t;
7831 target.Expr = Expr.Clone (clonectx);
7832 if (Arguments != null)
7833 target.Arguments = Arguments.Clone (clonectx);
7838 /// Implements array access
7840 public class ArrayAccess : Expression, IDynamicAssign, IMemoryLocation {
7842 // Points to our "data" repository
7846 LocalTemporary temp;
7850 public ArrayAccess (ElementAccess ea_data, Location l)
7856 public override Expression CreateExpressionTree (ResolveContext ec)
7858 return ea.CreateExpressionTree (ec);
7861 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
7863 return DoResolve (ec);
7866 protected override Expression DoResolve (ResolveContext ec)
7868 // dynamic is used per argument in ConvertExpressionToArrayIndex case
7870 ea.Arguments.Resolve (ec, out dynamic);
7872 var ac = ea.Expr.Type as ArrayContainer;
7873 int rank = ea.Arguments.Count;
7874 if (ac.Rank != rank) {
7875 ec.Report.Error (22, ea.Location, "Wrong number of indexes `{0}' inside [], expected `{1}'",
7876 rank.ToString (), ac.Rank.ToString ());
7881 if (type.IsPointer && !ec.IsUnsafe) {
7882 UnsafeError (ec, ea.Location);
7885 foreach (Argument a in ea.Arguments) {
7886 if (a is NamedArgument)
7887 ElementAccess.Error_NamedArgument ((NamedArgument) a, ec.Report);
7889 a.Expr = ConvertExpressionToArrayIndex (ec, a.Expr);
7892 eclass = ExprClass.Variable;
7897 protected override void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
7899 ec.Report.Warning (251, 2, loc, "Indexing an array with a negative index (array indices always start at zero)");
7903 // Load the array arguments into the stack.
7905 void LoadArrayAndArguments (EmitContext ec)
7909 for (int i = 0; i < ea.Arguments.Count; ++i) {
7910 ea.Arguments [i].Emit (ec);
7914 public void Emit (EmitContext ec, bool leave_copy)
7916 var ac = ea.Expr.Type as ArrayContainer;
7919 ec.EmitLoadFromPtr (type);
7921 LoadArrayAndArguments (ec);
7922 ec.EmitArrayLoad (ac);
7926 ec.Emit (OpCodes.Dup);
7927 temp = new LocalTemporary (this.type);
7932 public override void Emit (EmitContext ec)
7937 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
7939 var ac = (ArrayContainer) ea.Expr.Type;
7940 TypeSpec t = source.Type;
7941 prepared = prepare_for_load;
7944 AddressOf (ec, AddressOp.LoadStore);
7945 ec.Emit (OpCodes.Dup);
7947 LoadArrayAndArguments (ec);
7950 // If we are dealing with a struct, get the
7951 // address of it, so we can store it.
7953 // The stobj opcode used by value types will need
7954 // an address on the stack, not really an array/array
7957 if (ac.Rank == 1 && TypeManager.IsStruct (t) &&
7958 (!TypeManager.IsBuiltinOrEnum (t) ||
7959 t == TypeManager.decimal_type)) {
7961 ec.Emit (OpCodes.Ldelema, t);
7967 ec.Emit (OpCodes.Dup);
7968 temp = new LocalTemporary (this.type);
7973 ec.EmitStoreFromPtr (t);
7975 ec.EmitArrayStore (ac);
7984 public void EmitNew (EmitContext ec, New source, bool leave_copy)
7986 if (!source.Emit (ec, this)) {
7988 throw new NotImplementedException ();
7993 throw new NotImplementedException ();
7996 public void AddressOf (EmitContext ec, AddressOp mode)
7998 var ac = (ArrayContainer) ea.Expr.Type;
8000 LoadArrayAndArguments (ec);
8001 ec.EmitArrayAddress (ac);
8004 public SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
8007 return SLE.Expression.ArrayAccess (
8008 ea.Expr.MakeExpression (ctx),
8009 Arguments.MakeExpression (ea.Arguments, ctx));
8011 throw new NotImplementedException ();
8015 public override SLE.Expression MakeExpression (BuilderContext ctx)
8017 return SLE.Expression.ArrayIndex (
8018 ea.Expr.MakeExpression (ctx),
8019 Arguments.MakeExpression (ea.Arguments, ctx));
8024 // Indexer access expression
8026 class IndexerExpr : PropertyOrIndexerExpr<IndexerSpec>, OverloadResolver.IBaseMembersProvider
8028 LocalTemporary prepared_value;
8029 IList<MemberSpec> indexers;
8030 Arguments arguments;
8032 public IndexerExpr (IList<MemberSpec> indexers, ElementAccess ea)
8033 : base (ea.Location)
8035 this.indexers = indexers;
8036 this.InstanceExpression = ea.Expr;
8037 this.arguments = ea.Arguments;
8041 protected override TypeSpec DeclaringType {
8043 return best_candidate.DeclaringType;
8047 public override bool IsInstance {
8053 public override bool IsStatic {
8059 public override string Name {
8067 public override Expression CreateExpressionTree (ResolveContext ec)
8069 Arguments args = Arguments.CreateForExpressionTree (ec, arguments,
8070 InstanceExpression.CreateExpressionTree (ec),
8071 new TypeOfMethod (Getter, loc));
8073 return CreateExpressionFactoryCall (ec, "Call", args);
8076 public override void Emit (EmitContext ec, bool leave_copy)
8079 prepared_value.Emit (ec);
8081 Invocation.EmitCall (ec, InstanceExpression, Getter, arguments, loc, false, false);
8085 ec.Emit (OpCodes.Dup);
8086 temp = new LocalTemporary (Type);
8091 public override void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8093 prepared = prepare_for_load;
8094 Expression value = source;
8097 Invocation.EmitCall (ec, InstanceExpression, Getter,
8098 arguments, loc, true, false);
8100 prepared_value = new LocalTemporary (type);
8101 prepared_value.Store (ec);
8103 prepared_value.Release (ec);
8106 ec.Emit (OpCodes.Dup);
8107 temp = new LocalTemporary (Type);
8110 } else if (leave_copy) {
8111 temp = new LocalTemporary (Type);
8118 arguments.Add (new Argument (value));
8120 Invocation.EmitCall (ec, InstanceExpression, Setter, arguments, loc, false, prepared);
8128 public override string GetSignatureForError ()
8130 return best_candidate.GetSignatureForError ();
8133 public override SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
8135 var value = new[] { source.MakeExpression (ctx) };
8136 var args = Arguments.MakeExpression (arguments, ctx).Concat (value);
8138 return SLE.Expression.Block (
8139 SLE.Expression.Call (InstanceExpression.MakeExpression (ctx), (MethodInfo) Setter.GetMetaInfo (), args),
8142 return args.First ();
8146 public override SLE.Expression MakeExpression (BuilderContext ctx)
8148 var args = Arguments.MakeExpression (arguments, ctx);
8149 return SLE.Expression.Call (InstanceExpression.MakeExpression (ctx), (MethodInfo) Getter.GetMetaInfo (), args);
8152 protected override Expression OverloadResolve (ResolveContext rc, Expression right_side)
8154 if (best_candidate != null)
8157 eclass = ExprClass.IndexerAccess;
8160 arguments.Resolve (rc, out dynamic);
8162 if (indexers == null && InstanceExpression.Type == InternalType.Dynamic) {
8165 var res = new OverloadResolver (indexers, OverloadResolver.Restrictions.None, loc);
8166 res.BaseMembersProvider = this;
8168 // TODO: Do I need 2 argument sets?
8169 best_candidate = res.ResolveMember<IndexerSpec> (rc, ref arguments);
8170 if (best_candidate != null)
8171 type = best_candidate.MemberType;
8172 else if (!res.BestCandidateIsDynamic)
8177 // It has dynamic arguments
8180 Arguments args = new Arguments (arguments.Count + 1);
8182 rc.Report.Error (1972, loc,
8183 "The indexer base access cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access");
8185 args.Add (new Argument (InstanceExpression));
8187 args.AddRange (arguments);
8189 best_candidate = null;
8190 return new DynamicIndexBinder (args, loc);
8193 ResolveInstanceExpression (rc);
8194 CheckProtectedMemberAccess (rc, best_candidate);
8198 protected override void CloneTo (CloneContext clonectx, Expression t)
8200 IndexerExpr target = (IndexerExpr) t;
8202 if (arguments != null)
8203 target.arguments = arguments.Clone (clonectx);
8206 public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
8208 Error_TypeArgumentsCannotBeUsed (ec.Report, "indexer", GetSignatureForError (), loc);
8211 #region IBaseMembersProvider Members
8213 IList<MemberSpec> OverloadResolver.IBaseMembersProvider.GetBaseMembers (TypeSpec baseType)
8215 return baseType == null ? null : MemberCache.FindMembers (baseType, MemberCache.IndexerNameAlias, false);
8218 MethodGroupExpr OverloadResolver.IBaseMembersProvider.LookupExtensionMethod (ResolveContext rc)
8227 // A base access expression
8229 public class BaseThis : This
8231 public BaseThis (Location loc)
8236 public BaseThis (TypeSpec type, Location loc)
8240 eclass = ExprClass.Variable;
8245 public override string Name {
8253 public override Expression CreateExpressionTree (ResolveContext ec)
8255 ec.Report.Error (831, loc, "An expression tree may not contain a base access");
8256 return base.CreateExpressionTree (ec);
8259 public override void Emit (EmitContext ec)
8263 if (ec.CurrentType.IsStruct) {
8264 ec.Emit (OpCodes.Ldobj, ec.CurrentType);
8265 ec.Emit (OpCodes.Box, ec.CurrentType);
8269 protected override void Error_ThisNotAvailable (ResolveContext ec)
8272 ec.Report.Error (1511, loc, "Keyword `base' is not available in a static method");
8274 ec.Report.Error (1512, loc, "Keyword `base' is not available in the current context");
8278 public override void ResolveBase (ResolveContext ec)
8280 base.ResolveBase (ec);
8281 type = ec.CurrentType.BaseType;
8286 /// This class exists solely to pass the Type around and to be a dummy
8287 /// that can be passed to the conversion functions (this is used by
8288 /// foreach implementation to typecast the object return value from
8289 /// get_Current into the proper type. All code has been generated and
8290 /// we only care about the side effect conversions to be performed
8292 /// This is also now used as a placeholder where a no-action expression
8293 /// is needed (the `New' class).
8295 public class EmptyExpression : Expression {
8296 public static readonly Expression Null = new EmptyExpression ();
8298 public class OutAccess : EmptyExpression
8300 public static readonly OutAccess Instance = new OutAccess ();
8302 public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
8304 rc.Report.Error (206, right_side.Location,
8305 "A property, indexer or dynamic member access may not be passed as `ref' or `out' parameter");
8311 public static readonly EmptyExpression LValueMemberAccess = new EmptyExpression ();
8312 public static readonly EmptyExpression LValueMemberOutAccess = new EmptyExpression ();
8313 public static readonly EmptyExpression UnaryAddress = new EmptyExpression ();
8314 public static readonly EmptyExpression EventAddition = new EmptyExpression ();
8315 public static readonly EmptyExpression EventSubtraction = new EmptyExpression ();
8316 public static readonly EmptyExpression MissingValue = new EmptyExpression (InternalType.FakeInternalType);
8318 static EmptyExpression temp = new EmptyExpression ();
8319 public static EmptyExpression Grab ()
8321 EmptyExpression retval = temp == null ? new EmptyExpression () : temp;
8326 public static void Release (EmptyExpression e)
8333 // FIXME: Don't set to object
8334 type = TypeManager.object_type;
8335 eclass = ExprClass.Value;
8336 loc = Location.Null;
8339 public EmptyExpression (TypeSpec t)
8342 eclass = ExprClass.Value;
8343 loc = Location.Null;
8346 public override Expression CreateExpressionTree (ResolveContext ec)
8348 throw new NotSupportedException ("ET");
8351 protected override Expression DoResolve (ResolveContext ec)
8356 public override void Emit (EmitContext ec)
8358 // nothing, as we only exist to not do anything.
8361 public override void EmitSideEffect (EmitContext ec)
8366 // This is just because we might want to reuse this bad boy
8367 // instead of creating gazillions of EmptyExpressions.
8368 // (CanImplicitConversion uses it)
8370 public void SetType (TypeSpec t)
8377 // Empty statement expression
8379 public sealed class EmptyExpressionStatement : ExpressionStatement
8381 public static readonly EmptyExpressionStatement Instance = new EmptyExpressionStatement ();
8383 private EmptyExpressionStatement ()
8385 loc = Location.Null;
8388 public override Expression CreateExpressionTree (ResolveContext ec)
8393 public override void EmitStatement (EmitContext ec)
8398 protected override Expression DoResolve (ResolveContext ec)
8400 eclass = ExprClass.Value;
8401 type = TypeManager.object_type;
8405 public override void Emit (EmitContext ec)
8411 public class UserCast : Expression {
8415 public UserCast (MethodSpec method, Expression source, Location l)
8417 this.method = method;
8418 this.source = source;
8419 type = method.ReturnType;
8423 public Expression Source {
8429 public override Expression CreateExpressionTree (ResolveContext ec)
8431 Arguments args = new Arguments (3);
8432 args.Add (new Argument (source.CreateExpressionTree (ec)));
8433 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
8434 args.Add (new Argument (new TypeOfMethod (method, loc)));
8435 return CreateExpressionFactoryCall (ec, "Convert", args);
8438 protected override Expression DoResolve (ResolveContext ec)
8440 ObsoleteAttribute oa = method.GetAttributeObsolete ();
8442 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
8444 eclass = ExprClass.Value;
8448 public override void Emit (EmitContext ec)
8451 ec.Emit (OpCodes.Call, method);
8454 public override string GetSignatureForError ()
8456 return TypeManager.CSharpSignature (method);
8459 public override SLE.Expression MakeExpression (BuilderContext ctx)
8461 return SLE.Expression.Convert (source.MakeExpression (ctx), type.GetMetaInfo (), (MethodInfo) method.GetMetaInfo ());
8466 // Holds additional type specifiers like ?, *, []
8468 public class ComposedTypeSpecifier
8470 public static readonly ComposedTypeSpecifier SingleDimension = new ComposedTypeSpecifier (1, Location.Null);
8472 public readonly int Dimension;
8473 public readonly Location Location;
8475 public ComposedTypeSpecifier (int specifier, Location loc)
8477 this.Dimension = specifier;
8478 this.Location = loc;
8482 public bool IsNullable {
8484 return Dimension == -1;
8488 public bool IsPointer {
8490 return Dimension == -2;
8494 public ComposedTypeSpecifier Next { get; set; }
8498 public static ComposedTypeSpecifier CreateArrayDimension (int dimension, Location loc)
8500 return new ComposedTypeSpecifier (dimension, loc);
8503 public static ComposedTypeSpecifier CreateNullable (Location loc)
8505 return new ComposedTypeSpecifier (-1, loc);
8508 public static ComposedTypeSpecifier CreatePointer (Location loc)
8510 return new ComposedTypeSpecifier (-2, loc);
8513 public string GetSignatureForError ()
8518 ArrayContainer.GetPostfixSignature (Dimension);
8520 return Next != null ? s + Next.GetSignatureForError () : s;
8525 // This class is used to "construct" the type during a typecast
8526 // operation. Since the Type.GetType class in .NET can parse
8527 // the type specification, we just use this to construct the type
8528 // one bit at a time.
8530 public class ComposedCast : TypeExpr {
8531 FullNamedExpression left;
8532 ComposedTypeSpecifier spec;
8534 public ComposedCast (FullNamedExpression left, ComposedTypeSpecifier spec)
8537 throw new ArgumentNullException ("spec");
8541 this.loc = spec.Location;
8544 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
8546 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec, false);
8551 eclass = ExprClass.Type;
8553 var single_spec = spec;
8555 if (single_spec.IsNullable) {
8556 lexpr = new Nullable.NullableType (lexpr, loc);
8557 lexpr = lexpr.ResolveAsTypeTerminal (ec, false);
8561 single_spec = single_spec.Next;
8562 } else if (single_spec.IsPointer) {
8563 if (!TypeManager.VerifyUnmanaged (ec.Compiler, type, loc))
8567 UnsafeError (ec.Compiler.Report, loc);
8570 type = PointerContainer.MakeType (type);
8571 single_spec = single_spec.Next;
8574 if (single_spec != null && single_spec.Dimension > 0) {
8575 if (TypeManager.IsSpecialType (type)) {
8576 ec.Compiler.Report.Error (611, loc, "Array elements cannot be of type `{0}'", type.GetSignatureForError ());
8577 } else if (type.IsStatic) {
8578 ec.Compiler.Report.SymbolRelatedToPreviousError (type);
8579 ec.Compiler.Report.Error (719, loc, "Array elements cannot be of static type `{0}'",
8580 type.GetSignatureForError ());
8582 MakeArray (single_spec);
8589 void MakeArray (ComposedTypeSpecifier spec)
8591 if (spec.Next != null)
8592 MakeArray (spec.Next);
8594 type = ArrayContainer.MakeType (type, spec.Dimension);
8597 public override string GetSignatureForError ()
8599 return left.GetSignatureForError () + spec.GetSignatureForError ();
8603 public class FixedBufferPtr : Expression {
8606 public FixedBufferPtr (Expression array, TypeSpec array_type, Location l)
8611 type = PointerContainer.MakeType (array_type);
8612 eclass = ExprClass.Value;
8615 public override Expression CreateExpressionTree (ResolveContext ec)
8617 Error_PointerInsideExpressionTree (ec);
8621 public override void Emit(EmitContext ec)
8626 protected override Expression DoResolve (ResolveContext ec)
8629 // We are born fully resolved
8637 // This class is used to represent the address of an array, used
8638 // only by the Fixed statement, this generates "&a [0]" construct
8639 // for fixed (char *pa = a)
8641 public class ArrayPtr : FixedBufferPtr {
8642 TypeSpec array_type;
8644 public ArrayPtr (Expression array, TypeSpec array_type, Location l):
8645 base (array, array_type, l)
8647 this.array_type = array_type;
8650 public override void Emit (EmitContext ec)
8655 ec.Emit (OpCodes.Ldelema, array_type);
8660 // Encapsulates a conversion rules required for array indexes
8662 public class ArrayIndexCast : TypeCast
8664 public ArrayIndexCast (Expression expr)
8665 : base (expr, TypeManager.int32_type)
8667 if (expr.Type == TypeManager.int32_type)
8668 throw new ArgumentException ("unnecessary array index conversion");
8671 public override Expression CreateExpressionTree (ResolveContext ec)
8673 using (ec.Set (ResolveContext.Options.CheckedScope)) {
8674 return base.CreateExpressionTree (ec);
8678 public override void Emit (EmitContext ec)
8682 var expr_type = child.Type;
8684 if (expr_type == TypeManager.uint32_type)
8685 ec.Emit (OpCodes.Conv_U);
8686 else if (expr_type == TypeManager.int64_type)
8687 ec.Emit (OpCodes.Conv_Ovf_I);
8688 else if (expr_type == TypeManager.uint64_type)
8689 ec.Emit (OpCodes.Conv_Ovf_I_Un);
8691 throw new InternalErrorException ("Cannot emit cast to unknown array element type", type);
8696 // Implements the `stackalloc' keyword
8698 public class StackAlloc : Expression {
8703 public StackAlloc (Expression type, Expression count, Location l)
8710 public override Expression CreateExpressionTree (ResolveContext ec)
8712 throw new NotSupportedException ("ET");
8715 protected override Expression DoResolve (ResolveContext ec)
8717 count = count.Resolve (ec);
8721 if (count.Type != TypeManager.uint32_type){
8722 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8727 Constant c = count as Constant;
8728 if (c != null && c.IsNegative) {
8729 ec.Report.Error (247, loc, "Cannot use a negative size with stackalloc");
8732 if (ec.HasAny (ResolveContext.Options.CatchScope | ResolveContext.Options.FinallyScope)) {
8733 ec.Report.Error (255, loc, "Cannot use stackalloc in finally or catch");
8736 TypeExpr texpr = t.ResolveAsTypeTerminal (ec, false);
8742 if (!TypeManager.VerifyUnmanaged (ec.Compiler, otype, loc))
8745 type = PointerContainer.MakeType (otype);
8746 eclass = ExprClass.Value;
8751 public override void Emit (EmitContext ec)
8753 int size = GetTypeSize (otype);
8758 ec.Emit (OpCodes.Sizeof, otype);
8762 ec.Emit (OpCodes.Mul_Ovf_Un);
8763 ec.Emit (OpCodes.Localloc);
8766 protected override void CloneTo (CloneContext clonectx, Expression t)
8768 StackAlloc target = (StackAlloc) t;
8769 target.count = count.Clone (clonectx);
8770 target.t = t.Clone (clonectx);
8775 // An object initializer expression
8777 public class ElementInitializer : Assign
8779 public readonly string Name;
8781 public ElementInitializer (string name, Expression initializer, Location loc)
8782 : base (null, initializer, loc)
8787 protected override void CloneTo (CloneContext clonectx, Expression t)
8789 ElementInitializer target = (ElementInitializer) t;
8790 target.source = source.Clone (clonectx);
8793 public override Expression CreateExpressionTree (ResolveContext ec)
8795 Arguments args = new Arguments (2);
8796 FieldExpr fe = target as FieldExpr;
8798 args.Add (new Argument (fe.CreateTypeOfExpression ()));
8800 args.Add (new Argument (((PropertyExpr)target).CreateSetterTypeOfExpression ()));
8802 args.Add (new Argument (source.CreateExpressionTree (ec)));
8803 return CreateExpressionFactoryCall (ec,
8804 source is CollectionOrObjectInitializers ? "ListBind" : "Bind",
8808 protected override Expression DoResolve (ResolveContext ec)
8811 return EmptyExpressionStatement.Instance;
8813 var t = ec.CurrentInitializerVariable.Type;
8814 if (t == InternalType.Dynamic) {
8815 Arguments args = new Arguments (1);
8816 args.Add (new Argument (ec.CurrentInitializerVariable));
8817 target = new DynamicMemberBinder (Name, args, loc);
8820 var member = MemberLookup (ec, ec.CurrentType, t, Name, 0, false, loc);
8821 if (member == null) {
8822 member = Expression.MemberLookup (null, ec.CurrentType, t, Name, 0, false, loc);
8824 if (member != null) {
8825 // TODO: ec.Report.SymbolRelatedToPreviousError (member);
8826 ErrorIsInaccesible (ec, member.GetSignatureForError (), loc);
8831 if (member == null) {
8832 Error_TypeDoesNotContainDefinition (ec, loc, t, Name);
8836 if (!(member is PropertyExpr || member is FieldExpr)) {
8837 ec.Report.Error (1913, loc,
8838 "Member `{0}' cannot be initialized. An object initializer may only be used for fields, or properties",
8839 member.GetSignatureForError ());
8844 var me = member as MemberExpr;
8846 ec.Report.Error (1914, loc,
8847 "Static field or property `{0}' cannot be assigned in an object initializer",
8848 me.GetSignatureForError ());
8852 me.InstanceExpression = ec.CurrentInitializerVariable;
8855 if (source is CollectionOrObjectInitializers) {
8856 Expression previous = ec.CurrentInitializerVariable;
8857 ec.CurrentInitializerVariable = target;
8858 source = source.Resolve (ec);
8859 ec.CurrentInitializerVariable = previous;
8863 eclass = source.eclass;
8868 return base.DoResolve (ec);
8871 public override void EmitStatement (EmitContext ec)
8873 if (source is CollectionOrObjectInitializers)
8876 base.EmitStatement (ec);
8881 // A collection initializer expression
8883 class CollectionElementInitializer : Invocation
8885 public class ElementInitializerArgument : Argument
8887 public ElementInitializerArgument (Expression e)
8893 sealed class AddMemberAccess : MemberAccess
8895 public AddMemberAccess (Expression expr, Location loc)
8896 : base (expr, "Add", loc)
8900 protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
8902 if (TypeManager.HasElementType (type))
8905 base.Error_TypeDoesNotContainDefinition (ec, type, name);
8909 public CollectionElementInitializer (Expression argument)
8910 : base (null, new Arguments (1))
8912 base.arguments.Add (new ElementInitializerArgument (argument));
8913 this.loc = argument.Location;
8916 public CollectionElementInitializer (List<Expression> arguments, Location loc)
8917 : base (null, new Arguments (arguments.Count))
8919 foreach (Expression e in arguments)
8920 base.arguments.Add (new ElementInitializerArgument (e));
8925 public override Expression CreateExpressionTree (ResolveContext ec)
8927 Arguments args = new Arguments (2);
8928 args.Add (new Argument (mg.CreateExpressionTree (ec)));
8930 var expr_initializers = new ArrayInitializer (arguments.Count, loc);
8931 foreach (Argument a in arguments)
8932 expr_initializers.Add (a.CreateExpressionTree (ec));
8934 args.Add (new Argument (new ArrayCreation (
8935 CreateExpressionTypeExpression (ec, loc), expr_initializers, loc)));
8936 return CreateExpressionFactoryCall (ec, "ElementInit", args);
8939 protected override void CloneTo (CloneContext clonectx, Expression t)
8941 CollectionElementInitializer target = (CollectionElementInitializer) t;
8942 if (arguments != null)
8943 target.arguments = arguments.Clone (clonectx);
8946 protected override Expression DoResolve (ResolveContext ec)
8948 base.expr = new AddMemberAccess (ec.CurrentInitializerVariable, loc);
8950 return base.DoResolve (ec);
8955 // A block of object or collection initializers
8957 public class CollectionOrObjectInitializers : ExpressionStatement
8959 IList<Expression> initializers;
8960 bool is_collection_initialization;
8962 public static readonly CollectionOrObjectInitializers Empty =
8963 new CollectionOrObjectInitializers (Array.AsReadOnly (new Expression [0]), Location.Null);
8965 public CollectionOrObjectInitializers (IList<Expression> initializers, Location loc)
8967 this.initializers = initializers;
8971 public bool IsEmpty {
8973 return initializers.Count == 0;
8977 public bool IsCollectionInitializer {
8979 return is_collection_initialization;
8983 protected override void CloneTo (CloneContext clonectx, Expression target)
8985 CollectionOrObjectInitializers t = (CollectionOrObjectInitializers) target;
8987 t.initializers = new List<Expression> (initializers.Count);
8988 foreach (var e in initializers)
8989 t.initializers.Add (e.Clone (clonectx));
8992 public override Expression CreateExpressionTree (ResolveContext ec)
8994 var expr_initializers = new ArrayInitializer (initializers.Count, loc);
8995 foreach (Expression e in initializers) {
8996 Expression expr = e.CreateExpressionTree (ec);
8998 expr_initializers.Add (expr);
9001 return new ImplicitlyTypedArrayCreation (expr_initializers, loc);
9004 protected override Expression DoResolve (ResolveContext ec)
9006 List<string> element_names = null;
9007 for (int i = 0; i < initializers.Count; ++i) {
9008 Expression initializer = initializers [i];
9009 ElementInitializer element_initializer = initializer as ElementInitializer;
9012 if (element_initializer != null) {
9013 element_names = new List<string> (initializers.Count);
9014 element_names.Add (element_initializer.Name);
9015 } else if (initializer is CompletingExpression){
9016 initializer.Resolve (ec);
9017 throw new InternalErrorException ("This line should never be reached");
9019 if (!ec.CurrentInitializerVariable.Type.ImplementsInterface (TypeManager.ienumerable_type)) {
9020 ec.Report.Error (1922, loc, "A field or property `{0}' cannot be initialized with a collection " +
9021 "object initializer because type `{1}' does not implement `{2}' interface",
9022 ec.CurrentInitializerVariable.GetSignatureForError (),
9023 TypeManager.CSharpName (ec.CurrentInitializerVariable.Type),
9024 TypeManager.CSharpName (TypeManager.ienumerable_type));
9027 is_collection_initialization = true;
9030 if (is_collection_initialization != (element_initializer == null)) {
9031 ec.Report.Error (747, initializer.Location, "Inconsistent `{0}' member declaration",
9032 is_collection_initialization ? "collection initializer" : "object initializer");
9036 if (!is_collection_initialization) {
9037 if (element_names.Contains (element_initializer.Name)) {
9038 ec.Report.Error (1912, element_initializer.Location,
9039 "An object initializer includes more than one member `{0}' initialization",
9040 element_initializer.Name);
9042 element_names.Add (element_initializer.Name);
9047 Expression e = initializer.Resolve (ec);
9048 if (e == EmptyExpressionStatement.Instance)
9049 initializers.RemoveAt (i--);
9051 initializers [i] = e;
9054 type = ec.CurrentInitializerVariable.Type;
9055 if (is_collection_initialization) {
9056 if (TypeManager.HasElementType (type)) {
9057 ec.Report.Error (1925, loc, "Cannot initialize object of type `{0}' with a collection initializer",
9058 TypeManager.CSharpName (type));
9062 eclass = ExprClass.Variable;
9066 public override void Emit (EmitContext ec)
9071 public override void EmitStatement (EmitContext ec)
9073 foreach (ExpressionStatement e in initializers)
9074 e.EmitStatement (ec);
9079 // New expression with element/object initializers
9081 public class NewInitialize : New
9084 // This class serves as a proxy for variable initializer target instances.
9085 // A real variable is assigned later when we resolve left side of an
9088 sealed class InitializerTargetExpression : Expression, IMemoryLocation
9090 NewInitialize new_instance;
9092 public InitializerTargetExpression (NewInitialize newInstance)
9094 this.type = newInstance.type;
9095 this.loc = newInstance.loc;
9096 this.eclass = newInstance.eclass;
9097 this.new_instance = newInstance;
9100 public override Expression CreateExpressionTree (ResolveContext ec)
9102 // Should not be reached
9103 throw new NotSupportedException ("ET");
9106 protected override Expression DoResolve (ResolveContext ec)
9111 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
9116 public override void Emit (EmitContext ec)
9118 Expression e = (Expression) new_instance.instance;
9122 #region IMemoryLocation Members
9124 public void AddressOf (EmitContext ec, AddressOp mode)
9126 new_instance.instance.AddressOf (ec, mode);
9132 CollectionOrObjectInitializers initializers;
9133 IMemoryLocation instance;
9135 public NewInitialize (FullNamedExpression requested_type, Arguments arguments, CollectionOrObjectInitializers initializers, Location l)
9136 : base (requested_type, arguments, l)
9138 this.initializers = initializers;
9141 protected override IMemoryLocation EmitAddressOf (EmitContext ec, AddressOp Mode)
9143 instance = base.EmitAddressOf (ec, Mode);
9145 if (!initializers.IsEmpty)
9146 initializers.Emit (ec);
9151 protected override void CloneTo (CloneContext clonectx, Expression t)
9153 base.CloneTo (clonectx, t);
9155 NewInitialize target = (NewInitialize) t;
9156 target.initializers = (CollectionOrObjectInitializers) initializers.Clone (clonectx);
9159 public override Expression CreateExpressionTree (ResolveContext ec)
9161 Arguments args = new Arguments (2);
9162 args.Add (new Argument (base.CreateExpressionTree (ec)));
9163 if (!initializers.IsEmpty)
9164 args.Add (new Argument (initializers.CreateExpressionTree (ec)));
9166 return CreateExpressionFactoryCall (ec,
9167 initializers.IsCollectionInitializer ? "ListInit" : "MemberInit",
9171 protected override Expression DoResolve (ResolveContext ec)
9173 Expression e = base.DoResolve (ec);
9177 Expression previous = ec.CurrentInitializerVariable;
9178 ec.CurrentInitializerVariable = new InitializerTargetExpression (this);
9179 initializers.Resolve (ec);
9180 ec.CurrentInitializerVariable = previous;
9184 public override bool Emit (EmitContext ec, IMemoryLocation target)
9186 bool left_on_stack = base.Emit (ec, target);
9188 if (initializers.IsEmpty)
9189 return left_on_stack;
9191 LocalTemporary temp = target as LocalTemporary;
9193 if (!left_on_stack) {
9194 VariableReference vr = target as VariableReference;
9196 // FIXME: This still does not work correctly for pre-set variables
9197 if (vr != null && vr.IsRef)
9198 target.AddressOf (ec, AddressOp.Load);
9200 ((Expression) target).Emit (ec);
9201 left_on_stack = true;
9204 temp = new LocalTemporary (type);
9211 initializers.Emit (ec);
9213 if (left_on_stack) {
9218 return left_on_stack;
9221 public override bool HasInitializer {
9223 return !initializers.IsEmpty;
9228 public class NewAnonymousType : New
9230 static readonly AnonymousTypeParameter[] EmptyParameters = new AnonymousTypeParameter[0];
9232 List<AnonymousTypeParameter> parameters;
9233 readonly TypeContainer parent;
9234 AnonymousTypeClass anonymous_type;
9236 public NewAnonymousType (List<AnonymousTypeParameter> parameters, TypeContainer parent, Location loc)
9237 : base (null, null, loc)
9239 this.parameters = parameters;
9240 this.parent = parent;
9243 protected override void CloneTo (CloneContext clonectx, Expression target)
9245 if (parameters == null)
9248 NewAnonymousType t = (NewAnonymousType) target;
9249 t.parameters = new List<AnonymousTypeParameter> (parameters.Count);
9250 foreach (AnonymousTypeParameter atp in parameters)
9251 t.parameters.Add ((AnonymousTypeParameter) atp.Clone (clonectx));
9254 AnonymousTypeClass CreateAnonymousType (ResolveContext ec, IList<AnonymousTypeParameter> parameters)
9256 AnonymousTypeClass type = parent.Module.Compiled.GetAnonymousType (parameters);
9260 type = AnonymousTypeClass.Create (ec.Compiler, parent, parameters, loc);
9266 type.ResolveTypeParameters ();
9269 if (ec.Report.Errors == 0)
9272 parent.Module.Compiled.AddAnonymousType (type);
9276 public override Expression CreateExpressionTree (ResolveContext ec)
9278 if (parameters == null)
9279 return base.CreateExpressionTree (ec);
9281 var init = new ArrayInitializer (parameters.Count, loc);
9282 foreach (Property p in anonymous_type.Properties)
9283 init.Add (new TypeOfMethod (MemberCache.GetMember (type, p.Get.Spec), loc));
9285 var ctor_args = new ArrayInitializer (Arguments.Count, loc);
9286 foreach (Argument a in Arguments)
9287 ctor_args.Add (a.CreateExpressionTree (ec));
9289 Arguments args = new Arguments (3);
9290 args.Add (new Argument (new TypeOfMethod (method, loc)));
9291 args.Add (new Argument (new ArrayCreation (TypeManager.expression_type_expr, ctor_args, loc)));
9292 args.Add (new Argument (new ImplicitlyTypedArrayCreation (init, loc)));
9294 return CreateExpressionFactoryCall (ec, "New", args);
9297 protected override Expression DoResolve (ResolveContext ec)
9299 if (ec.HasSet (ResolveContext.Options.ConstantScope)) {
9300 ec.Report.Error (836, loc, "Anonymous types cannot be used in this expression");
9304 if (parameters == null) {
9305 anonymous_type = CreateAnonymousType (ec, EmptyParameters);
9306 RequestedType = new TypeExpression (anonymous_type.Definition, loc);
9307 return base.DoResolve (ec);
9311 Arguments = new Arguments (parameters.Count);
9312 TypeExpression [] t_args = new TypeExpression [parameters.Count];
9313 for (int i = 0; i < parameters.Count; ++i) {
9314 Expression e = ((AnonymousTypeParameter) parameters [i]).Resolve (ec);
9320 Arguments.Add (new Argument (e));
9321 t_args [i] = new TypeExpression (e.Type, e.Location);
9327 anonymous_type = CreateAnonymousType (ec, parameters);
9328 if (anonymous_type == null)
9331 RequestedType = new GenericTypeExpr (anonymous_type.Definition, new TypeArguments (t_args), loc);
9332 return base.DoResolve (ec);
9336 public class AnonymousTypeParameter : ShimExpression
9338 public readonly string Name;
9340 public AnonymousTypeParameter (Expression initializer, string name, Location loc)
9341 : base (initializer)
9347 public AnonymousTypeParameter (Parameter parameter)
9348 : base (new SimpleName (parameter.Name, parameter.Location))
9350 this.Name = parameter.Name;
9351 this.loc = parameter.Location;
9354 public override bool Equals (object o)
9356 AnonymousTypeParameter other = o as AnonymousTypeParameter;
9357 return other != null && Name == other.Name;
9360 public override int GetHashCode ()
9362 return Name.GetHashCode ();
9365 protected override Expression DoResolve (ResolveContext ec)
9367 Expression e = expr.Resolve (ec);
9371 if (e.eclass == ExprClass.MethodGroup) {
9372 Error_InvalidInitializer (ec, e.ExprClassName);
9377 if (type == TypeManager.void_type || type == InternalType.Null ||
9378 type == InternalType.AnonymousMethod || type.IsPointer) {
9379 Error_InvalidInitializer (ec, e.GetSignatureForError ());
9386 protected virtual void Error_InvalidInitializer (ResolveContext ec, string initializer)
9388 ec.Report.Error (828, loc, "An anonymous type property `{0}' cannot be initialized with `{1}'",