2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Copyright 2001, 2002, 2003 Ximian, Inc.
9 // Copyright 2003-2008 Novell, Inc.
12 namespace Mono.CSharp {
14 using System.Collections.Generic;
15 using System.Reflection;
16 using System.Reflection.Emit;
19 using SLE = System.Linq.Expressions;
22 // This is an user operator expression, automatically created during
25 public class UserOperatorCall : Expression {
26 protected readonly Arguments arguments;
27 protected readonly MethodSpec oper;
28 readonly Func<ResolveContext, Expression, Expression> expr_tree;
30 public UserOperatorCall (MethodSpec oper, Arguments args, Func<ResolveContext, Expression, Expression> expr_tree, Location loc)
33 this.arguments = args;
34 this.expr_tree = expr_tree;
36 type = oper.ReturnType;
37 eclass = ExprClass.Value;
41 public override Expression CreateExpressionTree (ResolveContext ec)
43 if (expr_tree != null)
44 return expr_tree (ec, new TypeOfMethod (oper, loc));
46 Arguments args = Arguments.CreateForExpressionTree (ec, arguments,
47 new NullLiteral (loc),
48 new TypeOfMethod (oper, loc));
50 return CreateExpressionFactoryCall (ec, "Call", args);
53 protected override void CloneTo (CloneContext context, Expression target)
58 protected override Expression DoResolve (ResolveContext ec)
61 // We are born fully resolved
66 public override void Emit (EmitContext ec)
68 Invocation.EmitCall (ec, null, oper, arguments, loc);
71 public override SLE.Expression MakeExpression (BuilderContext ctx)
73 var method = oper.GetMetaInfo () as MethodInfo;
74 return SLE.Expression.Call (method, Arguments.MakeExpression (arguments, ctx));
78 public class ParenthesizedExpression : ShimExpression
80 public ParenthesizedExpression (Expression expr)
86 protected override Expression DoResolve (ResolveContext ec)
88 return expr.Resolve (ec);
91 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
93 return expr.DoResolveLValue (ec, right_side);
98 // Unary implements unary expressions.
100 public class Unary : Expression
102 public enum Operator : byte {
103 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
107 static TypeSpec[][] predefined_operators;
109 public readonly Operator Oper;
110 public Expression Expr;
111 Expression enum_conversion;
113 public Unary (Operator op, Expression expr, Location loc)
121 // This routine will attempt to simplify the unary expression when the
122 // argument is a constant.
124 Constant TryReduceConstant (ResolveContext ec, Constant e)
126 if (e is EmptyConstantCast)
127 return TryReduceConstant (ec, ((EmptyConstantCast) e).child);
129 if (e is SideEffectConstant) {
130 Constant r = TryReduceConstant (ec, ((SideEffectConstant) e).value);
131 return r == null ? null : new SideEffectConstant (r, e, r.Location);
134 TypeSpec expr_type = e.Type;
137 case Operator.UnaryPlus:
138 // Unary numeric promotions
139 if (expr_type == TypeManager.byte_type)
140 return new IntConstant (((ByteConstant)e).Value, e.Location);
141 if (expr_type == TypeManager.sbyte_type)
142 return new IntConstant (((SByteConstant)e).Value, e.Location);
143 if (expr_type == TypeManager.short_type)
144 return new IntConstant (((ShortConstant)e).Value, e.Location);
145 if (expr_type == TypeManager.ushort_type)
146 return new IntConstant (((UShortConstant)e).Value, e.Location);
147 if (expr_type == TypeManager.char_type)
148 return new IntConstant (((CharConstant)e).Value, e.Location);
150 // Predefined operators
151 if (expr_type == TypeManager.int32_type || expr_type == TypeManager.uint32_type ||
152 expr_type == TypeManager.int64_type || expr_type == TypeManager.uint64_type ||
153 expr_type == TypeManager.float_type || expr_type == TypeManager.double_type ||
154 expr_type == TypeManager.decimal_type) {
160 case Operator.UnaryNegation:
161 // Unary numeric promotions
162 if (expr_type == TypeManager.byte_type)
163 return new IntConstant (-((ByteConstant)e).Value, e.Location);
164 if (expr_type == TypeManager.sbyte_type)
165 return new IntConstant (-((SByteConstant)e).Value, e.Location);
166 if (expr_type == TypeManager.short_type)
167 return new IntConstant (-((ShortConstant)e).Value, e.Location);
168 if (expr_type == TypeManager.ushort_type)
169 return new IntConstant (-((UShortConstant)e).Value, e.Location);
170 if (expr_type == TypeManager.char_type)
171 return new IntConstant (-((CharConstant)e).Value, e.Location);
173 // Predefined operators
174 if (expr_type == TypeManager.int32_type) {
175 int value = ((IntConstant)e).Value;
176 if (value == int.MinValue) {
177 if (ec.ConstantCheckState) {
178 ConstantFold.Error_CompileTimeOverflow (ec, loc);
183 return new IntConstant (-value, e.Location);
185 if (expr_type == TypeManager.int64_type) {
186 long value = ((LongConstant)e).Value;
187 if (value == long.MinValue) {
188 if (ec.ConstantCheckState) {
189 ConstantFold.Error_CompileTimeOverflow (ec, loc);
194 return new LongConstant (-value, e.Location);
197 if (expr_type == TypeManager.uint32_type) {
198 UIntLiteral uil = e as UIntLiteral;
200 if (uil.Value == int.MaxValue + (uint) 1)
201 return new IntLiteral (int.MinValue, e.Location);
202 return new LongLiteral (-uil.Value, e.Location);
204 return new LongConstant (-((UIntConstant)e).Value, e.Location);
207 if (expr_type == TypeManager.uint64_type) {
208 ULongLiteral ull = e as ULongLiteral;
209 if (ull != null && ull.Value == 9223372036854775808)
210 return new LongLiteral (long.MinValue, e.Location);
214 if (expr_type == TypeManager.float_type) {
215 FloatLiteral fl = e as FloatLiteral;
216 // For better error reporting
218 return new FloatLiteral (-fl.Value, e.Location);
220 return new FloatConstant (-((FloatConstant)e).Value, e.Location);
222 if (expr_type == TypeManager.double_type) {
223 DoubleLiteral dl = e as DoubleLiteral;
224 // For better error reporting
226 return new DoubleLiteral (-dl.Value, e.Location);
228 return new DoubleConstant (-((DoubleConstant)e).Value, e.Location);
230 if (expr_type == TypeManager.decimal_type)
231 return new DecimalConstant (-((DecimalConstant)e).Value, e.Location);
235 case Operator.LogicalNot:
236 if (expr_type != TypeManager.bool_type)
239 bool b = (bool)e.GetValue ();
240 return new BoolConstant (!b, e.Location);
242 case Operator.OnesComplement:
243 // Unary numeric promotions
244 if (expr_type == TypeManager.byte_type)
245 return new IntConstant (~((ByteConstant)e).Value, e.Location);
246 if (expr_type == TypeManager.sbyte_type)
247 return new IntConstant (~((SByteConstant)e).Value, e.Location);
248 if (expr_type == TypeManager.short_type)
249 return new IntConstant (~((ShortConstant)e).Value, e.Location);
250 if (expr_type == TypeManager.ushort_type)
251 return new IntConstant (~((UShortConstant)e).Value, e.Location);
252 if (expr_type == TypeManager.char_type)
253 return new IntConstant (~((CharConstant)e).Value, e.Location);
255 // Predefined operators
256 if (expr_type == TypeManager.int32_type)
257 return new IntConstant (~((IntConstant)e).Value, e.Location);
258 if (expr_type == TypeManager.uint32_type)
259 return new UIntConstant (~((UIntConstant)e).Value, e.Location);
260 if (expr_type == TypeManager.int64_type)
261 return new LongConstant (~((LongConstant)e).Value, e.Location);
262 if (expr_type == TypeManager.uint64_type){
263 return new ULongConstant (~((ULongConstant)e).Value, e.Location);
265 if (e is EnumConstant) {
266 e = TryReduceConstant (ec, ((EnumConstant)e).Child);
268 e = new EnumConstant (e, expr_type);
273 throw new Exception ("Can not constant fold: " + Oper.ToString());
276 protected Expression ResolveOperator (ResolveContext ec, Expression expr)
278 eclass = ExprClass.Value;
280 if (predefined_operators == null)
281 CreatePredefinedOperatorsTable ();
283 TypeSpec expr_type = expr.Type;
284 Expression best_expr;
287 // Primitive types first
289 if (TypeManager.IsPrimitiveType (expr_type)) {
290 best_expr = ResolvePrimitivePredefinedType (expr);
291 if (best_expr == null)
294 type = best_expr.Type;
300 // E operator ~(E x);
302 if (Oper == Operator.OnesComplement && TypeManager.IsEnumType (expr_type))
303 return ResolveEnumOperator (ec, expr);
305 return ResolveUserType (ec, expr);
308 protected virtual Expression ResolveEnumOperator (ResolveContext ec, Expression expr)
310 TypeSpec underlying_type = EnumSpec.GetUnderlyingType (expr.Type);
311 Expression best_expr = ResolvePrimitivePredefinedType (EmptyCast.Create (expr, underlying_type));
312 if (best_expr == null)
316 enum_conversion = Convert.ExplicitNumericConversion (new EmptyExpression (best_expr.Type), underlying_type);
318 return EmptyCast.Create (this, type);
321 public override Expression CreateExpressionTree (ResolveContext ec)
323 return CreateExpressionTree (ec, null);
326 Expression CreateExpressionTree (ResolveContext ec, Expression user_op)
330 case Operator.AddressOf:
331 Error_PointerInsideExpressionTree (ec);
333 case Operator.UnaryNegation:
334 if (ec.HasSet (ResolveContext.Options.CheckedScope) && user_op == null && !IsFloat (type))
335 method_name = "NegateChecked";
337 method_name = "Negate";
339 case Operator.OnesComplement:
340 case Operator.LogicalNot:
343 case Operator.UnaryPlus:
344 method_name = "UnaryPlus";
347 throw new InternalErrorException ("Unknown unary operator " + Oper.ToString ());
350 Arguments args = new Arguments (2);
351 args.Add (new Argument (Expr.CreateExpressionTree (ec)));
353 args.Add (new Argument (user_op));
355 return CreateExpressionFactoryCall (ec, method_name, args);
358 static void CreatePredefinedOperatorsTable ()
360 predefined_operators = new TypeSpec [(int) Operator.TOP] [];
363 // 7.6.1 Unary plus operator
365 predefined_operators [(int) Operator.UnaryPlus] = new TypeSpec [] {
366 TypeManager.int32_type, TypeManager.uint32_type,
367 TypeManager.int64_type, TypeManager.uint64_type,
368 TypeManager.float_type, TypeManager.double_type,
369 TypeManager.decimal_type
373 // 7.6.2 Unary minus operator
375 predefined_operators [(int) Operator.UnaryNegation] = new TypeSpec [] {
376 TypeManager.int32_type,
377 TypeManager.int64_type,
378 TypeManager.float_type, TypeManager.double_type,
379 TypeManager.decimal_type
383 // 7.6.3 Logical negation operator
385 predefined_operators [(int) Operator.LogicalNot] = new TypeSpec [] {
386 TypeManager.bool_type
390 // 7.6.4 Bitwise complement operator
392 predefined_operators [(int) Operator.OnesComplement] = new TypeSpec [] {
393 TypeManager.int32_type, TypeManager.uint32_type,
394 TypeManager.int64_type, TypeManager.uint64_type
399 // Unary numeric promotions
401 static Expression DoNumericPromotion (Operator op, Expression expr)
403 TypeSpec expr_type = expr.Type;
404 if ((op == Operator.UnaryPlus || op == Operator.UnaryNegation || op == Operator.OnesComplement) &&
405 expr_type == TypeManager.byte_type || expr_type == TypeManager.sbyte_type ||
406 expr_type == TypeManager.short_type || expr_type == TypeManager.ushort_type ||
407 expr_type == TypeManager.char_type)
408 return Convert.ImplicitNumericConversion (expr, TypeManager.int32_type);
410 if (op == Operator.UnaryNegation && expr_type == TypeManager.uint32_type)
411 return Convert.ImplicitNumericConversion (expr, TypeManager.int64_type);
416 protected override Expression DoResolve (ResolveContext ec)
418 if (Oper == Operator.AddressOf) {
419 return ResolveAddressOf (ec);
422 Expr = Expr.Resolve (ec);
426 if (Expr.Type == InternalType.Dynamic) {
427 Arguments args = new Arguments (1);
428 args.Add (new Argument (Expr));
429 return new DynamicUnaryConversion (GetOperatorExpressionTypeName (), args, loc).Resolve (ec);
432 if (TypeManager.IsNullableType (Expr.Type))
433 return new Nullable.LiftedUnaryOperator (Oper, Expr, loc).Resolve (ec);
436 // Attempt to use a constant folding operation.
438 Constant cexpr = Expr as Constant;
440 cexpr = TryReduceConstant (ec, cexpr);
442 return cexpr.Resolve (ec);
445 Expression expr = ResolveOperator (ec, Expr);
447 Error_OperatorCannotBeApplied (ec, loc, OperName (Oper), Expr.Type);
450 // Reduce unary operator on predefined types
452 if (expr == this && Oper == Operator.UnaryPlus)
458 public override Expression DoResolveLValue (ResolveContext ec, Expression right)
463 public override void Emit (EmitContext ec)
465 EmitOperator (ec, type);
468 protected void EmitOperator (EmitContext ec, TypeSpec type)
471 case Operator.UnaryPlus:
475 case Operator.UnaryNegation:
476 if (ec.HasSet (EmitContext.Options.CheckedScope) && !IsFloat (type)) {
477 ec.Emit (OpCodes.Ldc_I4_0);
478 if (type == TypeManager.int64_type)
479 ec.Emit (OpCodes.Conv_U8);
481 ec.Emit (OpCodes.Sub_Ovf);
484 ec.Emit (OpCodes.Neg);
489 case Operator.LogicalNot:
491 ec.Emit (OpCodes.Ldc_I4_0);
492 ec.Emit (OpCodes.Ceq);
495 case Operator.OnesComplement:
497 ec.Emit (OpCodes.Not);
500 case Operator.AddressOf:
501 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
505 throw new Exception ("This should not happen: Operator = "
510 // Same trick as in Binary expression
512 if (enum_conversion != null)
513 enum_conversion.Emit (ec);
516 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
518 if (Oper == Operator.LogicalNot)
519 Expr.EmitBranchable (ec, target, !on_true);
521 base.EmitBranchable (ec, target, on_true);
524 public override void EmitSideEffect (EmitContext ec)
526 Expr.EmitSideEffect (ec);
529 public static void Error_OperatorCannotBeApplied (ResolveContext ec, Location loc, string oper, TypeSpec t)
531 ec.Report.Error (23, loc, "The `{0}' operator cannot be applied to operand of type `{1}'",
532 oper, TypeManager.CSharpName (t));
536 // Converts operator to System.Linq.Expressions.ExpressionType enum name
538 string GetOperatorExpressionTypeName ()
541 case Operator.OnesComplement:
542 return "OnesComplement";
543 case Operator.LogicalNot:
545 case Operator.UnaryNegation:
547 case Operator.UnaryPlus:
550 throw new NotImplementedException ("Unknown express type operator " + Oper.ToString ());
554 static bool IsFloat (TypeSpec t)
556 return t == TypeManager.float_type || t == TypeManager.double_type;
560 // Returns a stringified representation of the Operator
562 public static string OperName (Operator oper)
565 case Operator.UnaryPlus:
567 case Operator.UnaryNegation:
569 case Operator.LogicalNot:
571 case Operator.OnesComplement:
573 case Operator.AddressOf:
577 throw new NotImplementedException (oper.ToString ());
580 public override SLE.Expression MakeExpression (BuilderContext ctx)
582 var expr = Expr.MakeExpression (ctx);
583 bool is_checked = ctx.HasSet (BuilderContext.Options.CheckedScope);
586 case Operator.UnaryNegation:
587 return is_checked ? SLE.Expression.NegateChecked (expr) : SLE.Expression.Negate (expr);
588 case Operator.LogicalNot:
589 return SLE.Expression.Not (expr);
591 case Operator.OnesComplement:
592 return SLE.Expression.OnesComplement (expr);
595 throw new NotImplementedException (Oper.ToString ());
599 public static void Reset ()
601 predefined_operators = null;
604 Expression ResolveAddressOf (ResolveContext ec)
607 UnsafeError (ec, loc);
609 Expr = Expr.DoResolveLValue (ec, EmptyExpression.UnaryAddress);
610 if (Expr == null || Expr.eclass != ExprClass.Variable) {
611 ec.Report.Error (211, loc, "Cannot take the address of the given expression");
615 if (!TypeManager.VerifyUnmanaged (ec.Compiler, Expr.Type, loc)) {
619 IVariableReference vr = Expr as IVariableReference;
622 VariableInfo vi = vr.VariableInfo;
624 if (vi.LocalInfo != null)
625 vi.LocalInfo.Used = true;
628 // A variable is considered definitely assigned if you take its address.
633 is_fixed = vr.IsFixed;
634 vr.SetHasAddressTaken ();
637 AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, vr, loc);
640 IFixedExpression fe = Expr as IFixedExpression;
641 is_fixed = fe != null && fe.IsFixed;
644 if (!is_fixed && !ec.HasSet (ResolveContext.Options.FixedInitializerScope)) {
645 ec.Report.Error (212, loc, "You can only take the address of unfixed expression inside of a fixed statement initializer");
648 type = PointerContainer.MakeType (Expr.Type);
649 eclass = ExprClass.Value;
653 Expression ResolvePrimitivePredefinedType (Expression expr)
655 expr = DoNumericPromotion (Oper, expr);
656 TypeSpec expr_type = expr.Type;
657 TypeSpec[] predefined = predefined_operators [(int) Oper];
658 foreach (TypeSpec t in predefined) {
666 // Perform user-operator overload resolution
668 protected virtual Expression ResolveUserOperator (ResolveContext ec, Expression expr)
670 CSharp.Operator.OpType op_type;
672 case Operator.LogicalNot:
673 op_type = CSharp.Operator.OpType.LogicalNot; break;
674 case Operator.OnesComplement:
675 op_type = CSharp.Operator.OpType.OnesComplement; break;
676 case Operator.UnaryNegation:
677 op_type = CSharp.Operator.OpType.UnaryNegation; break;
678 case Operator.UnaryPlus:
679 op_type = CSharp.Operator.OpType.UnaryPlus; break;
681 throw new InternalErrorException (Oper.ToString ());
684 var methods = MemberCache.GetUserOperator (expr.Type, op_type, false);
688 Arguments args = new Arguments (1);
689 args.Add (new Argument (expr));
691 var res = new OverloadResolver (methods, OverloadResolver.Restrictions.NoBaseMembers, loc);
692 var oper = res.ResolveOperator (ec, ref args);
697 Expr = args [0].Expr;
698 return new UserOperatorCall (oper, args, CreateExpressionTree, expr.Location);
702 // Unary user type overload resolution
704 Expression ResolveUserType (ResolveContext ec, Expression expr)
706 Expression best_expr = ResolveUserOperator (ec, expr);
707 if (best_expr != null)
710 TypeSpec[] predefined = predefined_operators [(int) Oper];
711 foreach (TypeSpec t in predefined) {
712 Expression oper_expr = Convert.ImplicitUserConversion (ec, expr, t, expr.Location);
713 if (oper_expr == null)
717 // decimal type is predefined but has user-operators
719 if (oper_expr.Type == TypeManager.decimal_type)
720 oper_expr = ResolveUserType (ec, oper_expr);
722 oper_expr = ResolvePrimitivePredefinedType (oper_expr);
724 if (oper_expr == null)
727 if (best_expr == null) {
728 best_expr = oper_expr;
732 int result = OverloadResolver.BetterTypeConversion (ec, best_expr.Type, t);
734 ec.Report.Error (35, loc, "Operator `{0}' is ambiguous on an operand of type `{1}'",
735 OperName (Oper), TypeManager.CSharpName (expr.Type));
740 best_expr = oper_expr;
743 if (best_expr == null)
747 // HACK: Decimal user-operator is included in standard operators
749 if (best_expr.Type == TypeManager.decimal_type)
753 type = best_expr.Type;
757 protected override void CloneTo (CloneContext clonectx, Expression t)
759 Unary target = (Unary) t;
761 target.Expr = Expr.Clone (clonectx);
766 // Unary operators are turned into Indirection expressions
767 // after semantic analysis (this is so we can take the address
768 // of an indirection).
770 public class Indirection : Expression, IMemoryLocation, IAssignMethod, IFixedExpression {
772 LocalTemporary temporary;
775 public Indirection (Expression expr, Location l)
781 public override Expression CreateExpressionTree (ResolveContext ec)
783 Error_PointerInsideExpressionTree (ec);
787 protected override void CloneTo (CloneContext clonectx, Expression t)
789 Indirection target = (Indirection) t;
790 target.expr = expr.Clone (clonectx);
793 public override void Emit (EmitContext ec)
798 ec.EmitLoadFromPtr (Type);
801 public void Emit (EmitContext ec, bool leave_copy)
805 ec.Emit (OpCodes.Dup);
806 temporary = new LocalTemporary (expr.Type);
807 temporary.Store (ec);
811 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
813 prepared = prepare_for_load;
817 if (prepare_for_load)
818 ec.Emit (OpCodes.Dup);
822 ec.Emit (OpCodes.Dup);
823 temporary = new LocalTemporary (expr.Type);
824 temporary.Store (ec);
827 ec.EmitStoreFromPtr (type);
829 if (temporary != null) {
831 temporary.Release (ec);
835 public void AddressOf (EmitContext ec, AddressOp Mode)
840 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
842 return DoResolve (ec);
845 protected override Expression DoResolve (ResolveContext ec)
847 expr = expr.Resolve (ec);
852 UnsafeError (ec, loc);
854 if (!expr.Type.IsPointer) {
855 ec.Report.Error (193, loc, "The * or -> operator must be applied to a pointer");
859 if (expr.Type == TypeManager.void_ptr_type) {
860 ec.Report.Error (242, loc, "The operation in question is undefined on void pointers");
864 type = TypeManager.GetElementType (expr.Type);
865 eclass = ExprClass.Variable;
869 public bool IsFixed {
873 public override string ToString ()
875 return "*(" + expr + ")";
880 /// Unary Mutator expressions (pre and post ++ and --)
884 /// UnaryMutator implements ++ and -- expressions. It derives from
885 /// ExpressionStatement becuase the pre/post increment/decrement
886 /// operators can be used in a statement context.
888 /// FIXME: Idea, we could split this up in two classes, one simpler
889 /// for the common case, and one with the extra fields for more complex
890 /// classes (indexers require temporary access; overloaded require method)
893 public class UnaryMutator : ExpressionStatement
895 class DynamicPostMutator : Expression, IAssignMethod
900 public DynamicPostMutator (Expression expr)
903 this.type = expr.Type;
904 this.loc = expr.Location;
907 public override Expression CreateExpressionTree (ResolveContext ec)
909 throw new NotImplementedException ("ET");
912 protected override Expression DoResolve (ResolveContext rc)
914 eclass = expr.eclass;
918 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
920 expr.DoResolveLValue (ec, right_side);
921 return DoResolve (ec);
924 public override void Emit (EmitContext ec)
929 public void Emit (EmitContext ec, bool leave_copy)
931 throw new NotImplementedException ();
935 // Emits target assignment using unmodified source value
937 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
940 // Allocate temporary variable to keep original value before it's modified
942 temp = new LocalTemporary (type);
946 ((IAssignMethod) expr).EmitAssign (ec, source, false, prepare_for_load);
957 public enum Mode : byte {
964 PreDecrement = IsDecrement,
965 PostIncrement = IsPost,
966 PostDecrement = IsPost | IsDecrement
970 bool is_expr, recurse;
974 // Holds the real operation
975 Expression operation;
977 public UnaryMutator (Mode m, Expression e, Location loc)
984 public override Expression CreateExpressionTree (ResolveContext ec)
986 return new SimpleAssign (this, this).CreateExpressionTree (ec);
989 protected override Expression DoResolve (ResolveContext ec)
991 expr = expr.Resolve (ec);
996 if (expr.Type == InternalType.Dynamic) {
998 // Handle postfix unary operators using local
999 // temporary variable
1001 if ((mode & Mode.IsPost) != 0)
1002 expr = new DynamicPostMutator (expr);
1004 Arguments args = new Arguments (1);
1005 args.Add (new Argument (expr));
1006 return new SimpleAssign (expr, new DynamicUnaryConversion (GetOperatorExpressionTypeName (), args, loc)).Resolve (ec);
1009 if (TypeManager.IsNullableType (expr.Type))
1010 return new Nullable.LiftedUnaryMutator (mode, expr, loc).Resolve (ec);
1012 eclass = ExprClass.Value;
1014 return ResolveOperator (ec);
1017 void EmitCode (EmitContext ec, bool is_expr)
1020 this.is_expr = is_expr;
1021 ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
1024 public override void Emit (EmitContext ec)
1027 // We use recurse to allow ourselfs to be the source
1028 // of an assignment. This little hack prevents us from
1029 // having to allocate another expression
1032 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
1034 operation.Emit (ec);
1040 EmitCode (ec, true);
1043 public override void EmitStatement (EmitContext ec)
1045 EmitCode (ec, false);
1049 // Converts operator to System.Linq.Expressions.ExpressionType enum name
1051 string GetOperatorExpressionTypeName ()
1053 return IsDecrement ? "Decrement" : "Increment";
1057 get { return (mode & Mode.IsDecrement) != 0; }
1061 // Returns whether an object of type `t' can be incremented
1062 // or decremented with add/sub (ie, basically whether we can
1063 // use pre-post incr-decr operations on it, but it is not a
1064 // System.Decimal, which we require operator overloading to catch)
1066 static bool IsPredefinedOperator (TypeSpec t)
1068 return (TypeManager.IsPrimitiveType (t) && t != TypeManager.bool_type) ||
1069 TypeManager.IsEnumType (t) ||
1070 t.IsPointer && t != TypeManager.void_ptr_type;
1074 public override SLE.Expression MakeExpression (BuilderContext ctx)
1076 var target = ((RuntimeValueExpression) expr).MetaObject.Expression;
1077 var source = SLE.Expression.Convert (operation.MakeExpression (ctx), target.Type);
1078 return SLE.Expression.Assign (target, source);
1082 protected override void CloneTo (CloneContext clonectx, Expression t)
1084 UnaryMutator target = (UnaryMutator) t;
1086 target.expr = expr.Clone (clonectx);
1089 Expression ResolveOperator (ResolveContext ec)
1091 if (expr is RuntimeValueExpression) {
1094 // Use itself at the top of the stack
1095 operation = new EmptyExpression (type);
1099 // The operand of the prefix/postfix increment decrement operators
1100 // should be an expression that is classified as a variable,
1101 // a property access or an indexer access
1103 if (expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.IndexerAccess || expr.eclass == ExprClass.PropertyAccess) {
1104 expr = expr.ResolveLValue (ec, expr);
1106 ec.Report.Error (1059, loc, "The operand of an increment or decrement operator must be a variable, property or indexer");
1110 // 1. Check predefined types
1112 if (IsPredefinedOperator (type)) {
1113 // TODO: Move to IntConstant once I get rid of int32_type
1114 var one = new IntConstant (1, loc);
1116 // TODO: Cache this based on type when using EmptyExpression in
1118 Binary.Operator op = IsDecrement ? Binary.Operator.Subtraction : Binary.Operator.Addition;
1119 operation = new Binary (op, operation, one, loc);
1120 operation = operation.Resolve (ec);
1121 if (operation != null && operation.Type != type)
1122 operation = Convert.ExplicitNumericConversion (operation, type);
1128 // Step 2: Perform Operator Overload location
1130 var user_op = IsDecrement ? Operator.OpType.Decrement : Operator.OpType.Increment;
1131 var methods = MemberCache.GetUserOperator (type, user_op, false);
1133 if (methods != null) {
1134 Arguments args = new Arguments (1);
1135 args.Add (new Argument (expr));
1137 var res = new OverloadResolver (methods, OverloadResolver.Restrictions.NoBaseMembers, loc);
1138 var op = res.ResolveOperator (ec, ref args);
1142 args[0].Expr = operation;
1143 operation = new UserOperatorCall (op, args, null, loc);
1144 operation = Convert.ImplicitConversionRequired (ec, operation, type, loc);
1148 string name = IsDecrement ?
1149 Operator.GetName (Operator.OpType.Decrement) :
1150 Operator.GetName (Operator.OpType.Increment);
1152 Unary.Error_OperatorCannotBeApplied (ec, loc, name, type);
1158 /// Base class for the `Is' and `As' classes.
1162 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1165 public abstract class Probe : Expression {
1166 public Expression ProbeType;
1167 protected Expression expr;
1168 protected TypeExpr probe_type_expr;
1170 public Probe (Expression expr, Expression probe_type, Location l)
1172 ProbeType = probe_type;
1177 public Expression Expr {
1183 protected override Expression DoResolve (ResolveContext ec)
1185 probe_type_expr = ProbeType.ResolveAsTypeTerminal (ec, false);
1186 if (probe_type_expr == null)
1189 expr = expr.Resolve (ec);
1193 if (probe_type_expr.Type.IsStatic) {
1194 ec.Report.Error (-244, loc, "The `{0}' operator cannot be applied to an operand of a static type",
1198 if (expr.Type.IsPointer || probe_type_expr.Type.IsPointer) {
1199 ec.Report.Error (244, loc, "The `{0}' operator cannot be applied to an operand of pointer type",
1204 if (expr.Type == InternalType.AnonymousMethod) {
1205 ec.Report.Error (837, loc, "The `{0}' operator cannot be applied to a lambda expression or anonymous method",
1213 protected abstract string OperatorName { get; }
1215 protected override void CloneTo (CloneContext clonectx, Expression t)
1217 Probe target = (Probe) t;
1219 target.expr = expr.Clone (clonectx);
1220 target.ProbeType = ProbeType.Clone (clonectx);
1226 /// Implementation of the `is' operator.
1228 public class Is : Probe {
1229 Nullable.Unwrap expr_unwrap;
1231 public Is (Expression expr, Expression probe_type, Location l)
1232 : base (expr, probe_type, l)
1236 public override Expression CreateExpressionTree (ResolveContext ec)
1238 Arguments args = Arguments.CreateForExpressionTree (ec, null,
1239 expr.CreateExpressionTree (ec),
1240 new TypeOf (probe_type_expr, loc));
1242 return CreateExpressionFactoryCall (ec, "TypeIs", args);
1245 public override void Emit (EmitContext ec)
1247 if (expr_unwrap != null) {
1248 expr_unwrap.EmitCheck (ec);
1253 ec.Emit (OpCodes.Isinst, probe_type_expr.Type);
1254 ec.Emit (OpCodes.Ldnull);
1255 ec.Emit (OpCodes.Cgt_Un);
1258 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
1260 if (expr_unwrap != null) {
1261 expr_unwrap.EmitCheck (ec);
1264 ec.Emit (OpCodes.Isinst, probe_type_expr.Type);
1266 ec.Emit (on_true ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1269 Expression CreateConstantResult (ResolveContext ec, bool result)
1272 ec.Report.Warning (183, 1, loc, "The given expression is always of the provided (`{0}') type",
1273 TypeManager.CSharpName (probe_type_expr.Type));
1275 ec.Report.Warning (184, 1, loc, "The given expression is never of the provided (`{0}') type",
1276 TypeManager.CSharpName (probe_type_expr.Type));
1278 return ReducedExpression.Create (new BoolConstant (result, loc).Resolve (ec), this);
1281 protected override Expression DoResolve (ResolveContext ec)
1283 if (base.DoResolve (ec) == null)
1286 TypeSpec d = expr.Type;
1287 bool d_is_nullable = false;
1290 // If E is a method group or the null literal, or if the type of E is a reference
1291 // type or a nullable type and the value of E is null, the result is false
1293 if (expr.IsNull || expr.eclass == ExprClass.MethodGroup)
1294 return CreateConstantResult (ec, false);
1296 if (TypeManager.IsNullableType (d)) {
1297 var ut = Nullable.NullableInfo.GetUnderlyingType (d);
1298 if (!ut.IsGenericParameter) {
1300 d_is_nullable = true;
1304 type = TypeManager.bool_type;
1305 eclass = ExprClass.Value;
1306 TypeSpec t = probe_type_expr.Type;
1307 bool t_is_nullable = false;
1308 if (TypeManager.IsNullableType (t)) {
1309 var ut = Nullable.NullableInfo.GetUnderlyingType (t);
1310 if (!ut.IsGenericParameter) {
1312 t_is_nullable = true;
1316 if (TypeManager.IsStruct (t)) {
1319 // D and T are the same value types but D can be null
1321 if (d_is_nullable && !t_is_nullable) {
1322 expr_unwrap = Nullable.Unwrap.Create (expr, false);
1327 // The result is true if D and T are the same value types
1329 return CreateConstantResult (ec, true);
1332 var tp = d as TypeParameterSpec;
1334 return ResolveGenericParameter (ec, t, tp);
1337 // An unboxing conversion exists
1339 if (Convert.ExplicitReferenceConversionExists (d, t))
1342 if (TypeManager.IsGenericParameter (t))
1343 return ResolveGenericParameter (ec, d, (TypeParameterSpec) t);
1345 if (TypeManager.IsStruct (d)) {
1346 if (Convert.ImplicitBoxingConversion (null, d, t) != null)
1347 return CreateConstantResult (ec, true);
1349 if (TypeManager.IsGenericParameter (d))
1350 return ResolveGenericParameter (ec, t, (TypeParameterSpec) d);
1352 if (TypeManager.ContainsGenericParameters (d))
1355 if (Convert.ImplicitReferenceConversionExists (expr, t) ||
1356 Convert.ExplicitReferenceConversionExists (d, t)) {
1362 return CreateConstantResult (ec, false);
1365 Expression ResolveGenericParameter (ResolveContext ec, TypeSpec d, TypeParameterSpec t)
1367 if (t.IsReferenceType) {
1368 if (TypeManager.IsStruct (d))
1369 return CreateConstantResult (ec, false);
1372 if (TypeManager.IsGenericParameter (expr.Type)) {
1373 if (t.IsValueType && expr.Type == t)
1374 return CreateConstantResult (ec, true);
1376 expr = new BoxedCast (expr, d);
1382 protected override string OperatorName {
1383 get { return "is"; }
1388 /// Implementation of the `as' operator.
1390 public class As : Probe {
1392 Expression resolved_type;
1394 public As (Expression expr, Expression probe_type, Location l)
1395 : base (expr, probe_type, l)
1399 public override Expression CreateExpressionTree (ResolveContext ec)
1401 Arguments args = Arguments.CreateForExpressionTree (ec, null,
1402 expr.CreateExpressionTree (ec),
1403 new TypeOf (probe_type_expr, loc));
1405 return CreateExpressionFactoryCall (ec, "TypeAs", args);
1408 public override void Emit (EmitContext ec)
1413 ec.Emit (OpCodes.Isinst, type);
1415 if (TypeManager.IsGenericParameter (type) || TypeManager.IsNullableType (type))
1416 ec.Emit (OpCodes.Unbox_Any, type);
1419 protected override Expression DoResolve (ResolveContext ec)
1421 if (resolved_type == null) {
1422 resolved_type = base.DoResolve (ec);
1424 if (resolved_type == null)
1428 type = probe_type_expr.Type;
1429 eclass = ExprClass.Value;
1430 TypeSpec etype = expr.Type;
1432 if (!TypeManager.IsReferenceType (type) && !TypeManager.IsNullableType (type)) {
1433 if (TypeManager.IsGenericParameter (type)) {
1434 ec.Report.Error (413, loc,
1435 "The `as' operator cannot be used with a non-reference type parameter `{0}'. Consider adding `class' or a reference type constraint",
1436 probe_type_expr.GetSignatureForError ());
1438 ec.Report.Error (77, loc,
1439 "The `as' operator cannot be used with a non-nullable value type `{0}'",
1440 TypeManager.CSharpName (type));
1445 if (expr.IsNull && TypeManager.IsNullableType (type)) {
1446 return Nullable.LiftedNull.CreateFromExpression (ec, this);
1449 // If the compile-time type of E is dynamic, unlike the cast operator the as operator is not dynamically bound
1450 if (etype == InternalType.Dynamic) {
1455 Expression e = Convert.ImplicitConversion (ec, expr, type, loc);
1461 if (Convert.ExplicitReferenceConversionExists (etype, type)){
1462 if (TypeManager.IsGenericParameter (etype))
1463 expr = new BoxedCast (expr, etype);
1469 if (TypeManager.ContainsGenericParameters (etype) ||
1470 TypeManager.ContainsGenericParameters (type)) {
1471 expr = new BoxedCast (expr, etype);
1476 ec.Report.Error (39, loc, "Cannot convert type `{0}' to `{1}' via a built-in conversion",
1477 TypeManager.CSharpName (etype), TypeManager.CSharpName (type));
1482 protected override string OperatorName {
1483 get { return "as"; }
1488 // This represents a typecast in the source language.
1490 public class Cast : ShimExpression {
1491 Expression target_type;
1493 public Cast (Expression cast_type, Expression expr, Location loc)
1496 this.target_type = cast_type;
1500 public Expression TargetType {
1501 get { return target_type; }
1504 protected override Expression DoResolve (ResolveContext ec)
1506 expr = expr.Resolve (ec);
1510 TypeExpr target = target_type.ResolveAsTypeTerminal (ec, false);
1516 if (type.IsStatic) {
1517 ec.Report.Error (716, loc, "Cannot convert to static type `{0}'", TypeManager.CSharpName (type));
1521 eclass = ExprClass.Value;
1523 Constant c = expr as Constant;
1525 c = c.TryReduce (ec, type, loc);
1530 if (type.IsPointer && !ec.IsUnsafe) {
1531 UnsafeError (ec, loc);
1532 } else if (expr.Type == InternalType.Dynamic) {
1533 Arguments arg = new Arguments (1);
1534 arg.Add (new Argument (expr));
1535 return new DynamicConversion (type, CSharpBinderFlags.ConvertExplicit, arg, loc).Resolve (ec);
1538 var res = Convert.ExplicitConversion (ec, expr, type, loc);
1540 return EmptyCast.Create (res, type);
1545 protected override void CloneTo (CloneContext clonectx, Expression t)
1547 Cast target = (Cast) t;
1549 target.target_type = target_type.Clone (clonectx);
1550 target.expr = expr.Clone (clonectx);
1554 public class ImplicitCast : ShimExpression
1558 public ImplicitCast (Expression expr, TypeSpec target, bool arrayAccess)
1561 this.loc = expr.Location;
1563 this.arrayAccess = arrayAccess;
1566 protected override Expression DoResolve (ResolveContext ec)
1568 expr = expr.Resolve (ec);
1573 expr = ConvertExpressionToArrayIndex (ec, expr);
1575 expr = Convert.ImplicitConversionRequired (ec, expr, type, loc);
1582 // C# 2.0 Default value expression
1584 public class DefaultValueExpression : Expression
1588 public DefaultValueExpression (Expression expr, Location loc)
1594 public override Expression CreateExpressionTree (ResolveContext ec)
1596 Arguments args = new Arguments (2);
1597 args.Add (new Argument (this));
1598 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
1599 return CreateExpressionFactoryCall (ec, "Constant", args);
1602 protected override Expression DoResolve (ResolveContext ec)
1604 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
1610 if (type.IsStatic) {
1611 ec.Report.Error (-244, loc, "The `default value' operator cannot be applied to an operand of a static type");
1615 return new NullLiteral (Location).ConvertImplicitly (ec, type);
1617 if (TypeManager.IsReferenceType (type))
1618 return new NullConstant (type, loc);
1620 Constant c = New.Constantify (type);
1622 return c.Resolve (ec);
1624 eclass = ExprClass.Variable;
1628 public override void Emit (EmitContext ec)
1630 LocalTemporary temp_storage = new LocalTemporary(type);
1632 temp_storage.AddressOf(ec, AddressOp.LoadStore);
1633 ec.Emit(OpCodes.Initobj, type);
1634 temp_storage.Emit(ec);
1637 protected override void CloneTo (CloneContext clonectx, Expression t)
1639 DefaultValueExpression target = (DefaultValueExpression) t;
1641 target.expr = expr.Clone (clonectx);
1646 /// Binary operators
1648 public class Binary : Expression, IDynamicBinder
1650 protected class PredefinedOperator {
1651 protected readonly TypeSpec left;
1652 protected readonly TypeSpec right;
1653 public readonly Operator OperatorsMask;
1654 public TypeSpec ReturnType;
1656 public PredefinedOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
1657 : this (ltype, rtype, op_mask, ltype)
1661 public PredefinedOperator (TypeSpec type, Operator op_mask, TypeSpec return_type)
1662 : this (type, type, op_mask, return_type)
1666 public PredefinedOperator (TypeSpec type, Operator op_mask)
1667 : this (type, type, op_mask, type)
1671 public PredefinedOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask, TypeSpec return_type)
1673 if ((op_mask & Operator.ValuesOnlyMask) != 0)
1674 throw new InternalErrorException ("Only masked values can be used");
1678 this.OperatorsMask = op_mask;
1679 this.ReturnType = return_type;
1682 public virtual Expression ConvertResult (ResolveContext ec, Binary b)
1684 b.type = ReturnType;
1686 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1687 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
1690 // A user operators does not support multiple user conversions, but decimal type
1691 // is considered to be predefined type therefore we apply predefined operators rules
1692 // and then look for decimal user-operator implementation
1694 if (left == TypeManager.decimal_type)
1695 return b.ResolveUserOperator (ec, b.left.Type, b.right.Type);
1697 var c = b.right as Constant;
1699 if (c.IsDefaultValue && (b.oper == Operator.Addition || b.oper == Operator.BitwiseOr || b.oper == Operator.Subtraction))
1700 return ReducedExpression.Create (b.left, b).Resolve (ec);
1701 if ((b.oper == Operator.Multiply || b.oper == Operator.Division) && c.IsOneInteger)
1702 return ReducedExpression.Create (b.left, b).Resolve (ec);
1706 c = b.left as Constant;
1708 if (c.IsDefaultValue && (b.oper == Operator.Addition || b.oper == Operator.BitwiseOr))
1709 return ReducedExpression.Create (b.right, b).Resolve (ec);
1710 if (b.oper == Operator.Multiply && c.IsOneInteger)
1711 return ReducedExpression.Create (b.right, b).Resolve (ec);
1718 public bool IsPrimitiveApplicable (TypeSpec ltype, TypeSpec rtype)
1721 // We are dealing with primitive types only
1723 return left == ltype && ltype == rtype;
1726 public virtual bool IsApplicable (ResolveContext ec, Expression lexpr, Expression rexpr)
1729 if (left == lexpr.Type && right == rexpr.Type)
1732 return Convert.ImplicitConversionExists (ec, lexpr, left) &&
1733 Convert.ImplicitConversionExists (ec, rexpr, right);
1736 public PredefinedOperator ResolveBetterOperator (ResolveContext ec, PredefinedOperator best_operator)
1739 if (left != null && best_operator.left != null) {
1740 result = OverloadResolver.BetterTypeConversion (ec, best_operator.left, left);
1744 // When second argument is same as the first one, the result is same
1746 if (right != null && (left != right || best_operator.left != best_operator.right)) {
1747 result |= OverloadResolver.BetterTypeConversion (ec, best_operator.right, right);
1750 if (result == 0 || result > 2)
1753 return result == 1 ? best_operator : this;
1757 class PredefinedStringOperator : PredefinedOperator {
1758 public PredefinedStringOperator (TypeSpec type, Operator op_mask)
1759 : base (type, op_mask, type)
1761 ReturnType = TypeManager.string_type;
1764 public PredefinedStringOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
1765 : base (ltype, rtype, op_mask)
1767 ReturnType = TypeManager.string_type;
1770 public override Expression ConvertResult (ResolveContext ec, Binary b)
1773 // Use original expression for nullable arguments
1775 Nullable.Unwrap unwrap = b.left as Nullable.Unwrap;
1777 b.left = unwrap.Original;
1779 unwrap = b.right as Nullable.Unwrap;
1781 b.right = unwrap.Original;
1783 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1784 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
1787 // Start a new concat expression using converted expression
1789 return StringConcat.Create (ec, b.left, b.right, b.loc);
1793 class PredefinedShiftOperator : PredefinedOperator {
1794 public PredefinedShiftOperator (TypeSpec ltype, Operator op_mask) :
1795 base (ltype, TypeManager.int32_type, op_mask)
1799 public override Expression ConvertResult (ResolveContext ec, Binary b)
1801 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1803 Expression expr_tree_expr = Convert.ImplicitConversion (ec, b.right, TypeManager.int32_type, b.right.Location);
1805 int right_mask = left == TypeManager.int32_type || left == TypeManager.uint32_type ? 0x1f : 0x3f;
1808 // b = b.left >> b.right & (0x1f|0x3f)
1810 b.right = new Binary (Operator.BitwiseAnd,
1811 b.right, new IntConstant (right_mask, b.right.Location), b.loc).Resolve (ec);
1814 // Expression tree representation does not use & mask
1816 b.right = ReducedExpression.Create (b.right, expr_tree_expr).Resolve (ec);
1817 b.type = ReturnType;
1820 // Optimize shift by 0
1822 var c = b.right as Constant;
1823 if (c != null && c.IsDefaultValue)
1824 return ReducedExpression.Create (b.left, b).Resolve (ec);
1830 class PredefinedEqualityOperator : PredefinedOperator
1832 MethodSpec equal_method, inequal_method;
1834 public PredefinedEqualityOperator (TypeSpec arg, TypeSpec retType)
1835 : base (arg, arg, Operator.EqualityMask, retType)
1839 public override Expression ConvertResult (ResolveContext ec, Binary b)
1841 b.type = ReturnType;
1843 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
1844 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
1846 Arguments args = new Arguments (2);
1847 args.Add (new Argument (b.left));
1848 args.Add (new Argument (b.right));
1851 if (b.oper == Operator.Equality) {
1852 if (equal_method == null) {
1853 equal_method = TypeManager.GetPredefinedMethod (left,
1854 new MemberFilter (CSharp.Operator.GetMetadataName (CSharp.Operator.OpType.Equality), 0, MemberKind.Operator, null, ReturnType), b.loc);
1857 method = equal_method;
1859 if (inequal_method == null) {
1860 inequal_method = TypeManager.GetPredefinedMethod (left,
1861 new MemberFilter (CSharp.Operator.GetMetadataName (CSharp.Operator.OpType.Inequality), 0, MemberKind.Operator, null, ReturnType), b.loc);
1864 method = inequal_method;
1867 return new UserOperatorCall (method, args, b.CreateExpressionTree, b.loc);
1871 class PredefinedPointerOperator : PredefinedOperator
1873 public PredefinedPointerOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
1874 : base (ltype, rtype, op_mask)
1878 public PredefinedPointerOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask, TypeSpec retType)
1879 : base (ltype, rtype, op_mask, retType)
1883 public PredefinedPointerOperator (TypeSpec type, Operator op_mask, TypeSpec return_type)
1884 : base (type, op_mask, return_type)
1888 public override bool IsApplicable (ResolveContext ec, Expression lexpr, Expression rexpr)
1891 if (!lexpr.Type.IsPointer)
1894 if (!Convert.ImplicitConversionExists (ec, lexpr, left))
1898 if (right == null) {
1899 if (!rexpr.Type.IsPointer)
1902 if (!Convert.ImplicitConversionExists (ec, rexpr, right))
1909 public override Expression ConvertResult (ResolveContext ec, Binary b)
1912 b.left = EmptyCast.Create (b.left, left);
1913 } else if (right != null) {
1914 b.right = EmptyCast.Create (b.right, right);
1917 TypeSpec r_type = ReturnType;
1918 Expression left_arg, right_arg;
1919 if (r_type == null) {
1922 right_arg = b.right;
1923 r_type = b.left.Type;
1927 r_type = b.right.Type;
1931 right_arg = b.right;
1934 return new PointerArithmetic (b.oper, left_arg, right_arg, r_type, b.loc).Resolve (ec);
1939 public enum Operator {
1940 Multiply = 0 | ArithmeticMask,
1941 Division = 1 | ArithmeticMask,
1942 Modulus = 2 | ArithmeticMask,
1943 Addition = 3 | ArithmeticMask | AdditionMask,
1944 Subtraction = 4 | ArithmeticMask | SubtractionMask,
1946 LeftShift = 5 | ShiftMask,
1947 RightShift = 6 | ShiftMask,
1949 LessThan = 7 | ComparisonMask | RelationalMask,
1950 GreaterThan = 8 | ComparisonMask | RelationalMask,
1951 LessThanOrEqual = 9 | ComparisonMask | RelationalMask,
1952 GreaterThanOrEqual = 10 | ComparisonMask | RelationalMask,
1953 Equality = 11 | ComparisonMask | EqualityMask,
1954 Inequality = 12 | ComparisonMask | EqualityMask,
1956 BitwiseAnd = 13 | BitwiseMask,
1957 ExclusiveOr = 14 | BitwiseMask,
1958 BitwiseOr = 15 | BitwiseMask,
1960 LogicalAnd = 16 | LogicalMask,
1961 LogicalOr = 17 | LogicalMask,
1966 ValuesOnlyMask = ArithmeticMask - 1,
1967 ArithmeticMask = 1 << 5,
1969 ComparisonMask = 1 << 7,
1970 EqualityMask = 1 << 8,
1971 BitwiseMask = 1 << 9,
1972 LogicalMask = 1 << 10,
1973 AdditionMask = 1 << 11,
1974 SubtractionMask = 1 << 12,
1975 RelationalMask = 1 << 13
1978 readonly Operator oper;
1979 protected Expression left, right;
1980 readonly bool is_compound;
1981 Expression enum_conversion;
1983 static PredefinedOperator[] standard_operators;
1984 static PredefinedOperator[] equality_operators;
1985 static PredefinedOperator[] pointer_operators;
1987 public Binary (Operator oper, Expression left, Expression right, bool isCompound, Location loc)
1988 : this (oper, left, right, loc)
1990 this.is_compound = isCompound;
1993 public Binary (Operator oper, Expression left, Expression right, Location loc)
2001 public Operator Oper {
2008 /// Returns a stringified representation of the Operator
2010 string OperName (Operator oper)
2014 case Operator.Multiply:
2017 case Operator.Division:
2020 case Operator.Modulus:
2023 case Operator.Addition:
2026 case Operator.Subtraction:
2029 case Operator.LeftShift:
2032 case Operator.RightShift:
2035 case Operator.LessThan:
2038 case Operator.GreaterThan:
2041 case Operator.LessThanOrEqual:
2044 case Operator.GreaterThanOrEqual:
2047 case Operator.Equality:
2050 case Operator.Inequality:
2053 case Operator.BitwiseAnd:
2056 case Operator.BitwiseOr:
2059 case Operator.ExclusiveOr:
2062 case Operator.LogicalOr:
2065 case Operator.LogicalAnd:
2069 s = oper.ToString ();
2079 public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, Operator oper, Location loc)
2081 new Binary (oper, left, right, loc).Error_OperatorCannotBeApplied (ec, left, right);
2084 public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, string oper, Location loc)
2087 l = TypeManager.CSharpName (left.Type);
2088 r = TypeManager.CSharpName (right.Type);
2090 ec.Report.Error (19, loc, "Operator `{0}' cannot be applied to operands of type `{1}' and `{2}'",
2094 protected void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right)
2096 Error_OperatorCannotBeApplied (ec, left, right, OperName (oper), loc);
2100 // Converts operator to System.Linq.Expressions.ExpressionType enum name
2102 string GetOperatorExpressionTypeName ()
2105 case Operator.Addition:
2106 return is_compound ? "AddAssign" : "Add";
2107 case Operator.BitwiseAnd:
2108 return is_compound ? "AndAssign" : "And";
2109 case Operator.BitwiseOr:
2110 return is_compound ? "OrAssign" : "Or";
2111 case Operator.Division:
2112 return is_compound ? "DivideAssign" : "Divide";
2113 case Operator.ExclusiveOr:
2114 return is_compound ? "ExclusiveOrAssign" : "ExclusiveOr";
2115 case Operator.Equality:
2117 case Operator.GreaterThan:
2118 return "GreaterThan";
2119 case Operator.GreaterThanOrEqual:
2120 return "GreaterThanOrEqual";
2121 case Operator.Inequality:
2123 case Operator.LeftShift:
2124 return is_compound ? "LeftShiftAssign" : "LeftShift";
2125 case Operator.LessThan:
2127 case Operator.LessThanOrEqual:
2128 return "LessThanOrEqual";
2129 case Operator.LogicalAnd:
2131 case Operator.LogicalOr:
2133 case Operator.Modulus:
2134 return is_compound ? "ModuloAssign" : "Modulo";
2135 case Operator.Multiply:
2136 return is_compound ? "MultiplyAssign" : "Multiply";
2137 case Operator.RightShift:
2138 return is_compound ? "RightShiftAssign" : "RightShift";
2139 case Operator.Subtraction:
2140 return is_compound ? "SubtractAssign" : "Subtract";
2142 throw new NotImplementedException ("Unknown expression type operator " + oper.ToString ());
2146 static CSharp.Operator.OpType ConvertBinaryToUserOperator (Operator op)
2149 case Operator.Addition:
2150 return CSharp.Operator.OpType.Addition;
2151 case Operator.BitwiseAnd:
2152 case Operator.LogicalAnd:
2153 return CSharp.Operator.OpType.BitwiseAnd;
2154 case Operator.BitwiseOr:
2155 case Operator.LogicalOr:
2156 return CSharp.Operator.OpType.BitwiseOr;
2157 case Operator.Division:
2158 return CSharp.Operator.OpType.Division;
2159 case Operator.Equality:
2160 return CSharp.Operator.OpType.Equality;
2161 case Operator.ExclusiveOr:
2162 return CSharp.Operator.OpType.ExclusiveOr;
2163 case Operator.GreaterThan:
2164 return CSharp.Operator.OpType.GreaterThan;
2165 case Operator.GreaterThanOrEqual:
2166 return CSharp.Operator.OpType.GreaterThanOrEqual;
2167 case Operator.Inequality:
2168 return CSharp.Operator.OpType.Inequality;
2169 case Operator.LeftShift:
2170 return CSharp.Operator.OpType.LeftShift;
2171 case Operator.LessThan:
2172 return CSharp.Operator.OpType.LessThan;
2173 case Operator.LessThanOrEqual:
2174 return CSharp.Operator.OpType.LessThanOrEqual;
2175 case Operator.Modulus:
2176 return CSharp.Operator.OpType.Modulus;
2177 case Operator.Multiply:
2178 return CSharp.Operator.OpType.Multiply;
2179 case Operator.RightShift:
2180 return CSharp.Operator.OpType.RightShift;
2181 case Operator.Subtraction:
2182 return CSharp.Operator.OpType.Subtraction;
2184 throw new InternalErrorException (op.ToString ());
2188 public static void EmitOperatorOpcode (EmitContext ec, Operator oper, TypeSpec l)
2193 case Operator.Multiply:
2194 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2195 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2196 opcode = OpCodes.Mul_Ovf;
2197 else if (!IsFloat (l))
2198 opcode = OpCodes.Mul_Ovf_Un;
2200 opcode = OpCodes.Mul;
2202 opcode = OpCodes.Mul;
2206 case Operator.Division:
2208 opcode = OpCodes.Div_Un;
2210 opcode = OpCodes.Div;
2213 case Operator.Modulus:
2215 opcode = OpCodes.Rem_Un;
2217 opcode = OpCodes.Rem;
2220 case Operator.Addition:
2221 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2222 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2223 opcode = OpCodes.Add_Ovf;
2224 else if (!IsFloat (l))
2225 opcode = OpCodes.Add_Ovf_Un;
2227 opcode = OpCodes.Add;
2229 opcode = OpCodes.Add;
2232 case Operator.Subtraction:
2233 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
2234 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2235 opcode = OpCodes.Sub_Ovf;
2236 else if (!IsFloat (l))
2237 opcode = OpCodes.Sub_Ovf_Un;
2239 opcode = OpCodes.Sub;
2241 opcode = OpCodes.Sub;
2244 case Operator.RightShift:
2246 opcode = OpCodes.Shr_Un;
2248 opcode = OpCodes.Shr;
2251 case Operator.LeftShift:
2252 opcode = OpCodes.Shl;
2255 case Operator.Equality:
2256 opcode = OpCodes.Ceq;
2259 case Operator.Inequality:
2260 ec.Emit (OpCodes.Ceq);
2261 ec.Emit (OpCodes.Ldc_I4_0);
2263 opcode = OpCodes.Ceq;
2266 case Operator.LessThan:
2268 opcode = OpCodes.Clt_Un;
2270 opcode = OpCodes.Clt;
2273 case Operator.GreaterThan:
2275 opcode = OpCodes.Cgt_Un;
2277 opcode = OpCodes.Cgt;
2280 case Operator.LessThanOrEqual:
2281 if (IsUnsigned (l) || IsFloat (l))
2282 ec.Emit (OpCodes.Cgt_Un);
2284 ec.Emit (OpCodes.Cgt);
2285 ec.Emit (OpCodes.Ldc_I4_0);
2287 opcode = OpCodes.Ceq;
2290 case Operator.GreaterThanOrEqual:
2291 if (IsUnsigned (l) || IsFloat (l))
2292 ec.Emit (OpCodes.Clt_Un);
2294 ec.Emit (OpCodes.Clt);
2296 ec.Emit (OpCodes.Ldc_I4_0);
2298 opcode = OpCodes.Ceq;
2301 case Operator.BitwiseOr:
2302 opcode = OpCodes.Or;
2305 case Operator.BitwiseAnd:
2306 opcode = OpCodes.And;
2309 case Operator.ExclusiveOr:
2310 opcode = OpCodes.Xor;
2314 throw new InternalErrorException (oper.ToString ());
2320 static bool IsUnsigned (TypeSpec t)
2325 return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2326 t == TypeManager.ushort_type || t == TypeManager.byte_type);
2329 static bool IsFloat (TypeSpec t)
2331 return t == TypeManager.float_type || t == TypeManager.double_type;
2334 public static void Reset ()
2336 equality_operators = pointer_operators = standard_operators = null;
2339 Expression ResolveOperator (ResolveContext ec)
2341 TypeSpec l = left.Type;
2342 TypeSpec r = right.Type;
2344 bool primitives_only = false;
2346 if (standard_operators == null)
2347 CreateStandardOperatorsTable ();
2350 // Handles predefined primitive types
2352 if (TypeManager.IsPrimitiveType (l) && TypeManager.IsPrimitiveType (r)) {
2353 if ((oper & Operator.ShiftMask) == 0) {
2354 if (l != TypeManager.bool_type && !DoBinaryOperatorPromotion (ec))
2357 primitives_only = true;
2361 if (l.IsPointer || r.IsPointer)
2362 return ResolveOperatorPointer (ec, l, r);
2365 bool lenum = TypeManager.IsEnumType (l);
2366 bool renum = TypeManager.IsEnumType (r);
2367 if (lenum || renum) {
2368 expr = ResolveOperatorEnum (ec, lenum, renum, l, r);
2370 // TODO: Can this be ambiguous
2376 if ((oper == Operator.Addition || oper == Operator.Subtraction) && (l.IsDelegate || r.IsDelegate)) {
2378 expr = ResolveOperatorDelegate (ec, l, r);
2380 // TODO: Can this be ambiguous
2386 expr = ResolveUserOperator (ec, l, r);
2390 // Predefined reference types equality
2391 if ((oper & Operator.EqualityMask) != 0) {
2392 expr = ResolveOperatorEquality (ec, l, r);
2398 return ResolveOperatorPredefined (ec, standard_operators, primitives_only, null);
2401 // at least one of 'left' or 'right' is an enumeration constant (EnumConstant or SideEffectConstant or ...)
2402 // if 'left' is not an enumeration constant, create one from the type of 'right'
2403 Constant EnumLiftUp (ResolveContext ec, Constant left, Constant right, Location loc)
2406 case Operator.BitwiseOr:
2407 case Operator.BitwiseAnd:
2408 case Operator.ExclusiveOr:
2409 case Operator.Equality:
2410 case Operator.Inequality:
2411 case Operator.LessThan:
2412 case Operator.LessThanOrEqual:
2413 case Operator.GreaterThan:
2414 case Operator.GreaterThanOrEqual:
2415 if (TypeManager.IsEnumType (left.Type))
2418 if (left.IsZeroInteger)
2419 return left.TryReduce (ec, right.Type, loc);
2423 case Operator.Addition:
2424 case Operator.Subtraction:
2427 case Operator.Multiply:
2428 case Operator.Division:
2429 case Operator.Modulus:
2430 case Operator.LeftShift:
2431 case Operator.RightShift:
2432 if (TypeManager.IsEnumType (right.Type) || TypeManager.IsEnumType (left.Type))
2436 Error_OperatorCannotBeApplied (ec, this.left, this.right);
2441 // The `|' operator used on types which were extended is dangerous
2443 void CheckBitwiseOrOnSignExtended (ResolveContext ec)
2445 OpcodeCast lcast = left as OpcodeCast;
2446 if (lcast != null) {
2447 if (IsUnsigned (lcast.UnderlyingType))
2451 OpcodeCast rcast = right as OpcodeCast;
2452 if (rcast != null) {
2453 if (IsUnsigned (rcast.UnderlyingType))
2457 if (lcast == null && rcast == null)
2460 // FIXME: consider constants
2462 ec.Report.Warning (675, 3, loc,
2463 "The operator `|' used on the sign-extended type `{0}'. Consider casting to a smaller unsigned type first",
2464 TypeManager.CSharpName (lcast != null ? lcast.UnderlyingType : rcast.UnderlyingType));
2467 static void CreatePointerOperatorsTable ()
2469 var temp = new List<PredefinedPointerOperator> ();
2472 // Pointer arithmetic:
2474 // T* operator + (T* x, int y); T* operator - (T* x, int y);
2475 // T* operator + (T* x, uint y); T* operator - (T* x, uint y);
2476 // T* operator + (T* x, long y); T* operator - (T* x, long y);
2477 // T* operator + (T* x, ulong y); T* operator - (T* x, ulong y);
2479 temp.Add (new PredefinedPointerOperator (null, TypeManager.int32_type, Operator.AdditionMask | Operator.SubtractionMask));
2480 temp.Add (new PredefinedPointerOperator (null, TypeManager.uint32_type, Operator.AdditionMask | Operator.SubtractionMask));
2481 temp.Add (new PredefinedPointerOperator (null, TypeManager.int64_type, Operator.AdditionMask | Operator.SubtractionMask));
2482 temp.Add (new PredefinedPointerOperator (null, TypeManager.uint64_type, Operator.AdditionMask | Operator.SubtractionMask));
2485 // T* operator + (int y, T* x);
2486 // T* operator + (uint y, T *x);
2487 // T* operator + (long y, T *x);
2488 // T* operator + (ulong y, T *x);
2490 temp.Add (new PredefinedPointerOperator (TypeManager.int32_type, null, Operator.AdditionMask, null));
2491 temp.Add (new PredefinedPointerOperator (TypeManager.uint32_type, null, Operator.AdditionMask, null));
2492 temp.Add (new PredefinedPointerOperator (TypeManager.int64_type, null, Operator.AdditionMask, null));
2493 temp.Add (new PredefinedPointerOperator (TypeManager.uint64_type, null, Operator.AdditionMask, null));
2496 // long operator - (T* x, T *y)
2498 temp.Add (new PredefinedPointerOperator (null, Operator.SubtractionMask, TypeManager.int64_type));
2500 pointer_operators = temp.ToArray ();
2503 static void CreateStandardOperatorsTable ()
2505 var temp = new List<PredefinedOperator> ();
2506 TypeSpec bool_type = TypeManager.bool_type;
2508 temp.Add (new PredefinedOperator (TypeManager.int32_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2509 temp.Add (new PredefinedOperator (TypeManager.uint32_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2510 temp.Add (new PredefinedOperator (TypeManager.int64_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2511 temp.Add (new PredefinedOperator (TypeManager.uint64_type, Operator.ArithmeticMask | Operator.BitwiseMask));
2512 temp.Add (new PredefinedOperator (TypeManager.float_type, Operator.ArithmeticMask));
2513 temp.Add (new PredefinedOperator (TypeManager.double_type, Operator.ArithmeticMask));
2514 temp.Add (new PredefinedOperator (TypeManager.decimal_type, Operator.ArithmeticMask));
2516 temp.Add (new PredefinedOperator (TypeManager.int32_type, Operator.ComparisonMask, bool_type));
2517 temp.Add (new PredefinedOperator (TypeManager.uint32_type, Operator.ComparisonMask, bool_type));
2518 temp.Add (new PredefinedOperator (TypeManager.int64_type, Operator.ComparisonMask, bool_type));
2519 temp.Add (new PredefinedOperator (TypeManager.uint64_type, Operator.ComparisonMask, bool_type));
2520 temp.Add (new PredefinedOperator (TypeManager.float_type, Operator.ComparisonMask, bool_type));
2521 temp.Add (new PredefinedOperator (TypeManager.double_type, Operator.ComparisonMask, bool_type));
2522 temp.Add (new PredefinedOperator (TypeManager.decimal_type, Operator.ComparisonMask, bool_type));
2524 temp.Add (new PredefinedStringOperator (TypeManager.string_type, Operator.AdditionMask));
2525 temp.Add (new PredefinedStringOperator (TypeManager.string_type, TypeManager.object_type, Operator.AdditionMask));
2526 temp.Add (new PredefinedStringOperator (TypeManager.object_type, TypeManager.string_type, Operator.AdditionMask));
2528 temp.Add (new PredefinedOperator (bool_type,
2529 Operator.BitwiseMask | Operator.LogicalMask | Operator.EqualityMask, bool_type));
2531 temp.Add (new PredefinedShiftOperator (TypeManager.int32_type, Operator.ShiftMask));
2532 temp.Add (new PredefinedShiftOperator (TypeManager.uint32_type, Operator.ShiftMask));
2533 temp.Add (new PredefinedShiftOperator (TypeManager.int64_type, Operator.ShiftMask));
2534 temp.Add (new PredefinedShiftOperator (TypeManager.uint64_type, Operator.ShiftMask));
2536 standard_operators = temp.ToArray ();
2538 var equality = new List<PredefinedOperator> () {
2539 new PredefinedEqualityOperator (TypeManager.string_type, bool_type),
2540 new PredefinedEqualityOperator (TypeManager.delegate_type, bool_type),
2541 new PredefinedOperator (bool_type, Operator.EqualityMask, bool_type)
2544 equality_operators = equality.ToArray ();
2548 // Rules used during binary numeric promotion
2550 static bool DoNumericPromotion (ResolveContext rc, ref Expression prim_expr, ref Expression second_expr, TypeSpec type)
2555 Constant c = prim_expr as Constant;
2557 temp = c.ConvertImplicitly (rc, type);
2564 if (type == TypeManager.uint32_type) {
2565 etype = prim_expr.Type;
2566 if (etype == TypeManager.int32_type || etype == TypeManager.short_type || etype == TypeManager.sbyte_type) {
2567 type = TypeManager.int64_type;
2569 if (type != second_expr.Type) {
2570 c = second_expr as Constant;
2572 temp = c.ConvertImplicitly (rc, type);
2574 temp = Convert.ImplicitNumericConversion (second_expr, type);
2580 } else if (type == TypeManager.uint64_type) {
2582 // A compile-time error occurs if the other operand is of type sbyte, short, int, or long
2584 if (type == TypeManager.int32_type || type == TypeManager.int64_type ||
2585 type == TypeManager.short_type || type == TypeManager.sbyte_type)
2589 temp = Convert.ImplicitNumericConversion (prim_expr, type);
2598 // 7.2.6.2 Binary numeric promotions
2600 public bool DoBinaryOperatorPromotion (ResolveContext ec)
2602 TypeSpec ltype = left.Type;
2603 TypeSpec rtype = right.Type;
2606 foreach (TypeSpec t in ConstantFold.BinaryPromotionsTypes) {
2608 return t == rtype || DoNumericPromotion (ec, ref right, ref left, t);
2611 return t == ltype || DoNumericPromotion (ec, ref left, ref right, t);
2614 TypeSpec int32 = TypeManager.int32_type;
2615 if (ltype != int32) {
2616 Constant c = left as Constant;
2618 temp = c.ConvertImplicitly (ec, int32);
2620 temp = Convert.ImplicitNumericConversion (left, int32);
2627 if (rtype != int32) {
2628 Constant c = right as Constant;
2630 temp = c.ConvertImplicitly (ec, int32);
2632 temp = Convert.ImplicitNumericConversion (right, int32);
2642 protected override Expression DoResolve (ResolveContext ec)
2647 if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
2648 left = ((ParenthesizedExpression) left).Expr;
2649 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
2653 if (left.eclass == ExprClass.Type) {
2654 ec.Report.Error (75, loc, "To cast a negative value, you must enclose the value in parentheses");
2658 left = left.Resolve (ec);
2663 Constant lc = left as Constant;
2665 if (lc != null && lc.Type == TypeManager.bool_type &&
2666 ((oper == Operator.LogicalAnd && lc.IsDefaultValue) ||
2667 (oper == Operator.LogicalOr && !lc.IsDefaultValue))) {
2669 // FIXME: resolve right expression as unreachable
2670 // right.Resolve (ec);
2672 ec.Report.Warning (429, 4, loc, "Unreachable expression code detected");
2676 right = right.Resolve (ec);
2680 eclass = ExprClass.Value;
2681 Constant rc = right as Constant;
2683 // The conversion rules are ignored in enum context but why
2684 if (!ec.HasSet (ResolveContext.Options.EnumScope) && lc != null && rc != null && (TypeManager.IsEnumType (left.Type) || TypeManager.IsEnumType (right.Type))) {
2685 lc = EnumLiftUp (ec, lc, rc, loc);
2687 rc = EnumLiftUp (ec, rc, lc, loc);
2690 if (rc != null && lc != null) {
2691 int prev_e = ec.Report.Errors;
2692 Expression e = ConstantFold.BinaryFold (ec, oper, lc, rc, loc);
2696 if (e != null || ec.Report.Errors != prev_e)
2700 // Comparison warnings
2701 if ((oper & Operator.ComparisonMask) != 0) {
2702 if (left.Equals (right)) {
2703 ec.Report.Warning (1718, 3, loc, "A comparison made to same variable. Did you mean to compare something else?");
2705 CheckUselessComparison (ec, lc, right.Type);
2706 CheckUselessComparison (ec, rc, left.Type);
2709 if (left.Type == InternalType.Dynamic || right.Type == InternalType.Dynamic) {
2710 Arguments args = new Arguments (2);
2711 args.Add (new Argument (left));
2712 args.Add (new Argument (right));
2713 return new DynamicExpressionStatement (this, args, loc).Resolve (ec);
2716 if (RootContext.Version >= LanguageVersion.ISO_2 &&
2717 ((TypeManager.IsNullableType (left.Type) && (right is NullLiteral || TypeManager.IsNullableType (right.Type) || TypeManager.IsValueType (right.Type))) ||
2718 (TypeManager.IsValueType (left.Type) && right is NullLiteral) ||
2719 (TypeManager.IsNullableType (right.Type) && (left is NullLiteral || TypeManager.IsNullableType (left.Type) || TypeManager.IsValueType (left.Type))) ||
2720 (TypeManager.IsValueType (right.Type) && left is NullLiteral)))
2721 return new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
2723 return DoResolveCore (ec, left, right);
2726 protected Expression DoResolveCore (ResolveContext ec, Expression left_orig, Expression right_orig)
2728 Expression expr = ResolveOperator (ec);
2730 Error_OperatorCannotBeApplied (ec, left_orig, right_orig);
2732 if (left == null || right == null)
2733 throw new InternalErrorException ("Invalid conversion");
2735 if (oper == Operator.BitwiseOr)
2736 CheckBitwiseOrOnSignExtended (ec);
2741 public override SLE.Expression MakeExpression (BuilderContext ctx)
2743 var le = left.MakeExpression (ctx);
2744 var re = right.MakeExpression (ctx);
2745 bool is_checked = ctx.HasSet (BuilderContext.Options.CheckedScope);
2748 case Operator.Addition:
2749 return is_checked ? SLE.Expression.AddChecked (le, re) : SLE.Expression.Add (le, re);
2750 case Operator.BitwiseAnd:
2751 return SLE.Expression.And (le, re);
2752 case Operator.BitwiseOr:
2753 return SLE.Expression.Or (le, re);
2754 case Operator.Division:
2755 return SLE.Expression.Divide (le, re);
2756 case Operator.Equality:
2757 return SLE.Expression.Equal (le, re);
2758 case Operator.ExclusiveOr:
2759 return SLE.Expression.ExclusiveOr (le, re);
2760 case Operator.GreaterThan:
2761 return SLE.Expression.GreaterThan (le, re);
2762 case Operator.GreaterThanOrEqual:
2763 return SLE.Expression.GreaterThanOrEqual (le, re);
2764 case Operator.Inequality:
2765 return SLE.Expression.NotEqual (le, re);
2766 case Operator.LeftShift:
2767 return SLE.Expression.LeftShift (le, re);
2768 case Operator.LessThan:
2769 return SLE.Expression.LessThan (le, re);
2770 case Operator.LessThanOrEqual:
2771 return SLE.Expression.LessThanOrEqual (le, re);
2772 case Operator.LogicalAnd:
2773 return SLE.Expression.AndAlso (le, re);
2774 case Operator.LogicalOr:
2775 return SLE.Expression.OrElse (le, re);
2776 case Operator.Modulus:
2777 return SLE.Expression.Modulo (le, re);
2778 case Operator.Multiply:
2779 return is_checked ? SLE.Expression.MultiplyChecked (le, re) : SLE.Expression.Multiply (le, re);
2780 case Operator.RightShift:
2781 return SLE.Expression.RightShift (le, re);
2782 case Operator.Subtraction:
2783 return is_checked ? SLE.Expression.SubtractChecked (le, re) : SLE.Expression.Subtract (le, re);
2785 throw new NotImplementedException (oper.ToString ());
2790 // D operator + (D x, D y)
2791 // D operator - (D x, D y)
2793 Expression ResolveOperatorDelegate (ResolveContext ec, TypeSpec l, TypeSpec r)
2795 if (l != r && !TypeSpecComparer.Variant.IsEqual (r, l)) {
2797 if (right.eclass == ExprClass.MethodGroup || r == InternalType.AnonymousMethod || r == InternalType.Null) {
2798 tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
2803 } else if (left.eclass == ExprClass.MethodGroup || (l == InternalType.AnonymousMethod)) {
2804 tmp = Convert.ImplicitConversionRequired (ec, left, r, loc);
2815 Arguments args = new Arguments (2);
2816 args.Add (new Argument (left));
2817 args.Add (new Argument (right));
2819 if (oper == Operator.Addition) {
2820 if (TypeManager.delegate_combine_delegate_delegate == null) {
2821 TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
2822 TypeManager.delegate_type, "Combine", loc, TypeManager.delegate_type, TypeManager.delegate_type);
2825 method = TypeManager.delegate_combine_delegate_delegate;
2826 } else if (oper == Operator.Subtraction) {
2827 if (TypeManager.delegate_remove_delegate_delegate == null) {
2828 TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
2829 TypeManager.delegate_type, "Remove", loc, TypeManager.delegate_type, TypeManager.delegate_type);
2832 method = TypeManager.delegate_remove_delegate_delegate;
2834 return new EmptyExpression (TypeManager.decimal_type);
2837 MethodGroupExpr mg = MethodGroupExpr.CreatePredefined (method, TypeManager.delegate_type, loc);
2838 Expression expr = new UserOperatorCall (mg.BestCandidate, args, CreateExpressionTree, loc);
2839 return new ClassCast (expr, l);
2843 // Enumeration operators
2845 Expression ResolveOperatorEnum (ResolveContext ec, bool lenum, bool renum, TypeSpec ltype, TypeSpec rtype)
2848 // bool operator == (E x, E y);
2849 // bool operator != (E x, E y);
2850 // bool operator < (E x, E y);
2851 // bool operator > (E x, E y);
2852 // bool operator <= (E x, E y);
2853 // bool operator >= (E x, E y);
2855 // E operator & (E x, E y);
2856 // E operator | (E x, E y);
2857 // E operator ^ (E x, E y);
2859 // U operator - (E e, E f)
2860 // E operator - (E e, U x)
2862 // E operator + (U x, E e)
2863 // E operator + (E e, U x)
2865 if (!((oper & (Operator.ComparisonMask | Operator.BitwiseMask)) != 0 ||
2866 (oper == Operator.Subtraction && lenum) ||
2867 (oper == Operator.Addition && (lenum != renum || type != null)))) // type != null for lifted null
2870 Expression ltemp = left;
2871 Expression rtemp = right;
2872 TypeSpec underlying_type;
2875 if ((oper & (Operator.ComparisonMask | Operator.BitwiseMask)) != 0) {
2877 expr = Convert.ImplicitConversion (ec, left, rtype, loc);
2883 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
2891 if (ltype == rtype) {
2892 underlying_type = EnumSpec.GetUnderlyingType (ltype);
2894 if (left is Constant)
2895 left = ((Constant) left).ConvertExplicitly (false, underlying_type).Resolve (ec);
2897 left = EmptyCast.Create (left, underlying_type);
2899 if (right is Constant)
2900 right = ((Constant) right).ConvertExplicitly (false, underlying_type).Resolve (ec);
2902 right = EmptyCast.Create (right, underlying_type);
2904 underlying_type = EnumSpec.GetUnderlyingType (ltype);
2906 if (oper != Operator.Subtraction && oper != Operator.Addition) {
2907 Constant c = right as Constant;
2908 if (c == null || !c.IsDefaultValue)
2911 if (!Convert.ImplicitStandardConversionExists (right, underlying_type))
2914 right = Convert.ImplicitConversionStandard (ec, right, underlying_type, right.Location);
2917 if (left is Constant)
2918 left = ((Constant) left).ConvertExplicitly (false, underlying_type).Resolve (ec);
2920 left = EmptyCast.Create (left, underlying_type);
2923 underlying_type = EnumSpec.GetUnderlyingType (rtype);
2925 if (oper != Operator.Addition) {
2926 Constant c = left as Constant;
2927 if (c == null || !c.IsDefaultValue)
2930 if (!Convert.ImplicitStandardConversionExists (left, underlying_type))
2933 left = Convert.ImplicitConversionStandard (ec, left, underlying_type, left.Location);
2936 if (right is Constant)
2937 right = ((Constant) right).ConvertExplicitly (false, underlying_type).Resolve (ec);
2939 right = EmptyCast.Create (right, underlying_type);
2946 // C# specification uses explicit cast syntax which means binary promotion
2947 // should happen, however it seems that csc does not do that
2949 if (!DoBinaryOperatorPromotion (ec)) {
2955 TypeSpec res_type = null;
2956 if ((oper & Operator.BitwiseMask) != 0 || oper == Operator.Subtraction || oper == Operator.Addition) {
2957 TypeSpec promoted_type = lenum ? left.Type : right.Type;
2958 enum_conversion = Convert.ExplicitNumericConversion (
2959 new EmptyExpression (promoted_type), underlying_type);
2961 if (oper == Operator.Subtraction && renum && lenum)
2962 res_type = underlying_type;
2963 else if (oper == Operator.Addition && renum)
2969 expr = ResolveOperatorPredefined (ec, standard_operators, true, res_type);
2970 if (!is_compound || expr == null)
2978 // If the return type of the selected operator is implicitly convertible to the type of x
2980 if (Convert.ImplicitConversionExists (ec, expr, ltype))
2984 // Otherwise, if the selected operator is a predefined operator, if the return type of the
2985 // selected operator is explicitly convertible to the type of x, and if y is implicitly
2986 // convertible to the type of x or the operator is a shift operator, then the operation
2987 // is evaluated as x = (T)(x op y), where T is the type of x
2989 expr = Convert.ExplicitConversion (ec, expr, ltype, loc);
2993 if (Convert.ImplicitConversionExists (ec, ltemp, ltype))
3000 // 7.9.6 Reference type equality operators
3002 Expression ResolveOperatorEquality (ResolveContext ec, TypeSpec l, TypeSpec r)
3005 type = TypeManager.bool_type;
3008 // a, Both operands are reference-type values or the value null
3009 // b, One operand is a value of type T where T is a type-parameter and
3010 // the other operand is the value null. Furthermore T does not have the
3011 // value type constraint
3013 // LAMESPEC: Very confusing details in the specification, basically any
3014 // reference like type-parameter is allowed
3016 var tparam_l = l as TypeParameterSpec;
3017 var tparam_r = r as TypeParameterSpec;
3018 if (tparam_l != null) {
3019 if (right is NullLiteral && !tparam_l.HasSpecialStruct) {
3020 left = new BoxedCast (left, TypeManager.object_type);
3024 if (!tparam_l.IsReferenceType)
3027 l = tparam_l.GetEffectiveBase ();
3028 left = new BoxedCast (left, l);
3029 } else if (left is NullLiteral && tparam_r == null) {
3030 if (!TypeManager.IsReferenceType (r) || r.Kind == MemberKind.InternalCompilerType)
3036 if (tparam_r != null) {
3037 if (left is NullLiteral && !tparam_r.HasSpecialStruct) {
3038 right = new BoxedCast (right, TypeManager.object_type);
3042 if (!tparam_r.IsReferenceType)
3045 r = tparam_r.GetEffectiveBase ();
3046 right = new BoxedCast (right, r);
3047 } else if (right is NullLiteral) {
3048 if (!TypeManager.IsReferenceType (l) || l.Kind == MemberKind.InternalCompilerType)
3055 // LAMESPEC: method groups can be compared when they convert to other side delegate
3058 if (right.eclass == ExprClass.MethodGroup) {
3059 result = Convert.ImplicitConversion (ec, right, l, loc);
3065 } else if (r.IsDelegate && l != r) {
3068 } else if (left.eclass == ExprClass.MethodGroup && r.IsDelegate) {
3069 result = Convert.ImplicitConversionRequired (ec, left, r, loc);
3078 // bool operator != (string a, string b)
3079 // bool operator == (string a, string b)
3081 // bool operator != (Delegate a, Delegate b)
3082 // bool operator == (Delegate a, Delegate b)
3084 // bool operator != (bool a, bool b)
3085 // bool operator == (bool a, bool b)
3087 // LAMESPEC: Reference equality comparison can apply to value types when
3088 // they implement an implicit conversion to any of types above.
3090 if (r != TypeManager.object_type && l != TypeManager.object_type) {
3091 result = ResolveOperatorPredefined (ec, equality_operators, false, null);
3097 // bool operator != (object a, object b)
3098 // bool operator == (object a, object b)
3100 // An explicit reference conversion exists from the
3101 // type of either operand to the type of the other operand.
3104 // Optimize common path
3106 return l.Kind == MemberKind.InternalCompilerType || l.Kind == MemberKind.Struct ? null : this;
3109 if (!Convert.ExplicitReferenceConversionExists (l, r) &&
3110 !Convert.ExplicitReferenceConversionExists (r, l))
3113 // Reject allowed explicit conversions like int->object
3114 if (!TypeManager.IsReferenceType (l) || !TypeManager.IsReferenceType (r))
3117 if (l == TypeManager.string_type || l == TypeManager.delegate_type || MemberCache.GetUserOperator (l, CSharp.Operator.OpType.Equality, false) != null)
3118 ec.Report.Warning (253, 2, loc,
3119 "Possible unintended reference comparison. Consider casting the right side expression to type `{0}' to get value comparison",
3120 l.GetSignatureForError ());
3122 if (r == TypeManager.string_type || r == TypeManager.delegate_type || MemberCache.GetUserOperator (r, CSharp.Operator.OpType.Equality, false) != null)
3123 ec.Report.Warning (252, 2, loc,
3124 "Possible unintended reference comparison. Consider casting the left side expression to type `{0}' to get value comparison",
3125 r.GetSignatureForError ());
3131 Expression ResolveOperatorPointer (ResolveContext ec, TypeSpec l, TypeSpec r)
3134 // bool operator == (void* x, void* y);
3135 // bool operator != (void* x, void* y);
3136 // bool operator < (void* x, void* y);
3137 // bool operator > (void* x, void* y);
3138 // bool operator <= (void* x, void* y);
3139 // bool operator >= (void* x, void* y);
3141 if ((oper & Operator.ComparisonMask) != 0) {
3144 temp = Convert.ImplicitConversion (ec, left, r, left.Location);
3151 temp = Convert.ImplicitConversion (ec, right, l, right.Location);
3157 type = TypeManager.bool_type;
3161 if (pointer_operators == null)
3162 CreatePointerOperatorsTable ();
3164 return ResolveOperatorPredefined (ec, pointer_operators, false, null);
3168 // Build-in operators method overloading
3170 protected virtual Expression ResolveOperatorPredefined (ResolveContext ec, PredefinedOperator [] operators, bool primitives_only, TypeSpec enum_type)
3172 PredefinedOperator best_operator = null;
3173 TypeSpec l = left.Type;
3174 TypeSpec r = right.Type;
3175 Operator oper_mask = oper & ~Operator.ValuesOnlyMask;
3177 foreach (PredefinedOperator po in operators) {
3178 if ((po.OperatorsMask & oper_mask) == 0)
3181 if (primitives_only) {
3182 if (!po.IsPrimitiveApplicable (l, r))
3185 if (!po.IsApplicable (ec, left, right))
3189 if (best_operator == null) {
3191 if (primitives_only)
3197 best_operator = po.ResolveBetterOperator (ec, best_operator);
3199 if (best_operator == null) {
3200 ec.Report.Error (34, loc, "Operator `{0}' is ambiguous on operands of type `{1}' and `{2}'",
3201 OperName (oper), TypeManager.CSharpName (l), TypeManager.CSharpName (r));
3208 if (best_operator == null)
3211 Expression expr = best_operator.ConvertResult (ec, this);
3214 // Optimize &/&& constant expressions with 0 value
3216 if (oper == Operator.BitwiseAnd || oper == Operator.LogicalAnd) {
3217 Constant rc = right as Constant;
3218 Constant lc = left as Constant;
3219 if ((lc != null && lc.IsDefaultValue) || (rc != null && rc.IsDefaultValue)) {
3221 // The result is a constant with side-effect
3223 Constant side_effect = rc == null ?
3224 new SideEffectConstant (lc, right, loc) :
3225 new SideEffectConstant (rc, left, loc);
3227 return ReducedExpression.Create (side_effect.Resolve (ec), expr);
3231 if (enum_type == null)
3235 // HACK: required by enum_conversion
3237 expr.Type = enum_type;
3238 return EmptyCast.Create (expr, enum_type);
3242 // Performs user-operator overloading
3244 protected virtual Expression ResolveUserOperator (ResolveContext ec, TypeSpec l, TypeSpec r)
3246 var op = ConvertBinaryToUserOperator (oper);
3247 IList<MemberSpec> left_operators = MemberCache.GetUserOperator (l, op, false);
3248 IList<MemberSpec> right_operators = null;
3251 right_operators = MemberCache.GetUserOperator (r, op, false);
3252 if (right_operators == null && left_operators == null)
3254 } else if (left_operators == null) {
3258 Arguments args = new Arguments (2);
3259 Argument larg = new Argument (left);
3261 Argument rarg = new Argument (right);
3265 // User-defined operator implementations always take precedence
3266 // over predefined operator implementations
3268 if (left_operators != null && right_operators != null) {
3269 left_operators = CombineUserOperators (left_operators, right_operators);
3270 } else if (right_operators != null) {
3271 left_operators = right_operators;
3274 var res = new OverloadResolver (left_operators, OverloadResolver.Restrictions.ProbingOnly, loc);
3276 var oper_method = res.ResolveOperator (ec, ref args);
3277 if (oper_method == null)
3280 Expression oper_expr;
3282 // TODO: CreateExpressionTree is allocated every time
3283 if ((oper & Operator.LogicalMask) != 0) {
3284 oper_expr = new ConditionalLogicalOperator (oper_method, args, CreateExpressionTree,
3285 oper == Operator.LogicalAnd, loc).Resolve (ec);
3287 oper_expr = new UserOperatorCall (oper_method, args, CreateExpressionTree, loc);
3296 // Merge two sets of user operators into one, they are mostly distinguish
3297 // expect when they share base type and it contains an operator
3299 static IList<MemberSpec> CombineUserOperators (IList<MemberSpec> left, IList<MemberSpec> right)
3301 var combined = new List<MemberSpec> (left.Count + right.Count);
3302 combined.AddRange (left);
3303 foreach (var r in right) {
3305 foreach (var l in left) {
3306 if (l.DeclaringType == r.DeclaringType) {
3319 public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
3324 private void CheckUselessComparison (ResolveContext ec, Constant c, TypeSpec type)
3326 if (c == null || !IsTypeIntegral (type)
3327 || c is StringConstant
3328 || c is BoolConstant
3329 || c is FloatConstant
3330 || c is DoubleConstant
3331 || c is DecimalConstant
3337 if (c is ULongConstant) {
3338 ulong uvalue = ((ULongConstant) c).Value;
3339 if (uvalue > long.MaxValue) {
3340 if (type == TypeManager.byte_type ||
3341 type == TypeManager.sbyte_type ||
3342 type == TypeManager.short_type ||
3343 type == TypeManager.ushort_type ||
3344 type == TypeManager.int32_type ||
3345 type == TypeManager.uint32_type ||
3346 type == TypeManager.int64_type ||
3347 type == TypeManager.char_type)
3348 WarnUselessComparison (ec, type);
3351 value = (long) uvalue;
3353 else if (c is ByteConstant)
3354 value = ((ByteConstant) c).Value;
3355 else if (c is SByteConstant)
3356 value = ((SByteConstant) c).Value;
3357 else if (c is ShortConstant)
3358 value = ((ShortConstant) c).Value;
3359 else if (c is UShortConstant)
3360 value = ((UShortConstant) c).Value;
3361 else if (c is IntConstant)
3362 value = ((IntConstant) c).Value;
3363 else if (c is UIntConstant)
3364 value = ((UIntConstant) c).Value;
3365 else if (c is LongConstant)
3366 value = ((LongConstant) c).Value;
3367 else if (c is CharConstant)
3368 value = ((CharConstant)c).Value;
3373 if (IsValueOutOfRange (value, type))
3374 WarnUselessComparison (ec, type);
3377 static bool IsValueOutOfRange (long value, TypeSpec type)
3379 if (IsTypeUnsigned (type) && value < 0)
3381 return type == TypeManager.sbyte_type && (value >= 0x80 || value < -0x80) ||
3382 type == TypeManager.byte_type && value >= 0x100 ||
3383 type == TypeManager.short_type && (value >= 0x8000 || value < -0x8000) ||
3384 type == TypeManager.ushort_type && value >= 0x10000 ||
3385 type == TypeManager.int32_type && (value >= 0x80000000 || value < -0x80000000) ||
3386 type == TypeManager.uint32_type && value >= 0x100000000;
3389 private static bool IsTypeIntegral (TypeSpec type)
3391 return type == TypeManager.uint64_type ||
3392 type == TypeManager.int64_type ||
3393 type == TypeManager.uint32_type ||
3394 type == TypeManager.int32_type ||
3395 type == TypeManager.ushort_type ||
3396 type == TypeManager.short_type ||
3397 type == TypeManager.sbyte_type ||
3398 type == TypeManager.byte_type ||
3399 type == TypeManager.char_type;
3402 private static bool IsTypeUnsigned (TypeSpec type)
3404 return type == TypeManager.uint64_type ||
3405 type == TypeManager.uint32_type ||
3406 type == TypeManager.ushort_type ||
3407 type == TypeManager.byte_type ||
3408 type == TypeManager.char_type;
3411 private void WarnUselessComparison (ResolveContext ec, TypeSpec type)
3413 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}'",
3414 TypeManager.CSharpName (type));
3418 /// EmitBranchable is called from Statement.EmitBoolExpression in the
3419 /// context of a conditional bool expression. This function will return
3420 /// false if it is was possible to use EmitBranchable, or true if it was.
3422 /// The expression's code is generated, and we will generate a branch to `target'
3423 /// if the resulting expression value is equal to isTrue
3425 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
3428 // This is more complicated than it looks, but its just to avoid
3429 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
3430 // but on top of that we want for == and != to use a special path
3431 // if we are comparing against null
3433 if ((oper & Operator.EqualityMask) != 0 && (left is Constant || right is Constant)) {
3434 bool my_on_true = oper == Operator.Inequality ? on_true : !on_true;
3437 // put the constant on the rhs, for simplicity
3439 if (left is Constant) {
3440 Expression swap = right;
3446 // brtrue/brfalse works with native int only
3448 if (((Constant) right).IsZeroInteger && right.Type != TypeManager.int64_type && right.Type != TypeManager.uint64_type) {
3449 left.EmitBranchable (ec, target, my_on_true);
3452 if (right.Type == TypeManager.bool_type) {
3453 // right is a boolean, and it's not 'false' => it is 'true'
3454 left.EmitBranchable (ec, target, !my_on_true);
3458 } else if (oper == Operator.LogicalAnd) {
3461 Label tests_end = ec.DefineLabel ();
3463 left.EmitBranchable (ec, tests_end, false);
3464 right.EmitBranchable (ec, target, true);
3465 ec.MarkLabel (tests_end);
3468 // This optimizes code like this
3469 // if (true && i > 4)
3471 if (!(left is Constant))
3472 left.EmitBranchable (ec, target, false);
3474 if (!(right is Constant))
3475 right.EmitBranchable (ec, target, false);
3480 } else if (oper == Operator.LogicalOr){
3482 left.EmitBranchable (ec, target, true);
3483 right.EmitBranchable (ec, target, true);
3486 Label tests_end = ec.DefineLabel ();
3487 left.EmitBranchable (ec, tests_end, true);
3488 right.EmitBranchable (ec, target, false);
3489 ec.MarkLabel (tests_end);
3494 } else if ((oper & Operator.ComparisonMask) == 0) {
3495 base.EmitBranchable (ec, target, on_true);
3502 TypeSpec t = left.Type;
3503 bool is_float = IsFloat (t);
3504 bool is_unsigned = is_float || IsUnsigned (t);
3507 case Operator.Equality:
3509 ec.Emit (OpCodes.Beq, target);
3511 ec.Emit (OpCodes.Bne_Un, target);
3514 case Operator.Inequality:
3516 ec.Emit (OpCodes.Bne_Un, target);
3518 ec.Emit (OpCodes.Beq, target);
3521 case Operator.LessThan:
3523 if (is_unsigned && !is_float)
3524 ec.Emit (OpCodes.Blt_Un, target);
3526 ec.Emit (OpCodes.Blt, target);
3529 ec.Emit (OpCodes.Bge_Un, target);
3531 ec.Emit (OpCodes.Bge, target);
3534 case Operator.GreaterThan:
3536 if (is_unsigned && !is_float)
3537 ec.Emit (OpCodes.Bgt_Un, target);
3539 ec.Emit (OpCodes.Bgt, target);
3542 ec.Emit (OpCodes.Ble_Un, target);
3544 ec.Emit (OpCodes.Ble, target);
3547 case Operator.LessThanOrEqual:
3549 if (is_unsigned && !is_float)
3550 ec.Emit (OpCodes.Ble_Un, target);
3552 ec.Emit (OpCodes.Ble, target);
3555 ec.Emit (OpCodes.Bgt_Un, target);
3557 ec.Emit (OpCodes.Bgt, target);
3561 case Operator.GreaterThanOrEqual:
3563 if (is_unsigned && !is_float)
3564 ec.Emit (OpCodes.Bge_Un, target);
3566 ec.Emit (OpCodes.Bge, target);
3569 ec.Emit (OpCodes.Blt_Un, target);
3571 ec.Emit (OpCodes.Blt, target);
3574 throw new InternalErrorException (oper.ToString ());
3578 public override void Emit (EmitContext ec)
3580 EmitOperator (ec, left.Type);
3583 protected virtual void EmitOperator (EmitContext ec, TypeSpec l)
3586 // Handle short-circuit operators differently
3589 if ((oper & Operator.LogicalMask) != 0) {
3590 Label load_result = ec.DefineLabel ();
3591 Label end = ec.DefineLabel ();
3593 bool is_or = oper == Operator.LogicalOr;
3594 left.EmitBranchable (ec, load_result, is_or);
3596 ec.Emit (OpCodes.Br_S, end);
3598 ec.MarkLabel (load_result);
3599 ec.Emit (is_or ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
3605 // Optimize zero-based operations which cannot be optimized at expression level
3607 if (oper == Operator.Subtraction) {
3608 var lc = left as IntegralConstant;
3609 if (lc != null && lc.IsDefaultValue) {
3611 ec.Emit (OpCodes.Neg);
3618 EmitOperatorOpcode (ec, oper, l);
3621 // Nullable enum could require underlying type cast and we cannot simply wrap binary
3622 // expression because that would wrap lifted binary operation
3624 if (enum_conversion != null)
3625 enum_conversion.Emit (ec);
3628 public override void EmitSideEffect (EmitContext ec)
3630 if ((oper & Operator.LogicalMask) != 0 ||
3631 (ec.HasSet (EmitContext.Options.CheckedScope) && (oper == Operator.Multiply || oper == Operator.Addition || oper == Operator.Subtraction))) {
3632 base.EmitSideEffect (ec);
3634 left.EmitSideEffect (ec);
3635 right.EmitSideEffect (ec);
3639 protected override void CloneTo (CloneContext clonectx, Expression t)
3641 Binary target = (Binary) t;
3643 target.left = left.Clone (clonectx);
3644 target.right = right.Clone (clonectx);
3647 public Expression CreateCallSiteBinder (ResolveContext ec, Arguments args)
3649 Arguments binder_args = new Arguments (4);
3651 MemberAccess sle = new MemberAccess (new MemberAccess (
3652 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Linq", loc), "Expressions", loc);
3654 CSharpBinderFlags flags = 0;
3655 if (ec.HasSet (ResolveContext.Options.CheckedScope))
3656 flags = CSharpBinderFlags.CheckedContext;
3658 if ((oper & Operator.LogicalMask) != 0)
3659 flags |= CSharpBinderFlags.BinaryOperationLogical;
3661 binder_args.Add (new Argument (new EnumConstant (new IntLiteral ((int) flags, loc), TypeManager.binder_flags)));
3662 binder_args.Add (new Argument (new MemberAccess (new MemberAccess (sle, "ExpressionType", loc), GetOperatorExpressionTypeName (), loc)));
3663 binder_args.Add (new Argument (new TypeOf (new TypeExpression (ec.CurrentType, loc), loc)));
3664 binder_args.Add (new Argument (new ImplicitlyTypedArrayCreation (args.CreateDynamicBinderArguments (ec), loc)));
3666 return new Invocation (DynamicExpressionStatement.GetBinder ("BinaryOperation", loc), binder_args);
3669 public override Expression CreateExpressionTree (ResolveContext ec)
3671 return CreateExpressionTree (ec, null);
3674 Expression CreateExpressionTree (ResolveContext ec, Expression method)
3677 bool lift_arg = false;
3680 case Operator.Addition:
3681 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
3682 method_name = "AddChecked";
3684 method_name = "Add";
3686 case Operator.BitwiseAnd:
3687 method_name = "And";
3689 case Operator.BitwiseOr:
3692 case Operator.Division:
3693 method_name = "Divide";
3695 case Operator.Equality:
3696 method_name = "Equal";
3699 case Operator.ExclusiveOr:
3700 method_name = "ExclusiveOr";
3702 case Operator.GreaterThan:
3703 method_name = "GreaterThan";
3706 case Operator.GreaterThanOrEqual:
3707 method_name = "GreaterThanOrEqual";
3710 case Operator.Inequality:
3711 method_name = "NotEqual";
3714 case Operator.LeftShift:
3715 method_name = "LeftShift";
3717 case Operator.LessThan:
3718 method_name = "LessThan";
3721 case Operator.LessThanOrEqual:
3722 method_name = "LessThanOrEqual";
3725 case Operator.LogicalAnd:
3726 method_name = "AndAlso";
3728 case Operator.LogicalOr:
3729 method_name = "OrElse";
3731 case Operator.Modulus:
3732 method_name = "Modulo";
3734 case Operator.Multiply:
3735 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
3736 method_name = "MultiplyChecked";
3738 method_name = "Multiply";
3740 case Operator.RightShift:
3741 method_name = "RightShift";
3743 case Operator.Subtraction:
3744 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
3745 method_name = "SubtractChecked";
3747 method_name = "Subtract";
3751 throw new InternalErrorException ("Unknown expression tree binary operator " + oper);
3754 Arguments args = new Arguments (2);
3755 args.Add (new Argument (left.CreateExpressionTree (ec)));
3756 args.Add (new Argument (right.CreateExpressionTree (ec)));
3757 if (method != null) {
3759 args.Add (new Argument (new BoolConstant (false, loc)));
3761 args.Add (new Argument (method));
3764 return CreateExpressionFactoryCall (ec, method_name, args);
3769 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3770 // b, c, d... may be strings or objects.
3772 public class StringConcat : Expression {
3773 Arguments arguments;
3774 static IList<MemberSpec> concat_members;
3776 public StringConcat (Expression left, Expression right, Location loc)
3779 type = TypeManager.string_type;
3780 eclass = ExprClass.Value;
3782 arguments = new Arguments (2);
3785 public static StringConcat Create (ResolveContext rc, Expression left, Expression right, Location loc)
3787 if (left.eclass == ExprClass.Unresolved || right.eclass == ExprClass.Unresolved)
3788 throw new ArgumentException ();
3790 var s = new StringConcat (left, right, loc);
3791 s.Append (rc, left);
3792 s.Append (rc, right);
3796 public override Expression CreateExpressionTree (ResolveContext ec)
3798 Argument arg = arguments [0];
3799 return CreateExpressionAddCall (ec, arg, arg.CreateExpressionTree (ec), 1);
3803 // Creates nested calls tree from an array of arguments used for IL emit
3805 Expression CreateExpressionAddCall (ResolveContext ec, Argument left, Expression left_etree, int pos)
3807 Arguments concat_args = new Arguments (2);
3808 Arguments add_args = new Arguments (3);
3810 concat_args.Add (left);
3811 add_args.Add (new Argument (left_etree));
3813 concat_args.Add (arguments [pos]);
3814 add_args.Add (new Argument (arguments [pos].CreateExpressionTree (ec)));
3816 var methods = CreateConcatMethodCandidates ();
3817 if (methods == null)
3820 var res = new OverloadResolver (methods, OverloadResolver.Restrictions.NoBaseMembers, loc);
3821 var method = res.ResolveMember<MethodSpec> (ec, ref concat_args);
3825 add_args.Add (new Argument (new TypeOfMethod (method, loc)));
3827 Expression expr = CreateExpressionFactoryCall (ec, "Add", add_args);
3828 if (++pos == arguments.Count)
3831 left = new Argument (new EmptyExpression (method.ReturnType));
3832 return CreateExpressionAddCall (ec, left, expr, pos);
3835 protected override Expression DoResolve (ResolveContext ec)
3840 void Append (ResolveContext rc, Expression operand)
3845 StringConstant sc = operand as StringConstant;
3847 if (arguments.Count != 0) {
3848 Argument last_argument = arguments [arguments.Count - 1];
3849 StringConstant last_expr_constant = last_argument.Expr as StringConstant;
3850 if (last_expr_constant != null) {
3851 last_argument.Expr = new StringConstant (
3852 last_expr_constant.Value + sc.Value, sc.Location).Resolve (rc);
3858 // Multiple (3+) concatenation are resolved as multiple StringConcat instances
3860 StringConcat concat_oper = operand as StringConcat;
3861 if (concat_oper != null) {
3862 arguments.AddRange (concat_oper.arguments);
3867 arguments.Add (new Argument (operand));
3870 IList<MemberSpec> CreateConcatMethodCandidates ()
3872 if (concat_members == null) {
3873 concat_members = MemberCache.FindMembers (type, "Concat", true);
3876 return concat_members;
3879 public override void Emit (EmitContext ec)
3881 var members = CreateConcatMethodCandidates ();
3882 var res = new OverloadResolver (members, OverloadResolver.Restrictions.NoBaseMembers, loc);
3883 var method = res.ResolveMember<MethodSpec> (new ResolveContext (ec.MemberContext), ref arguments);
3885 Invocation.EmitCall (ec, null, method, arguments, loc);
3888 public override SLE.Expression MakeExpression (BuilderContext ctx)
3890 if (arguments.Count != 2)
3891 throw new NotImplementedException ("arguments.Count != 2");
3893 var concat = typeof (string).GetMethod ("Concat", new[] { typeof (object), typeof (object) });
3894 return SLE.Expression.Add (arguments[0].Expr.MakeExpression (ctx), arguments[1].Expr.MakeExpression (ctx), concat);
3897 public static void Reset ()
3899 concat_members = null;
3904 // User-defined conditional logical operator
3906 public class ConditionalLogicalOperator : UserOperatorCall {
3907 readonly bool is_and;
3908 Expression oper_expr;
3910 public ConditionalLogicalOperator (MethodSpec oper, Arguments arguments, Func<ResolveContext, Expression, Expression> expr_tree, bool is_and, Location loc)
3911 : base (oper, arguments, expr_tree, loc)
3913 this.is_and = is_and;
3914 eclass = ExprClass.Unresolved;
3917 protected override Expression DoResolve (ResolveContext ec)
3919 AParametersCollection pd = oper.Parameters;
3920 if (!TypeSpecComparer.IsEqual (type, pd.Types[0]) || !TypeSpecComparer.IsEqual (type, pd.Types[1])) {
3921 ec.Report.Error (217, loc,
3922 "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",
3923 oper.GetSignatureForError ());
3927 Expression left_dup = new EmptyExpression (type);
3928 Expression op_true = GetOperatorTrue (ec, left_dup, loc);
3929 Expression op_false = GetOperatorFalse (ec, left_dup, loc);
3930 if (op_true == null || op_false == null) {
3931 ec.Report.Error (218, loc,
3932 "The type `{0}' must have operator `true' and operator `false' defined when `{1}' is used as a short circuit operator",
3933 TypeManager.CSharpName (type), oper.GetSignatureForError ());
3937 oper_expr = is_and ? op_false : op_true;
3938 eclass = ExprClass.Value;
3942 public override void Emit (EmitContext ec)
3944 Label end_target = ec.DefineLabel ();
3947 // Emit and duplicate left argument
3949 arguments [0].Expr.Emit (ec);
3950 ec.Emit (OpCodes.Dup);
3951 arguments.RemoveAt (0);
3953 oper_expr.EmitBranchable (ec, end_target, true);
3955 ec.MarkLabel (end_target);
3959 public class PointerArithmetic : Expression {
3960 Expression left, right;
3964 // We assume that `l' is always a pointer
3966 public PointerArithmetic (Binary.Operator op, Expression l, Expression r, TypeSpec t, Location loc)
3975 public override Expression CreateExpressionTree (ResolveContext ec)
3977 Error_PointerInsideExpressionTree (ec);
3981 protected override Expression DoResolve (ResolveContext ec)
3983 eclass = ExprClass.Variable;
3985 if (left.Type == TypeManager.void_ptr_type) {
3986 ec.Report.Error (242, loc, "The operation in question is undefined on void pointers");
3993 public override void Emit (EmitContext ec)
3995 TypeSpec op_type = left.Type;
3997 // It must be either array or fixed buffer
3999 if (TypeManager.HasElementType (op_type)) {
4000 element = TypeManager.GetElementType (op_type);
4002 FieldExpr fe = left as FieldExpr;
4004 element = ((FixedFieldSpec) (fe.Spec)).ElementType;
4009 int size = GetTypeSize (element);
4010 TypeSpec rtype = right.Type;
4012 if ((op & Binary.Operator.SubtractionMask) != 0 && rtype.IsPointer){
4014 // handle (pointer - pointer)
4018 ec.Emit (OpCodes.Sub);
4022 ec.Emit (OpCodes.Sizeof, element);
4025 ec.Emit (OpCodes.Div);
4027 ec.Emit (OpCodes.Conv_I8);
4030 // handle + and - on (pointer op int)
4032 Constant left_const = left as Constant;
4033 if (left_const != null) {
4035 // Optimize ((T*)null) pointer operations
4037 if (left_const.IsDefaultValue) {
4038 left = EmptyExpression.Null;
4046 var right_const = right as Constant;
4047 if (right_const != null) {
4049 // Optimize 0-based arithmetic
4051 if (right_const.IsDefaultValue)
4055 right = new IntConstant (size, right.Location);
4057 right = new SizeOf (new TypeExpression (element, right.Location), right.Location);
4059 // TODO: Should be the checks resolve context sensitive?
4060 ResolveContext rc = new ResolveContext (ec.MemberContext, ResolveContext.Options.UnsafeScope);
4061 right = new Binary (Binary.Operator.Multiply, right, right_const, loc).Resolve (rc);
4067 if (rtype == TypeManager.sbyte_type || rtype == TypeManager.byte_type ||
4068 rtype == TypeManager.short_type || rtype == TypeManager.ushort_type) {
4069 ec.Emit (OpCodes.Conv_I);
4070 } else if (rtype == TypeManager.uint32_type) {
4071 ec.Emit (OpCodes.Conv_U);
4074 if (right_const == null && size != 1){
4076 ec.Emit (OpCodes.Sizeof, element);
4079 if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
4080 ec.Emit (OpCodes.Conv_I8);
4082 Binary.EmitOperatorOpcode (ec, Binary.Operator.Multiply, rtype);
4085 if (left_const == null) {
4086 if (rtype == TypeManager.int64_type)
4087 ec.Emit (OpCodes.Conv_I);
4088 else if (rtype == TypeManager.uint64_type)
4089 ec.Emit (OpCodes.Conv_U);
4091 Binary.EmitOperatorOpcode (ec, op, op_type);
4098 // A boolean-expression is an expression that yields a result
4101 public class BooleanExpression : ShimExpression
4103 public BooleanExpression (Expression expr)
4106 this.loc = expr.Location;
4109 public override Expression CreateExpressionTree (ResolveContext ec)
4111 // TODO: We should emit IsTrue (v4) instead of direct user operator
4112 // call but that would break csc compatibility
4113 return base.CreateExpressionTree (ec);
4116 protected override Expression DoResolve (ResolveContext ec)
4118 // A boolean-expression is required to be of a type
4119 // that can be implicitly converted to bool or of
4120 // a type that implements operator true
4122 expr = expr.Resolve (ec);
4126 Assign ass = expr as Assign;
4127 if (ass != null && ass.Source is Constant) {
4128 ec.Report.Warning (665, 3, loc,
4129 "Assignment in conditional expression is always constant. Did you mean to use `==' instead ?");
4132 if (expr.Type == TypeManager.bool_type)
4135 if (expr.Type == InternalType.Dynamic) {
4136 Arguments args = new Arguments (1);
4137 args.Add (new Argument (expr));
4138 return new DynamicUnaryConversion ("IsTrue", args, loc).Resolve (ec);
4141 type = TypeManager.bool_type;
4142 Expression converted = Convert.ImplicitConversion (ec, expr, type, loc);
4143 if (converted != null)
4147 // If no implicit conversion to bool exists, try using `operator true'
4149 converted = GetOperatorTrue (ec, expr, loc);
4150 if (converted == null) {
4151 expr.Error_ValueCannotBeConverted (ec, loc, type, false);
4160 /// Implements the ternary conditional operator (?:)
4162 public class Conditional : Expression {
4163 Expression expr, true_expr, false_expr;
4165 public Conditional (BooleanExpression expr, Expression true_expr, Expression false_expr, Location loc)
4168 this.true_expr = true_expr;
4169 this.false_expr = false_expr;
4173 public Expression Expr {
4179 public Expression TrueExpr {
4185 public Expression FalseExpr {
4191 public override Expression CreateExpressionTree (ResolveContext ec)
4193 Arguments args = new Arguments (3);
4194 args.Add (new Argument (expr.CreateExpressionTree (ec)));
4195 args.Add (new Argument (true_expr.CreateExpressionTree (ec)));
4196 args.Add (new Argument (false_expr.CreateExpressionTree (ec)));
4197 return CreateExpressionFactoryCall (ec, "Condition", args);
4200 protected override Expression DoResolve (ResolveContext ec)
4202 expr = expr.Resolve (ec);
4203 true_expr = true_expr.Resolve (ec);
4204 false_expr = false_expr.Resolve (ec);
4206 if (true_expr == null || false_expr == null || expr == null)
4209 eclass = ExprClass.Value;
4210 TypeSpec true_type = true_expr.Type;
4211 TypeSpec false_type = false_expr.Type;
4215 // First, if an implicit conversion exists from true_expr
4216 // to false_expr, then the result type is of type false_expr.Type
4218 if (!TypeSpecComparer.IsEqual (true_type, false_type)) {
4219 Expression conv = Convert.ImplicitConversion (ec, true_expr, false_type, loc);
4222 // Check if both can convert implicitly to each other's type
4224 if (true_type != InternalType.Dynamic) {
4227 if (false_type != InternalType.Dynamic && Convert.ImplicitConversion (ec, false_expr, true_type, loc) != null) {
4228 ec.Report.Error (172, true_expr.Location,
4229 "Type of conditional expression cannot be determined as `{0}' and `{1}' convert implicitly to each other",
4230 TypeManager.CSharpName (true_type), TypeManager.CSharpName (false_type));
4236 } else if ((conv = Convert.ImplicitConversion (ec, false_expr, true_type, loc)) != null) {
4239 ec.Report.Error (173, true_expr.Location,
4240 "Type of conditional expression cannot be determined because there is no implicit conversion between `{0}' and `{1}'",
4241 TypeManager.CSharpName (true_type), TypeManager.CSharpName (false_type));
4246 // Dead code optimalization
4247 Constant c = expr as Constant;
4249 bool is_false = c.IsDefaultValue;
4250 ec.Report.Warning (429, 4, is_false ? true_expr.Location : false_expr.Location, "Unreachable expression code detected");
4251 return ReducedExpression.Create (is_false ? false_expr : true_expr, this).Resolve (ec);
4257 public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
4262 public override void Emit (EmitContext ec)
4264 Label false_target = ec.DefineLabel ();
4265 Label end_target = ec.DefineLabel ();
4267 expr.EmitBranchable (ec, false_target, false);
4268 true_expr.Emit (ec);
4270 if (type.IsInterface) {
4271 LocalBuilder temp = ec.GetTemporaryLocal (type);
4272 ec.Emit (OpCodes.Stloc, temp);
4273 ec.Emit (OpCodes.Ldloc, temp);
4274 ec.FreeTemporaryLocal (temp, type);
4277 ec.Emit (OpCodes.Br, end_target);
4278 ec.MarkLabel (false_target);
4279 false_expr.Emit (ec);
4280 ec.MarkLabel (end_target);
4283 protected override void CloneTo (CloneContext clonectx, Expression t)
4285 Conditional target = (Conditional) t;
4287 target.expr = expr.Clone (clonectx);
4288 target.true_expr = true_expr.Clone (clonectx);
4289 target.false_expr = false_expr.Clone (clonectx);
4293 public abstract class VariableReference : Expression, IAssignMethod, IMemoryLocation, IVariableReference {
4294 LocalTemporary temp;
4297 public abstract HoistedVariable GetHoistedVariable (AnonymousExpression ae);
4298 public abstract bool IsFixed { get; }
4299 public abstract bool IsRef { get; }
4300 public abstract string Name { get; }
4301 public abstract void SetHasAddressTaken ();
4304 // Variable IL data, it has to be protected to encapsulate hoisted variables
4306 protected abstract ILocalVariable Variable { get; }
4309 // Variable flow-analysis data
4311 public abstract VariableInfo VariableInfo { get; }
4314 public virtual void AddressOf (EmitContext ec, AddressOp mode)
4316 HoistedVariable hv = GetHoistedVariable (ec);
4318 hv.AddressOf (ec, mode);
4322 Variable.EmitAddressOf (ec);
4325 public HoistedVariable GetHoistedVariable (ResolveContext rc)
4327 return GetHoistedVariable (rc.CurrentAnonymousMethod);
4330 public HoistedVariable GetHoistedVariable (EmitContext ec)
4332 return GetHoistedVariable (ec.CurrentAnonymousMethod);
4335 public override string GetSignatureForError ()
4340 public override void Emit (EmitContext ec)
4345 public override void EmitSideEffect (EmitContext ec)
4351 // This method is used by parameters that are references, that are
4352 // being passed as references: we only want to pass the pointer (that
4353 // is already stored in the parameter, not the address of the pointer,
4354 // and not the value of the variable).
4356 public void EmitLoad (EmitContext ec)
4361 public void Emit (EmitContext ec, bool leave_copy)
4363 Report.Debug (64, "VARIABLE EMIT", this, Variable, type, IsRef, loc);
4365 HoistedVariable hv = GetHoistedVariable (ec);
4367 hv.Emit (ec, leave_copy);
4375 // If we are a reference, we loaded on the stack a pointer
4376 // Now lets load the real value
4378 ec.EmitLoadFromPtr (type);
4382 ec.Emit (OpCodes.Dup);
4385 temp = new LocalTemporary (Type);
4391 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy,
4392 bool prepare_for_load)
4394 HoistedVariable hv = GetHoistedVariable (ec);
4396 hv.EmitAssign (ec, source, leave_copy, prepare_for_load);
4400 New n_source = source as New;
4401 if (n_source != null) {
4402 if (!n_source.Emit (ec, this)) {
4406 ec.EmitLoadFromPtr (type);
4418 ec.Emit (OpCodes.Dup);
4420 temp = new LocalTemporary (Type);
4426 ec.EmitStoreFromPtr (type);
4428 Variable.EmitAssign (ec);
4436 public bool IsHoisted {
4437 get { return GetHoistedVariable ((AnonymousExpression) null) != null; }
4444 public class LocalVariableReference : VariableReference {
4445 readonly string name;
4447 public LocalInfo local_info;
4450 public LocalVariableReference (Block block, string name, Location l)
4458 // Setting `is_readonly' to false will allow you to create a writable
4459 // reference to a read-only variable. This is used by foreach and using.
4461 public LocalVariableReference (Block block, string name, Location l,
4462 LocalInfo local_info, bool is_readonly)
4463 : this (block, name, l)
4465 this.local_info = local_info;
4466 this.is_readonly = is_readonly;
4469 public override VariableInfo VariableInfo {
4470 get { return local_info.VariableInfo; }
4473 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
4475 return local_info.HoistedVariant;
4479 // A local variable is always fixed
4481 public override bool IsFixed {
4482 get { return true; }
4485 public override bool IsRef {
4486 get { return false; }
4489 public bool IsReadOnly {
4490 get { return is_readonly; }
4493 public override string Name {
4494 get { return name; }
4497 public bool VerifyAssigned (ResolveContext ec)
4499 VariableInfo variable_info = local_info.VariableInfo;
4500 return variable_info == null || variable_info.IsAssigned (ec, loc);
4503 void ResolveLocalInfo ()
4505 if (local_info == null) {
4506 local_info = Block.GetLocalInfo (Name);
4507 type = local_info.VariableType;
4508 is_readonly = local_info.ReadOnly;
4512 public override void SetHasAddressTaken ()
4514 local_info.AddressTaken = true;
4517 public override Expression CreateExpressionTree (ResolveContext ec)
4519 HoistedVariable hv = GetHoistedVariable (ec);
4521 return hv.CreateExpressionTree ();
4523 Arguments arg = new Arguments (1);
4524 arg.Add (new Argument (this));
4525 return CreateExpressionFactoryCall (ec, "Constant", arg);
4528 Expression DoResolveBase (ResolveContext ec)
4530 Expression e = Block.GetConstantExpression (Name);
4532 return e.Resolve (ec);
4534 VerifyAssigned (ec);
4537 // If we are referencing a variable from the external block
4538 // flag it for capturing
4540 if (ec.MustCaptureVariable (local_info)) {
4541 if (local_info.AddressTaken)
4542 AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, this, loc);
4544 if (ec.IsVariableCapturingRequired) {
4545 AnonymousMethodStorey storey = local_info.Block.Explicit.CreateAnonymousMethodStorey (ec);
4546 storey.CaptureLocalVariable (ec, local_info);
4550 eclass = ExprClass.Variable;
4551 type = local_info.VariableType;
4555 protected override Expression DoResolve (ResolveContext ec)
4557 ResolveLocalInfo ();
4558 local_info.Used = true;
4560 if (type == null && local_info.Type is VarExpr) {
4561 local_info.VariableType = TypeManager.object_type;
4562 Error_VariableIsUsedBeforeItIsDeclared (ec.Report, Name);
4566 return DoResolveBase (ec);
4569 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
4571 ResolveLocalInfo ();
4574 if (right_side == EmptyExpression.OutAccess.Instance)
4575 local_info.Used = true;
4577 // Infer implicitly typed local variable
4579 VarExpr ve = local_info.Type as VarExpr;
4581 if (!ve.InferType (ec, right_side))
4583 type = local_info.VariableType = ve.Type;
4590 if (right_side == EmptyExpression.OutAccess.Instance) {
4591 code = 1657; msg = "Cannot pass `{0}' as a ref or out argument because it is a `{1}'";
4592 } else if (right_side == EmptyExpression.LValueMemberAccess) {
4593 code = 1654; msg = "Cannot assign to members of `{0}' because it is a `{1}'";
4594 } else if (right_side == EmptyExpression.LValueMemberOutAccess) {
4595 code = 1655; msg = "Cannot pass members of `{0}' as ref or out arguments because it is a `{1}'";
4596 } else if (right_side == EmptyExpression.UnaryAddress) {
4597 code = 459; msg = "Cannot take the address of {1} `{0}'";
4599 code = 1656; msg = "Cannot assign to `{0}' because it is a `{1}'";
4601 ec.Report.Error (code, loc, msg, Name, local_info.GetReadOnlyContext ());
4602 } else if (VariableInfo != null) {
4603 VariableInfo.SetAssigned (ec);
4606 return DoResolveBase (ec);
4609 public override int GetHashCode ()
4611 return Name.GetHashCode ();
4614 public override bool Equals (object obj)
4616 LocalVariableReference lvr = obj as LocalVariableReference;
4620 return Name == lvr.Name && Block == lvr.Block;
4623 protected override ILocalVariable Variable {
4624 get { return local_info; }
4627 public override string ToString ()
4629 return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
4632 protected override void CloneTo (CloneContext clonectx, Expression t)
4634 LocalVariableReference target = (LocalVariableReference) t;
4636 target.Block = clonectx.LookupBlock (Block);
4637 if (local_info != null)
4638 target.local_info = clonectx.LookupVariable (local_info);
4643 /// This represents a reference to a parameter in the intermediate
4646 public class ParameterReference : VariableReference {
4647 readonly ToplevelParameterInfo pi;
4649 public ParameterReference (ToplevelParameterInfo pi, Location loc)
4655 public override bool IsRef {
4656 get { return (pi.Parameter.ModFlags & Parameter.Modifier.ISBYREF) != 0; }
4659 bool HasOutModifier {
4660 get { return pi.Parameter.ModFlags == Parameter.Modifier.OUT; }
4663 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
4665 return pi.Parameter.HoistedVariant;
4669 // A ref or out parameter is classified as a moveable variable, even
4670 // if the argument given for the parameter is a fixed variable
4672 public override bool IsFixed {
4673 get { return !IsRef; }
4676 public override string Name {
4677 get { return Parameter.Name; }
4680 public Parameter Parameter {
4681 get { return pi.Parameter; }
4684 public override VariableInfo VariableInfo {
4685 get { return pi.VariableInfo; }
4688 protected override ILocalVariable Variable {
4689 get { return Parameter; }
4692 public bool IsAssigned (ResolveContext ec, Location loc)
4694 // HACK: Variables are not captured in probing mode
4695 if (ec.IsInProbingMode)
4698 if (!ec.DoFlowAnalysis || !HasOutModifier || ec.CurrentBranching.IsAssigned (VariableInfo))
4701 ec.Report.Error (269, loc, "Use of unassigned out parameter `{0}'", Name);
4705 public override void SetHasAddressTaken ()
4707 Parameter.HasAddressTaken = true;
4710 void SetAssigned (ResolveContext ec)
4712 if (HasOutModifier && ec.DoFlowAnalysis)
4713 ec.CurrentBranching.SetAssigned (VariableInfo);
4716 bool DoResolveBase (ResolveContext ec)
4718 type = pi.ParameterType;
4719 eclass = ExprClass.Variable;
4721 AnonymousExpression am = ec.CurrentAnonymousMethod;
4725 Block b = ec.CurrentBlock;
4728 IParameterData[] p = b.Toplevel.Parameters.FixedParameters;
4729 for (int i = 0; i < p.Length; ++i) {
4730 if (p [i] != Parameter)
4734 // Don't capture local parameters
4736 if (b == ec.CurrentBlock.Toplevel && !am.IsIterator)
4740 ec.Report.Error (1628, loc,
4741 "Parameter `{0}' cannot be used inside `{1}' when using `ref' or `out' modifier",
4742 Name, am.ContainerType);
4745 if (pi.Parameter.HasAddressTaken)
4746 AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, this, loc);
4748 if (ec.IsVariableCapturingRequired && !b.Toplevel.IsExpressionTree) {
4749 AnonymousMethodStorey storey = pi.Block.CreateAnonymousMethodStorey (ec);
4750 storey.CaptureParameter (ec, this);
4762 public override int GetHashCode ()
4764 return Name.GetHashCode ();
4767 public override bool Equals (object obj)
4769 ParameterReference pr = obj as ParameterReference;
4773 return Name == pr.Name;
4776 public override void AddressOf (EmitContext ec, AddressOp mode)
4779 // ParameterReferences might already be a reference
4786 base.AddressOf (ec, mode);
4789 protected override void CloneTo (CloneContext clonectx, Expression target)
4794 public override Expression CreateExpressionTree (ResolveContext ec)
4796 HoistedVariable hv = GetHoistedVariable (ec);
4798 return hv.CreateExpressionTree ();
4800 return Parameter.ExpressionTreeVariableReference ();
4804 // Notice that for ref/out parameters, the type exposed is not the
4805 // same type exposed externally.
4808 // externally we expose "int&"
4809 // here we expose "int".
4811 // We record this in "is_ref". This means that the type system can treat
4812 // the type as it is expected, but when we generate the code, we generate
4813 // the alternate kind of code.
4815 protected override Expression DoResolve (ResolveContext ec)
4817 if (!DoResolveBase (ec))
4820 // HACK: Variables are not captured in probing mode
4821 if (ec.IsInProbingMode)
4824 if (HasOutModifier && ec.DoFlowAnalysis &&
4825 (!ec.OmitStructFlowAnalysis || !VariableInfo.TypeInfo.IsStruct) && !IsAssigned (ec, loc))
4831 override public Expression DoResolveLValue (ResolveContext ec, Expression right_side)
4833 if (!DoResolveBase (ec))
4840 static public void EmitLdArg (EmitContext ec, int x)
4843 case 0: ec.Emit (OpCodes.Ldarg_0); break;
4844 case 1: ec.Emit (OpCodes.Ldarg_1); break;
4845 case 2: ec.Emit (OpCodes.Ldarg_2); break;
4846 case 3: ec.Emit (OpCodes.Ldarg_3); break;
4848 if (x > byte.MaxValue)
4849 ec.Emit (OpCodes.Ldarg, x);
4851 ec.Emit (OpCodes.Ldarg_S, (byte) x);
4858 /// Invocation of methods or delegates.
4860 public class Invocation : ExpressionStatement
4862 protected Arguments arguments;
4863 protected Expression expr;
4864 protected MethodGroupExpr mg;
4866 public Invocation (Expression expr, Arguments arguments)
4869 this.arguments = arguments;
4871 loc = expr.Location;
4875 public Arguments Arguments {
4881 public Expression Expression {
4888 protected override void CloneTo (CloneContext clonectx, Expression t)
4890 Invocation target = (Invocation) t;
4892 if (arguments != null)
4893 target.arguments = arguments.Clone (clonectx);
4895 target.expr = expr.Clone (clonectx);
4899 public override Expression CreateExpressionTree (ResolveContext ec)
4901 Expression instance = mg.IsInstance ?
4902 mg.InstanceExpression.CreateExpressionTree (ec) :
4903 new NullLiteral (loc);
4905 var args = Arguments.CreateForExpressionTree (ec, arguments,
4907 mg.CreateExpressionTree (ec));
4909 return CreateExpressionFactoryCall (ec, "Call", args);
4912 protected override Expression DoResolve (ResolveContext ec)
4914 Expression member_expr;
4915 var atn = expr as ATypeNameExpression;
4917 member_expr = atn.LookupNameExpression (ec, true, true);
4918 if (member_expr != null)
4919 member_expr = member_expr.Resolve (ec);
4921 member_expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4924 if (member_expr == null)
4928 // Next, evaluate all the expressions in the argument list
4930 bool dynamic_arg = false;
4931 if (arguments != null)
4932 arguments.Resolve (ec, out dynamic_arg);
4934 TypeSpec expr_type = member_expr.Type;
4935 mg = member_expr as MethodGroupExpr;
4937 bool dynamic_member = expr_type == InternalType.Dynamic;
4939 if (!dynamic_member) {
4940 Expression invoke = null;
4943 if (expr_type != null && TypeManager.IsDelegateType (expr_type)) {
4944 invoke = new DelegateInvocation (member_expr, arguments, loc);
4945 invoke = invoke.Resolve (ec);
4946 if (invoke == null || !dynamic_arg)
4949 MemberExpr me = member_expr as MemberExpr;
4951 member_expr.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup, loc);
4955 ec.Report.Error (1955, loc, "The member `{0}' cannot be used as method or delegate",
4956 member_expr.GetSignatureForError ());
4961 if (invoke == null) {
4962 mg = DoResolveOverload (ec);
4968 if (dynamic_arg || dynamic_member)
4969 return DoResolveDynamic (ec, member_expr);
4971 var method = mg.BestCandidate;
4972 if (method != null) {
4973 type = method.ReturnType;
4976 if (arguments == null && method.DeclaringType == TypeManager.object_type && method.Name == Destructor.MetadataName) {
4978 ec.Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
4980 ec.Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
4984 IsSpecialMethodInvocation (ec, method, loc);
4986 if (mg.InstanceExpression != null)
4987 mg.InstanceExpression.CheckMarshalByRefAccess (ec);
4989 eclass = ExprClass.Value;
4993 Expression DoResolveDynamic (ResolveContext ec, Expression memberExpr)
4996 DynamicMemberBinder dmb = memberExpr as DynamicMemberBinder;
4998 args = dmb.Arguments;
4999 if (arguments != null)
5000 args.AddRange (arguments);
5001 } else if (mg == null) {
5002 if (arguments == null)
5003 args = new Arguments (1);
5007 args.Insert (0, new Argument (memberExpr));
5011 ec.Report.Error (1971, loc,
5012 "The base call to method `{0}' cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access",
5017 if (arguments == null)
5018 args = new Arguments (1);
5022 MemberAccess ma = expr as MemberAccess;
5024 var left_type = ma.LeftExpression as TypeExpr;
5025 if (left_type != null) {
5026 args.Insert (0, new Argument (new TypeOf (left_type, loc).Resolve (ec), Argument.AType.DynamicTypeName));
5028 args.Insert (0, new Argument (ma.LeftExpression.Resolve (ec)));
5030 } else { // is SimpleName
5032 args.Insert (0, new Argument (new TypeOf (new TypeExpression (ec.CurrentType, loc), loc).Resolve (ec), Argument.AType.DynamicTypeName));
5034 args.Insert (0, new Argument (new This (loc).Resolve (ec)));
5039 return new DynamicInvocation (expr as ATypeNameExpression, args, loc).Resolve (ec);
5042 protected virtual MethodGroupExpr DoResolveOverload (ResolveContext ec)
5044 return mg.OverloadResolve (ec, ref arguments, null, OverloadResolver.Restrictions.None);
5047 static Type[] GetVarargsTypes (MethodSpec mb, Arguments arguments)
5049 AParametersCollection pd = mb.Parameters;
5051 Argument a = arguments[pd.Count - 1];
5052 Arglist list = (Arglist) a.Expr;
5054 return list.ArgumentTypes;
5058 // If a member is a method or event, or if it is a constant, field or property of either a delegate type
5059 // or the type dynamic, then the member is invocable
5061 public static bool IsMemberInvocable (MemberSpec member)
5063 switch (member.Kind) {
5064 case MemberKind.Event:
5066 case MemberKind.Field:
5067 case MemberKind.Property:
5068 var m = member as IInterfaceMemberSpec;
5069 return m.MemberType.IsDelegate || m.MemberType == InternalType.Dynamic;
5075 public static bool IsSpecialMethodInvocation (ResolveContext ec, MethodSpec method, Location loc)
5077 if (!method.IsReservedMethod)
5080 if (ec.HasSet (ResolveContext.Options.InvokeSpecialName) || ec.CurrentMemberDefinition.IsCompilerGenerated)
5083 ec.Report.SymbolRelatedToPreviousError (method);
5084 ec.Report.Error (571, loc, "`{0}': cannot explicitly call operator or accessor",
5085 method.GetSignatureForError ());
5091 // Used to decide whether call or callvirt is needed
5093 static bool IsVirtualCallRequired (Expression instance, MethodSpec method)
5096 // There are 2 scenarious where we emit callvirt
5098 // Case 1: A method is virtual and it's not used to call base
5099 // Case 2: A method instance expression can be null. In this casen callvirt ensures
5100 // correct NRE exception when the method is called
5102 var decl_type = method.DeclaringType;
5103 if (decl_type.IsStruct || decl_type.IsEnum)
5106 if (instance is BaseThis)
5110 // It's non-virtual and will never be null
5112 if (!method.IsVirtual && (instance is This || instance is New || instance is ArrayCreation || instance is DelegateCreation || instance is TypeOf))
5119 /// is_base tells whether we want to force the use of the `call'
5120 /// opcode instead of using callvirt. Call is required to call
5121 /// a specific method, while callvirt will always use the most
5122 /// recent method in the vtable.
5124 /// is_static tells whether this is an invocation on a static method
5126 /// instance_expr is an expression that represents the instance
5127 /// it must be non-null if is_static is false.
5129 /// method is the method to invoke.
5131 /// Arguments is the list of arguments to pass to the method or constructor.
5133 public static void EmitCall (EmitContext ec, Expression instance_expr,
5134 MethodSpec method, Arguments Arguments, Location loc)
5136 EmitCall (ec, instance_expr, method, Arguments, loc, false, false);
5139 // `dup_args' leaves an extra copy of the arguments on the stack
5140 // `omit_args' does not leave any arguments at all.
5141 // So, basically, you could make one call with `dup_args' set to true,
5142 // and then another with `omit_args' set to true, and the two calls
5143 // would have the same set of arguments. However, each argument would
5144 // only have been evaluated once.
5145 public static void EmitCall (EmitContext ec, Expression instance_expr,
5146 MethodSpec method, Arguments Arguments, Location loc,
5147 bool dup_args, bool omit_args)
5149 LocalTemporary this_arg = null;
5151 // Speed up the check by not doing it on not allowed targets
5152 if (method.ReturnType == TypeManager.void_type && method.IsConditionallyExcluded (loc))
5156 TypeSpec iexpr_type;
5158 if (method.IsStatic) {
5160 call_op = OpCodes.Call;
5162 iexpr_type = instance_expr.Type;
5164 if (IsVirtualCallRequired (instance_expr, method)) {
5165 call_op = OpCodes.Callvirt;
5167 call_op = OpCodes.Call;
5171 // If this is ourselves, push "this"
5174 TypeSpec t = iexpr_type;
5177 // Push the instance expression
5179 if ((iexpr_type.IsStruct && (call_op == OpCodes.Callvirt || (call_op == OpCodes.Call && method.DeclaringType == iexpr_type))) ||
5180 iexpr_type.IsGenericParameter || TypeManager.IsNullableType (method.DeclaringType)) {
5182 // If the expression implements IMemoryLocation, then
5183 // we can optimize and use AddressOf on the
5186 // If not we have to use some temporary storage for
5188 var iml = instance_expr as IMemoryLocation;
5190 iml.AddressOf (ec, AddressOp.LoadStore);
5192 LocalTemporary temp = new LocalTemporary (iexpr_type);
5193 instance_expr.Emit (ec);
5195 temp.AddressOf (ec, AddressOp.Load);
5198 // avoid the overhead of doing this all the time.
5200 t = ReferenceContainer.MakeType (iexpr_type);
5201 } else if (iexpr_type.IsEnum || iexpr_type.IsStruct) {
5202 instance_expr.Emit (ec);
5203 ec.Emit (OpCodes.Box, iexpr_type);
5204 t = iexpr_type = TypeManager.object_type;
5206 instance_expr.Emit (ec);
5210 ec.Emit (OpCodes.Dup);
5211 if (Arguments != null && Arguments.Count != 0) {
5212 this_arg = new LocalTemporary (t);
5213 this_arg.Store (ec);
5219 if (!omit_args && Arguments != null)
5220 Arguments.Emit (ec, dup_args, this_arg);
5222 if (call_op == OpCodes.Callvirt && (iexpr_type.IsGenericParameter || iexpr_type.IsStruct)) {
5223 ec.Emit (OpCodes.Constrained, iexpr_type);
5226 if (method.Parameters.HasArglist) {
5227 Type[] varargs_types = GetVarargsTypes (method, Arguments);
5228 ec.Emit (call_op, method, varargs_types);
5235 // and DoFoo is not virtual, you can omit the callvirt,
5236 // because you don't need the null checking behavior.
5238 ec.Emit (call_op, method);
5241 public override void Emit (EmitContext ec)
5243 mg.EmitCall (ec, arguments);
5246 public override void EmitStatement (EmitContext ec)
5251 // Pop the return value if there is one
5253 if (type != TypeManager.void_type)
5254 ec.Emit (OpCodes.Pop);
5257 public override SLE.Expression MakeExpression (BuilderContext ctx)
5259 return MakeExpression (ctx, mg.InstanceExpression, mg.BestCandidate, arguments);
5262 public static SLE.Expression MakeExpression (BuilderContext ctx, Expression instance, MethodSpec mi, Arguments args)
5264 var instance_expr = instance == null ? null : instance.MakeExpression (ctx);
5265 return SLE.Expression.Call (instance_expr, (MethodInfo) mi.GetMetaInfo (), Arguments.MakeExpression (args, ctx));
5270 /// Implements the new expression
5272 public class New : ExpressionStatement, IMemoryLocation {
5273 protected Arguments Arguments;
5276 // During bootstrap, it contains the RequestedType,
5277 // but if `type' is not null, it *might* contain a NewDelegate
5278 // (because of field multi-initialization)
5280 protected Expression RequestedType;
5282 protected MethodSpec method;
5284 public New (Expression requested_type, Arguments arguments, Location l)
5286 RequestedType = requested_type;
5287 Arguments = arguments;
5292 /// Converts complex core type syntax like 'new int ()' to simple constant
5294 public static Constant Constantify (TypeSpec t)
5296 if (t == TypeManager.int32_type)
5297 return new IntConstant (0, Location.Null);
5298 if (t == TypeManager.uint32_type)
5299 return new UIntConstant (0, Location.Null);
5300 if (t == TypeManager.int64_type)
5301 return new LongConstant (0, Location.Null);
5302 if (t == TypeManager.uint64_type)
5303 return new ULongConstant (0, Location.Null);
5304 if (t == TypeManager.float_type)
5305 return new FloatConstant (0, Location.Null);
5306 if (t == TypeManager.double_type)
5307 return new DoubleConstant (0, Location.Null);
5308 if (t == TypeManager.short_type)
5309 return new ShortConstant (0, Location.Null);
5310 if (t == TypeManager.ushort_type)
5311 return new UShortConstant (0, Location.Null);
5312 if (t == TypeManager.sbyte_type)
5313 return new SByteConstant (0, Location.Null);
5314 if (t == TypeManager.byte_type)
5315 return new ByteConstant (0, Location.Null);
5316 if (t == TypeManager.char_type)
5317 return new CharConstant ('\0', Location.Null);
5318 if (t == TypeManager.bool_type)
5319 return new BoolConstant (false, Location.Null);
5320 if (t == TypeManager.decimal_type)
5321 return new DecimalConstant (0, Location.Null);
5322 if (TypeManager.IsEnumType (t))
5323 return new EnumConstant (Constantify (EnumSpec.GetUnderlyingType (t)), t);
5324 if (TypeManager.IsNullableType (t))
5325 return Nullable.LiftedNull.Create (t, Location.Null);
5331 // Checks whether the type is an interface that has the
5332 // [ComImport, CoClass] attributes and must be treated
5335 public Expression CheckComImport (ResolveContext ec)
5337 if (!type.IsInterface)
5341 // Turn the call into:
5342 // (the-interface-stated) (new class-referenced-in-coclassattribute ())
5344 var real_class = type.MemberDefinition.GetAttributeCoClass ();
5345 if (real_class == null)
5348 New proxy = new New (new TypeExpression (real_class, loc), Arguments, loc);
5349 Cast cast = new Cast (new TypeExpression (type, loc), proxy, loc);
5350 return cast.Resolve (ec);
5353 public override Expression CreateExpressionTree (ResolveContext ec)
5356 if (method == null) {
5357 args = new Arguments (1);
5358 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
5360 args = Arguments.CreateForExpressionTree (ec,
5361 Arguments, new TypeOfMethod (method, loc));
5364 return CreateExpressionFactoryCall (ec, "New", args);
5367 protected override Expression DoResolve (ResolveContext ec)
5369 TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec, false);
5374 eclass = ExprClass.Value;
5376 if (type.IsPointer) {
5377 ec.Report.Error (1919, loc, "Unsafe type `{0}' cannot be used in an object creation expression",
5378 TypeManager.CSharpName (type));
5382 if (Arguments == null) {
5383 Constant c = Constantify (type);
5385 return ReducedExpression.Create (c.Resolve (ec), this);
5388 if (TypeManager.IsDelegateType (type)) {
5389 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5392 var tparam = type as TypeParameterSpec;
5393 if (tparam != null) {
5394 if (!tparam.HasSpecialConstructor && !tparam.HasSpecialStruct) {
5395 ec.Report.Error (304, loc,
5396 "Cannot create an instance of the variable type `{0}' because it does not have the new() constraint",
5397 TypeManager.CSharpName (type));
5400 if ((Arguments != null) && (Arguments.Count != 0)) {
5401 ec.Report.Error (417, loc,
5402 "`{0}': cannot provide arguments when creating an instance of a variable type",
5403 TypeManager.CSharpName (type));
5406 if (TypeManager.activator_create_instance == null) {
5407 TypeSpec activator_type = TypeManager.CoreLookupType (ec.Compiler, "System", "Activator", MemberKind.Class, true);
5408 if (activator_type != null) {
5409 TypeManager.activator_create_instance = TypeManager.GetPredefinedMethod (
5410 activator_type, MemberFilter.Method ("CreateInstance", 1, ParametersCompiled.EmptyReadOnlyParameters, null), loc);
5417 if (type.IsStatic) {
5418 ec.Report.SymbolRelatedToPreviousError (type);
5419 ec.Report.Error (712, loc, "Cannot create an instance of the static class `{0}'", TypeManager.CSharpName (type));
5423 if (type.IsInterface || type.IsAbstract){
5424 if (!TypeManager.IsGenericType (type)) {
5425 RequestedType = CheckComImport (ec);
5426 if (RequestedType != null)
5427 return RequestedType;
5430 ec.Report.SymbolRelatedToPreviousError (type);
5431 ec.Report.Error (144, loc, "Cannot create an instance of the abstract class or interface `{0}'", TypeManager.CSharpName (type));
5436 // Any struct always defines parameterless constructor
5438 if (type.IsStruct && Arguments == null)
5442 if (Arguments != null) {
5443 Arguments.Resolve (ec, out dynamic);
5448 method = ConstructorLookup (ec, type, ref Arguments, loc);
5451 Arguments.Insert (0, new Argument (new TypeOf (texpr, loc).Resolve (ec), Argument.AType.DynamicTypeName));
5452 return new DynamicConstructorBinder (type, Arguments, loc).Resolve (ec);
5458 bool DoEmitTypeParameter (EmitContext ec)
5460 var ctor_factory = TypeManager.activator_create_instance.MakeGenericMethod (type);
5461 var tparam = (TypeParameterSpec) type;
5463 if (tparam.IsReferenceType) {
5464 ec.Emit (OpCodes.Call, ctor_factory);
5468 // Allow DoEmit() to be called multiple times.
5469 // We need to create a new LocalTemporary each time since
5470 // you can't share LocalBuilders among ILGeneators.
5471 LocalTemporary temp = new LocalTemporary (type);
5473 Label label_activator = ec.DefineLabel ();
5474 Label label_end = ec.DefineLabel ();
5476 temp.AddressOf (ec, AddressOp.Store);
5477 ec.Emit (OpCodes.Initobj, type);
5480 ec.Emit (OpCodes.Box, type);
5481 ec.Emit (OpCodes.Brfalse, label_activator);
5483 temp.AddressOf (ec, AddressOp.Store);
5484 ec.Emit (OpCodes.Initobj, type);
5486 ec.Emit (OpCodes.Br_S, label_end);
5488 ec.MarkLabel (label_activator);
5490 ec.Emit (OpCodes.Call, ctor_factory);
5491 ec.MarkLabel (label_end);
5496 // This Emit can be invoked in two contexts:
5497 // * As a mechanism that will leave a value on the stack (new object)
5498 // * As one that wont (init struct)
5500 // If we are dealing with a ValueType, we have a few
5501 // situations to deal with:
5503 // * The target is a ValueType, and we have been provided
5504 // the instance (this is easy, we are being assigned).
5506 // * The target of New is being passed as an argument,
5507 // to a boxing operation or a function that takes a
5510 // In this case, we need to create a temporary variable
5511 // that is the argument of New.
5513 // Returns whether a value is left on the stack
5515 // *** Implementation note ***
5517 // To benefit from this optimization, each assignable expression
5518 // has to manually cast to New and call this Emit.
5520 // TODO: It's worth to implement it for arrays and fields
5522 public virtual bool Emit (EmitContext ec, IMemoryLocation target)
5524 bool is_value_type = TypeManager.IsValueType (type);
5525 VariableReference vr = target as VariableReference;
5527 if (target != null && is_value_type && (vr != null || method == null)) {
5528 target.AddressOf (ec, AddressOp.Store);
5529 } else if (vr != null && vr.IsRef) {
5533 if (Arguments != null)
5534 Arguments.Emit (ec);
5536 if (is_value_type) {
5537 if (method == null) {
5538 ec.Emit (OpCodes.Initobj, type);
5543 ec.Emit (OpCodes.Call, method);
5548 if (type is TypeParameterSpec)
5549 return DoEmitTypeParameter (ec);
5551 ec.Emit (OpCodes.Newobj, method);
5555 public override void Emit (EmitContext ec)
5557 LocalTemporary v = null;
5558 if (method == null && TypeManager.IsValueType (type)) {
5559 // TODO: Use temporary variable from pool
5560 v = new LocalTemporary (type);
5567 public override void EmitStatement (EmitContext ec)
5569 LocalTemporary v = null;
5570 if (method == null && TypeManager.IsValueType (type)) {
5571 // TODO: Use temporary variable from pool
5572 v = new LocalTemporary (type);
5576 ec.Emit (OpCodes.Pop);
5579 public virtual bool HasInitializer {
5585 public void AddressOf (EmitContext ec, AddressOp mode)
5587 EmitAddressOf (ec, mode);
5590 protected virtual IMemoryLocation EmitAddressOf (EmitContext ec, AddressOp mode)
5592 LocalTemporary value_target = new LocalTemporary (type);
5594 if (type is TypeParameterSpec) {
5595 DoEmitTypeParameter (ec);
5596 value_target.Store (ec);
5597 value_target.AddressOf (ec, mode);
5598 return value_target;
5601 if (!TypeManager.IsStruct (type)){
5603 // We throw an exception. So far, I believe we only need to support
5605 // foreach (int j in new StructType ())
5608 throw new Exception ("AddressOf should not be used for classes");
5611 value_target.AddressOf (ec, AddressOp.Store);
5613 if (method == null) {
5614 ec.Emit (OpCodes.Initobj, type);
5616 if (Arguments != null)
5617 Arguments.Emit (ec);
5619 ec.Emit (OpCodes.Call, method);
5622 value_target.AddressOf (ec, mode);
5623 return value_target;
5626 protected override void CloneTo (CloneContext clonectx, Expression t)
5628 New target = (New) t;
5630 target.RequestedType = RequestedType.Clone (clonectx);
5631 if (Arguments != null){
5632 target.Arguments = Arguments.Clone (clonectx);
5636 public override SLE.Expression MakeExpression (BuilderContext ctx)
5638 return SLE.Expression.New ((ConstructorInfo) method.GetMetaInfo (), Arguments.MakeExpression (Arguments, ctx));
5642 public class ArrayInitializer : Expression
5644 List<Expression> elements;
5646 public ArrayInitializer (List<Expression> init, Location loc)
5652 public ArrayInitializer (int count, Location loc)
5654 elements = new List<Expression> (count);
5658 public ArrayInitializer (Location loc)
5663 public void Add (Expression expr)
5665 elements.Add (expr);
5668 public override Expression CreateExpressionTree (ResolveContext ec)
5670 throw new NotSupportedException ("ET");
5673 protected override void CloneTo (CloneContext clonectx, Expression t)
5675 var target = (ArrayInitializer) t;
5677 target.elements = new List<Expression> (elements.Count);
5678 foreach (var element in elements)
5679 target.elements.Add (element.Clone (clonectx));
5683 get { return elements.Count; }
5686 protected override Expression DoResolve (ResolveContext rc)
5688 var current_field = rc.CurrentMemberDefinition as FieldBase;
5689 return new ArrayCreation (new TypeExpression (current_field.MemberType, current_field.Location), this).Resolve (rc);
5692 public override void Emit (EmitContext ec)
5694 throw new InternalErrorException ("Missing Resolve call");
5697 public Expression this [int index] {
5698 get { return elements [index]; }
5703 /// 14.5.10.2: Represents an array creation expression.
5707 /// There are two possible scenarios here: one is an array creation
5708 /// expression that specifies the dimensions and optionally the
5709 /// initialization data and the other which does not need dimensions
5710 /// specified but where initialization data is mandatory.
5712 public class ArrayCreation : Expression
5714 FullNamedExpression requested_base_type;
5715 ArrayInitializer initializers;
5718 // The list of Argument types.
5719 // This is used to construct the `newarray' or constructor signature
5721 protected List<Expression> arguments;
5723 protected TypeSpec array_element_type;
5724 int num_arguments = 0;
5725 protected int dimensions;
5726 protected readonly ComposedTypeSpecifier rank;
5727 Expression first_emit;
5728 LocalTemporary first_emit_temp;
5730 protected List<Expression> array_data;
5732 Dictionary<int, int> bounds;
5734 // The number of constants in array initializers
5735 int const_initializers_count;
5736 bool only_constant_initializers;
5738 public ArrayCreation (FullNamedExpression requested_base_type, List<Expression> exprs, ComposedTypeSpecifier rank, ArrayInitializer initializers, Location l)
5739 : this (requested_base_type, rank, initializers, l)
5741 arguments = new List<Expression> (exprs);
5742 num_arguments = arguments.Count;
5746 // For expressions like int[] foo = new int[] { 1, 2, 3 };
5748 public ArrayCreation (FullNamedExpression requested_base_type, ComposedTypeSpecifier rank, ArrayInitializer initializers, Location loc)
5750 this.requested_base_type = requested_base_type;
5752 this.initializers = initializers;
5756 num_arguments = rank.Dimension;
5760 // For compiler generated single dimensional arrays only
5762 public ArrayCreation (FullNamedExpression requested_base_type, ArrayInitializer initializers, Location loc)
5763 : this (requested_base_type, ComposedTypeSpecifier.SingleDimension, initializers, loc)
5768 // For expressions like int[] foo = { 1, 2, 3 };
5770 public ArrayCreation (FullNamedExpression requested_base_type, ArrayInitializer initializers)
5771 : this (requested_base_type, null, initializers, initializers.Location)
5775 protected override void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
5777 ec.Report.Error (248, loc, "Cannot create an array with a negative size");
5780 bool CheckIndices (ResolveContext ec, ArrayInitializer probe, int idx, bool specified_dims, int child_bounds)
5782 if (initializers != null && bounds == null) {
5784 // We use this to store all the date values in the order in which we
5785 // will need to store them in the byte blob later
5787 array_data = new List<Expression> ();
5788 bounds = new Dictionary<int, int> ();
5791 if (specified_dims) {
5792 Expression a = arguments [idx];
5797 a = ConvertExpressionToArrayIndex (ec, a);
5803 if (initializers != null) {
5804 Constant c = a as Constant;
5805 if (c == null && a is ArrayIndexCast)
5806 c = ((ArrayIndexCast) a).Child as Constant;
5809 ec.Report.Error (150, a.Location, "A constant value is expected");
5815 value = System.Convert.ToInt32 (c.GetValue ());
5817 ec.Report.Error (150, a.Location, "A constant value is expected");
5821 // TODO: probe.Count does not fit ulong in
5822 if (value != probe.Count) {
5823 ec.Report.Error (847, loc, "An array initializer of length `{0}' was expected", value.ToString ());
5827 bounds[idx] = value;
5831 if (initializers == null)
5834 only_constant_initializers = true;
5835 for (int i = 0; i < probe.Count; ++i) {
5837 if (o is ArrayInitializer) {
5838 var sub_probe = o as ArrayInitializer;
5839 if (idx + 1 >= dimensions){
5840 ec.Report.Error (623, loc, "Array initializers can only be used in a variable or field initializer. Try using a new expression instead");
5844 bool ret = CheckIndices (ec, sub_probe, idx + 1, specified_dims, child_bounds - 1);
5847 } else if (child_bounds > 1) {
5848 ec.Report.Error (846, o.Location, "A nested array initializer was expected");
5850 Expression element = ResolveArrayElement (ec, o);
5851 if (element == null)
5854 // Initializers with the default values can be ignored
5855 Constant c = element as Constant;
5857 if (!c.IsDefaultInitializer (array_element_type)) {
5858 ++const_initializers_count;
5861 only_constant_initializers = false;
5864 array_data.Add (element);
5871 public override Expression CreateExpressionTree (ResolveContext ec)
5875 if (array_data == null) {
5876 args = new Arguments (arguments.Count + 1);
5877 args.Add (new Argument (new TypeOf (new TypeExpression (array_element_type, loc), loc)));
5878 foreach (Expression a in arguments)
5879 args.Add (new Argument (a.CreateExpressionTree (ec)));
5881 return CreateExpressionFactoryCall (ec, "NewArrayBounds", args);
5884 if (dimensions > 1) {
5885 ec.Report.Error (838, loc, "An expression tree cannot contain a multidimensional array initializer");
5889 args = new Arguments (array_data == null ? 1 : array_data.Count + 1);
5890 args.Add (new Argument (new TypeOf (new TypeExpression (array_element_type, loc), loc)));
5891 if (array_data != null) {
5892 for (int i = 0; i < array_data.Count; ++i) {
5893 Expression e = array_data [i];
5894 args.Add (new Argument (e.CreateExpressionTree (ec)));
5898 return CreateExpressionFactoryCall (ec, "NewArrayInit", args);
5901 public void UpdateIndices ()
5904 for (var probe = initializers; probe != null;) {
5905 if (probe.Count > 0 && probe [0] is ArrayInitializer) {
5906 Expression e = new IntConstant (probe.Count, Location.Null);
5909 bounds [i++] = probe.Count;
5911 probe = (ArrayInitializer) probe[0];
5914 Expression e = new IntConstant (probe.Count, Location.Null);
5917 bounds [i++] = probe.Count;
5923 protected virtual Expression ResolveArrayElement (ResolveContext ec, Expression element)
5925 element = element.Resolve (ec);
5926 if (element == null)
5929 if (element is CompoundAssign.TargetExpression) {
5930 if (first_emit != null)
5931 throw new InternalErrorException ("Can only handle one mutator at a time");
5932 first_emit = element;
5933 element = first_emit_temp = new LocalTemporary (element.Type);
5936 return Convert.ImplicitConversionRequired (
5937 ec, element, array_element_type, loc);
5940 protected bool ResolveInitializers (ResolveContext ec)
5942 if (arguments != null) {
5944 for (int i = 0; i < arguments.Count; ++i) {
5945 res &= CheckIndices (ec, initializers, i, true, dimensions);
5946 if (initializers != null)
5953 arguments = new List<Expression> ();
5955 if (!CheckIndices (ec, initializers, 0, false, dimensions))
5964 // Resolved the type of the array
5966 bool ResolveArrayType (ResolveContext ec)
5968 if (requested_base_type is VarExpr) {
5969 ec.Report.Error (820, loc, "An implicitly typed local variable declarator cannot use an array initializer");
5976 FullNamedExpression array_type_expr;
5977 if (num_arguments > 0) {
5978 array_type_expr = new ComposedCast (requested_base_type, rank);
5980 array_type_expr = requested_base_type;
5983 array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec, false);
5984 if (array_type_expr == null)
5987 type = array_type_expr.Type;
5988 var ac = type as ArrayContainer;
5990 ec.Report.Error (622, loc, "Can only use array initializer expressions to assign to array types. Try using a new expression instead");
5994 array_element_type = ac.Element;
5995 dimensions = ac.Rank;
6000 protected override Expression DoResolve (ResolveContext ec)
6005 if (!ResolveArrayType (ec))
6009 // validate the initializers and fill in any missing bits
6011 if (!ResolveInitializers (ec))
6014 eclass = ExprClass.Value;
6018 byte [] MakeByteBlob ()
6023 int count = array_data.Count;
6025 TypeSpec element_type = array_element_type;
6026 if (TypeManager.IsEnumType (element_type))
6027 element_type = EnumSpec.GetUnderlyingType (element_type);
6029 factor = GetTypeSize (element_type);
6031 throw new Exception ("unrecognized type in MakeByteBlob: " + element_type);
6033 data = new byte [(count * factor + 3) & ~3];
6036 for (int i = 0; i < count; ++i) {
6037 object v = array_data [i];
6039 if (v is EnumConstant)
6040 v = ((EnumConstant) v).Child;
6042 if (v is Constant && !(v is StringConstant))
6043 v = ((Constant) v).GetValue ();
6049 if (element_type == TypeManager.int64_type){
6050 if (!(v is Expression)){
6051 long val = (long) v;
6053 for (int j = 0; j < factor; ++j) {
6054 data [idx + j] = (byte) (val & 0xFF);
6058 } else if (element_type == TypeManager.uint64_type){
6059 if (!(v is Expression)){
6060 ulong val = (ulong) v;
6062 for (int j = 0; j < factor; ++j) {
6063 data [idx + j] = (byte) (val & 0xFF);
6067 } else if (element_type == TypeManager.float_type) {
6068 if (!(v is Expression)){
6069 element = BitConverter.GetBytes ((float) v);
6071 for (int j = 0; j < factor; ++j)
6072 data [idx + j] = element [j];
6073 if (!BitConverter.IsLittleEndian)
6074 System.Array.Reverse (data, idx, 4);
6076 } else if (element_type == TypeManager.double_type) {
6077 if (!(v is Expression)){
6078 element = BitConverter.GetBytes ((double) v);
6080 for (int j = 0; j < factor; ++j)
6081 data [idx + j] = element [j];
6083 // FIXME: Handle the ARM float format.
6084 if (!BitConverter.IsLittleEndian)
6085 System.Array.Reverse (data, idx, 8);
6087 } else if (element_type == TypeManager.char_type){
6088 if (!(v is Expression)){
6089 int val = (int) ((char) v);
6091 data [idx] = (byte) (val & 0xff);
6092 data [idx+1] = (byte) (val >> 8);
6094 } else if (element_type == TypeManager.short_type){
6095 if (!(v is Expression)){
6096 int val = (int) ((short) v);
6098 data [idx] = (byte) (val & 0xff);
6099 data [idx+1] = (byte) (val >> 8);
6101 } else if (element_type == TypeManager.ushort_type){
6102 if (!(v is Expression)){
6103 int val = (int) ((ushort) v);
6105 data [idx] = (byte) (val & 0xff);
6106 data [idx+1] = (byte) (val >> 8);
6108 } else if (element_type == TypeManager.int32_type) {
6109 if (!(v is Expression)){
6112 data [idx] = (byte) (val & 0xff);
6113 data [idx+1] = (byte) ((val >> 8) & 0xff);
6114 data [idx+2] = (byte) ((val >> 16) & 0xff);
6115 data [idx+3] = (byte) (val >> 24);
6117 } else if (element_type == TypeManager.uint32_type) {
6118 if (!(v is Expression)){
6119 uint val = (uint) v;
6121 data [idx] = (byte) (val & 0xff);
6122 data [idx+1] = (byte) ((val >> 8) & 0xff);
6123 data [idx+2] = (byte) ((val >> 16) & 0xff);
6124 data [idx+3] = (byte) (val >> 24);
6126 } else if (element_type == TypeManager.sbyte_type) {
6127 if (!(v is Expression)){
6128 sbyte val = (sbyte) v;
6129 data [idx] = (byte) val;
6131 } else if (element_type == TypeManager.byte_type) {
6132 if (!(v is Expression)){
6133 byte val = (byte) v;
6134 data [idx] = (byte) val;
6136 } else if (element_type == TypeManager.bool_type) {
6137 if (!(v is Expression)){
6138 bool val = (bool) v;
6139 data [idx] = (byte) (val ? 1 : 0);
6141 } else if (element_type == TypeManager.decimal_type){
6142 if (!(v is Expression)){
6143 int [] bits = Decimal.GetBits ((decimal) v);
6146 // FIXME: For some reason, this doesn't work on the MS runtime.
6147 int [] nbits = new int [4];
6148 nbits [0] = bits [3];
6149 nbits [1] = bits [2];
6150 nbits [2] = bits [0];
6151 nbits [3] = bits [1];
6153 for (int j = 0; j < 4; j++){
6154 data [p++] = (byte) (nbits [j] & 0xff);
6155 data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
6156 data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
6157 data [p++] = (byte) (nbits [j] >> 24);
6161 throw new Exception ("Unrecognized type in MakeByteBlob: " + element_type);
6171 public override SLE.Expression MakeExpression (BuilderContext ctx)
6173 var initializers = new SLE.Expression [array_data.Count];
6174 for (var i = 0; i < initializers.Length; i++) {
6175 if (array_data [i] == null)
6176 initializers [i] = SLE.Expression.Default (array_element_type.GetMetaInfo ());
6178 initializers [i] = array_data [i].MakeExpression (ctx);
6181 return SLE.Expression.NewArrayInit (array_element_type.GetMetaInfo (), initializers);
6185 // Emits the initializers for the array
6187 void EmitStaticInitializers (EmitContext ec)
6189 // FIXME: This should go to Resolve !
6190 if (TypeManager.void_initializearray_array_fieldhandle == null) {
6191 TypeManager.void_initializearray_array_fieldhandle = TypeManager.GetPredefinedMethod (
6192 TypeManager.runtime_helpers_type, "InitializeArray", loc,
6193 TypeManager.array_type, TypeManager.runtime_field_handle_type);
6194 if (TypeManager.void_initializearray_array_fieldhandle == null)
6199 // First, the static data
6203 byte [] data = MakeByteBlob ();
6205 fb = RootContext.MakeStaticData (data);
6207 ec.Emit (OpCodes.Dup);
6208 ec.Emit (OpCodes.Ldtoken, fb);
6209 ec.Emit (OpCodes.Call, TypeManager.void_initializearray_array_fieldhandle);
6213 // Emits pieces of the array that can not be computed at compile
6214 // time (variables and string locations).
6216 // This always expect the top value on the stack to be the array
6218 void EmitDynamicInitializers (EmitContext ec, bool emitConstants)
6220 int dims = bounds.Count;
6221 var current_pos = new int [dims];
6223 for (int i = 0; i < array_data.Count; i++){
6225 Expression e = array_data [i];
6226 var c = e as Constant;
6228 // Constant can be initialized via StaticInitializer
6229 if (c == null || (c != null && emitConstants && !c.IsDefaultInitializer (array_element_type))) {
6230 TypeSpec etype = e.Type;
6232 ec.Emit (OpCodes.Dup);
6234 for (int idx = 0; idx < dims; idx++)
6235 ec.EmitInt (current_pos [idx]);
6238 // If we are dealing with a struct, get the
6239 // address of it, so we can store it.
6241 if ((dims == 1) && TypeManager.IsStruct (etype) &&
6242 (!TypeManager.IsBuiltinOrEnum (etype) ||
6243 etype == TypeManager.decimal_type)) {
6245 ec.Emit (OpCodes.Ldelema, etype);
6250 ec.EmitArrayStore ((ArrayContainer) type);
6256 for (int j = dims - 1; j >= 0; j--){
6258 if (current_pos [j] < bounds [j])
6260 current_pos [j] = 0;
6265 public override void Emit (EmitContext ec)
6267 if (first_emit != null) {
6268 first_emit.Emit (ec);
6269 first_emit_temp.Store (ec);
6272 foreach (Expression e in arguments)
6275 ec.EmitArrayNew ((ArrayContainer) type);
6277 if (initializers == null)
6280 // Emit static initializer for arrays which have contain more than 2 items and
6281 // the static initializer will initialize at least 25% of array values.
6282 // NOTE: const_initializers_count does not contain default constant values.
6283 if (const_initializers_count > 2 && const_initializers_count * 4 > (array_data.Count) &&
6284 (TypeManager.IsPrimitiveType (array_element_type) || TypeManager.IsEnumType (array_element_type))) {
6285 EmitStaticInitializers (ec);
6287 if (!only_constant_initializers)
6288 EmitDynamicInitializers (ec, false);
6290 EmitDynamicInitializers (ec, true);
6293 if (first_emit_temp != null)
6294 first_emit_temp.Release (ec);
6297 public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
6299 // no multi dimensional or jagged arrays
6300 if (arguments.Count != 1 || array_element_type.IsArray) {
6301 base.EncodeAttributeValue (rc, enc, targetType);
6305 // No array covariance, except for array -> object
6306 if (type != targetType) {
6307 if (targetType != TypeManager.object_type) {
6308 base.EncodeAttributeValue (rc, enc, targetType);
6312 if (enc.Encode (type) == AttributeEncoder.EncodedTypeProperties.DynamicType) {
6313 Attribute.Error_AttributeArgumentIsDynamic (rc, loc);
6318 // Single dimensional array of 0 size
6319 if (array_data == null) {
6320 IntConstant ic = arguments[0] as IntConstant;
6321 if (ic == null || !ic.IsDefaultValue) {
6322 base.EncodeAttributeValue (rc, enc, targetType);
6324 enc.Stream.Write (0);
6330 enc.Stream.Write ((int) array_data.Count);
6331 foreach (var element in array_data) {
6332 element.EncodeAttributeValue (rc, enc, array_element_type);
6336 protected override void CloneTo (CloneContext clonectx, Expression t)
6338 ArrayCreation target = (ArrayCreation) t;
6340 if (requested_base_type != null)
6341 target.requested_base_type = (FullNamedExpression)requested_base_type.Clone (clonectx);
6343 if (arguments != null){
6344 target.arguments = new List<Expression> (arguments.Count);
6345 foreach (Expression e in arguments)
6346 target.arguments.Add (e.Clone (clonectx));
6349 if (initializers != null)
6350 target.initializers = (ArrayInitializer) initializers.Clone (clonectx);
6355 // Represents an implicitly typed array epxression
6357 class ImplicitlyTypedArrayCreation : ArrayCreation
6359 public ImplicitlyTypedArrayCreation (ComposedTypeSpecifier rank, ArrayInitializer initializers, Location loc)
6360 : base (null, rank, initializers, loc)
6364 public ImplicitlyTypedArrayCreation (ArrayInitializer initializers, Location loc)
6365 : base (null, initializers, loc)
6369 protected override Expression DoResolve (ResolveContext ec)
6374 dimensions = rank.Dimension;
6376 if (!ResolveInitializers (ec))
6379 if (array_element_type == null || array_element_type == InternalType.Null ||
6380 array_element_type == TypeManager.void_type || array_element_type == InternalType.AnonymousMethod ||
6381 array_element_type == InternalType.MethodGroup ||
6382 arguments.Count != rank.Dimension) {
6383 Error_NoBestType (ec);
6388 // At this point we found common base type for all initializer elements
6389 // but we have to be sure that all static initializer elements are of
6392 UnifyInitializerElement (ec);
6394 type = ArrayContainer.MakeType (array_element_type, dimensions);
6395 eclass = ExprClass.Value;
6399 void Error_NoBestType (ResolveContext ec)
6401 ec.Report.Error (826, loc,
6402 "The type of an implicitly typed array cannot be inferred from the initializer. Try specifying array type explicitly");
6406 // Converts static initializer only
6408 void UnifyInitializerElement (ResolveContext ec)
6410 for (int i = 0; i < array_data.Count; ++i) {
6411 Expression e = array_data[i];
6413 array_data [i] = Convert.ImplicitConversion (ec, e, array_element_type, Location.Null);
6417 protected override Expression ResolveArrayElement (ResolveContext ec, Expression element)
6419 element = element.Resolve (ec);
6420 if (element == null)
6423 if (array_element_type == null) {
6424 if (element.Type != InternalType.Null)
6425 array_element_type = element.Type;
6430 if (Convert.ImplicitConversionExists (ec, element, array_element_type)) {
6434 if (Convert.ImplicitConversionExists (ec, new TypeExpression (array_element_type, loc), element.Type)) {
6435 array_element_type = element.Type;
6439 Error_NoBestType (ec);
6444 public sealed class CompilerGeneratedThis : This
6446 public static This Instance = new CompilerGeneratedThis ();
6448 private CompilerGeneratedThis ()
6449 : base (Location.Null)
6453 public CompilerGeneratedThis (TypeSpec type, Location loc)
6459 protected override Expression DoResolve (ResolveContext ec)
6461 eclass = ExprClass.Variable;
6463 type = ec.CurrentType;
6468 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
6475 /// Represents the `this' construct
6478 public class This : VariableReference
6480 sealed class ThisVariable : ILocalVariable
6482 public static readonly ILocalVariable Instance = new ThisVariable ();
6484 public void Emit (EmitContext ec)
6486 ec.Emit (OpCodes.Ldarg_0);
6489 public void EmitAssign (EmitContext ec)
6491 throw new InvalidOperationException ();
6494 public void EmitAddressOf (EmitContext ec)
6496 ec.Emit (OpCodes.Ldarg_0);
6500 VariableInfo variable_info;
6502 public This (Location loc)
6509 public override string Name {
6510 get { return "this"; }
6513 public override bool IsRef {
6514 get { return type.IsStruct; }
6517 protected override ILocalVariable Variable {
6518 get { return ThisVariable.Instance; }
6521 public override VariableInfo VariableInfo {
6522 get { return variable_info; }
6525 public override bool IsFixed {
6526 get { return false; }
6531 protected virtual void Error_ThisNotAvailable (ResolveContext ec)
6533 if (ec.IsStatic && !ec.HasSet (ResolveContext.Options.ConstantScope)) {
6534 ec.Report.Error (26, loc, "Keyword `this' is not valid in a static property, static method, or static field initializer");
6535 } else if (ec.CurrentAnonymousMethod != null) {
6536 ec.Report.Error (1673, loc,
6537 "Anonymous methods inside structs cannot access instance members of `this'. " +
6538 "Consider copying `this' to a local variable outside the anonymous method and using the local instead");
6540 ec.Report.Error (27, loc, "Keyword `this' is not available in the current context");
6544 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
6549 AnonymousMethodStorey storey = ae.Storey;
6550 while (storey != null) {
6551 AnonymousMethodStorey temp = storey.Parent as AnonymousMethodStorey;
6553 return storey.HoistedThis;
6561 public static bool IsThisAvailable (ResolveContext ec, bool ignoreAnonymous)
6563 if (ec.IsStatic || ec.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.BaseInitializer | ResolveContext.Options.ConstantScope))
6566 if (ignoreAnonymous || ec.CurrentAnonymousMethod == null)
6569 if (TypeManager.IsStruct (ec.CurrentType) && ec.CurrentIterator == null)
6575 public virtual void ResolveBase (ResolveContext ec)
6577 if (!IsThisAvailable (ec, false)) {
6578 Error_ThisNotAvailable (ec);
6581 var block = ec.CurrentBlock;
6582 if (block != null) {
6583 if (block.Toplevel.ThisVariable != null)
6584 variable_info = block.Toplevel.ThisVariable.VariableInfo;
6586 AnonymousExpression am = ec.CurrentAnonymousMethod;
6587 if (am != null && ec.IsVariableCapturingRequired) {
6588 am.SetHasThisAccess ();
6592 eclass = ExprClass.Variable;
6593 type = ec.CurrentType;
6597 // Called from Invocation to check if the invocation is correct
6599 public override void CheckMarshalByRefAccess (ResolveContext ec)
6601 if ((variable_info != null) && !(TypeManager.IsStruct (type) && ec.OmitStructFlowAnalysis) &&
6602 !variable_info.IsAssigned (ec)) {
6603 ec.Report.Error (188, loc,
6604 "The `this' object cannot be used before all of its fields are assigned to");
6605 variable_info.SetAssigned (ec);
6609 public override Expression CreateExpressionTree (ResolveContext ec)
6611 Arguments args = new Arguments (1);
6612 args.Add (new Argument (this));
6614 // Use typeless constant for ldarg.0 to save some
6615 // space and avoid problems with anonymous stories
6616 return CreateExpressionFactoryCall (ec, "Constant", args);
6619 protected override Expression DoResolve (ResolveContext ec)
6625 override public Expression DoResolveLValue (ResolveContext ec, Expression right_side)
6629 if (variable_info != null)
6630 variable_info.SetAssigned (ec);
6632 if (ec.CurrentType.IsClass){
6633 if (right_side == EmptyExpression.UnaryAddress)
6634 ec.Report.Error (459, loc, "Cannot take the address of `this' because it is read-only");
6635 else if (right_side == EmptyExpression.OutAccess.Instance)
6636 ec.Report.Error (1605, loc, "Cannot pass `this' as a ref or out argument because it is read-only");
6638 ec.Report.Error (1604, loc, "Cannot assign to `this' because it is read-only");
6644 public override int GetHashCode()
6646 throw new NotImplementedException ();
6649 public override bool Equals (object obj)
6651 This t = obj as This;
6658 protected override void CloneTo (CloneContext clonectx, Expression t)
6663 public override void SetHasAddressTaken ()
6670 /// Represents the `__arglist' construct
6672 public class ArglistAccess : Expression
6674 public ArglistAccess (Location loc)
6679 public override Expression CreateExpressionTree (ResolveContext ec)
6681 throw new NotSupportedException ("ET");
6684 protected override Expression DoResolve (ResolveContext ec)
6686 eclass = ExprClass.Variable;
6687 type = TypeManager.runtime_argument_handle_type;
6689 if (ec.HasSet (ResolveContext.Options.FieldInitializerScope) || !ec.CurrentBlock.Toplevel.Parameters.HasArglist) {
6690 ec.Report.Error (190, loc,
6691 "The __arglist construct is valid only within a variable argument method");
6697 public override void Emit (EmitContext ec)
6699 ec.Emit (OpCodes.Arglist);
6702 protected override void CloneTo (CloneContext clonectx, Expression target)
6709 /// Represents the `__arglist (....)' construct
6711 public class Arglist : Expression
6713 Arguments Arguments;
6715 public Arglist (Location loc)
6720 public Arglist (Arguments args, Location l)
6726 public Type[] ArgumentTypes {
6728 if (Arguments == null)
6729 return System.Type.EmptyTypes;
6731 var retval = new Type [Arguments.Count];
6732 for (int i = 0; i < retval.Length; i++)
6733 retval[i] = Arguments[i].Expr.Type.GetMetaInfo ();
6739 public override Expression CreateExpressionTree (ResolveContext ec)
6741 ec.Report.Error (1952, loc, "An expression tree cannot contain a method with variable arguments");
6745 protected override Expression DoResolve (ResolveContext ec)
6747 eclass = ExprClass.Variable;
6748 type = InternalType.Arglist;
6749 if (Arguments != null) {
6750 bool dynamic; // Can be ignored as there is always only 1 overload
6751 Arguments.Resolve (ec, out dynamic);
6757 public override void Emit (EmitContext ec)
6759 if (Arguments != null)
6760 Arguments.Emit (ec);
6763 protected override void CloneTo (CloneContext clonectx, Expression t)
6765 Arglist target = (Arglist) t;
6767 if (Arguments != null)
6768 target.Arguments = Arguments.Clone (clonectx);
6773 /// Implements the typeof operator
6775 public class TypeOf : Expression {
6776 FullNamedExpression QueriedType;
6779 public TypeOf (FullNamedExpression queried_type, Location l)
6781 QueriedType = queried_type;
6786 public TypeSpec TypeArgument {
6792 public FullNamedExpression TypeExpression {
6800 public override Expression CreateExpressionTree (ResolveContext ec)
6802 Arguments args = new Arguments (2);
6803 args.Add (new Argument (this));
6804 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
6805 return CreateExpressionFactoryCall (ec, "Constant", args);
6808 protected override Expression DoResolve (ResolveContext ec)
6810 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
6814 typearg = texpr.Type;
6816 if (typearg == TypeManager.void_type && !(QueriedType is TypeExpression)) {
6817 ec.Report.Error (673, loc, "System.Void cannot be used from C#. Use typeof (void) to get the void type object");
6818 } else if (typearg.IsPointer && !ec.IsUnsafe){
6819 UnsafeError (ec, loc);
6820 } else if (texpr is DynamicTypeExpr) {
6821 ec.Report.Error (1962, QueriedType.Location,
6822 "The typeof operator cannot be used on the dynamic type");
6825 type = TypeManager.type_type;
6826 QueriedType = texpr;
6828 return DoResolveBase ();
6831 protected Expression DoResolveBase ()
6833 if (TypeManager.system_type_get_type_from_handle == null) {
6834 TypeManager.system_type_get_type_from_handle = TypeManager.GetPredefinedMethod (
6835 TypeManager.type_type, "GetTypeFromHandle", loc, TypeManager.runtime_handle_type);
6838 // Even though what is returned is a type object, it's treated as a value by the compiler.
6839 // In particular, 'typeof (Foo).X' is something totally different from 'Foo.X'.
6840 eclass = ExprClass.Value;
6844 static bool ContainsDynamicType (TypeSpec type)
6846 if (type == InternalType.Dynamic)
6849 var element_container = type as ElementTypeSpec;
6850 if (element_container != null)
6851 return ContainsDynamicType (element_container.Element);
6853 foreach (var t in type.TypeArguments) {
6854 if (ContainsDynamicType (t)) {
6862 static bool ContainsTypeParameter (TypeSpec type)
6864 if (type.Kind == MemberKind.TypeParameter)
6867 var element_container = type as ElementTypeSpec;
6868 if (element_container != null)
6869 return ContainsTypeParameter (element_container.Element);
6871 foreach (var t in type.TypeArguments) {
6872 if (ContainsTypeParameter (t)) {
6880 public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
6882 // Target type is not System.Type therefore must be object
6883 // and we need to use different encoding sequence
6884 if (targetType != type)
6887 if (!(QueriedType is GenericOpenTypeExpr)) {
6889 while (gt != null) {
6890 if (ContainsTypeParameter (gt)) {
6891 rc.Compiler.Report.Error (416, loc, "`{0}': an attribute argument cannot use type parameters",
6892 typearg.GetSignatureForError ());
6896 gt = gt.DeclaringType;
6899 if (ContainsDynamicType (typearg)) {
6900 Attribute.Error_AttributeArgumentIsDynamic (rc, loc);
6905 enc.EncodeTypeName (typearg);
6908 public override void Emit (EmitContext ec)
6910 ec.Emit (OpCodes.Ldtoken, typearg);
6911 ec.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6914 protected override void CloneTo (CloneContext clonectx, Expression t)
6916 TypeOf target = (TypeOf) t;
6917 if (QueriedType != null)
6918 target.QueriedType = (FullNamedExpression) QueriedType.Clone (clonectx);
6922 class TypeOfMethod : TypeOfMember<MethodSpec>
6924 public TypeOfMethod (MethodSpec method, Location loc)
6925 : base (method, loc)
6929 protected override Expression DoResolve (ResolveContext ec)
6931 if (member.IsConstructor) {
6932 type = TypeManager.ctorinfo_type;
6934 type = TypeManager.ctorinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", "ConstructorInfo", MemberKind.Class, true);
6936 type = TypeManager.methodinfo_type;
6938 type = TypeManager.methodinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", "MethodInfo", MemberKind.Class, true);
6941 return base.DoResolve (ec);
6944 public override void Emit (EmitContext ec)
6946 ec.Emit (OpCodes.Ldtoken, member);
6949 ec.Emit (OpCodes.Castclass, type);
6952 protected override string GetMethodName {
6953 get { return "GetMethodFromHandle"; }
6956 protected override string RuntimeHandleName {
6957 get { return "RuntimeMethodHandle"; }
6960 protected override MethodSpec TypeFromHandle {
6962 return TypeManager.methodbase_get_type_from_handle;
6965 TypeManager.methodbase_get_type_from_handle = value;
6969 protected override MethodSpec TypeFromHandleGeneric {
6971 return TypeManager.methodbase_get_type_from_handle_generic;
6974 TypeManager.methodbase_get_type_from_handle_generic = value;
6978 protected override string TypeName {
6979 get { return "MethodBase"; }
6983 abstract class TypeOfMember<T> : Expression where T : MemberSpec
6985 protected readonly T member;
6987 protected TypeOfMember (T member, Location loc)
6989 this.member = member;
6993 public override Expression CreateExpressionTree (ResolveContext ec)
6995 Arguments args = new Arguments (2);
6996 args.Add (new Argument (this));
6997 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
6998 return CreateExpressionFactoryCall (ec, "Constant", args);
7001 protected override Expression DoResolve (ResolveContext ec)
7003 bool is_generic = member.DeclaringType.IsGenericOrParentIsGeneric;
7004 var mi = is_generic ? TypeFromHandleGeneric : TypeFromHandle;
7007 TypeSpec t = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", TypeName, MemberKind.Class, true);
7008 TypeSpec handle_type = TypeManager.CoreLookupType (ec.Compiler, "System", RuntimeHandleName, MemberKind.Struct, true);
7010 if (t == null || handle_type == null)
7013 mi = TypeManager.GetPredefinedMethod (t, GetMethodName, loc,
7015 new TypeSpec[] { handle_type, TypeManager.runtime_handle_type } :
7016 new TypeSpec[] { handle_type } );
7019 TypeFromHandleGeneric = mi;
7021 TypeFromHandle = mi;
7024 eclass = ExprClass.Value;
7028 public override void Emit (EmitContext ec)
7030 bool is_generic = member.DeclaringType.IsGenericOrParentIsGeneric;
7033 mi = TypeFromHandleGeneric;
7034 ec.Emit (OpCodes.Ldtoken, member.DeclaringType);
7036 mi = TypeFromHandle;
7039 ec.Emit (OpCodes.Call, mi);
7042 protected abstract string GetMethodName { get; }
7043 protected abstract string RuntimeHandleName { get; }
7044 protected abstract MethodSpec TypeFromHandle { get; set; }
7045 protected abstract MethodSpec TypeFromHandleGeneric { get; set; }
7046 protected abstract string TypeName { get; }
7049 class TypeOfField : TypeOfMember<FieldSpec>
7051 public TypeOfField (FieldSpec field, Location loc)
7056 protected override Expression DoResolve (ResolveContext ec)
7058 if (TypeManager.fieldinfo_type == null)
7059 TypeManager.fieldinfo_type = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", TypeName, MemberKind.Class, true);
7061 type = TypeManager.fieldinfo_type;
7062 return base.DoResolve (ec);
7065 public override void Emit (EmitContext ec)
7067 ec.Emit (OpCodes.Ldtoken, member);
7071 protected override string GetMethodName {
7072 get { return "GetFieldFromHandle"; }
7075 protected override string RuntimeHandleName {
7076 get { return "RuntimeFieldHandle"; }
7079 protected override MethodSpec TypeFromHandle {
7081 return TypeManager.fieldinfo_get_field_from_handle;
7084 TypeManager.fieldinfo_get_field_from_handle = value;
7088 protected override MethodSpec TypeFromHandleGeneric {
7090 return TypeManager.fieldinfo_get_field_from_handle_generic;
7093 TypeManager.fieldinfo_get_field_from_handle_generic = value;
7097 protected override string TypeName {
7098 get { return "FieldInfo"; }
7103 /// Implements the sizeof expression
7105 public class SizeOf : Expression {
7106 readonly Expression QueriedType;
7107 TypeSpec type_queried;
7109 public SizeOf (Expression queried_type, Location l)
7111 this.QueriedType = queried_type;
7115 public override Expression CreateExpressionTree (ResolveContext ec)
7117 Error_PointerInsideExpressionTree (ec);
7121 protected override Expression DoResolve (ResolveContext ec)
7123 TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
7127 type_queried = texpr.Type;
7128 if (TypeManager.IsEnumType (type_queried))
7129 type_queried = EnumSpec.GetUnderlyingType (type_queried);
7131 int size_of = GetTypeSize (type_queried);
7133 return new IntConstant (size_of, loc).Resolve (ec);
7136 if (!TypeManager.VerifyUnmanaged (ec.Compiler, type_queried, loc)){
7141 ec.Report.Error (233, loc,
7142 "`{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)",
7143 TypeManager.CSharpName (type_queried));
7146 type = TypeManager.int32_type;
7147 eclass = ExprClass.Value;
7151 public override void Emit (EmitContext ec)
7153 ec.Emit (OpCodes.Sizeof, type_queried);
7156 protected override void CloneTo (CloneContext clonectx, Expression t)
7162 /// Implements the qualified-alias-member (::) expression.
7164 public class QualifiedAliasMember : MemberAccess
7166 readonly string alias;
7167 public static readonly string GlobalAlias = "global";
7169 public QualifiedAliasMember (string alias, string identifier, Location l)
7170 : base (null, identifier, l)
7175 public QualifiedAliasMember (string alias, string identifier, TypeArguments targs, Location l)
7176 : base (null, identifier, targs, l)
7181 public QualifiedAliasMember (string alias, string identifier, int arity, Location l)
7182 : base (null, identifier, arity, l)
7187 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
7189 if (alias == GlobalAlias) {
7190 expr = GlobalRootNamespace.Instance;
7191 return base.ResolveAsTypeStep (ec, silent);
7194 int errors = ec.Compiler.Report.Errors;
7195 expr = ec.LookupNamespaceAlias (alias);
7197 if (errors == ec.Compiler.Report.Errors)
7198 ec.Compiler.Report.Error (432, loc, "Alias `{0}' not found", alias);
7202 FullNamedExpression fne = base.ResolveAsTypeStep (ec, silent);
7206 if (expr.eclass == ExprClass.Type) {
7208 ec.Compiler.Report.Error (431, loc,
7209 "Alias `{0}' cannot be used with '::' since it denotes a type. Consider replacing '::' with '.'", alias);
7217 protected override Expression DoResolve (ResolveContext ec)
7219 return ResolveAsTypeStep (ec, false);
7222 protected override void Error_IdentifierNotFound (IMemberContext rc, TypeSpec expr_type, string identifier)
7224 rc.Compiler.Report.Error (687, loc,
7225 "A namespace alias qualifier `{0}' did not resolve to a namespace or a type",
7226 GetSignatureForError ());
7229 public override string GetSignatureForError ()
7232 if (targs != null) {
7233 name = Name + "<" + targs.GetSignatureForError () + ">";
7236 return alias + "::" + name;
7239 public override Expression LookupNameExpression (ResolveContext rc, bool readMode, bool invocableOnly)
7241 return DoResolve (rc);
7244 protected override void CloneTo (CloneContext clonectx, Expression t)
7251 /// Implements the member access expression
7253 public class MemberAccess : ATypeNameExpression
7255 protected Expression expr;
7257 public MemberAccess (Expression expr, string id)
7258 : base (id, expr.Location)
7263 public MemberAccess (Expression expr, string identifier, Location loc)
7264 : base (identifier, loc)
7269 public MemberAccess (Expression expr, string identifier, TypeArguments args, Location loc)
7270 : base (identifier, args, loc)
7275 public MemberAccess (Expression expr, string identifier, int arity, Location loc)
7276 : base (identifier, arity, loc)
7281 public Expression LeftExpression {
7287 protected override Expression DoResolve (ResolveContext ec)
7289 return DoResolveName (ec, null);
7292 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
7294 return DoResolveName (ec, right_side);
7297 Expression DoResolveName (ResolveContext rc, Expression right_side)
7299 Expression e = LookupNameExpression (rc, right_side == null, false);
7303 if (right_side != null)
7304 e = e.ResolveLValue (rc, right_side);
7306 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);
7359 TypeSpec expr_type = expr.Type;
7360 if (expr_type == InternalType.Dynamic) {
7361 Arguments args = new Arguments (1);
7362 args.Add (new Argument (expr));
7363 return new DynamicMemberBinder (Name, args, loc);
7366 const MemberKind dot_kinds = MemberKind.Class | MemberKind.Struct | MemberKind.Delegate | MemberKind.Enum |
7367 MemberKind.Interface | MemberKind.TypeParameter | MemberKind.ArrayType;
7369 if ((expr_type.Kind & dot_kinds) == 0 || expr_type == TypeManager.void_type) {
7370 Unary.Error_OperatorCannotBeApplied (rc, loc, ".", expr_type);
7374 var current_type = rc.CurrentType;
7375 var lookup_arity = Arity;
7376 bool errorMode = false;
7377 Expression member_lookup;
7379 member_lookup = MemberLookup (errorMode ? null : rc, current_type, expr_type, Name, lookup_arity, invocableOnly, loc);
7380 if (member_lookup == null) {
7382 // Try to look for extension method when member lookup failed
7384 if (MethodGroupExpr.IsExtensionMethodArgument (expr)) {
7385 NamespaceEntry scope = null;
7386 var methods = rc.LookupExtensionMethod (expr_type, Name, lookup_arity, ref scope);
7387 if (methods != null) {
7388 var emg = new ExtensionMethodGroupExpr (methods, scope, expr, loc);
7389 if (HasTypeArguments) {
7390 if (!targs.Resolve (rc))
7393 emg.SetTypeArguments (rc, targs);
7396 // TODO: Should it really skip the checks bellow
7397 return emg.Resolve (rc);
7403 if (member_lookup == null) {
7404 if (expr is TypeExpr)
7405 base.Error_TypeDoesNotContainDefinition (rc, expr_type, Name);
7407 Error_TypeDoesNotContainDefinition (rc, expr_type, Name);
7412 if (member_lookup is MethodGroupExpr) {
7413 // Leave it to overload resolution to report correct error
7415 // TODO: rc.SymbolRelatedToPreviousError
7416 ErrorIsInaccesible (rc, member_lookup.GetSignatureForError (), loc);
7421 if (member_lookup != null)
7424 current_type = null;
7426 invocableOnly = false;
7431 TypeExpr texpr = member_lookup as TypeExpr;
7433 if (texpr != null) {
7434 if (!(expr is TypeExpr)) {
7435 me = expr as MemberExpr;
7436 if (me == null || me.ProbeIdenticalTypeName (rc, expr, sn) == expr) {
7437 rc.Report.Error (572, loc, "`{0}': cannot reference a type through an expression; try `{1}' instead",
7438 Name, member_lookup.GetSignatureForError ());
7443 if (!texpr.Type.IsAccessible (rc.CurrentType)) {
7444 rc.Report.SymbolRelatedToPreviousError (member_lookup.Type);
7445 ErrorIsInaccesible (rc, member_lookup.Type.GetSignatureForError (), loc);
7449 if (HasTypeArguments) {
7450 return new GenericTypeExpr (member_lookup.Type, targs, loc);
7453 return member_lookup;
7456 me = member_lookup as MemberExpr;
7458 if (sn != null && me.IsStatic)
7459 expr = me.ProbeIdenticalTypeName (rc, expr, sn);
7461 me = me.ResolveMemberAccess (rc, expr, sn);
7464 if (!targs.Resolve (rc))
7467 me.SetTypeArguments (rc, targs);
7470 if (sn != null && (!TypeManager.IsValueType (expr_type) || me is PropertyExpr)) {
7471 if (me.IsInstance) {
7472 LocalVariableReference var = expr as LocalVariableReference;
7473 if (var != null && !var.VerifyAssigned (rc))
7481 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
7483 return ResolveNamespaceOrType (ec, silent);
7486 public FullNamedExpression ResolveNamespaceOrType (IMemberContext rc, bool silent)
7488 FullNamedExpression expr_resolved = expr.ResolveAsTypeStep (rc, silent);
7490 if (expr_resolved == null)
7493 Namespace ns = expr_resolved as Namespace;
7495 FullNamedExpression retval = ns.Lookup (rc.Compiler, Name, Arity, loc);
7497 if (retval == null) {
7499 ns.Error_NamespaceDoesNotExist (loc, Name, Arity, rc);
7500 } else if (HasTypeArguments) {
7501 retval = new GenericTypeExpr (retval.Type, targs, loc).ResolveAsTypeStep (rc, silent);
7507 TypeExpr tnew_expr = expr_resolved.ResolveAsTypeTerminal (rc, false);
7508 if (tnew_expr == null)
7511 TypeSpec expr_type = tnew_expr.Type;
7512 if (TypeManager.IsGenericParameter (expr_type)) {
7513 rc.Compiler.Report.Error (704, loc, "A nested type cannot be specified through a type parameter `{0}'",
7514 tnew_expr.GetSignatureForError ());
7518 var nested = MemberCache.FindNestedType (expr_type, Name, Arity);
7519 if (nested == null) {
7523 Error_IdentifierNotFound (rc, expr_type, Name);
7527 if (!nested.IsAccessible (rc.CurrentType ?? InternalType.FakeInternalType)) {
7528 ErrorIsInaccesible (rc, nested.GetSignatureForError (), loc);
7533 if (HasTypeArguments) {
7534 texpr = new GenericTypeExpr (nested, targs, loc);
7536 texpr = new GenericOpenTypeExpr (nested, loc);
7539 texpr = new TypeExpression (nested, loc);
7542 return texpr.ResolveAsTypeStep (rc, false);
7545 protected virtual void Error_IdentifierNotFound (IMemberContext rc, TypeSpec expr_type, string identifier)
7547 var nested = MemberCache.FindNestedType (expr_type, Name, -System.Math.Max (1, Arity));
7549 if (nested != null) {
7550 Error_TypeArgumentsCannotBeUsed (rc.Compiler.Report, expr.Location, nested, Arity);
7554 var any_other_member = MemberLookup (null, rc.CurrentType, expr_type, Name, 0, false, loc);
7555 if (any_other_member != null) {
7556 any_other_member.Error_UnexpectedKind (rc.Compiler.Report, null, "type", loc);
7560 rc.Compiler.Report.Error (426, loc, "The nested type `{0}' does not exist in the type `{1}'",
7561 Name, expr_type.GetSignatureForError ());
7564 protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
7566 if (RootContext.Version > LanguageVersion.ISO_2 && !ec.Compiler.IsRuntimeBinder && MethodGroupExpr.IsExtensionMethodArgument (expr)) {
7567 ec.Report.Error (1061, loc,
7568 "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?)",
7569 type.GetSignatureForError (), name);
7573 base.Error_TypeDoesNotContainDefinition (ec, type, name);
7576 public override string GetSignatureForError ()
7578 return expr.GetSignatureForError () + "." + base.GetSignatureForError ();
7581 protected override void CloneTo (CloneContext clonectx, Expression t)
7583 MemberAccess target = (MemberAccess) t;
7585 target.expr = expr.Clone (clonectx);
7590 /// Implements checked expressions
7592 public class CheckedExpr : Expression {
7594 public Expression Expr;
7596 public CheckedExpr (Expression e, Location l)
7602 public override Expression CreateExpressionTree (ResolveContext ec)
7604 using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
7605 return Expr.CreateExpressionTree (ec);
7608 protected override Expression DoResolve (ResolveContext ec)
7610 using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
7611 Expr = Expr.Resolve (ec);
7616 if (Expr is Constant || Expr is MethodGroupExpr || Expr is AnonymousMethodExpression || Expr is DefaultValueExpression)
7619 eclass = Expr.eclass;
7624 public override void Emit (EmitContext ec)
7626 using (ec.With (EmitContext.Options.AllCheckStateFlags, true))
7630 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
7632 using (ec.With (EmitContext.Options.AllCheckStateFlags, true))
7633 Expr.EmitBranchable (ec, target, on_true);
7636 public override SLE.Expression MakeExpression (BuilderContext ctx)
7638 using (ctx.With (BuilderContext.Options.AllCheckStateFlags, true)) {
7639 return Expr.MakeExpression (ctx);
7643 protected override void CloneTo (CloneContext clonectx, Expression t)
7645 CheckedExpr target = (CheckedExpr) t;
7647 target.Expr = Expr.Clone (clonectx);
7652 /// Implements the unchecked expression
7654 public class UnCheckedExpr : Expression {
7656 public Expression Expr;
7658 public UnCheckedExpr (Expression e, Location l)
7664 public override Expression CreateExpressionTree (ResolveContext ec)
7666 using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
7667 return Expr.CreateExpressionTree (ec);
7670 protected override Expression DoResolve (ResolveContext ec)
7672 using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
7673 Expr = Expr.Resolve (ec);
7678 if (Expr is Constant || Expr is MethodGroupExpr || Expr is AnonymousMethodExpression || Expr is DefaultValueExpression)
7681 eclass = Expr.eclass;
7686 public override void Emit (EmitContext ec)
7688 using (ec.With (EmitContext.Options.AllCheckStateFlags, false))
7692 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
7694 using (ec.With (EmitContext.Options.AllCheckStateFlags, false))
7695 Expr.EmitBranchable (ec, target, on_true);
7698 protected override void CloneTo (CloneContext clonectx, Expression t)
7700 UnCheckedExpr target = (UnCheckedExpr) t;
7702 target.Expr = Expr.Clone (clonectx);
7707 /// An Element Access expression.
7709 /// During semantic analysis these are transformed into
7710 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7712 public class ElementAccess : Expression {
7713 public Arguments Arguments;
7714 public Expression Expr;
7716 public ElementAccess (Expression e, Arguments args, Location loc)
7720 this.Arguments = args;
7724 // We perform some simple tests, and then to "split" the emit and store
7725 // code we create an instance of a different class, and return that.
7727 Expression CreateAccessExpression (ResolveContext ec)
7730 return (new ArrayAccess (this, loc));
7733 return MakePointerAccess (ec, type);
7735 FieldExpr fe = Expr as FieldExpr;
7737 var ff = fe.Spec as FixedFieldSpec;
7739 return MakePointerAccess (ec, ff.ElementType);
7743 var indexers = MemberCache.FindMembers (type, MemberCache.IndexerNameAlias, false);
7744 if (indexers != null || type == InternalType.Dynamic) {
7745 return new IndexerExpr (indexers, this);
7748 ec.Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
7749 type.GetSignatureForError ());
7753 public override Expression CreateExpressionTree (ResolveContext ec)
7755 Arguments args = Arguments.CreateForExpressionTree (ec, Arguments,
7756 Expr.CreateExpressionTree (ec));
7758 return CreateExpressionFactoryCall (ec, "ArrayIndex", args);
7761 Expression MakePointerAccess (ResolveContext ec, TypeSpec type)
7763 if (Arguments.Count != 1){
7764 ec.Report.Error (196, loc, "A pointer must be indexed by only one value");
7768 if (Arguments [0] is NamedArgument)
7769 Error_NamedArgument ((NamedArgument) Arguments[0], ec.Report);
7771 Expression p = new PointerArithmetic (Binary.Operator.Addition, Expr, Arguments [0].Expr.Resolve (ec), type, loc);
7772 return new Indirection (p, loc);
7775 protected override Expression DoResolve (ResolveContext ec)
7777 Expr = Expr.Resolve (ec);
7783 // TODO: Create 1 result for Resolve and ResolveLValue ?
7784 var res = CreateAccessExpression (ec);
7788 return res.Resolve (ec);
7791 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
7793 Expr = Expr.Resolve (ec);
7799 var res = CreateAccessExpression (ec);
7803 return res.ResolveLValue (ec, right_side);
7806 public override void Emit (EmitContext ec)
7808 throw new Exception ("Should never be reached");
7811 public static void Error_NamedArgument (NamedArgument na, Report Report)
7813 Report.Error (1742, na.Location, "An element access expression cannot use named argument");
7816 public override string GetSignatureForError ()
7818 return Expr.GetSignatureForError ();
7821 protected override void CloneTo (CloneContext clonectx, Expression t)
7823 ElementAccess target = (ElementAccess) t;
7825 target.Expr = Expr.Clone (clonectx);
7826 if (Arguments != null)
7827 target.Arguments = Arguments.Clone (clonectx);
7832 /// Implements array access
7834 public class ArrayAccess : Expression, IDynamicAssign, IMemoryLocation {
7836 // Points to our "data" repository
7840 LocalTemporary temp;
7844 public ArrayAccess (ElementAccess ea_data, Location l)
7850 public override Expression CreateExpressionTree (ResolveContext ec)
7852 return ea.CreateExpressionTree (ec);
7855 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
7857 return DoResolve (ec);
7860 protected override Expression DoResolve (ResolveContext ec)
7862 // dynamic is used per argument in ConvertExpressionToArrayIndex case
7864 ea.Arguments.Resolve (ec, out dynamic);
7866 var ac = ea.Expr.Type as ArrayContainer;
7867 int rank = ea.Arguments.Count;
7868 if (ac.Rank != rank) {
7869 ec.Report.Error (22, ea.Location, "Wrong number of indexes `{0}' inside [], expected `{1}'",
7870 rank.ToString (), ac.Rank.ToString ());
7875 if (type.IsPointer && !ec.IsUnsafe) {
7876 UnsafeError (ec, ea.Location);
7879 foreach (Argument a in ea.Arguments) {
7880 if (a is NamedArgument)
7881 ElementAccess.Error_NamedArgument ((NamedArgument) a, ec.Report);
7883 a.Expr = ConvertExpressionToArrayIndex (ec, a.Expr);
7886 eclass = ExprClass.Variable;
7891 protected override void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
7893 ec.Report.Warning (251, 2, loc, "Indexing an array with a negative index (array indices always start at zero)");
7897 // Load the array arguments into the stack.
7899 void LoadArrayAndArguments (EmitContext ec)
7903 for (int i = 0; i < ea.Arguments.Count; ++i) {
7904 ea.Arguments [i].Emit (ec);
7908 public void Emit (EmitContext ec, bool leave_copy)
7910 var ac = ea.Expr.Type as ArrayContainer;
7913 ec.EmitLoadFromPtr (type);
7915 LoadArrayAndArguments (ec);
7916 ec.EmitArrayLoad (ac);
7920 ec.Emit (OpCodes.Dup);
7921 temp = new LocalTemporary (this.type);
7926 public override void Emit (EmitContext ec)
7931 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
7933 var ac = (ArrayContainer) ea.Expr.Type;
7934 TypeSpec t = source.Type;
7935 prepared = prepare_for_load;
7938 AddressOf (ec, AddressOp.LoadStore);
7939 ec.Emit (OpCodes.Dup);
7941 LoadArrayAndArguments (ec);
7944 // If we are dealing with a struct, get the
7945 // address of it, so we can store it.
7947 // The stobj opcode used by value types will need
7948 // an address on the stack, not really an array/array
7951 if (ac.Rank == 1 && TypeManager.IsStruct (t) &&
7952 (!TypeManager.IsBuiltinOrEnum (t) ||
7953 t == TypeManager.decimal_type)) {
7955 ec.Emit (OpCodes.Ldelema, t);
7961 ec.Emit (OpCodes.Dup);
7962 temp = new LocalTemporary (this.type);
7967 ec.EmitStoreFromPtr (t);
7969 ec.EmitArrayStore (ac);
7978 public void EmitNew (EmitContext ec, New source, bool leave_copy)
7980 if (!source.Emit (ec, this)) {
7982 throw new NotImplementedException ();
7987 throw new NotImplementedException ();
7990 public void AddressOf (EmitContext ec, AddressOp mode)
7992 var ac = (ArrayContainer) ea.Expr.Type;
7994 LoadArrayAndArguments (ec);
7995 ec.EmitArrayAddress (ac);
7998 public SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
8001 return SLE.Expression.ArrayAccess (
8002 ea.Expr.MakeExpression (ctx),
8003 Arguments.MakeExpression (ea.Arguments, ctx));
8005 throw new NotImplementedException ();
8009 public override SLE.Expression MakeExpression (BuilderContext ctx)
8011 return SLE.Expression.ArrayIndex (
8012 ea.Expr.MakeExpression (ctx),
8013 Arguments.MakeExpression (ea.Arguments, ctx));
8018 // Indexer access expression
8020 class IndexerExpr : PropertyOrIndexerExpr<IndexerSpec>, OverloadResolver.IBaseMembersProvider
8022 LocalTemporary prepared_value;
8023 IList<MemberSpec> indexers;
8024 Arguments arguments;
8026 public IndexerExpr (IList<MemberSpec> indexers, ElementAccess ea)
8027 : base (ea.Location)
8029 this.indexers = indexers;
8030 this.InstanceExpression = ea.Expr;
8031 this.arguments = ea.Arguments;
8035 protected override TypeSpec DeclaringType {
8037 return best_candidate.DeclaringType;
8041 public override bool IsInstance {
8047 public override bool IsStatic {
8053 public override string Name {
8061 public override Expression CreateExpressionTree (ResolveContext ec)
8063 Arguments args = Arguments.CreateForExpressionTree (ec, arguments,
8064 InstanceExpression.CreateExpressionTree (ec),
8065 new TypeOfMethod (Getter, loc));
8067 return CreateExpressionFactoryCall (ec, "Call", args);
8070 public override void Emit (EmitContext ec, bool leave_copy)
8073 prepared_value.Emit (ec);
8075 Invocation.EmitCall (ec, InstanceExpression, Getter, arguments, loc, false, false);
8079 ec.Emit (OpCodes.Dup);
8080 temp = new LocalTemporary (Type);
8085 public override void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
8087 prepared = prepare_for_load;
8088 Expression value = source;
8091 Invocation.EmitCall (ec, InstanceExpression, Getter,
8092 arguments, loc, true, false);
8094 prepared_value = new LocalTemporary (type);
8095 prepared_value.Store (ec);
8097 prepared_value.Release (ec);
8100 ec.Emit (OpCodes.Dup);
8101 temp = new LocalTemporary (Type);
8104 } else if (leave_copy) {
8105 temp = new LocalTemporary (Type);
8112 arguments.Add (new Argument (value));
8114 Invocation.EmitCall (ec, InstanceExpression, Setter, arguments, loc, false, prepared);
8122 public override string GetSignatureForError ()
8124 return best_candidate.GetSignatureForError ();
8127 public override SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
8129 var value = new[] { source.MakeExpression (ctx) };
8130 var args = Arguments.MakeExpression (arguments, ctx).Concat (value);
8132 return SLE.Expression.Block (
8133 SLE.Expression.Call (InstanceExpression.MakeExpression (ctx), (MethodInfo) Setter.GetMetaInfo (), args),
8136 return args.First ();
8140 public override SLE.Expression MakeExpression (BuilderContext ctx)
8142 var args = Arguments.MakeExpression (arguments, ctx);
8143 return SLE.Expression.Call (InstanceExpression.MakeExpression (ctx), (MethodInfo) Getter.GetMetaInfo (), args);
8146 protected override Expression OverloadResolve (ResolveContext rc, Expression right_side)
8148 if (best_candidate != null)
8151 eclass = ExprClass.IndexerAccess;
8154 arguments.Resolve (rc, out dynamic);
8156 if (indexers == null && InstanceExpression.Type == InternalType.Dynamic) {
8159 var res = new OverloadResolver (indexers, OverloadResolver.Restrictions.None, loc);
8160 res.BaseMembersProvider = this;
8162 // TODO: Do I need 2 argument sets?
8163 best_candidate = res.ResolveMember<IndexerSpec> (rc, ref arguments);
8164 if (best_candidate != null)
8165 type = best_candidate.MemberType;
8166 else if (!res.BestCandidateIsDynamic)
8170 if (dynamic || type == InternalType.Dynamic) {
8171 Arguments args = new Arguments (arguments.Count + 1);
8173 rc.Report.Error (1972, loc,
8174 "The indexer base access cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access");
8176 args.Add (new Argument (InstanceExpression));
8178 args.AddRange (arguments);
8180 best_candidate = null;
8181 return new DynamicIndexBinder (args, loc);
8184 ResolveInstanceExpression (rc);
8185 CheckProtectedMemberAccess (rc, best_candidate);
8189 protected override void CloneTo (CloneContext clonectx, Expression t)
8191 IndexerExpr target = (IndexerExpr) t;
8193 if (arguments != null)
8194 target.arguments = arguments.Clone (clonectx);
8197 public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
8199 Error_TypeArgumentsCannotBeUsed (ec.Report, "indexer", GetSignatureForError (), loc);
8202 #region IBaseMembersProvider Members
8204 IList<MemberSpec> OverloadResolver.IBaseMembersProvider.GetBaseMembers (TypeSpec baseType)
8206 return baseType == null ? null : MemberCache.FindMembers (baseType, MemberCache.IndexerNameAlias, false);
8209 MethodGroupExpr OverloadResolver.IBaseMembersProvider.LookupExtensionMethod (ResolveContext rc)
8218 // A base access expression
8220 public class BaseThis : This
8222 public BaseThis (Location loc)
8227 public BaseThis (TypeSpec type, Location loc)
8231 eclass = ExprClass.Variable;
8236 public override string Name {
8244 public override Expression CreateExpressionTree (ResolveContext ec)
8246 ec.Report.Error (831, loc, "An expression tree may not contain a base access");
8247 return base.CreateExpressionTree (ec);
8250 public override void Emit (EmitContext ec)
8254 if (ec.CurrentType.IsStruct) {
8255 ec.Emit (OpCodes.Ldobj, ec.CurrentType);
8256 ec.Emit (OpCodes.Box, ec.CurrentType);
8260 protected override void Error_ThisNotAvailable (ResolveContext ec)
8263 ec.Report.Error (1511, loc, "Keyword `base' is not available in a static method");
8265 ec.Report.Error (1512, loc, "Keyword `base' is not available in the current context");
8269 public override void ResolveBase (ResolveContext ec)
8271 base.ResolveBase (ec);
8272 type = ec.CurrentType.BaseType;
8277 /// This class exists solely to pass the Type around and to be a dummy
8278 /// that can be passed to the conversion functions (this is used by
8279 /// foreach implementation to typecast the object return value from
8280 /// get_Current into the proper type. All code has been generated and
8281 /// we only care about the side effect conversions to be performed
8283 /// This is also now used as a placeholder where a no-action expression
8284 /// is needed (the `New' class).
8286 public class EmptyExpression : Expression {
8287 public static readonly Expression Null = new EmptyExpression ();
8289 public class OutAccess : EmptyExpression
8291 public static readonly OutAccess Instance = new OutAccess ();
8293 public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
8295 rc.Report.Error (206, right_side.Location,
8296 "A property, indexer or dynamic member access may not be passed as `ref' or `out' parameter");
8302 public static readonly EmptyExpression LValueMemberAccess = new EmptyExpression ();
8303 public static readonly EmptyExpression LValueMemberOutAccess = new EmptyExpression ();
8304 public static readonly EmptyExpression UnaryAddress = new EmptyExpression ();
8305 public static readonly EmptyExpression EventAddition = new EmptyExpression ();
8306 public static readonly EmptyExpression EventSubtraction = new EmptyExpression ();
8308 static EmptyExpression temp = new EmptyExpression ();
8309 public static EmptyExpression Grab ()
8311 EmptyExpression retval = temp == null ? new EmptyExpression () : temp;
8316 public static void Release (EmptyExpression e)
8323 // FIXME: Don't set to object
8324 type = TypeManager.object_type;
8325 eclass = ExprClass.Value;
8326 loc = Location.Null;
8329 public EmptyExpression (TypeSpec t)
8332 eclass = ExprClass.Value;
8333 loc = Location.Null;
8336 public override Expression CreateExpressionTree (ResolveContext ec)
8338 throw new NotSupportedException ("ET");
8341 protected override Expression DoResolve (ResolveContext ec)
8346 public override void Emit (EmitContext ec)
8348 // nothing, as we only exist to not do anything.
8351 public override void EmitSideEffect (EmitContext ec)
8356 // This is just because we might want to reuse this bad boy
8357 // instead of creating gazillions of EmptyExpressions.
8358 // (CanImplicitConversion uses it)
8360 public void SetType (TypeSpec t)
8367 // Empty statement expression
8369 public sealed class EmptyExpressionStatement : ExpressionStatement
8371 public static readonly EmptyExpressionStatement Instance = new EmptyExpressionStatement ();
8373 private EmptyExpressionStatement ()
8375 loc = Location.Null;
8378 public override Expression CreateExpressionTree (ResolveContext ec)
8383 public override void EmitStatement (EmitContext ec)
8388 protected override Expression DoResolve (ResolveContext ec)
8390 eclass = ExprClass.Value;
8391 type = TypeManager.object_type;
8395 public override void Emit (EmitContext ec)
8401 public class UserCast : Expression {
8405 public UserCast (MethodSpec method, Expression source, Location l)
8407 this.method = method;
8408 this.source = source;
8409 type = method.ReturnType;
8413 public Expression Source {
8419 public override Expression CreateExpressionTree (ResolveContext ec)
8421 Arguments args = new Arguments (3);
8422 args.Add (new Argument (source.CreateExpressionTree (ec)));
8423 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
8424 args.Add (new Argument (new TypeOfMethod (method, loc)));
8425 return CreateExpressionFactoryCall (ec, "Convert", args);
8428 protected override Expression DoResolve (ResolveContext ec)
8430 ObsoleteAttribute oa = method.GetAttributeObsolete ();
8432 AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
8434 eclass = ExprClass.Value;
8438 public override void Emit (EmitContext ec)
8441 ec.Emit (OpCodes.Call, method);
8444 public override string GetSignatureForError ()
8446 return TypeManager.CSharpSignature (method);
8449 public override SLE.Expression MakeExpression (BuilderContext ctx)
8451 return SLE.Expression.Convert (source.MakeExpression (ctx), type.GetMetaInfo (), (MethodInfo) method.GetMetaInfo ());
8456 // Holds additional type specifiers like ?, *, []
8458 public class ComposedTypeSpecifier
8460 public static readonly ComposedTypeSpecifier SingleDimension = new ComposedTypeSpecifier (1, Location.Null);
8462 public readonly int Dimension;
8463 public readonly Location Location;
8465 public ComposedTypeSpecifier (int specifier, Location loc)
8467 this.Dimension = specifier;
8468 this.Location = loc;
8472 public bool IsNullable {
8474 return Dimension == -1;
8478 public bool IsPointer {
8480 return Dimension == -2;
8484 public ComposedTypeSpecifier Next { get; set; }
8488 public static ComposedTypeSpecifier CreateArrayDimension (int dimension, Location loc)
8490 return new ComposedTypeSpecifier (dimension, loc);
8493 public static ComposedTypeSpecifier CreateNullable (Location loc)
8495 return new ComposedTypeSpecifier (-1, loc);
8498 public static ComposedTypeSpecifier CreatePointer (Location loc)
8500 return new ComposedTypeSpecifier (-2, loc);
8503 public string GetSignatureForError ()
8508 ArrayContainer.GetPostfixSignature (Dimension);
8510 return Next != null ? s + Next.GetSignatureForError () : s;
8515 // This class is used to "construct" the type during a typecast
8516 // operation. Since the Type.GetType class in .NET can parse
8517 // the type specification, we just use this to construct the type
8518 // one bit at a time.
8520 public class ComposedCast : TypeExpr {
8521 FullNamedExpression left;
8522 ComposedTypeSpecifier spec;
8524 public ComposedCast (FullNamedExpression left, ComposedTypeSpecifier spec)
8527 throw new ArgumentNullException ("spec");
8531 this.loc = spec.Location;
8534 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
8536 TypeExpr lexpr = left.ResolveAsTypeTerminal (ec, false);
8541 eclass = ExprClass.Type;
8543 var single_spec = spec;
8545 if (single_spec.IsNullable) {
8546 lexpr = new Nullable.NullableType (lexpr, loc);
8547 lexpr = lexpr.ResolveAsTypeTerminal (ec, false);
8551 single_spec = single_spec.Next;
8552 } else if (single_spec.IsPointer) {
8553 if (!TypeManager.VerifyUnmanaged (ec.Compiler, type, loc))
8557 UnsafeError (ec.Compiler.Report, loc);
8560 type = PointerContainer.MakeType (type);
8561 single_spec = single_spec.Next;
8564 if (single_spec != null && single_spec.Dimension > 0) {
8565 if (TypeManager.IsSpecialType (type)) {
8566 ec.Compiler.Report.Error (611, loc, "Array elements cannot be of type `{0}'", type.GetSignatureForError ());
8567 } else if (type.IsStatic) {
8568 ec.Compiler.Report.SymbolRelatedToPreviousError (type);
8569 ec.Compiler.Report.Error (719, loc, "Array elements cannot be of static type `{0}'",
8570 type.GetSignatureForError ());
8572 MakeArray (single_spec);
8579 void MakeArray (ComposedTypeSpecifier spec)
8581 if (spec.Next != null)
8582 MakeArray (spec.Next);
8584 type = ArrayContainer.MakeType (type, spec.Dimension);
8587 public override string GetSignatureForError ()
8589 return left.GetSignatureForError () + spec.GetSignatureForError ();
8593 public class FixedBufferPtr : Expression {
8596 public FixedBufferPtr (Expression array, TypeSpec array_type, Location l)
8601 type = PointerContainer.MakeType (array_type);
8602 eclass = ExprClass.Value;
8605 public override Expression CreateExpressionTree (ResolveContext ec)
8607 Error_PointerInsideExpressionTree (ec);
8611 public override void Emit(EmitContext ec)
8616 protected override Expression DoResolve (ResolveContext ec)
8619 // We are born fully resolved
8627 // This class is used to represent the address of an array, used
8628 // only by the Fixed statement, this generates "&a [0]" construct
8629 // for fixed (char *pa = a)
8631 public class ArrayPtr : FixedBufferPtr {
8632 TypeSpec array_type;
8634 public ArrayPtr (Expression array, TypeSpec array_type, Location l):
8635 base (array, array_type, l)
8637 this.array_type = array_type;
8640 public override void Emit (EmitContext ec)
8645 ec.Emit (OpCodes.Ldelema, array_type);
8650 // Encapsulates a conversion rules required for array indexes
8652 public class ArrayIndexCast : TypeCast
8654 public ArrayIndexCast (Expression expr)
8655 : base (expr, TypeManager.int32_type)
8657 if (expr.Type == TypeManager.int32_type)
8658 throw new ArgumentException ("unnecessary array index conversion");
8661 public override Expression CreateExpressionTree (ResolveContext ec)
8663 using (ec.Set (ResolveContext.Options.CheckedScope)) {
8664 return base.CreateExpressionTree (ec);
8668 public override void Emit (EmitContext ec)
8672 var expr_type = child.Type;
8674 if (expr_type == TypeManager.uint32_type)
8675 ec.Emit (OpCodes.Conv_U);
8676 else if (expr_type == TypeManager.int64_type)
8677 ec.Emit (OpCodes.Conv_Ovf_I);
8678 else if (expr_type == TypeManager.uint64_type)
8679 ec.Emit (OpCodes.Conv_Ovf_I_Un);
8681 throw new InternalErrorException ("Cannot emit cast to unknown array element type", type);
8686 // Implements the `stackalloc' keyword
8688 public class StackAlloc : Expression {
8693 public StackAlloc (Expression type, Expression count, Location l)
8700 public override Expression CreateExpressionTree (ResolveContext ec)
8702 throw new NotSupportedException ("ET");
8705 protected override Expression DoResolve (ResolveContext ec)
8707 count = count.Resolve (ec);
8711 if (count.Type != TypeManager.uint32_type){
8712 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
8717 Constant c = count as Constant;
8718 if (c != null && c.IsNegative) {
8719 ec.Report.Error (247, loc, "Cannot use a negative size with stackalloc");
8722 if (ec.HasAny (ResolveContext.Options.CatchScope | ResolveContext.Options.FinallyScope)) {
8723 ec.Report.Error (255, loc, "Cannot use stackalloc in finally or catch");
8726 TypeExpr texpr = t.ResolveAsTypeTerminal (ec, false);
8732 if (!TypeManager.VerifyUnmanaged (ec.Compiler, otype, loc))
8735 type = PointerContainer.MakeType (otype);
8736 eclass = ExprClass.Value;
8741 public override void Emit (EmitContext ec)
8743 int size = GetTypeSize (otype);
8748 ec.Emit (OpCodes.Sizeof, otype);
8752 ec.Emit (OpCodes.Mul_Ovf_Un);
8753 ec.Emit (OpCodes.Localloc);
8756 protected override void CloneTo (CloneContext clonectx, Expression t)
8758 StackAlloc target = (StackAlloc) t;
8759 target.count = count.Clone (clonectx);
8760 target.t = t.Clone (clonectx);
8765 // An object initializer expression
8767 public class ElementInitializer : Assign
8769 public readonly string Name;
8771 public ElementInitializer (string name, Expression initializer, Location loc)
8772 : base (null, initializer, loc)
8777 protected override void CloneTo (CloneContext clonectx, Expression t)
8779 ElementInitializer target = (ElementInitializer) t;
8780 target.source = source.Clone (clonectx);
8783 public override Expression CreateExpressionTree (ResolveContext ec)
8785 Arguments args = new Arguments (2);
8786 FieldExpr fe = target as FieldExpr;
8788 args.Add (new Argument (fe.CreateTypeOfExpression ()));
8790 args.Add (new Argument (((PropertyExpr)target).CreateSetterTypeOfExpression ()));
8792 args.Add (new Argument (source.CreateExpressionTree (ec)));
8793 return CreateExpressionFactoryCall (ec,
8794 source is CollectionOrObjectInitializers ? "ListBind" : "Bind",
8798 protected override Expression DoResolve (ResolveContext ec)
8801 return EmptyExpressionStatement.Instance;
8803 var t = ec.CurrentInitializerVariable.Type;
8804 if (t == InternalType.Dynamic) {
8805 Arguments args = new Arguments (1);
8806 args.Add (new Argument (ec.CurrentInitializerVariable));
8807 target = new DynamicMemberBinder (Name, args, loc);
8810 var member = MemberLookup (ec, ec.CurrentType, t, Name, 0, false, loc);
8811 if (member == null) {
8812 member = Expression.MemberLookup (null, ec.CurrentType, t, Name, 0, false, loc);
8814 if (member != null) {
8815 // TODO: ec.Report.SymbolRelatedToPreviousError (member);
8816 ErrorIsInaccesible (ec, member.GetSignatureForError (), loc);
8821 if (member == null) {
8822 Error_TypeDoesNotContainDefinition (ec, loc, t, Name);
8826 if (!(member is PropertyExpr || member is FieldExpr)) {
8827 ec.Report.Error (1913, loc,
8828 "Member `{0}' cannot be initialized. An object initializer may only be used for fields, or properties",
8829 member.GetSignatureForError ());
8834 var me = member as MemberExpr;
8836 ec.Report.Error (1914, loc,
8837 "Static field or property `{0}' cannot be assigned in an object initializer",
8838 me.GetSignatureForError ());
8842 me.InstanceExpression = ec.CurrentInitializerVariable;
8845 if (source is CollectionOrObjectInitializers) {
8846 Expression previous = ec.CurrentInitializerVariable;
8847 ec.CurrentInitializerVariable = target;
8848 source = source.Resolve (ec);
8849 ec.CurrentInitializerVariable = previous;
8853 eclass = source.eclass;
8858 return base.DoResolve (ec);
8861 public override void EmitStatement (EmitContext ec)
8863 if (source is CollectionOrObjectInitializers)
8866 base.EmitStatement (ec);
8871 // A collection initializer expression
8873 class CollectionElementInitializer : Invocation
8875 public class ElementInitializerArgument : Argument
8877 public ElementInitializerArgument (Expression e)
8883 sealed class AddMemberAccess : MemberAccess
8885 public AddMemberAccess (Expression expr, Location loc)
8886 : base (expr, "Add", loc)
8890 protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
8892 if (TypeManager.HasElementType (type))
8895 base.Error_TypeDoesNotContainDefinition (ec, type, name);
8899 public CollectionElementInitializer (Expression argument)
8900 : base (null, new Arguments (1))
8902 base.arguments.Add (new ElementInitializerArgument (argument));
8903 this.loc = argument.Location;
8906 public CollectionElementInitializer (List<Expression> arguments, Location loc)
8907 : base (null, new Arguments (arguments.Count))
8909 foreach (Expression e in arguments)
8910 base.arguments.Add (new ElementInitializerArgument (e));
8915 public override Expression CreateExpressionTree (ResolveContext ec)
8917 Arguments args = new Arguments (2);
8918 args.Add (new Argument (mg.CreateExpressionTree (ec)));
8920 var expr_initializers = new ArrayInitializer (arguments.Count, loc);
8921 foreach (Argument a in arguments)
8922 expr_initializers.Add (a.CreateExpressionTree (ec));
8924 args.Add (new Argument (new ArrayCreation (
8925 CreateExpressionTypeExpression (ec, loc), expr_initializers, loc)));
8926 return CreateExpressionFactoryCall (ec, "ElementInit", args);
8929 protected override void CloneTo (CloneContext clonectx, Expression t)
8931 CollectionElementInitializer target = (CollectionElementInitializer) t;
8932 if (arguments != null)
8933 target.arguments = arguments.Clone (clonectx);
8936 protected override Expression DoResolve (ResolveContext ec)
8938 base.expr = new AddMemberAccess (ec.CurrentInitializerVariable, loc);
8940 return base.DoResolve (ec);
8945 // A block of object or collection initializers
8947 public class CollectionOrObjectInitializers : ExpressionStatement
8949 IList<Expression> initializers;
8950 bool is_collection_initialization;
8952 public static readonly CollectionOrObjectInitializers Empty =
8953 new CollectionOrObjectInitializers (Array.AsReadOnly (new Expression [0]), Location.Null);
8955 public CollectionOrObjectInitializers (IList<Expression> initializers, Location loc)
8957 this.initializers = initializers;
8961 public bool IsEmpty {
8963 return initializers.Count == 0;
8967 public bool IsCollectionInitializer {
8969 return is_collection_initialization;
8973 protected override void CloneTo (CloneContext clonectx, Expression target)
8975 CollectionOrObjectInitializers t = (CollectionOrObjectInitializers) target;
8977 t.initializers = new List<Expression> (initializers.Count);
8978 foreach (var e in initializers)
8979 t.initializers.Add (e.Clone (clonectx));
8982 public override Expression CreateExpressionTree (ResolveContext ec)
8984 var expr_initializers = new ArrayInitializer (initializers.Count, loc);
8985 foreach (Expression e in initializers) {
8986 Expression expr = e.CreateExpressionTree (ec);
8988 expr_initializers.Add (expr);
8991 return new ImplicitlyTypedArrayCreation (expr_initializers, loc);
8994 protected override Expression DoResolve (ResolveContext ec)
8996 List<string> element_names = null;
8997 for (int i = 0; i < initializers.Count; ++i) {
8998 Expression initializer = initializers [i];
8999 ElementInitializer element_initializer = initializer as ElementInitializer;
9002 if (element_initializer != null) {
9003 element_names = new List<string> (initializers.Count);
9004 element_names.Add (element_initializer.Name);
9005 } else if (initializer is CompletingExpression){
9006 initializer.Resolve (ec);
9007 throw new InternalErrorException ("This line should never be reached");
9009 if (!ec.CurrentInitializerVariable.Type.ImplementsInterface (TypeManager.ienumerable_type)) {
9010 ec.Report.Error (1922, loc, "A field or property `{0}' cannot be initialized with a collection " +
9011 "object initializer because type `{1}' does not implement `{2}' interface",
9012 ec.CurrentInitializerVariable.GetSignatureForError (),
9013 TypeManager.CSharpName (ec.CurrentInitializerVariable.Type),
9014 TypeManager.CSharpName (TypeManager.ienumerable_type));
9017 is_collection_initialization = true;
9020 if (is_collection_initialization != (element_initializer == null)) {
9021 ec.Report.Error (747, initializer.Location, "Inconsistent `{0}' member declaration",
9022 is_collection_initialization ? "collection initializer" : "object initializer");
9026 if (!is_collection_initialization) {
9027 if (element_names.Contains (element_initializer.Name)) {
9028 ec.Report.Error (1912, element_initializer.Location,
9029 "An object initializer includes more than one member `{0}' initialization",
9030 element_initializer.Name);
9032 element_names.Add (element_initializer.Name);
9037 Expression e = initializer.Resolve (ec);
9038 if (e == EmptyExpressionStatement.Instance)
9039 initializers.RemoveAt (i--);
9041 initializers [i] = e;
9044 type = ec.CurrentInitializerVariable.Type;
9045 if (is_collection_initialization) {
9046 if (TypeManager.HasElementType (type)) {
9047 ec.Report.Error (1925, loc, "Cannot initialize object of type `{0}' with a collection initializer",
9048 TypeManager.CSharpName (type));
9052 eclass = ExprClass.Variable;
9056 public override void Emit (EmitContext ec)
9061 public override void EmitStatement (EmitContext ec)
9063 foreach (ExpressionStatement e in initializers)
9064 e.EmitStatement (ec);
9069 // New expression with element/object initializers
9071 public class NewInitialize : New
9074 // This class serves as a proxy for variable initializer target instances.
9075 // A real variable is assigned later when we resolve left side of an
9078 sealed class InitializerTargetExpression : Expression, IMemoryLocation
9080 NewInitialize new_instance;
9082 public InitializerTargetExpression (NewInitialize newInstance)
9084 this.type = newInstance.type;
9085 this.loc = newInstance.loc;
9086 this.eclass = newInstance.eclass;
9087 this.new_instance = newInstance;
9090 public override Expression CreateExpressionTree (ResolveContext ec)
9092 // Should not be reached
9093 throw new NotSupportedException ("ET");
9096 protected override Expression DoResolve (ResolveContext ec)
9101 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
9106 public override void Emit (EmitContext ec)
9108 Expression e = (Expression) new_instance.instance;
9112 #region IMemoryLocation Members
9114 public void AddressOf (EmitContext ec, AddressOp mode)
9116 new_instance.instance.AddressOf (ec, mode);
9122 CollectionOrObjectInitializers initializers;
9123 IMemoryLocation instance;
9125 public NewInitialize (FullNamedExpression requested_type, Arguments arguments, CollectionOrObjectInitializers initializers, Location l)
9126 : base (requested_type, arguments, l)
9128 this.initializers = initializers;
9131 protected override IMemoryLocation EmitAddressOf (EmitContext ec, AddressOp Mode)
9133 instance = base.EmitAddressOf (ec, Mode);
9135 if (!initializers.IsEmpty)
9136 initializers.Emit (ec);
9141 protected override void CloneTo (CloneContext clonectx, Expression t)
9143 base.CloneTo (clonectx, t);
9145 NewInitialize target = (NewInitialize) t;
9146 target.initializers = (CollectionOrObjectInitializers) initializers.Clone (clonectx);
9149 public override Expression CreateExpressionTree (ResolveContext ec)
9151 Arguments args = new Arguments (2);
9152 args.Add (new Argument (base.CreateExpressionTree (ec)));
9153 if (!initializers.IsEmpty)
9154 args.Add (new Argument (initializers.CreateExpressionTree (ec)));
9156 return CreateExpressionFactoryCall (ec,
9157 initializers.IsCollectionInitializer ? "ListInit" : "MemberInit",
9161 protected override Expression DoResolve (ResolveContext ec)
9163 Expression e = base.DoResolve (ec);
9167 Expression previous = ec.CurrentInitializerVariable;
9168 ec.CurrentInitializerVariable = new InitializerTargetExpression (this);
9169 initializers.Resolve (ec);
9170 ec.CurrentInitializerVariable = previous;
9174 public override bool Emit (EmitContext ec, IMemoryLocation target)
9176 bool left_on_stack = base.Emit (ec, target);
9178 if (initializers.IsEmpty)
9179 return left_on_stack;
9181 LocalTemporary temp = target as LocalTemporary;
9183 if (!left_on_stack) {
9184 VariableReference vr = target as VariableReference;
9186 // FIXME: This still does not work correctly for pre-set variables
9187 if (vr != null && vr.IsRef)
9188 target.AddressOf (ec, AddressOp.Load);
9190 ((Expression) target).Emit (ec);
9191 left_on_stack = true;
9194 temp = new LocalTemporary (type);
9201 initializers.Emit (ec);
9203 if (left_on_stack) {
9208 return left_on_stack;
9211 public override bool HasInitializer {
9213 return !initializers.IsEmpty;
9218 public class NewAnonymousType : New
9220 static readonly AnonymousTypeParameter[] EmptyParameters = new AnonymousTypeParameter[0];
9222 List<AnonymousTypeParameter> parameters;
9223 readonly TypeContainer parent;
9224 AnonymousTypeClass anonymous_type;
9226 public NewAnonymousType (List<AnonymousTypeParameter> parameters, TypeContainer parent, Location loc)
9227 : base (null, null, loc)
9229 this.parameters = parameters;
9230 this.parent = parent;
9233 protected override void CloneTo (CloneContext clonectx, Expression target)
9235 if (parameters == null)
9238 NewAnonymousType t = (NewAnonymousType) target;
9239 t.parameters = new List<AnonymousTypeParameter> (parameters.Count);
9240 foreach (AnonymousTypeParameter atp in parameters)
9241 t.parameters.Add ((AnonymousTypeParameter) atp.Clone (clonectx));
9244 AnonymousTypeClass CreateAnonymousType (ResolveContext ec, IList<AnonymousTypeParameter> parameters)
9246 AnonymousTypeClass type = parent.Module.Compiled.GetAnonymousType (parameters);
9250 type = AnonymousTypeClass.Create (ec.Compiler, parent, parameters, loc);
9256 type.ResolveTypeParameters ();
9259 if (ec.Report.Errors == 0)
9262 parent.Module.Compiled.AddAnonymousType (type);
9266 public override Expression CreateExpressionTree (ResolveContext ec)
9268 if (parameters == null)
9269 return base.CreateExpressionTree (ec);
9271 var init = new ArrayInitializer (parameters.Count, loc);
9272 foreach (Property p in anonymous_type.Properties)
9273 init.Add (new TypeOfMethod (MemberCache.GetMember (type, p.Get.Spec), loc));
9275 var ctor_args = new ArrayInitializer (Arguments.Count, loc);
9276 foreach (Argument a in Arguments)
9277 ctor_args.Add (a.CreateExpressionTree (ec));
9279 Arguments args = new Arguments (3);
9280 args.Add (new Argument (new TypeOfMethod (method, loc)));
9281 args.Add (new Argument (new ArrayCreation (TypeManager.expression_type_expr, ctor_args, loc)));
9282 args.Add (new Argument (new ImplicitlyTypedArrayCreation (init, loc)));
9284 return CreateExpressionFactoryCall (ec, "New", args);
9287 protected override Expression DoResolve (ResolveContext ec)
9289 if (ec.HasSet (ResolveContext.Options.ConstantScope)) {
9290 ec.Report.Error (836, loc, "Anonymous types cannot be used in this expression");
9294 if (parameters == null) {
9295 anonymous_type = CreateAnonymousType (ec, EmptyParameters);
9296 RequestedType = new TypeExpression (anonymous_type.Definition, loc);
9297 return base.DoResolve (ec);
9301 Arguments = new Arguments (parameters.Count);
9302 TypeExpression [] t_args = new TypeExpression [parameters.Count];
9303 for (int i = 0; i < parameters.Count; ++i) {
9304 Expression e = ((AnonymousTypeParameter) parameters [i]).Resolve (ec);
9310 Arguments.Add (new Argument (e));
9311 t_args [i] = new TypeExpression (e.Type, e.Location);
9317 anonymous_type = CreateAnonymousType (ec, parameters);
9318 if (anonymous_type == null)
9321 RequestedType = new GenericTypeExpr (anonymous_type.Definition, new TypeArguments (t_args), loc);
9322 return base.DoResolve (ec);
9326 public class AnonymousTypeParameter : ShimExpression
9328 public readonly string Name;
9330 public AnonymousTypeParameter (Expression initializer, string name, Location loc)
9331 : base (initializer)
9337 public AnonymousTypeParameter (Parameter parameter)
9338 : base (new SimpleName (parameter.Name, parameter.Location))
9340 this.Name = parameter.Name;
9341 this.loc = parameter.Location;
9344 public override bool Equals (object o)
9346 AnonymousTypeParameter other = o as AnonymousTypeParameter;
9347 return other != null && Name == other.Name;
9350 public override int GetHashCode ()
9352 return Name.GetHashCode ();
9355 protected override Expression DoResolve (ResolveContext ec)
9357 Expression e = expr.Resolve (ec);
9361 if (e.eclass == ExprClass.MethodGroup) {
9362 Error_InvalidInitializer (ec, e.ExprClassName);
9367 if (type == TypeManager.void_type || type == InternalType.Null ||
9368 type == InternalType.AnonymousMethod || type.IsPointer) {
9369 Error_InvalidInitializer (ec, e.GetSignatureForError ());
9376 protected virtual void Error_InvalidInitializer (ResolveContext ec, string initializer)
9378 ec.Report.Error (828, loc, "An anonymous type property `{0}' cannot be initialized with `{1}'",