2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Copyright 2001, 2002, 2003 Ximian, Inc.
9 // Copyright 2003-2008 Novell, Inc.
13 namespace Mono
.CSharp
{
15 using System
.Collections
.Generic
;
16 using System
.Reflection
;
17 using System
.Reflection
.Emit
;
20 using SLE
= System
.Linq
.Expressions
;
23 // This is an user operator expression, automatically created during
26 public class UserOperatorCall
: Expression
{
27 public delegate Expression
ExpressionTreeExpression (ResolveContext ec
, MethodGroupExpr mg
);
29 protected readonly Arguments arguments
;
30 protected readonly MethodGroupExpr mg
;
31 readonly ExpressionTreeExpression expr_tree
;
33 public UserOperatorCall (MethodGroupExpr mg
, Arguments args
, ExpressionTreeExpression expr_tree
, Location loc
)
36 this.arguments
= args
;
37 this.expr_tree
= expr_tree
;
39 type
= mg
.BestCandidate
.ReturnType
;
40 eclass
= ExprClass
.Value
;
44 public override Expression
CreateExpressionTree (ResolveContext ec
)
46 if (expr_tree
!= null)
47 return expr_tree (ec
, mg
);
49 Arguments args
= Arguments
.CreateForExpressionTree (ec
, arguments
,
50 new NullLiteral (loc
),
51 mg
.CreateExpressionTree (ec
));
53 return CreateExpressionFactoryCall (ec
, "Call", args
);
56 protected override void CloneTo (CloneContext context
, Expression target
)
61 protected override Expression
DoResolve (ResolveContext ec
)
64 // We are born fully resolved
69 public override void Emit (EmitContext ec
)
71 mg
.EmitCall (ec
, arguments
);
74 public override SLE
.Expression
MakeExpression (BuilderContext ctx
)
76 var method
= mg
.BestCandidate
.GetMetaInfo () as MethodInfo
;
77 return SLE
.Expression
.Call (method
, Arguments
.MakeExpression (arguments
, ctx
));
80 public MethodGroupExpr Method
{
85 public class ParenthesizedExpression
: ShimExpression
87 public ParenthesizedExpression (Expression expr
)
93 protected override Expression
DoResolve (ResolveContext ec
)
95 return expr
.Resolve (ec
);
98 public override Expression
DoResolveLValue (ResolveContext ec
, Expression right_side
)
100 return expr
.DoResolveLValue (ec
, right_side
);
105 // Unary implements unary expressions.
107 public class Unary
: Expression
109 public enum Operator
: byte {
110 UnaryPlus
, UnaryNegation
, LogicalNot
, OnesComplement
,
114 static TypeSpec
[][] predefined_operators
;
116 public readonly Operator Oper
;
117 public Expression Expr
;
118 Expression enum_conversion
;
120 public Unary (Operator op
, Expression expr
, Location loc
)
128 // This routine will attempt to simplify the unary expression when the
129 // argument is a constant.
131 Constant
TryReduceConstant (ResolveContext ec
, Constant e
)
133 if (e
is EmptyConstantCast
)
134 return TryReduceConstant (ec
, ((EmptyConstantCast
) e
).child
);
136 if (e
is SideEffectConstant
) {
137 Constant r
= TryReduceConstant (ec
, ((SideEffectConstant
) e
).value);
138 return r
== null ? null : new SideEffectConstant (r
, e
, r
.Location
);
141 TypeSpec expr_type
= e
.Type
;
144 case Operator
.UnaryPlus
:
145 // Unary numeric promotions
146 if (expr_type
== TypeManager
.byte_type
)
147 return new IntConstant (((ByteConstant
)e
).Value
, e
.Location
);
148 if (expr_type
== TypeManager
.sbyte_type
)
149 return new IntConstant (((SByteConstant
)e
).Value
, e
.Location
);
150 if (expr_type
== TypeManager
.short_type
)
151 return new IntConstant (((ShortConstant
)e
).Value
, e
.Location
);
152 if (expr_type
== TypeManager
.ushort_type
)
153 return new IntConstant (((UShortConstant
)e
).Value
, e
.Location
);
154 if (expr_type
== TypeManager
.char_type
)
155 return new IntConstant (((CharConstant
)e
).Value
, e
.Location
);
157 // Predefined operators
158 if (expr_type
== TypeManager
.int32_type
|| expr_type
== TypeManager
.uint32_type
||
159 expr_type
== TypeManager
.int64_type
|| expr_type
== TypeManager
.uint64_type
||
160 expr_type
== TypeManager
.float_type
|| expr_type
== TypeManager
.double_type
||
161 expr_type
== TypeManager
.decimal_type
) {
167 case Operator
.UnaryNegation
:
168 // Unary numeric promotions
169 if (expr_type
== TypeManager
.byte_type
)
170 return new IntConstant (-((ByteConstant
)e
).Value
, e
.Location
);
171 if (expr_type
== TypeManager
.sbyte_type
)
172 return new IntConstant (-((SByteConstant
)e
).Value
, e
.Location
);
173 if (expr_type
== TypeManager
.short_type
)
174 return new IntConstant (-((ShortConstant
)e
).Value
, e
.Location
);
175 if (expr_type
== TypeManager
.ushort_type
)
176 return new IntConstant (-((UShortConstant
)e
).Value
, e
.Location
);
177 if (expr_type
== TypeManager
.char_type
)
178 return new IntConstant (-((CharConstant
)e
).Value
, e
.Location
);
180 // Predefined operators
181 if (expr_type
== TypeManager
.int32_type
) {
182 int value = ((IntConstant
)e
).Value
;
183 if (value == int.MinValue
) {
184 if (ec
.ConstantCheckState
) {
185 ConstantFold
.Error_CompileTimeOverflow (ec
, loc
);
190 return new IntConstant (-value, e
.Location
);
192 if (expr_type
== TypeManager
.int64_type
) {
193 long value = ((LongConstant
)e
).Value
;
194 if (value == long.MinValue
) {
195 if (ec
.ConstantCheckState
) {
196 ConstantFold
.Error_CompileTimeOverflow (ec
, loc
);
201 return new LongConstant (-value, e
.Location
);
204 if (expr_type
== TypeManager
.uint32_type
) {
205 UIntLiteral uil
= e
as UIntLiteral
;
207 if (uil
.Value
== int.MaxValue
+ (uint) 1)
208 return new IntLiteral (int.MinValue
, e
.Location
);
209 return new LongLiteral (-uil
.Value
, e
.Location
);
211 return new LongConstant (-((UIntConstant
)e
).Value
, e
.Location
);
214 if (expr_type
== TypeManager
.uint64_type
) {
215 ULongLiteral ull
= e
as ULongLiteral
;
216 if (ull
!= null && ull
.Value
== 9223372036854775808)
217 return new LongLiteral (long.MinValue
, e
.Location
);
221 if (expr_type
== TypeManager
.float_type
) {
222 FloatLiteral fl
= e
as FloatLiteral
;
223 // For better error reporting
225 return new FloatLiteral (-fl
.Value
, e
.Location
);
227 return new FloatConstant (-((FloatConstant
)e
).Value
, e
.Location
);
229 if (expr_type
== TypeManager
.double_type
) {
230 DoubleLiteral dl
= e
as DoubleLiteral
;
231 // For better error reporting
233 return new DoubleLiteral (-dl
.Value
, e
.Location
);
235 return new DoubleConstant (-((DoubleConstant
)e
).Value
, e
.Location
);
237 if (expr_type
== TypeManager
.decimal_type
)
238 return new DecimalConstant (-((DecimalConstant
)e
).Value
, e
.Location
);
242 case Operator
.LogicalNot
:
243 if (expr_type
!= TypeManager
.bool_type
)
246 bool b
= (bool)e
.GetValue ();
247 return new BoolConstant (!b
, e
.Location
);
249 case Operator
.OnesComplement
:
250 // Unary numeric promotions
251 if (expr_type
== TypeManager
.byte_type
)
252 return new IntConstant (~
((ByteConstant
)e
).Value
, e
.Location
);
253 if (expr_type
== TypeManager
.sbyte_type
)
254 return new IntConstant (~
((SByteConstant
)e
).Value
, e
.Location
);
255 if (expr_type
== TypeManager
.short_type
)
256 return new IntConstant (~
((ShortConstant
)e
).Value
, e
.Location
);
257 if (expr_type
== TypeManager
.ushort_type
)
258 return new IntConstant (~
((UShortConstant
)e
).Value
, e
.Location
);
259 if (expr_type
== TypeManager
.char_type
)
260 return new IntConstant (~
((CharConstant
)e
).Value
, e
.Location
);
262 // Predefined operators
263 if (expr_type
== TypeManager
.int32_type
)
264 return new IntConstant (~
((IntConstant
)e
).Value
, e
.Location
);
265 if (expr_type
== TypeManager
.uint32_type
)
266 return new UIntConstant (~
((UIntConstant
)e
).Value
, e
.Location
);
267 if (expr_type
== TypeManager
.int64_type
)
268 return new LongConstant (~
((LongConstant
)e
).Value
, e
.Location
);
269 if (expr_type
== TypeManager
.uint64_type
){
270 return new ULongConstant (~
((ULongConstant
)e
).Value
, e
.Location
);
272 if (e
is EnumConstant
) {
273 e
= TryReduceConstant (ec
, ((EnumConstant
)e
).Child
);
275 e
= new EnumConstant (e
, expr_type
);
280 throw new Exception ("Can not constant fold: " + Oper
.ToString());
283 protected Expression
ResolveOperator (ResolveContext ec
, Expression expr
)
285 eclass
= ExprClass
.Value
;
287 if (predefined_operators
== null)
288 CreatePredefinedOperatorsTable ();
290 TypeSpec expr_type
= expr
.Type
;
291 Expression best_expr
;
294 // Primitive types first
296 if (TypeManager
.IsPrimitiveType (expr_type
)) {
297 best_expr
= ResolvePrimitivePredefinedType (expr
);
298 if (best_expr
== null)
301 type
= best_expr
.Type
;
307 // E operator ~(E x);
309 if (Oper
== Operator
.OnesComplement
&& TypeManager
.IsEnumType (expr_type
))
310 return ResolveEnumOperator (ec
, expr
);
312 return ResolveUserType (ec
, expr
);
315 protected virtual Expression
ResolveEnumOperator (ResolveContext ec
, Expression expr
)
317 TypeSpec underlying_type
= EnumSpec
.GetUnderlyingType (expr
.Type
);
318 Expression best_expr
= ResolvePrimitivePredefinedType (EmptyCast
.Create (expr
, underlying_type
));
319 if (best_expr
== null)
323 enum_conversion
= Convert
.ExplicitNumericConversion (new EmptyExpression (best_expr
.Type
), underlying_type
);
325 return EmptyCast
.Create (this, type
);
328 public override Expression
CreateExpressionTree (ResolveContext ec
)
330 return CreateExpressionTree (ec
, null);
333 Expression
CreateExpressionTree (ResolveContext ec
, MethodGroupExpr user_op
)
337 case Operator
.AddressOf
:
338 Error_PointerInsideExpressionTree (ec
);
340 case Operator
.UnaryNegation
:
341 if (ec
.HasSet (ResolveContext
.Options
.CheckedScope
) && user_op
== null && !IsFloat (type
))
342 method_name
= "NegateChecked";
344 method_name
= "Negate";
346 case Operator
.OnesComplement
:
347 case Operator
.LogicalNot
:
350 case Operator
.UnaryPlus
:
351 method_name
= "UnaryPlus";
354 throw new InternalErrorException ("Unknown unary operator " + Oper
.ToString ());
357 Arguments args
= new Arguments (2);
358 args
.Add (new Argument (Expr
.CreateExpressionTree (ec
)));
360 args
.Add (new Argument (user_op
.CreateExpressionTree (ec
)));
361 return CreateExpressionFactoryCall (ec
, method_name
, args
);
364 static void CreatePredefinedOperatorsTable ()
366 predefined_operators
= new TypeSpec
[(int) Operator
.TOP
] [];
369 // 7.6.1 Unary plus operator
371 predefined_operators
[(int) Operator
.UnaryPlus
] = new TypeSpec
[] {
372 TypeManager
.int32_type
, TypeManager
.uint32_type
,
373 TypeManager
.int64_type
, TypeManager
.uint64_type
,
374 TypeManager
.float_type
, TypeManager
.double_type
,
375 TypeManager
.decimal_type
379 // 7.6.2 Unary minus operator
381 predefined_operators
[(int) Operator
.UnaryNegation
] = new TypeSpec
[] {
382 TypeManager
.int32_type
,
383 TypeManager
.int64_type
,
384 TypeManager
.float_type
, TypeManager
.double_type
,
385 TypeManager
.decimal_type
389 // 7.6.3 Logical negation operator
391 predefined_operators
[(int) Operator
.LogicalNot
] = new TypeSpec
[] {
392 TypeManager
.bool_type
396 // 7.6.4 Bitwise complement operator
398 predefined_operators
[(int) Operator
.OnesComplement
] = new TypeSpec
[] {
399 TypeManager
.int32_type
, TypeManager
.uint32_type
,
400 TypeManager
.int64_type
, TypeManager
.uint64_type
405 // Unary numeric promotions
407 static Expression
DoNumericPromotion (Operator op
, Expression expr
)
409 TypeSpec expr_type
= expr
.Type
;
410 if ((op
== Operator
.UnaryPlus
|| op
== Operator
.UnaryNegation
|| op
== Operator
.OnesComplement
) &&
411 expr_type
== TypeManager
.byte_type
|| expr_type
== TypeManager
.sbyte_type
||
412 expr_type
== TypeManager
.short_type
|| expr_type
== TypeManager
.ushort_type
||
413 expr_type
== TypeManager
.char_type
)
414 return Convert
.ImplicitNumericConversion (expr
, TypeManager
.int32_type
);
416 if (op
== Operator
.UnaryNegation
&& expr_type
== TypeManager
.uint32_type
)
417 return Convert
.ImplicitNumericConversion (expr
, TypeManager
.int64_type
);
422 protected override Expression
DoResolve (ResolveContext ec
)
424 if (Oper
== Operator
.AddressOf
) {
425 return ResolveAddressOf (ec
);
428 Expr
= Expr
.Resolve (ec
);
432 if (Expr
.Type
== InternalType
.Dynamic
) {
433 Arguments args
= new Arguments (1);
434 args
.Add (new Argument (Expr
));
435 return new DynamicUnaryConversion (GetOperatorExpressionTypeName (), args
, loc
).Resolve (ec
);
438 if (TypeManager
.IsNullableType (Expr
.Type
))
439 return new Nullable
.LiftedUnaryOperator (Oper
, Expr
, loc
).Resolve (ec
);
442 // Attempt to use a constant folding operation.
444 Constant cexpr
= Expr
as Constant
;
446 cexpr
= TryReduceConstant (ec
, cexpr
);
448 return cexpr
.Resolve (ec
);
451 Expression expr
= ResolveOperator (ec
, Expr
);
453 Error_OperatorCannotBeApplied (ec
, loc
, OperName (Oper
), Expr
.Type
);
456 // Reduce unary operator on predefined types
458 if (expr
== this && Oper
== Operator
.UnaryPlus
)
464 public override Expression
DoResolveLValue (ResolveContext ec
, Expression right
)
469 public override void Emit (EmitContext ec
)
471 EmitOperator (ec
, type
);
474 protected void EmitOperator (EmitContext ec
, TypeSpec type
)
477 case Operator
.UnaryPlus
:
481 case Operator
.UnaryNegation
:
482 if (ec
.HasSet (EmitContext
.Options
.CheckedScope
) && !IsFloat (type
)) {
483 ec
.Emit (OpCodes
.Ldc_I4_0
);
484 if (type
== TypeManager
.int64_type
)
485 ec
.Emit (OpCodes
.Conv_U8
);
487 ec
.Emit (OpCodes
.Sub_Ovf
);
490 ec
.Emit (OpCodes
.Neg
);
495 case Operator
.LogicalNot
:
497 ec
.Emit (OpCodes
.Ldc_I4_0
);
498 ec
.Emit (OpCodes
.Ceq
);
501 case Operator
.OnesComplement
:
503 ec
.Emit (OpCodes
.Not
);
506 case Operator
.AddressOf
:
507 ((IMemoryLocation
)Expr
).AddressOf (ec
, AddressOp
.LoadStore
);
511 throw new Exception ("This should not happen: Operator = "
516 // Same trick as in Binary expression
518 if (enum_conversion
!= null)
519 enum_conversion
.Emit (ec
);
522 public override void EmitBranchable (EmitContext ec
, Label target
, bool on_true
)
524 if (Oper
== Operator
.LogicalNot
)
525 Expr
.EmitBranchable (ec
, target
, !on_true
);
527 base.EmitBranchable (ec
, target
, on_true
);
530 public override void EmitSideEffect (EmitContext ec
)
532 Expr
.EmitSideEffect (ec
);
535 public static void Error_OperatorCannotBeApplied (ResolveContext ec
, Location loc
, string oper
, TypeSpec t
)
537 ec
.Report
.Error (23, loc
, "The `{0}' operator cannot be applied to operand of type `{1}'",
538 oper
, TypeManager
.CSharpName (t
));
542 // Converts operator to System.Linq.Expressions.ExpressionType enum name
544 string GetOperatorExpressionTypeName ()
547 case Operator
.OnesComplement
:
548 return "OnesComplement";
549 case Operator
.LogicalNot
:
551 case Operator
.UnaryNegation
:
553 case Operator
.UnaryPlus
:
556 throw new NotImplementedException ("Unknown express type operator " + Oper
.ToString ());
560 static bool IsFloat (TypeSpec t
)
562 return t
== TypeManager
.float_type
|| t
== TypeManager
.double_type
;
566 // Returns a stringified representation of the Operator
568 public static string OperName (Operator oper
)
571 case Operator
.UnaryPlus
:
573 case Operator
.UnaryNegation
:
575 case Operator
.LogicalNot
:
577 case Operator
.OnesComplement
:
579 case Operator
.AddressOf
:
583 throw new NotImplementedException (oper
.ToString ());
586 public override SLE
.Expression
MakeExpression (BuilderContext ctx
)
588 var expr
= Expr
.MakeExpression (ctx
);
589 bool is_checked
= ctx
.HasSet (BuilderContext
.Options
.CheckedScope
);
592 case Operator
.UnaryNegation
:
593 return is_checked
? SLE
.Expression
.NegateChecked (expr
) : SLE
.Expression
.Negate (expr
);
594 case Operator
.LogicalNot
:
595 return SLE
.Expression
.Not (expr
);
597 case Operator
.OnesComplement
:
598 return SLE
.Expression
.OnesComplement (expr
);
601 throw new NotImplementedException (Oper
.ToString ());
605 public static void Reset ()
607 predefined_operators
= null;
610 Expression
ResolveAddressOf (ResolveContext ec
)
613 UnsafeError (ec
, loc
);
615 Expr
= Expr
.DoResolveLValue (ec
, EmptyExpression
.UnaryAddress
);
616 if (Expr
== null || Expr
.eclass
!= ExprClass
.Variable
) {
617 ec
.Report
.Error (211, loc
, "Cannot take the address of the given expression");
621 if (!TypeManager
.VerifyUnmanaged (ec
.Compiler
, Expr
.Type
, loc
)) {
625 IVariableReference vr
= Expr
as IVariableReference
;
628 VariableInfo vi
= vr
.VariableInfo
;
630 if (vi
.LocalInfo
!= null)
631 vi
.LocalInfo
.Used
= true;
634 // A variable is considered definitely assigned if you take its address.
639 is_fixed
= vr
.IsFixed
;
640 vr
.SetHasAddressTaken ();
643 AnonymousMethodExpression
.Error_AddressOfCapturedVar (ec
, vr
, loc
);
646 IFixedExpression fe
= Expr
as IFixedExpression
;
647 is_fixed
= fe
!= null && fe
.IsFixed
;
650 if (!is_fixed
&& !ec
.HasSet (ResolveContext
.Options
.FixedInitializerScope
)) {
651 ec
.Report
.Error (212, loc
, "You can only take the address of unfixed expression inside of a fixed statement initializer");
654 type
= PointerContainer
.MakeType (Expr
.Type
);
655 eclass
= ExprClass
.Value
;
659 Expression
ResolvePrimitivePredefinedType (Expression expr
)
661 expr
= DoNumericPromotion (Oper
, expr
);
662 TypeSpec expr_type
= expr
.Type
;
663 TypeSpec
[] predefined
= predefined_operators
[(int) Oper
];
664 foreach (TypeSpec t
in predefined
) {
672 // Perform user-operator overload resolution
674 protected virtual Expression
ResolveUserOperator (ResolveContext ec
, Expression expr
)
676 CSharp
.Operator
.OpType op_type
;
678 case Operator
.LogicalNot
:
679 op_type
= CSharp
.Operator
.OpType
.LogicalNot
; break;
680 case Operator
.OnesComplement
:
681 op_type
= CSharp
.Operator
.OpType
.OnesComplement
; break;
682 case Operator
.UnaryNegation
:
683 op_type
= CSharp
.Operator
.OpType
.UnaryNegation
; break;
684 case Operator
.UnaryPlus
:
685 op_type
= CSharp
.Operator
.OpType
.UnaryPlus
; break;
687 throw new InternalErrorException (Oper
.ToString ());
690 string op_name
= CSharp
.Operator
.GetMetadataName (op_type
);
691 MethodGroupExpr user_op
= MethodLookup (ec
.Compiler
, ec
.CurrentType
, expr
.Type
, MemberKind
.Operator
, op_name
, 0, expr
.Location
);
695 Arguments args
= new Arguments (1);
696 args
.Add (new Argument (expr
));
697 user_op
= user_op
.OverloadResolve (ec
, ref args
, false, expr
.Location
);
702 Expr
= args
[0].Expr
;
703 return new UserOperatorCall (user_op
, args
, CreateExpressionTree
, expr
.Location
);
707 // Unary user type overload resolution
709 Expression
ResolveUserType (ResolveContext ec
, Expression expr
)
711 Expression best_expr
= ResolveUserOperator (ec
, expr
);
712 if (best_expr
!= null)
715 TypeSpec
[] predefined
= predefined_operators
[(int) Oper
];
716 foreach (TypeSpec t
in predefined
) {
717 Expression oper_expr
= Convert
.UserDefinedConversion (ec
, expr
, t
, expr
.Location
, false, false);
718 if (oper_expr
== null)
722 // decimal type is predefined but has user-operators
724 if (oper_expr
.Type
== TypeManager
.decimal_type
)
725 oper_expr
= ResolveUserType (ec
, oper_expr
);
727 oper_expr
= ResolvePrimitivePredefinedType (oper_expr
);
729 if (oper_expr
== null)
732 if (best_expr
== null) {
733 best_expr
= oper_expr
;
737 int result
= MethodGroupExpr
.BetterTypeConversion (ec
, best_expr
.Type
, t
);
739 ec
.Report
.Error (35, loc
, "Operator `{0}' is ambiguous on an operand of type `{1}'",
740 OperName (Oper
), TypeManager
.CSharpName (expr
.Type
));
745 best_expr
= oper_expr
;
748 if (best_expr
== null)
752 // HACK: Decimal user-operator is included in standard operators
754 if (best_expr
.Type
== TypeManager
.decimal_type
)
758 type
= best_expr
.Type
;
762 protected override void CloneTo (CloneContext clonectx
, Expression t
)
764 Unary target
= (Unary
) t
;
766 target
.Expr
= Expr
.Clone (clonectx
);
771 // Unary operators are turned into Indirection expressions
772 // after semantic analysis (this is so we can take the address
773 // of an indirection).
775 public class Indirection
: Expression
, IMemoryLocation
, IAssignMethod
, IFixedExpression
{
777 LocalTemporary temporary
;
780 public Indirection (Expression expr
, Location l
)
786 public override Expression
CreateExpressionTree (ResolveContext ec
)
788 Error_PointerInsideExpressionTree (ec
);
792 protected override void CloneTo (CloneContext clonectx
, Expression t
)
794 Indirection target
= (Indirection
) t
;
795 target
.expr
= expr
.Clone (clonectx
);
798 public override void Emit (EmitContext ec
)
803 ec
.EmitLoadFromPtr (Type
);
806 public void Emit (EmitContext ec
, bool leave_copy
)
810 ec
.Emit (OpCodes
.Dup
);
811 temporary
= new LocalTemporary (expr
.Type
);
812 temporary
.Store (ec
);
816 public void EmitAssign (EmitContext ec
, Expression source
, bool leave_copy
, bool prepare_for_load
)
818 prepared
= prepare_for_load
;
822 if (prepare_for_load
)
823 ec
.Emit (OpCodes
.Dup
);
827 ec
.Emit (OpCodes
.Dup
);
828 temporary
= new LocalTemporary (expr
.Type
);
829 temporary
.Store (ec
);
832 ec
.EmitStoreFromPtr (type
);
834 if (temporary
!= null) {
836 temporary
.Release (ec
);
840 public void AddressOf (EmitContext ec
, AddressOp Mode
)
845 public override Expression
DoResolveLValue (ResolveContext ec
, Expression right_side
)
847 return DoResolve (ec
);
850 protected override Expression
DoResolve (ResolveContext ec
)
852 expr
= expr
.Resolve (ec
);
857 UnsafeError (ec
, loc
);
859 if (!expr
.Type
.IsPointer
) {
860 ec
.Report
.Error (193, loc
, "The * or -> operator must be applied to a pointer");
864 if (expr
.Type
== TypeManager
.void_ptr_type
) {
865 ec
.Report
.Error (242, loc
, "The operation in question is undefined on void pointers");
869 type
= TypeManager
.GetElementType (expr
.Type
);
870 eclass
= ExprClass
.Variable
;
874 public bool IsFixed
{
878 public override string ToString ()
880 return "*(" + expr
+ ")";
885 /// Unary Mutator expressions (pre and post ++ and --)
889 /// UnaryMutator implements ++ and -- expressions. It derives from
890 /// ExpressionStatement becuase the pre/post increment/decrement
891 /// operators can be used in a statement context.
893 /// FIXME: Idea, we could split this up in two classes, one simpler
894 /// for the common case, and one with the extra fields for more complex
895 /// classes (indexers require temporary access; overloaded require method)
898 public class UnaryMutator
: ExpressionStatement
900 class DynamicPostMutator
: Expression
, IAssignMethod
905 public DynamicPostMutator (Expression expr
)
908 this.type
= expr
.Type
;
909 this.loc
= expr
.Location
;
912 public override Expression
CreateExpressionTree (ResolveContext ec
)
914 throw new NotImplementedException ("ET");
917 protected override Expression
DoResolve (ResolveContext rc
)
919 eclass
= expr
.eclass
;
923 public override Expression
DoResolveLValue (ResolveContext ec
, Expression right_side
)
925 expr
.DoResolveLValue (ec
, right_side
);
926 return DoResolve (ec
);
929 public override void Emit (EmitContext ec
)
934 public void Emit (EmitContext ec
, bool leave_copy
)
936 throw new NotImplementedException ();
940 // Emits target assignment using unmodified source value
942 public void EmitAssign (EmitContext ec
, Expression source
, bool leave_copy
, bool prepare_for_load
)
945 // Allocate temporary variable to keep original value before it's modified
947 temp
= new LocalTemporary (type
);
951 ((IAssignMethod
) expr
).EmitAssign (ec
, source
, false, prepare_for_load
);
962 public enum Mode
: byte {
969 PreDecrement
= IsDecrement
,
970 PostIncrement
= IsPost
,
971 PostDecrement
= IsPost
| IsDecrement
975 bool is_expr
, recurse
;
979 // Holds the real operation
980 Expression operation
;
982 public UnaryMutator (Mode m
, Expression e
, Location loc
)
989 public override Expression
CreateExpressionTree (ResolveContext ec
)
991 return new SimpleAssign (this, this).CreateExpressionTree (ec
);
994 protected override Expression
DoResolve (ResolveContext ec
)
996 expr
= expr
.Resolve (ec
);
1001 if (expr
.Type
== InternalType
.Dynamic
) {
1003 // Handle postfix unary operators using local
1004 // temporary variable
1006 if ((mode
& Mode
.IsPost
) != 0)
1007 expr
= new DynamicPostMutator (expr
);
1009 Arguments args
= new Arguments (1);
1010 args
.Add (new Argument (expr
));
1011 return new SimpleAssign (expr
, new DynamicUnaryConversion (GetOperatorExpressionTypeName (), args
, loc
)).Resolve (ec
);
1014 if (TypeManager
.IsNullableType (expr
.Type
))
1015 return new Nullable
.LiftedUnaryMutator (mode
, expr
, loc
).Resolve (ec
);
1017 eclass
= ExprClass
.Value
;
1019 return ResolveOperator (ec
);
1022 void EmitCode (EmitContext ec
, bool is_expr
)
1025 this.is_expr
= is_expr
;
1026 ((IAssignMethod
) expr
).EmitAssign (ec
, this, is_expr
&& (mode
== Mode
.PreIncrement
|| mode
== Mode
.PreDecrement
), true);
1029 public override void Emit (EmitContext ec
)
1032 // We use recurse to allow ourselfs to be the source
1033 // of an assignment. This little hack prevents us from
1034 // having to allocate another expression
1037 ((IAssignMethod
) expr
).Emit (ec
, is_expr
&& (mode
== Mode
.PostIncrement
|| mode
== Mode
.PostDecrement
));
1039 operation
.Emit (ec
);
1045 EmitCode (ec
, true);
1048 public override void EmitStatement (EmitContext ec
)
1050 EmitCode (ec
, false);
1054 // Converts operator to System.Linq.Expressions.ExpressionType enum name
1056 string GetOperatorExpressionTypeName ()
1058 return IsDecrement
? "Decrement" : "Increment";
1062 get { return (mode & Mode.IsDecrement) != 0; }
1066 // Returns whether an object of type `t' can be incremented
1067 // or decremented with add/sub (ie, basically whether we can
1068 // use pre-post incr-decr operations on it, but it is not a
1069 // System.Decimal, which we require operator overloading to catch)
1071 static bool IsPredefinedOperator (TypeSpec t
)
1073 return (TypeManager
.IsPrimitiveType (t
) && t
!= TypeManager
.bool_type
) ||
1074 TypeManager
.IsEnumType (t
) ||
1075 t
.IsPointer
&& t
!= TypeManager
.void_ptr_type
;
1079 public override SLE
.Expression
MakeExpression (BuilderContext ctx
)
1081 var target
= ((RuntimeValueExpression
) expr
).MetaObject
.Expression
;
1082 var source
= SLE
.Expression
.Convert (operation
.MakeExpression (ctx
), target
.Type
);
1083 return SLE
.Expression
.Assign (target
, source
);
1087 protected override void CloneTo (CloneContext clonectx
, Expression t
)
1089 UnaryMutator target
= (UnaryMutator
) t
;
1091 target
.expr
= expr
.Clone (clonectx
);
1094 Expression
ResolveOperator (ResolveContext ec
)
1096 if (expr
is RuntimeValueExpression
) {
1099 // Use itself at the top of the stack
1100 operation
= new EmptyExpression (type
);
1104 // The operand of the prefix/postfix increment decrement operators
1105 // should be an expression that is classified as a variable,
1106 // a property access or an indexer access
1108 if (expr
.eclass
== ExprClass
.Variable
|| expr
.eclass
== ExprClass
.IndexerAccess
|| expr
.eclass
== ExprClass
.PropertyAccess
) {
1109 expr
= expr
.ResolveLValue (ec
, expr
);
1111 ec
.Report
.Error (1059, loc
, "The operand of an increment or decrement operator must be a variable, property or indexer");
1115 // 1. Check predefined types
1117 if (IsPredefinedOperator (type
)) {
1118 // TODO: Move to IntConstant once I get rid of int32_type
1119 var one
= new IntConstant (1, loc
);
1121 // TODO: Cache this based on type when using EmptyExpression in
1123 Binary
.Operator op
= IsDecrement
? Binary
.Operator
.Subtraction
: Binary
.Operator
.Addition
;
1124 operation
= new Binary (op
, operation
, one
, loc
);
1125 operation
= operation
.Resolve (ec
);
1126 if (operation
!= null && operation
.Type
!= type
)
1127 operation
= Convert
.ExplicitNumericConversion (operation
, type
);
1133 // Step 2: Perform Operator Overload location
1138 op_name
= Operator
.GetMetadataName (Operator
.OpType
.Decrement
);
1140 op_name
= Operator
.GetMetadataName (Operator
.OpType
.Increment
);
1142 var mg
= MethodLookup (ec
.Compiler
, ec
.CurrentType
, type
, MemberKind
.Operator
, op_name
, 0, loc
);
1145 Arguments args
= new Arguments (1);
1146 args
.Add (new Argument (expr
));
1147 mg
= mg
.OverloadResolve (ec
, ref args
, false, loc
);
1151 args
[0].Expr
= operation
;
1152 operation
= new UserOperatorCall (mg
, args
, null, loc
);
1153 operation
= Convert
.ImplicitConversionRequired (ec
, operation
, type
, loc
);
1157 string name
= IsDecrement
?
1158 Operator
.GetName (Operator
.OpType
.Decrement
) :
1159 Operator
.GetName (Operator
.OpType
.Increment
);
1161 Unary
.Error_OperatorCannotBeApplied (ec
, loc
, name
, type
);
1167 /// Base class for the `Is' and `As' classes.
1171 /// FIXME: Split this in two, and we get to save the `Operator' Oper
1174 public abstract class Probe
: Expression
{
1175 public Expression ProbeType
;
1176 protected Expression expr
;
1177 protected TypeExpr probe_type_expr
;
1179 public Probe (Expression expr
, Expression probe_type
, Location l
)
1181 ProbeType
= probe_type
;
1186 public Expression Expr
{
1192 protected override Expression
DoResolve (ResolveContext ec
)
1194 probe_type_expr
= ProbeType
.ResolveAsTypeTerminal (ec
, false);
1195 if (probe_type_expr
== null)
1198 expr
= expr
.Resolve (ec
);
1202 if (probe_type_expr
.Type
.IsStatic
) {
1203 ec
.Report
.Error (-244, loc
, "The `{0}' operator cannot be applied to an operand of a static type",
1207 if (expr
.Type
.IsPointer
|| probe_type_expr
.Type
.IsPointer
) {
1208 ec
.Report
.Error (244, loc
, "The `{0}' operator cannot be applied to an operand of pointer type",
1213 if (expr
.Type
== InternalType
.AnonymousMethod
) {
1214 ec
.Report
.Error (837, loc
, "The `{0}' operator cannot be applied to a lambda expression or anonymous method",
1222 protected abstract string OperatorName { get; }
1224 protected override void CloneTo (CloneContext clonectx
, Expression t
)
1226 Probe target
= (Probe
) t
;
1228 target
.expr
= expr
.Clone (clonectx
);
1229 target
.ProbeType
= ProbeType
.Clone (clonectx
);
1235 /// Implementation of the `is' operator.
1237 public class Is
: Probe
{
1238 Nullable
.Unwrap expr_unwrap
;
1240 public Is (Expression expr
, Expression probe_type
, Location l
)
1241 : base (expr
, probe_type
, l
)
1245 public override Expression
CreateExpressionTree (ResolveContext ec
)
1247 Arguments args
= Arguments
.CreateForExpressionTree (ec
, null,
1248 expr
.CreateExpressionTree (ec
),
1249 new TypeOf (probe_type_expr
, loc
));
1251 return CreateExpressionFactoryCall (ec
, "TypeIs", args
);
1254 public override void Emit (EmitContext ec
)
1256 if (expr_unwrap
!= null) {
1257 expr_unwrap
.EmitCheck (ec
);
1262 ec
.Emit (OpCodes
.Isinst
, probe_type_expr
.Type
);
1263 ec
.Emit (OpCodes
.Ldnull
);
1264 ec
.Emit (OpCodes
.Cgt_Un
);
1267 public override void EmitBranchable (EmitContext ec
, Label target
, bool on_true
)
1269 if (expr_unwrap
!= null) {
1270 expr_unwrap
.EmitCheck (ec
);
1273 ec
.Emit (OpCodes
.Isinst
, probe_type_expr
.Type
);
1275 ec
.Emit (on_true
? OpCodes
.Brtrue
: OpCodes
.Brfalse
, target
);
1278 Expression
CreateConstantResult (ResolveContext ec
, bool result
)
1281 ec
.Report
.Warning (183, 1, loc
, "The given expression is always of the provided (`{0}') type",
1282 TypeManager
.CSharpName (probe_type_expr
.Type
));
1284 ec
.Report
.Warning (184, 1, loc
, "The given expression is never of the provided (`{0}') type",
1285 TypeManager
.CSharpName (probe_type_expr
.Type
));
1287 return ReducedExpression
.Create (new BoolConstant (result
, loc
).Resolve (ec
), this);
1290 protected override Expression
DoResolve (ResolveContext ec
)
1292 if (base.DoResolve (ec
) == null)
1295 TypeSpec d
= expr
.Type
;
1296 bool d_is_nullable
= false;
1299 // If E is a method group or the null literal, or if the type of E is a reference
1300 // type or a nullable type and the value of E is null, the result is false
1302 if (expr
.IsNull
|| expr
.eclass
== ExprClass
.MethodGroup
)
1303 return CreateConstantResult (ec
, false);
1305 if (TypeManager
.IsNullableType (d
)) {
1306 var ut
= Nullable
.NullableInfo
.GetUnderlyingType (d
);
1307 if (!ut
.IsGenericParameter
) {
1309 d_is_nullable
= true;
1313 type
= TypeManager
.bool_type
;
1314 eclass
= ExprClass
.Value
;
1315 TypeSpec t
= probe_type_expr
.Type
;
1316 bool t_is_nullable
= false;
1317 if (TypeManager
.IsNullableType (t
)) {
1318 var ut
= Nullable
.NullableInfo
.GetUnderlyingType (t
);
1319 if (!ut
.IsGenericParameter
) {
1321 t_is_nullable
= true;
1325 if (TypeManager
.IsStruct (t
)) {
1328 // D and T are the same value types but D can be null
1330 if (d_is_nullable
&& !t_is_nullable
) {
1331 expr_unwrap
= Nullable
.Unwrap
.Create (expr
, false);
1336 // The result is true if D and T are the same value types
1338 return CreateConstantResult (ec
, true);
1341 var tp
= d
as TypeParameterSpec
;
1343 return ResolveGenericParameter (ec
, t
, tp
);
1346 // An unboxing conversion exists
1348 if (Convert
.ExplicitReferenceConversionExists (d
, t
))
1351 if (TypeManager
.IsGenericParameter (t
))
1352 return ResolveGenericParameter (ec
, d
, (TypeParameterSpec
) t
);
1354 if (TypeManager
.IsStruct (d
)) {
1355 if (Convert
.ImplicitBoxingConversion (null, d
, t
) != null)
1356 return CreateConstantResult (ec
, true);
1358 if (TypeManager
.IsGenericParameter (d
))
1359 return ResolveGenericParameter (ec
, t
, (TypeParameterSpec
) d
);
1361 if (TypeManager
.ContainsGenericParameters (d
))
1364 if (Convert
.ImplicitReferenceConversionExists (expr
, t
) ||
1365 Convert
.ExplicitReferenceConversionExists (d
, t
)) {
1371 return CreateConstantResult (ec
, false);
1374 Expression
ResolveGenericParameter (ResolveContext ec
, TypeSpec d
, TypeParameterSpec t
)
1376 if (t
.IsReferenceType
) {
1377 if (TypeManager
.IsStruct (d
))
1378 return CreateConstantResult (ec
, false);
1381 if (TypeManager
.IsGenericParameter (expr
.Type
)) {
1382 if (t
.IsValueType
&& expr
.Type
== t
)
1383 return CreateConstantResult (ec
, true);
1385 expr
= new BoxedCast (expr
, d
);
1391 protected override string OperatorName
{
1392 get { return "is"; }
1397 /// Implementation of the `as' operator.
1399 public class As
: Probe
{
1401 Expression resolved_type
;
1403 public As (Expression expr
, Expression probe_type
, Location l
)
1404 : base (expr
, probe_type
, l
)
1408 public override Expression
CreateExpressionTree (ResolveContext ec
)
1410 Arguments args
= Arguments
.CreateForExpressionTree (ec
, null,
1411 expr
.CreateExpressionTree (ec
),
1412 new TypeOf (probe_type_expr
, loc
));
1414 return CreateExpressionFactoryCall (ec
, "TypeAs", args
);
1417 public override void Emit (EmitContext ec
)
1422 ec
.Emit (OpCodes
.Isinst
, type
);
1424 if (TypeManager
.IsGenericParameter (type
) || TypeManager
.IsNullableType (type
))
1425 ec
.Emit (OpCodes
.Unbox_Any
, type
);
1428 protected override Expression
DoResolve (ResolveContext ec
)
1430 if (resolved_type
== null) {
1431 resolved_type
= base.DoResolve (ec
);
1433 if (resolved_type
== null)
1437 type
= probe_type_expr
.Type
;
1438 eclass
= ExprClass
.Value
;
1439 TypeSpec etype
= expr
.Type
;
1441 if (!TypeManager
.IsReferenceType (type
) && !TypeManager
.IsNullableType (type
)) {
1442 if (TypeManager
.IsGenericParameter (type
)) {
1443 ec
.Report
.Error (413, loc
,
1444 "The `as' operator cannot be used with a non-reference type parameter `{0}'. Consider adding `class' or a reference type constraint",
1445 probe_type_expr
.GetSignatureForError ());
1447 ec
.Report
.Error (77, loc
,
1448 "The `as' operator cannot be used with a non-nullable value type `{0}'",
1449 TypeManager
.CSharpName (type
));
1454 if (expr
.IsNull
&& TypeManager
.IsNullableType (type
)) {
1455 return Nullable
.LiftedNull
.CreateFromExpression (ec
, this);
1458 Expression e
= Convert
.ImplicitConversion (ec
, expr
, type
, loc
);
1465 if (Convert
.ExplicitReferenceConversionExists (etype
, type
)){
1466 if (TypeManager
.IsGenericParameter (etype
))
1467 expr
= new BoxedCast (expr
, etype
);
1473 if (TypeManager
.ContainsGenericParameters (etype
) ||
1474 TypeManager
.ContainsGenericParameters (type
)) {
1475 expr
= new BoxedCast (expr
, etype
);
1480 ec
.Report
.Error (39, loc
, "Cannot convert type `{0}' to `{1}' via a built-in conversion",
1481 TypeManager
.CSharpName (etype
), TypeManager
.CSharpName (type
));
1486 protected override string OperatorName
{
1487 get { return "as"; }
1492 /// This represents a typecast in the source language.
1494 /// FIXME: Cast expressions have an unusual set of parsing
1495 /// rules, we need to figure those out.
1497 public class Cast
: ShimExpression
{
1498 Expression target_type
;
1500 public Cast (Expression cast_type
, Expression expr
)
1501 : this (cast_type
, expr
, cast_type
.Location
)
1505 public Cast (Expression cast_type
, Expression expr
, Location loc
)
1508 this.target_type
= cast_type
;
1512 public Expression TargetType
{
1513 get { return target_type; }
1516 protected override Expression
DoResolve (ResolveContext ec
)
1518 expr
= expr
.Resolve (ec
);
1522 TypeExpr target
= target_type
.ResolveAsTypeTerminal (ec
, false);
1528 if (type
.IsStatic
) {
1529 ec
.Report
.Error (716, loc
, "Cannot convert to static type `{0}'", TypeManager
.CSharpName (type
));
1533 eclass
= ExprClass
.Value
;
1535 Constant c
= expr
as Constant
;
1537 c
= c
.TryReduce (ec
, type
, loc
);
1542 if (type
.IsPointer
&& !ec
.IsUnsafe
) {
1543 UnsafeError (ec
, loc
);
1544 } else if (expr
.Type
== InternalType
.Dynamic
) {
1545 Arguments arg
= new Arguments (1);
1546 arg
.Add (new Argument (expr
));
1547 return new DynamicConversion (type
, CSharpBinderFlags
.ConvertExplicit
, arg
, loc
).Resolve (ec
);
1550 expr
= Convert
.ExplicitConversion (ec
, expr
, type
, loc
);
1554 protected override void CloneTo (CloneContext clonectx
, Expression t
)
1556 Cast target
= (Cast
) t
;
1558 target
.target_type
= target_type
.Clone (clonectx
);
1559 target
.expr
= expr
.Clone (clonectx
);
1563 public class ImplicitCast
: ShimExpression
1567 public ImplicitCast (Expression expr
, TypeSpec target
, bool arrayAccess
)
1570 this.loc
= expr
.Location
;
1572 this.arrayAccess
= arrayAccess
;
1575 protected override Expression
DoResolve (ResolveContext ec
)
1577 expr
= expr
.Resolve (ec
);
1582 expr
= ConvertExpressionToArrayIndex (ec
, expr
);
1584 expr
= Convert
.ImplicitConversionRequired (ec
, expr
, type
, loc
);
1591 // C# 2.0 Default value expression
1593 public class DefaultValueExpression
: Expression
1597 public DefaultValueExpression (Expression expr
, Location loc
)
1603 public override Expression
CreateExpressionTree (ResolveContext ec
)
1605 Arguments args
= new Arguments (2);
1606 args
.Add (new Argument (this));
1607 args
.Add (new Argument (new TypeOf (new TypeExpression (type
, loc
), loc
)));
1608 return CreateExpressionFactoryCall (ec
, "Constant", args
);
1611 protected override Expression
DoResolve (ResolveContext ec
)
1613 TypeExpr texpr
= expr
.ResolveAsTypeTerminal (ec
, false);
1619 if (type
.IsStatic
) {
1620 ec
.Report
.Error (-244, loc
, "The `default value' operator cannot be applied to an operand of a static type");
1624 return new NullLiteral (Location
).ConvertImplicitly (ec
, type
);
1626 if (TypeManager
.IsReferenceType (type
))
1627 return new NullConstant (type
, loc
);
1629 Constant c
= New
.Constantify (type
);
1631 return c
.Resolve (ec
);
1633 eclass
= ExprClass
.Variable
;
1637 public override void Emit (EmitContext ec
)
1639 LocalTemporary temp_storage
= new LocalTemporary(type
);
1641 temp_storage
.AddressOf(ec
, AddressOp
.LoadStore
);
1642 ec
.Emit(OpCodes
.Initobj
, type
);
1643 temp_storage
.Emit(ec
);
1646 protected override void CloneTo (CloneContext clonectx
, Expression t
)
1648 DefaultValueExpression target
= (DefaultValueExpression
) t
;
1650 target
.expr
= expr
.Clone (clonectx
);
1655 /// Binary operators
1657 public class Binary
: Expression
, IDynamicBinder
1659 protected class PredefinedOperator
{
1660 protected readonly TypeSpec left
;
1661 protected readonly TypeSpec right
;
1662 public readonly Operator OperatorsMask
;
1663 public TypeSpec ReturnType
;
1665 public PredefinedOperator (TypeSpec ltype
, TypeSpec rtype
, Operator op_mask
)
1666 : this (ltype
, rtype
, op_mask
, ltype
)
1670 public PredefinedOperator (TypeSpec type
, Operator op_mask
, TypeSpec return_type
)
1671 : this (type
, type
, op_mask
, return_type
)
1675 public PredefinedOperator (TypeSpec type
, Operator op_mask
)
1676 : this (type
, type
, op_mask
, type
)
1680 public PredefinedOperator (TypeSpec ltype
, TypeSpec rtype
, Operator op_mask
, TypeSpec return_type
)
1682 if ((op_mask
& Operator
.ValuesOnlyMask
) != 0)
1683 throw new InternalErrorException ("Only masked values can be used");
1687 this.OperatorsMask
= op_mask
;
1688 this.ReturnType
= return_type
;
1691 public virtual Expression
ConvertResult (ResolveContext ec
, Binary b
)
1693 b
.type
= ReturnType
;
1695 b
.left
= Convert
.ImplicitConversion (ec
, b
.left
, left
, b
.left
.Location
);
1696 b
.right
= Convert
.ImplicitConversion (ec
, b
.right
, right
, b
.right
.Location
);
1699 // A user operators does not support multiple user conversions, but decimal type
1700 // is considered to be predefined type therefore we apply predefined operators rules
1701 // and then look for decimal user-operator implementation
1703 if (left
== TypeManager
.decimal_type
)
1704 return b
.ResolveUserOperator (ec
, b
.left
.Type
, b
.right
.Type
);
1706 var c
= b
.right
as Constant
;
1708 if (c
.IsDefaultValue
&& (b
.oper
== Operator
.Addition
|| b
.oper
== Operator
.BitwiseOr
|| b
.oper
== Operator
.Subtraction
))
1709 return ReducedExpression
.Create (b
.left
, b
).Resolve (ec
);
1710 if ((b
.oper
== Operator
.Multiply
|| b
.oper
== Operator
.Division
) && c
.IsOneInteger
)
1711 return ReducedExpression
.Create (b
.left
, b
).Resolve (ec
);
1715 c
= b
.left
as Constant
;
1717 if (c
.IsDefaultValue
&& (b
.oper
== Operator
.Addition
|| b
.oper
== Operator
.BitwiseOr
))
1718 return ReducedExpression
.Create (b
.right
, b
).Resolve (ec
);
1719 if (b
.oper
== Operator
.Multiply
&& c
.IsOneInteger
)
1720 return ReducedExpression
.Create (b
.right
, b
).Resolve (ec
);
1727 public bool IsPrimitiveApplicable (TypeSpec ltype
, TypeSpec rtype
)
1730 // We are dealing with primitive types only
1732 return left
== ltype
&& ltype
== rtype
;
1735 public virtual bool IsApplicable (ResolveContext ec
, Expression lexpr
, Expression rexpr
)
1737 if (TypeManager
.IsEqual (left
, lexpr
.Type
) &&
1738 TypeManager
.IsEqual (right
, rexpr
.Type
))
1741 return Convert
.ImplicitConversionExists (ec
, lexpr
, left
) &&
1742 Convert
.ImplicitConversionExists (ec
, rexpr
, right
);
1745 public PredefinedOperator
ResolveBetterOperator (ResolveContext ec
, PredefinedOperator best_operator
)
1748 if (left
!= null && best_operator
.left
!= null) {
1749 result
= MethodGroupExpr
.BetterTypeConversion (ec
, best_operator
.left
, left
);
1753 // When second arguments are same as the first one, the result is same
1755 if (right
!= null && (left
!= right
|| best_operator
.left
!= best_operator
.right
)) {
1756 result
|= MethodGroupExpr
.BetterTypeConversion (ec
, best_operator
.right
, right
);
1759 if (result
== 0 || result
> 2)
1762 return result
== 1 ? best_operator
: this;
1766 class PredefinedStringOperator
: PredefinedOperator
{
1767 public PredefinedStringOperator (TypeSpec type
, Operator op_mask
)
1768 : base (type
, op_mask
, type
)
1770 ReturnType
= TypeManager
.string_type
;
1773 public PredefinedStringOperator (TypeSpec ltype
, TypeSpec rtype
, Operator op_mask
)
1774 : base (ltype
, rtype
, op_mask
)
1776 ReturnType
= TypeManager
.string_type
;
1779 public override Expression
ConvertResult (ResolveContext ec
, Binary b
)
1782 // Use original expression for nullable arguments
1784 Nullable
.Unwrap unwrap
= b
.left
as Nullable
.Unwrap
;
1786 b
.left
= unwrap
.Original
;
1788 unwrap
= b
.right
as Nullable
.Unwrap
;
1790 b
.right
= unwrap
.Original
;
1792 b
.left
= Convert
.ImplicitConversion (ec
, b
.left
, left
, b
.left
.Location
);
1793 b
.right
= Convert
.ImplicitConversion (ec
, b
.right
, right
, b
.right
.Location
);
1796 // Start a new concat expression using converted expression
1798 return StringConcat
.Create (ec
, b
.left
, b
.right
, b
.loc
);
1802 class PredefinedShiftOperator
: PredefinedOperator
{
1803 public PredefinedShiftOperator (TypeSpec ltype
, Operator op_mask
) :
1804 base (ltype
, TypeManager
.int32_type
, op_mask
)
1808 public override Expression
ConvertResult (ResolveContext ec
, Binary b
)
1810 b
.left
= Convert
.ImplicitConversion (ec
, b
.left
, left
, b
.left
.Location
);
1812 Expression expr_tree_expr
= Convert
.ImplicitConversion (ec
, b
.right
, TypeManager
.int32_type
, b
.right
.Location
);
1814 int right_mask
= left
== TypeManager
.int32_type
|| left
== TypeManager
.uint32_type
? 0x1f : 0x3f;
1817 // b = b.left >> b.right & (0x1f|0x3f)
1819 b
.right
= new Binary (Operator
.BitwiseAnd
,
1820 b
.right
, new IntConstant (right_mask
, b
.right
.Location
), b
.loc
).Resolve (ec
);
1823 // Expression tree representation does not use & mask
1825 b
.right
= ReducedExpression
.Create (b
.right
, expr_tree_expr
).Resolve (ec
);
1826 b
.type
= ReturnType
;
1829 // Optimize shift by 0
1831 var c
= b
.right
as Constant
;
1832 if (c
!= null && c
.IsDefaultValue
)
1833 return ReducedExpression
.Create (b
.left
, b
).Resolve (ec
);
1839 class PredefinedPointerOperator
: PredefinedOperator
{
1840 public PredefinedPointerOperator (TypeSpec ltype
, TypeSpec rtype
, Operator op_mask
)
1841 : base (ltype
, rtype
, op_mask
)
1845 public PredefinedPointerOperator (TypeSpec ltype
, TypeSpec rtype
, Operator op_mask
, TypeSpec retType
)
1846 : base (ltype
, rtype
, op_mask
, retType
)
1850 public PredefinedPointerOperator (TypeSpec type
, Operator op_mask
, TypeSpec return_type
)
1851 : base (type
, op_mask
, return_type
)
1855 public override bool IsApplicable (ResolveContext ec
, Expression lexpr
, Expression rexpr
)
1858 if (!lexpr
.Type
.IsPointer
)
1861 if (!Convert
.ImplicitConversionExists (ec
, lexpr
, left
))
1865 if (right
== null) {
1866 if (!rexpr
.Type
.IsPointer
)
1869 if (!Convert
.ImplicitConversionExists (ec
, rexpr
, right
))
1876 public override Expression
ConvertResult (ResolveContext ec
, Binary b
)
1879 b
.left
= EmptyCast
.Create (b
.left
, left
);
1880 } else if (right
!= null) {
1881 b
.right
= EmptyCast
.Create (b
.right
, right
);
1884 TypeSpec r_type
= ReturnType
;
1885 Expression left_arg
, right_arg
;
1886 if (r_type
== null) {
1889 right_arg
= b
.right
;
1890 r_type
= b
.left
.Type
;
1894 r_type
= b
.right
.Type
;
1898 right_arg
= b
.right
;
1901 return new PointerArithmetic (b
.oper
, left_arg
, right_arg
, r_type
, b
.loc
).Resolve (ec
);
1906 public enum Operator
{
1907 Multiply
= 0 | ArithmeticMask
,
1908 Division
= 1 | ArithmeticMask
,
1909 Modulus
= 2 | ArithmeticMask
,
1910 Addition
= 3 | ArithmeticMask
| AdditionMask
,
1911 Subtraction
= 4 | ArithmeticMask
| SubtractionMask
,
1913 LeftShift
= 5 | ShiftMask
,
1914 RightShift
= 6 | ShiftMask
,
1916 LessThan
= 7 | ComparisonMask
| RelationalMask
,
1917 GreaterThan
= 8 | ComparisonMask
| RelationalMask
,
1918 LessThanOrEqual
= 9 | ComparisonMask
| RelationalMask
,
1919 GreaterThanOrEqual
= 10 | ComparisonMask
| RelationalMask
,
1920 Equality
= 11 | ComparisonMask
| EqualityMask
,
1921 Inequality
= 12 | ComparisonMask
| EqualityMask
,
1923 BitwiseAnd
= 13 | BitwiseMask
,
1924 ExclusiveOr
= 14 | BitwiseMask
,
1925 BitwiseOr
= 15 | BitwiseMask
,
1927 LogicalAnd
= 16 | LogicalMask
,
1928 LogicalOr
= 17 | LogicalMask
,
1933 ValuesOnlyMask
= ArithmeticMask
- 1,
1934 ArithmeticMask
= 1 << 5,
1936 ComparisonMask
= 1 << 7,
1937 EqualityMask
= 1 << 8,
1938 BitwiseMask
= 1 << 9,
1939 LogicalMask
= 1 << 10,
1940 AdditionMask
= 1 << 11,
1941 SubtractionMask
= 1 << 12,
1942 RelationalMask
= 1 << 13
1945 readonly Operator oper
;
1946 protected Expression left
, right
;
1947 readonly bool is_compound
;
1948 Expression enum_conversion
;
1950 static PredefinedOperator
[] standard_operators
;
1951 static PredefinedOperator
[] pointer_operators
;
1953 public Binary (Operator oper
, Expression left
, Expression right
, bool isCompound
, Location loc
)
1954 : this (oper
, left
, right
, loc
)
1956 this.is_compound
= isCompound
;
1959 public Binary (Operator oper
, Expression left
, Expression right
, Location loc
)
1967 public Operator Oper
{
1974 /// Returns a stringified representation of the Operator
1976 string OperName (Operator oper
)
1980 case Operator
.Multiply
:
1983 case Operator
.Division
:
1986 case Operator
.Modulus
:
1989 case Operator
.Addition
:
1992 case Operator
.Subtraction
:
1995 case Operator
.LeftShift
:
1998 case Operator
.RightShift
:
2001 case Operator
.LessThan
:
2004 case Operator
.GreaterThan
:
2007 case Operator
.LessThanOrEqual
:
2010 case Operator
.GreaterThanOrEqual
:
2013 case Operator
.Equality
:
2016 case Operator
.Inequality
:
2019 case Operator
.BitwiseAnd
:
2022 case Operator
.BitwiseOr
:
2025 case Operator
.ExclusiveOr
:
2028 case Operator
.LogicalOr
:
2031 case Operator
.LogicalAnd
:
2035 s
= oper
.ToString ();
2045 public static void Error_OperatorCannotBeApplied (ResolveContext ec
, Expression left
, Expression right
, Operator oper
, Location loc
)
2047 new Binary (oper
, left
, right
, loc
).Error_OperatorCannotBeApplied (ec
, left
, right
);
2050 public static void Error_OperatorCannotBeApplied (ResolveContext ec
, Expression left
, Expression right
, string oper
, Location loc
)
2053 l
= TypeManager
.CSharpName (left
.Type
);
2054 r
= TypeManager
.CSharpName (right
.Type
);
2056 ec
.Report
.Error (19, loc
, "Operator `{0}' cannot be applied to operands of type `{1}' and `{2}'",
2060 protected void Error_OperatorCannotBeApplied (ResolveContext ec
, Expression left
, Expression right
)
2062 Error_OperatorCannotBeApplied (ec
, left
, right
, OperName (oper
), loc
);
2066 // Converts operator to System.Linq.Expressions.ExpressionType enum name
2068 string GetOperatorExpressionTypeName ()
2071 case Operator
.Addition
:
2072 return is_compound
? "AddAssign" : "Add";
2073 case Operator
.BitwiseAnd
:
2074 return is_compound
? "AndAssign" : "And";
2075 case Operator
.BitwiseOr
:
2076 return is_compound
? "OrAssign" : "Or";
2077 case Operator
.Division
:
2078 return is_compound
? "DivideAssign" : "Divide";
2079 case Operator
.ExclusiveOr
:
2080 return is_compound
? "ExclusiveOrAssign" : "ExclusiveOr";
2081 case Operator
.Equality
:
2083 case Operator
.GreaterThan
:
2084 return "GreaterThan";
2085 case Operator
.GreaterThanOrEqual
:
2086 return "GreaterThanOrEqual";
2087 case Operator
.Inequality
:
2089 case Operator
.LeftShift
:
2090 return is_compound
? "LeftShiftAssign" : "LeftShift";
2091 case Operator
.LessThan
:
2093 case Operator
.LessThanOrEqual
:
2094 return "LessThanOrEqual";
2095 case Operator
.LogicalAnd
:
2097 case Operator
.LogicalOr
:
2099 case Operator
.Modulus
:
2100 return is_compound
? "ModuloAssign" : "Modulo";
2101 case Operator
.Multiply
:
2102 return is_compound
? "MultiplyAssign" : "Multiply";
2103 case Operator
.RightShift
:
2104 return is_compound
? "RightShiftAssign" : "RightShift";
2105 case Operator
.Subtraction
:
2106 return is_compound
? "SubtractAssign" : "Subtract";
2108 throw new NotImplementedException ("Unknown expression type operator " + oper
.ToString ());
2112 static string GetOperatorMetadataName (Operator op
)
2114 CSharp
.Operator
.OpType op_type
;
2116 case Operator
.Addition
:
2117 op_type
= CSharp
.Operator
.OpType
.Addition
; break;
2118 case Operator
.BitwiseAnd
:
2119 op_type
= CSharp
.Operator
.OpType
.BitwiseAnd
; break;
2120 case Operator
.BitwiseOr
:
2121 op_type
= CSharp
.Operator
.OpType
.BitwiseOr
; break;
2122 case Operator
.Division
:
2123 op_type
= CSharp
.Operator
.OpType
.Division
; break;
2124 case Operator
.Equality
:
2125 op_type
= CSharp
.Operator
.OpType
.Equality
; break;
2126 case Operator
.ExclusiveOr
:
2127 op_type
= CSharp
.Operator
.OpType
.ExclusiveOr
; break;
2128 case Operator
.GreaterThan
:
2129 op_type
= CSharp
.Operator
.OpType
.GreaterThan
; break;
2130 case Operator
.GreaterThanOrEqual
:
2131 op_type
= CSharp
.Operator
.OpType
.GreaterThanOrEqual
; break;
2132 case Operator
.Inequality
:
2133 op_type
= CSharp
.Operator
.OpType
.Inequality
; break;
2134 case Operator
.LeftShift
:
2135 op_type
= CSharp
.Operator
.OpType
.LeftShift
; break;
2136 case Operator
.LessThan
:
2137 op_type
= CSharp
.Operator
.OpType
.LessThan
; break;
2138 case Operator
.LessThanOrEqual
:
2139 op_type
= CSharp
.Operator
.OpType
.LessThanOrEqual
; break;
2140 case Operator
.Modulus
:
2141 op_type
= CSharp
.Operator
.OpType
.Modulus
; break;
2142 case Operator
.Multiply
:
2143 op_type
= CSharp
.Operator
.OpType
.Multiply
; break;
2144 case Operator
.RightShift
:
2145 op_type
= CSharp
.Operator
.OpType
.RightShift
; break;
2146 case Operator
.Subtraction
:
2147 op_type
= CSharp
.Operator
.OpType
.Subtraction
; break;
2149 throw new InternalErrorException (op
.ToString ());
2152 return CSharp
.Operator
.GetMetadataName (op_type
);
2155 public static void EmitOperatorOpcode (EmitContext ec
, Operator oper
, TypeSpec l
)
2160 case Operator
.Multiply
:
2161 if (ec
.HasSet (EmitContext
.Options
.CheckedScope
)) {
2162 if (l
== TypeManager
.int32_type
|| l
== TypeManager
.int64_type
)
2163 opcode
= OpCodes
.Mul_Ovf
;
2164 else if (!IsFloat (l
))
2165 opcode
= OpCodes
.Mul_Ovf_Un
;
2167 opcode
= OpCodes
.Mul
;
2169 opcode
= OpCodes
.Mul
;
2173 case Operator
.Division
:
2175 opcode
= OpCodes
.Div_Un
;
2177 opcode
= OpCodes
.Div
;
2180 case Operator
.Modulus
:
2182 opcode
= OpCodes
.Rem_Un
;
2184 opcode
= OpCodes
.Rem
;
2187 case Operator
.Addition
:
2188 if (ec
.HasSet (EmitContext
.Options
.CheckedScope
)) {
2189 if (l
== TypeManager
.int32_type
|| l
== TypeManager
.int64_type
)
2190 opcode
= OpCodes
.Add_Ovf
;
2191 else if (!IsFloat (l
))
2192 opcode
= OpCodes
.Add_Ovf_Un
;
2194 opcode
= OpCodes
.Add
;
2196 opcode
= OpCodes
.Add
;
2199 case Operator
.Subtraction
:
2200 if (ec
.HasSet (EmitContext
.Options
.CheckedScope
)) {
2201 if (l
== TypeManager
.int32_type
|| l
== TypeManager
.int64_type
)
2202 opcode
= OpCodes
.Sub_Ovf
;
2203 else if (!IsFloat (l
))
2204 opcode
= OpCodes
.Sub_Ovf_Un
;
2206 opcode
= OpCodes
.Sub
;
2208 opcode
= OpCodes
.Sub
;
2211 case Operator
.RightShift
:
2213 opcode
= OpCodes
.Shr_Un
;
2215 opcode
= OpCodes
.Shr
;
2218 case Operator
.LeftShift
:
2219 opcode
= OpCodes
.Shl
;
2222 case Operator
.Equality
:
2223 opcode
= OpCodes
.Ceq
;
2226 case Operator
.Inequality
:
2227 ec
.Emit (OpCodes
.Ceq
);
2228 ec
.Emit (OpCodes
.Ldc_I4_0
);
2230 opcode
= OpCodes
.Ceq
;
2233 case Operator
.LessThan
:
2235 opcode
= OpCodes
.Clt_Un
;
2237 opcode
= OpCodes
.Clt
;
2240 case Operator
.GreaterThan
:
2242 opcode
= OpCodes
.Cgt_Un
;
2244 opcode
= OpCodes
.Cgt
;
2247 case Operator
.LessThanOrEqual
:
2248 if (IsUnsigned (l
) || IsFloat (l
))
2249 ec
.Emit (OpCodes
.Cgt_Un
);
2251 ec
.Emit (OpCodes
.Cgt
);
2252 ec
.Emit (OpCodes
.Ldc_I4_0
);
2254 opcode
= OpCodes
.Ceq
;
2257 case Operator
.GreaterThanOrEqual
:
2258 if (IsUnsigned (l
) || IsFloat (l
))
2259 ec
.Emit (OpCodes
.Clt_Un
);
2261 ec
.Emit (OpCodes
.Clt
);
2263 ec
.Emit (OpCodes
.Ldc_I4_0
);
2265 opcode
= OpCodes
.Ceq
;
2268 case Operator
.BitwiseOr
:
2269 opcode
= OpCodes
.Or
;
2272 case Operator
.BitwiseAnd
:
2273 opcode
= OpCodes
.And
;
2276 case Operator
.ExclusiveOr
:
2277 opcode
= OpCodes
.Xor
;
2281 throw new InternalErrorException (oper
.ToString ());
2287 static bool IsUnsigned (TypeSpec t
)
2292 return (t
== TypeManager
.uint32_type
|| t
== TypeManager
.uint64_type
||
2293 t
== TypeManager
.ushort_type
|| t
== TypeManager
.byte_type
);
2296 static bool IsFloat (TypeSpec t
)
2298 return t
== TypeManager
.float_type
|| t
== TypeManager
.double_type
;
2301 public static void Reset ()
2303 pointer_operators
= standard_operators
= null;
2306 Expression
ResolveOperator (ResolveContext ec
)
2308 TypeSpec l
= left
.Type
;
2309 TypeSpec r
= right
.Type
;
2311 bool primitives_only
= false;
2313 if (standard_operators
== null)
2314 CreateStandardOperatorsTable ();
2317 // Handles predefined primitive types
2319 if (TypeManager
.IsPrimitiveType (l
) && TypeManager
.IsPrimitiveType (r
)) {
2320 if ((oper
& Operator
.ShiftMask
) == 0) {
2321 if (l
!= TypeManager
.bool_type
&& !DoBinaryOperatorPromotion (ec
))
2324 primitives_only
= true;
2328 if (l
.IsPointer
|| r
.IsPointer
)
2329 return ResolveOperatorPointer (ec
, l
, r
);
2332 bool lenum
= TypeManager
.IsEnumType (l
);
2333 bool renum
= TypeManager
.IsEnumType (r
);
2334 if (lenum
|| renum
) {
2335 expr
= ResolveOperatorEnum (ec
, lenum
, renum
, l
, r
);
2337 // TODO: Can this be ambiguous
2343 if ((oper
== Operator
.Addition
|| oper
== Operator
.Subtraction
|| (oper
& Operator
.EqualityMask
) != 0) &&
2344 (TypeManager
.IsDelegateType (l
) || TypeManager
.IsDelegateType (r
))) {
2346 expr
= ResolveOperatorDelegate (ec
, l
, r
);
2348 // TODO: Can this be ambiguous
2354 expr
= ResolveUserOperator (ec
, l
, r
);
2358 // Predefined reference types equality
2359 if ((oper
& Operator
.EqualityMask
) != 0) {
2360 expr
= ResolveOperatorEqualityRerefence (ec
, l
, r
);
2366 return ResolveOperatorPredefined (ec
, standard_operators
, primitives_only
, null);
2369 // at least one of 'left' or 'right' is an enumeration constant (EnumConstant or SideEffectConstant or ...)
2370 // if 'left' is not an enumeration constant, create one from the type of 'right'
2371 Constant
EnumLiftUp (ResolveContext ec
, Constant left
, Constant right
, Location loc
)
2374 case Operator
.BitwiseOr
:
2375 case Operator
.BitwiseAnd
:
2376 case Operator
.ExclusiveOr
:
2377 case Operator
.Equality
:
2378 case Operator
.Inequality
:
2379 case Operator
.LessThan
:
2380 case Operator
.LessThanOrEqual
:
2381 case Operator
.GreaterThan
:
2382 case Operator
.GreaterThanOrEqual
:
2383 if (TypeManager
.IsEnumType (left
.Type
))
2386 if (left
.IsZeroInteger
)
2387 return left
.TryReduce (ec
, right
.Type
, loc
);
2391 case Operator
.Addition
:
2392 case Operator
.Subtraction
:
2395 case Operator
.Multiply
:
2396 case Operator
.Division
:
2397 case Operator
.Modulus
:
2398 case Operator
.LeftShift
:
2399 case Operator
.RightShift
:
2400 if (TypeManager
.IsEnumType (right
.Type
) || TypeManager
.IsEnumType (left
.Type
))
2404 Error_OperatorCannotBeApplied (ec
, this.left
, this.right
);
2409 // The `|' operator used on types which were extended is dangerous
2411 void CheckBitwiseOrOnSignExtended (ResolveContext ec
)
2413 OpcodeCast lcast
= left
as OpcodeCast
;
2414 if (lcast
!= null) {
2415 if (IsUnsigned (lcast
.UnderlyingType
))
2419 OpcodeCast rcast
= right
as OpcodeCast
;
2420 if (rcast
!= null) {
2421 if (IsUnsigned (rcast
.UnderlyingType
))
2425 if (lcast
== null && rcast
== null)
2428 // FIXME: consider constants
2430 ec
.Report
.Warning (675, 3, loc
,
2431 "The operator `|' used on the sign-extended type `{0}'. Consider casting to a smaller unsigned type first",
2432 TypeManager
.CSharpName (lcast
!= null ? lcast
.UnderlyingType
: rcast
.UnderlyingType
));
2435 static void CreatePointerOperatorsTable ()
2437 var temp
= new List
<PredefinedPointerOperator
> ();
2440 // Pointer arithmetic:
2442 // T* operator + (T* x, int y); T* operator - (T* x, int y);
2443 // T* operator + (T* x, uint y); T* operator - (T* x, uint y);
2444 // T* operator + (T* x, long y); T* operator - (T* x, long y);
2445 // T* operator + (T* x, ulong y); T* operator - (T* x, ulong y);
2447 temp
.Add (new PredefinedPointerOperator (null, TypeManager
.int32_type
, Operator
.AdditionMask
| Operator
.SubtractionMask
));
2448 temp
.Add (new PredefinedPointerOperator (null, TypeManager
.uint32_type
, Operator
.AdditionMask
| Operator
.SubtractionMask
));
2449 temp
.Add (new PredefinedPointerOperator (null, TypeManager
.int64_type
, Operator
.AdditionMask
| Operator
.SubtractionMask
));
2450 temp
.Add (new PredefinedPointerOperator (null, TypeManager
.uint64_type
, Operator
.AdditionMask
| Operator
.SubtractionMask
));
2453 // T* operator + (int y, T* x);
2454 // T* operator + (uint y, T *x);
2455 // T* operator + (long y, T *x);
2456 // T* operator + (ulong y, T *x);
2458 temp
.Add (new PredefinedPointerOperator (TypeManager
.int32_type
, null, Operator
.AdditionMask
, null));
2459 temp
.Add (new PredefinedPointerOperator (TypeManager
.uint32_type
, null, Operator
.AdditionMask
, null));
2460 temp
.Add (new PredefinedPointerOperator (TypeManager
.int64_type
, null, Operator
.AdditionMask
, null));
2461 temp
.Add (new PredefinedPointerOperator (TypeManager
.uint64_type
, null, Operator
.AdditionMask
, null));
2464 // long operator - (T* x, T *y)
2466 temp
.Add (new PredefinedPointerOperator (null, Operator
.SubtractionMask
, TypeManager
.int64_type
));
2468 pointer_operators
= temp
.ToArray ();
2471 static void CreateStandardOperatorsTable ()
2473 var temp
= new List
<PredefinedOperator
> ();
2474 TypeSpec bool_type
= TypeManager
.bool_type
;
2476 temp
.Add (new PredefinedOperator (TypeManager
.int32_type
, Operator
.ArithmeticMask
| Operator
.BitwiseMask
));
2477 temp
.Add (new PredefinedOperator (TypeManager
.uint32_type
, Operator
.ArithmeticMask
| Operator
.BitwiseMask
));
2478 temp
.Add (new PredefinedOperator (TypeManager
.int64_type
, Operator
.ArithmeticMask
| Operator
.BitwiseMask
));
2479 temp
.Add (new PredefinedOperator (TypeManager
.uint64_type
, Operator
.ArithmeticMask
| Operator
.BitwiseMask
));
2480 temp
.Add (new PredefinedOperator (TypeManager
.float_type
, Operator
.ArithmeticMask
));
2481 temp
.Add (new PredefinedOperator (TypeManager
.double_type
, Operator
.ArithmeticMask
));
2482 temp
.Add (new PredefinedOperator (TypeManager
.decimal_type
, Operator
.ArithmeticMask
));
2484 temp
.Add (new PredefinedOperator (TypeManager
.int32_type
, Operator
.ComparisonMask
, bool_type
));
2485 temp
.Add (new PredefinedOperator (TypeManager
.uint32_type
, Operator
.ComparisonMask
, bool_type
));
2486 temp
.Add (new PredefinedOperator (TypeManager
.int64_type
, Operator
.ComparisonMask
, bool_type
));
2487 temp
.Add (new PredefinedOperator (TypeManager
.uint64_type
, Operator
.ComparisonMask
, bool_type
));
2488 temp
.Add (new PredefinedOperator (TypeManager
.float_type
, Operator
.ComparisonMask
, bool_type
));
2489 temp
.Add (new PredefinedOperator (TypeManager
.double_type
, Operator
.ComparisonMask
, bool_type
));
2490 temp
.Add (new PredefinedOperator (TypeManager
.decimal_type
, Operator
.ComparisonMask
, bool_type
));
2492 temp
.Add (new PredefinedOperator (TypeManager
.string_type
, Operator
.EqualityMask
, bool_type
));
2494 temp
.Add (new PredefinedStringOperator (TypeManager
.string_type
, Operator
.AdditionMask
));
2495 temp
.Add (new PredefinedStringOperator (TypeManager
.string_type
, TypeManager
.object_type
, Operator
.AdditionMask
));
2496 temp
.Add (new PredefinedStringOperator (TypeManager
.object_type
, TypeManager
.string_type
, Operator
.AdditionMask
));
2498 temp
.Add (new PredefinedOperator (bool_type
,
2499 Operator
.BitwiseMask
| Operator
.LogicalMask
| Operator
.EqualityMask
, bool_type
));
2501 temp
.Add (new PredefinedShiftOperator (TypeManager
.int32_type
, Operator
.ShiftMask
));
2502 temp
.Add (new PredefinedShiftOperator (TypeManager
.uint32_type
, Operator
.ShiftMask
));
2503 temp
.Add (new PredefinedShiftOperator (TypeManager
.int64_type
, Operator
.ShiftMask
));
2504 temp
.Add (new PredefinedShiftOperator (TypeManager
.uint64_type
, Operator
.ShiftMask
));
2506 standard_operators
= temp
.ToArray ();
2510 // Rules used during binary numeric promotion
2512 static bool DoNumericPromotion (ResolveContext rc
, ref Expression prim_expr
, ref Expression second_expr
, TypeSpec type
)
2517 Constant c
= prim_expr
as Constant
;
2519 temp
= c
.ConvertImplicitly (rc
, type
);
2526 if (type
== TypeManager
.uint32_type
) {
2527 etype
= prim_expr
.Type
;
2528 if (etype
== TypeManager
.int32_type
|| etype
== TypeManager
.short_type
|| etype
== TypeManager
.sbyte_type
) {
2529 type
= TypeManager
.int64_type
;
2531 if (type
!= second_expr
.Type
) {
2532 c
= second_expr
as Constant
;
2534 temp
= c
.ConvertImplicitly (rc
, type
);
2536 temp
= Convert
.ImplicitNumericConversion (second_expr
, type
);
2542 } else if (type
== TypeManager
.uint64_type
) {
2544 // A compile-time error occurs if the other operand is of type sbyte, short, int, or long
2546 if (type
== TypeManager
.int32_type
|| type
== TypeManager
.int64_type
||
2547 type
== TypeManager
.short_type
|| type
== TypeManager
.sbyte_type
)
2551 temp
= Convert
.ImplicitNumericConversion (prim_expr
, type
);
2560 // 7.2.6.2 Binary numeric promotions
2562 public bool DoBinaryOperatorPromotion (ResolveContext ec
)
2564 TypeSpec ltype
= left
.Type
;
2565 TypeSpec rtype
= right
.Type
;
2568 foreach (TypeSpec t
in ConstantFold
.BinaryPromotionsTypes
) {
2570 return t
== rtype
|| DoNumericPromotion (ec
, ref right
, ref left
, t
);
2573 return t
== ltype
|| DoNumericPromotion (ec
, ref left
, ref right
, t
);
2576 TypeSpec int32
= TypeManager
.int32_type
;
2577 if (ltype
!= int32
) {
2578 Constant c
= left
as Constant
;
2580 temp
= c
.ConvertImplicitly (ec
, int32
);
2582 temp
= Convert
.ImplicitNumericConversion (left
, int32
);
2589 if (rtype
!= int32
) {
2590 Constant c
= right
as Constant
;
2592 temp
= c
.ConvertImplicitly (ec
, int32
);
2594 temp
= Convert
.ImplicitNumericConversion (right
, int32
);
2604 protected override Expression
DoResolve (ResolveContext ec
)
2609 if ((oper
== Operator
.Subtraction
) && (left
is ParenthesizedExpression
)) {
2610 left
= ((ParenthesizedExpression
) left
).Expr
;
2611 left
= left
.Resolve (ec
, ResolveFlags
.VariableOrValue
| ResolveFlags
.Type
);
2615 if (left
.eclass
== ExprClass
.Type
) {
2616 ec
.Report
.Error (75, loc
, "To cast a negative value, you must enclose the value in parentheses");
2620 left
= left
.Resolve (ec
);
2625 Constant lc
= left
as Constant
;
2627 if (lc
!= null && lc
.Type
== TypeManager
.bool_type
&&
2628 ((oper
== Operator
.LogicalAnd
&& lc
.IsDefaultValue
) ||
2629 (oper
== Operator
.LogicalOr
&& !lc
.IsDefaultValue
))) {
2631 // FIXME: resolve right expression as unreachable
2632 // right.Resolve (ec);
2634 ec
.Report
.Warning (429, 4, loc
, "Unreachable expression code detected");
2638 right
= right
.Resolve (ec
);
2642 eclass
= ExprClass
.Value
;
2643 Constant rc
= right
as Constant
;
2645 // The conversion rules are ignored in enum context but why
2646 if (!ec
.HasSet (ResolveContext
.Options
.EnumScope
) && lc
!= null && rc
!= null && (TypeManager
.IsEnumType (left
.Type
) || TypeManager
.IsEnumType (right
.Type
))) {
2647 lc
= EnumLiftUp (ec
, lc
, rc
, loc
);
2649 rc
= EnumLiftUp (ec
, rc
, lc
, loc
);
2652 if (rc
!= null && lc
!= null) {
2653 int prev_e
= ec
.Report
.Errors
;
2654 Expression e
= ConstantFold
.BinaryFold (ec
, oper
, lc
, rc
, loc
);
2658 if (e
!= null || ec
.Report
.Errors
!= prev_e
)
2662 // Comparison warnings
2663 if ((oper
& Operator
.ComparisonMask
) != 0) {
2664 if (left
.Equals (right
)) {
2665 ec
.Report
.Warning (1718, 3, loc
, "A comparison made to same variable. Did you mean to compare something else?");
2667 CheckUselessComparison (ec
, lc
, right
.Type
);
2668 CheckUselessComparison (ec
, rc
, left
.Type
);
2671 if (left
.Type
== InternalType
.Dynamic
|| right
.Type
== InternalType
.Dynamic
) {
2672 Arguments args
= new Arguments (2);
2673 args
.Add (new Argument (left
));
2674 args
.Add (new Argument (right
));
2675 return new DynamicExpressionStatement (this, args
, loc
).Resolve (ec
);
2678 if (RootContext
.Version
>= LanguageVersion
.ISO_2
&&
2679 ((TypeManager
.IsNullableType (left
.Type
) && (right
is NullLiteral
|| TypeManager
.IsNullableType (right
.Type
) || TypeManager
.IsValueType (right
.Type
))) ||
2680 (TypeManager
.IsValueType (left
.Type
) && right
is NullLiteral
) ||
2681 (TypeManager
.IsNullableType (right
.Type
) && (left
is NullLiteral
|| TypeManager
.IsNullableType (left
.Type
) || TypeManager
.IsValueType (left
.Type
))) ||
2682 (TypeManager
.IsValueType (right
.Type
) && left
is NullLiteral
)))
2683 return new Nullable
.LiftedBinaryOperator (oper
, left
, right
, loc
).Resolve (ec
);
2685 return DoResolveCore (ec
, left
, right
);
2688 protected Expression
DoResolveCore (ResolveContext ec
, Expression left_orig
, Expression right_orig
)
2690 Expression expr
= ResolveOperator (ec
);
2692 Error_OperatorCannotBeApplied (ec
, left_orig
, right_orig
);
2694 if (left
== null || right
== null)
2695 throw new InternalErrorException ("Invalid conversion");
2697 if (oper
== Operator
.BitwiseOr
)
2698 CheckBitwiseOrOnSignExtended (ec
);
2703 public override SLE
.Expression
MakeExpression (BuilderContext ctx
)
2705 var le
= left
.MakeExpression (ctx
);
2706 var re
= right
.MakeExpression (ctx
);
2707 bool is_checked
= ctx
.HasSet (BuilderContext
.Options
.CheckedScope
);
2710 case Operator
.Addition
:
2711 return is_checked
? SLE
.Expression
.AddChecked (le
, re
) : SLE
.Expression
.Add (le
, re
);
2712 case Operator
.BitwiseAnd
:
2713 return SLE
.Expression
.And (le
, re
);
2714 case Operator
.BitwiseOr
:
2715 return SLE
.Expression
.Or (le
, re
);
2716 case Operator
.Division
:
2717 return SLE
.Expression
.Divide (le
, re
);
2718 case Operator
.Equality
:
2719 return SLE
.Expression
.Equal (le
, re
);
2720 case Operator
.ExclusiveOr
:
2721 return SLE
.Expression
.ExclusiveOr (le
, re
);
2722 case Operator
.GreaterThan
:
2723 return SLE
.Expression
.GreaterThan (le
, re
);
2724 case Operator
.GreaterThanOrEqual
:
2725 return SLE
.Expression
.GreaterThanOrEqual (le
, re
);
2726 case Operator
.Inequality
:
2727 return SLE
.Expression
.NotEqual (le
, re
);
2728 case Operator
.LeftShift
:
2729 return SLE
.Expression
.LeftShift (le
, re
);
2730 case Operator
.LessThan
:
2731 return SLE
.Expression
.LessThan (le
, re
);
2732 case Operator
.LessThanOrEqual
:
2733 return SLE
.Expression
.LessThanOrEqual (le
, re
);
2734 case Operator
.LogicalAnd
:
2735 return SLE
.Expression
.AndAlso (le
, re
);
2736 case Operator
.LogicalOr
:
2737 return SLE
.Expression
.OrElse (le
, re
);
2738 case Operator
.Modulus
:
2739 return SLE
.Expression
.Modulo (le
, re
);
2740 case Operator
.Multiply
:
2741 return is_checked
? SLE
.Expression
.MultiplyChecked (le
, re
) : SLE
.Expression
.Multiply (le
, re
);
2742 case Operator
.RightShift
:
2743 return SLE
.Expression
.RightShift (le
, re
);
2744 case Operator
.Subtraction
:
2745 return is_checked
? SLE
.Expression
.SubtractChecked (le
, re
) : SLE
.Expression
.Subtract (le
, re
);
2747 throw new NotImplementedException (oper
.ToString ());
2752 // D operator + (D x, D y)
2753 // D operator - (D x, D y)
2754 // bool operator == (D x, D y)
2755 // bool operator != (D x, D y)
2757 Expression
ResolveOperatorDelegate (ResolveContext ec
, TypeSpec l
, TypeSpec r
)
2759 bool is_equality
= (oper
& Operator
.EqualityMask
) != 0;
2760 if (!TypeManager
.IsEqual (l
, r
) && !TypeSpecComparer
.Variant
.IsEqual (r
, l
)) {
2762 if (right
.eclass
== ExprClass
.MethodGroup
|| (r
== InternalType
.AnonymousMethod
&& !is_equality
)) {
2763 tmp
= Convert
.ImplicitConversionRequired (ec
, right
, l
, loc
);
2768 } else if (left
.eclass
== ExprClass
.MethodGroup
|| (l
== InternalType
.AnonymousMethod
&& !is_equality
)) {
2769 tmp
= Convert
.ImplicitConversionRequired (ec
, left
, r
, loc
);
2780 // Resolve delegate equality as a user operator
2783 return ResolveUserOperator (ec
, l
, r
);
2786 Arguments args
= new Arguments (2);
2787 args
.Add (new Argument (left
));
2788 args
.Add (new Argument (right
));
2790 if (oper
== Operator
.Addition
) {
2791 if (TypeManager
.delegate_combine_delegate_delegate
== null) {
2792 TypeManager
.delegate_combine_delegate_delegate
= TypeManager
.GetPredefinedMethod (
2793 TypeManager
.delegate_type
, "Combine", loc
, TypeManager
.delegate_type
, TypeManager
.delegate_type
);
2796 method
= TypeManager
.delegate_combine_delegate_delegate
;
2798 if (TypeManager
.delegate_remove_delegate_delegate
== null) {
2799 TypeManager
.delegate_remove_delegate_delegate
= TypeManager
.GetPredefinedMethod (
2800 TypeManager
.delegate_type
, "Remove", loc
, TypeManager
.delegate_type
, TypeManager
.delegate_type
);
2803 method
= TypeManager
.delegate_remove_delegate_delegate
;
2807 return new EmptyExpression (TypeManager
.decimal_type
);
2809 MethodGroupExpr mg
= new MethodGroupExpr (method
, TypeManager
.delegate_type
, loc
);
2810 mg
= mg
.OverloadResolve (ec
, ref args
, false, loc
);
2812 return new ClassCast (new UserOperatorCall (mg
, args
, CreateExpressionTree
, loc
), l
);
2816 // Enumeration operators
2818 Expression
ResolveOperatorEnum (ResolveContext ec
, bool lenum
, bool renum
, TypeSpec ltype
, TypeSpec rtype
)
2821 // bool operator == (E x, E y);
2822 // bool operator != (E x, E y);
2823 // bool operator < (E x, E y);
2824 // bool operator > (E x, E y);
2825 // bool operator <= (E x, E y);
2826 // bool operator >= (E x, E y);
2828 // E operator & (E x, E y);
2829 // E operator | (E x, E y);
2830 // E operator ^ (E x, E y);
2832 // U operator - (E e, E f)
2833 // E operator - (E e, U x)
2835 // E operator + (U x, E e)
2836 // E operator + (E e, U x)
2838 if (!((oper
& (Operator
.ComparisonMask
| Operator
.BitwiseMask
)) != 0 ||
2839 (oper
== Operator
.Subtraction
&& lenum
) ||
2840 (oper
== Operator
.Addition
&& (lenum
!= renum
|| type
!= null)))) // type != null for lifted null
2843 Expression ltemp
= left
;
2844 Expression rtemp
= right
;
2845 TypeSpec underlying_type
;
2848 if ((oper
& (Operator
.ComparisonMask
| Operator
.BitwiseMask
)) != 0) {
2850 expr
= Convert
.ImplicitConversion (ec
, left
, rtype
, loc
);
2856 expr
= Convert
.ImplicitConversion (ec
, right
, ltype
, loc
);
2864 if (TypeManager
.IsEqual (ltype
, rtype
)) {
2865 underlying_type
= EnumSpec
.GetUnderlyingType (ltype
);
2867 if (left
is Constant
)
2868 left
= ((Constant
) left
).ConvertExplicitly (false, underlying_type
).Resolve (ec
);
2870 left
= EmptyCast
.Create (left
, underlying_type
);
2872 if (right
is Constant
)
2873 right
= ((Constant
) right
).ConvertExplicitly (false, underlying_type
).Resolve (ec
);
2875 right
= EmptyCast
.Create (right
, underlying_type
);
2877 underlying_type
= EnumSpec
.GetUnderlyingType (ltype
);
2879 if (oper
!= Operator
.Subtraction
&& oper
!= Operator
.Addition
) {
2880 Constant c
= right
as Constant
;
2881 if (c
== null || !c
.IsDefaultValue
)
2884 if (!Convert
.ImplicitStandardConversionExists (right
, underlying_type
))
2887 right
= Convert
.ImplicitConversionStandard (ec
, right
, underlying_type
, right
.Location
);
2890 if (left
is Constant
)
2891 left
= ((Constant
) left
).ConvertExplicitly (false, underlying_type
).Resolve (ec
);
2893 left
= EmptyCast
.Create (left
, underlying_type
);
2896 underlying_type
= EnumSpec
.GetUnderlyingType (rtype
);
2898 if (oper
!= Operator
.Addition
) {
2899 Constant c
= left
as Constant
;
2900 if (c
== null || !c
.IsDefaultValue
)
2903 if (!Convert
.ImplicitStandardConversionExists (left
, underlying_type
))
2906 left
= Convert
.ImplicitConversionStandard (ec
, left
, underlying_type
, left
.Location
);
2909 if (right
is Constant
)
2910 right
= ((Constant
) right
).ConvertExplicitly (false, underlying_type
).Resolve (ec
);
2912 right
= EmptyCast
.Create (right
, underlying_type
);
2919 // C# specification uses explicit cast syntax which means binary promotion
2920 // should happen, however it seems that csc does not do that
2922 if (!DoBinaryOperatorPromotion (ec
)) {
2928 TypeSpec res_type
= null;
2929 if ((oper
& Operator
.BitwiseMask
) != 0 || oper
== Operator
.Subtraction
|| oper
== Operator
.Addition
) {
2930 TypeSpec promoted_type
= lenum
? left
.Type
: right
.Type
;
2931 enum_conversion
= Convert
.ExplicitNumericConversion (
2932 new EmptyExpression (promoted_type
), underlying_type
);
2934 if (oper
== Operator
.Subtraction
&& renum
&& lenum
)
2935 res_type
= underlying_type
;
2936 else if (oper
== Operator
.Addition
&& renum
)
2942 expr
= ResolveOperatorPredefined (ec
, standard_operators
, true, res_type
);
2943 if (!is_compound
|| expr
== null)
2951 // If the return type of the selected operator is implicitly convertible to the type of x
2953 if (Convert
.ImplicitConversionExists (ec
, expr
, ltype
))
2957 // Otherwise, if the selected operator is a predefined operator, if the return type of the
2958 // selected operator is explicitly convertible to the type of x, and if y is implicitly
2959 // convertible to the type of x or the operator is a shift operator, then the operation
2960 // is evaluated as x = (T)(x op y), where T is the type of x
2962 expr
= Convert
.ExplicitConversion (ec
, expr
, ltype
, loc
);
2966 if (Convert
.ImplicitConversionExists (ec
, ltemp
, ltype
))
2973 // 7.9.6 Reference type equality operators
2975 Binary
ResolveOperatorEqualityRerefence (ResolveContext ec
, TypeSpec l
, TypeSpec r
)
2978 // operator != (object a, object b)
2979 // operator == (object a, object b)
2982 // TODO: this method is almost equivalent to Convert.ImplicitReferenceConversion
2984 if (left
.eclass
== ExprClass
.MethodGroup
|| right
.eclass
== ExprClass
.MethodGroup
)
2987 type
= TypeManager
.bool_type
;
2989 var lgen
= l
as TypeParameterSpec
;
2992 if (l
is InternalType
)
2997 // Only allow to compare same reference type parameter
2999 if (TypeManager
.IsReferenceType (l
)) {
3000 left
= new BoxedCast (left
, TypeManager
.object_type
);
3001 right
= new BoxedCast (right
, TypeManager
.object_type
);
3008 if (TypeManager
.IsValueType (l
))
3014 var rgen
= r
as TypeParameterSpec
;
3017 // a, Both operands are reference-type values or the value null
3018 // b, One operand is a value of type T where T is a type-parameter and
3019 // the other operand is the value null. Furthermore T does not have the
3020 // value type constrain
3022 if (left
is NullLiteral
|| right
is NullLiteral
) {
3024 if (lgen
.HasSpecialStruct
)
3027 left
= new BoxedCast (left
, TypeManager
.object_type
);
3032 if (rgen
.HasSpecialStruct
)
3035 right
= new BoxedCast (right
, TypeManager
.object_type
);
3041 // An interface is converted to the object before the
3042 // standard conversion is applied. It's not clear from the
3043 // standard but it looks like it works like that.
3046 if (!TypeManager
.IsReferenceType (l
))
3049 l
= TypeManager
.object_type
;
3050 left
= new BoxedCast (left
, l
);
3051 } else if (l
.IsInterface
) {
3052 l
= TypeManager
.object_type
;
3053 } else if (TypeManager
.IsStruct (l
)) {
3058 if (!TypeManager
.IsReferenceType (r
))
3061 r
= TypeManager
.object_type
;
3062 right
= new BoxedCast (right
, r
);
3063 } else if (r
.IsInterface
) {
3064 r
= TypeManager
.object_type
;
3065 } else if (TypeManager
.IsStruct (r
)) {
3070 const string ref_comparison
= "Possible unintended reference comparison. " +
3071 "Consider casting the {0} side of the expression to `string' to compare the values";
3074 // A standard implicit conversion exists from the type of either
3075 // operand to the type of the other operand
3077 if (Convert
.ImplicitReferenceConversionExists (left
, r
)) {
3078 if (l
== TypeManager
.string_type
)
3079 ec
.Report
.Warning (253, 2, loc
, ref_comparison
, "right");
3084 if (Convert
.ImplicitReferenceConversionExists (right
, l
)) {
3085 if (r
== TypeManager
.string_type
)
3086 ec
.Report
.Warning (252, 2, loc
, ref_comparison
, "left");
3095 Expression
ResolveOperatorPointer (ResolveContext ec
, TypeSpec l
, TypeSpec r
)
3098 // bool operator == (void* x, void* y);
3099 // bool operator != (void* x, void* y);
3100 // bool operator < (void* x, void* y);
3101 // bool operator > (void* x, void* y);
3102 // bool operator <= (void* x, void* y);
3103 // bool operator >= (void* x, void* y);
3105 if ((oper
& Operator
.ComparisonMask
) != 0) {
3108 temp
= Convert
.ImplicitConversion (ec
, left
, r
, left
.Location
);
3115 temp
= Convert
.ImplicitConversion (ec
, right
, l
, right
.Location
);
3121 type
= TypeManager
.bool_type
;
3125 if (pointer_operators
== null)
3126 CreatePointerOperatorsTable ();
3128 return ResolveOperatorPredefined (ec
, pointer_operators
, false, null);
3132 // Build-in operators method overloading
3134 protected virtual Expression
ResolveOperatorPredefined (ResolveContext ec
, PredefinedOperator
[] operators
, bool primitives_only
, TypeSpec enum_type
)
3136 PredefinedOperator best_operator
= null;
3137 TypeSpec l
= left
.Type
;
3138 TypeSpec r
= right
.Type
;
3139 Operator oper_mask
= oper
& ~Operator
.ValuesOnlyMask
;
3141 foreach (PredefinedOperator po
in operators
) {
3142 if ((po
.OperatorsMask
& oper_mask
) == 0)
3145 if (primitives_only
) {
3146 if (!po
.IsPrimitiveApplicable (l
, r
))
3149 if (!po
.IsApplicable (ec
, left
, right
))
3153 if (best_operator
== null) {
3155 if (primitives_only
)
3161 best_operator
= po
.ResolveBetterOperator (ec
, best_operator
);
3163 if (best_operator
== null) {
3164 ec
.Report
.Error (34, loc
, "Operator `{0}' is ambiguous on operands of type `{1}' and `{2}'",
3165 OperName (oper
), TypeManager
.CSharpName (l
), TypeManager
.CSharpName (r
));
3172 if (best_operator
== null)
3175 Expression expr
= best_operator
.ConvertResult (ec
, this);
3178 // Optimize &/&& constant expressions with 0 value
3180 if (oper
== Operator
.BitwiseAnd
|| oper
== Operator
.LogicalAnd
) {
3181 Constant rc
= right
as Constant
;
3182 Constant lc
= left
as Constant
;
3183 if ((lc
!= null && lc
.IsDefaultValue
) || (rc
!= null && rc
.IsDefaultValue
)) {
3185 // The result is a constant with side-effect
3187 Constant side_effect
= rc
== null ?
3188 new SideEffectConstant (lc
, right
, loc
) :
3189 new SideEffectConstant (rc
, left
, loc
);
3191 return ReducedExpression
.Create (side_effect
.Resolve (ec
), expr
);
3195 if (enum_type
== null)
3199 // HACK: required by enum_conversion
3201 expr
.Type
= enum_type
;
3202 return EmptyCast
.Create (expr
, enum_type
);
3206 // Performs user-operator overloading
3208 protected virtual Expression
ResolveUserOperator (ResolveContext ec
, TypeSpec l
, TypeSpec r
)
3211 if (oper
== Operator
.LogicalAnd
)
3212 user_oper
= Operator
.BitwiseAnd
;
3213 else if (oper
== Operator
.LogicalOr
)
3214 user_oper
= Operator
.BitwiseOr
;
3218 string op
= GetOperatorMetadataName (user_oper
);
3220 MethodGroupExpr left_operators
= MethodLookup (ec
.Compiler
, ec
.CurrentType
, l
, MemberKind
.Operator
, op
, 0, loc
);
3221 MethodGroupExpr right_operators
= null;
3223 if (!TypeManager
.IsEqual (r
, l
)) {
3224 right_operators
= MethodLookup (ec
.Compiler
, ec
.CurrentType
, r
, MemberKind
.Operator
, op
, 0, loc
);
3225 if (right_operators
== null && left_operators
== null)
3227 } else if (left_operators
== null) {
3231 Arguments args
= new Arguments (2);
3232 Argument larg
= new Argument (left
);
3234 Argument rarg
= new Argument (right
);
3237 MethodGroupExpr union
;
3240 // User-defined operator implementations always take precedence
3241 // over predefined operator implementations
3243 if (left_operators
!= null && right_operators
!= null) {
3244 if (IsPredefinedUserOperator (l
, user_oper
)) {
3245 union
= right_operators
.OverloadResolve (ec
, ref args
, true, loc
);
3247 union
= left_operators
;
3248 } else if (IsPredefinedUserOperator (r
, user_oper
)) {
3249 union
= left_operators
.OverloadResolve (ec
, ref args
, true, loc
);
3251 union
= right_operators
;
3253 union
= MethodGroupExpr
.MakeUnionSet (left_operators
, right_operators
, loc
);
3255 } else if (left_operators
!= null) {
3256 union
= left_operators
;
3258 union
= right_operators
;
3261 union
= union
.OverloadResolve (ec
, ref args
, true, loc
);
3265 Expression oper_expr
;
3267 // TODO: CreateExpressionTree is allocated every time
3268 if (user_oper
!= oper
) {
3269 oper_expr
= new ConditionalLogicalOperator (union
, args
, CreateExpressionTree
,
3270 oper
== Operator
.LogicalAnd
, loc
).Resolve (ec
);
3272 oper_expr
= new UserOperatorCall (union
, args
, CreateExpressionTree
, loc
);
3275 // This is used to check if a test 'x == null' can be optimized to a reference equals,
3276 // and not invoke user operator
3278 if ((oper
& Operator
.EqualityMask
) != 0) {
3279 if ((left
is NullLiteral
&& IsBuildInEqualityOperator (r
)) ||
3280 (right
is NullLiteral
&& IsBuildInEqualityOperator (l
))) {
3281 type
= TypeManager
.bool_type
;
3282 if (left
is NullLiteral
|| right
is NullLiteral
)
3283 oper_expr
= ReducedExpression
.Create (this, oper_expr
);
3284 } else if (l
!= r
) {
3285 var mi
= union
.BestCandidate
;
3288 // Two System.Delegate(s) are never equal
3290 if (mi
.DeclaringType
== TypeManager
.multicast_delegate_type
)
3301 public override TypeExpr
ResolveAsTypeTerminal (IMemberContext ec
, bool silent
)
3306 private void CheckUselessComparison (ResolveContext ec
, Constant c
, TypeSpec type
)
3308 if (c
== null || !IsTypeIntegral (type
)
3309 || c
is StringConstant
3310 || c
is BoolConstant
3311 || c
is FloatConstant
3312 || c
is DoubleConstant
3313 || c
is DecimalConstant
3319 if (c
is ULongConstant
) {
3320 ulong uvalue
= ((ULongConstant
) c
).Value
;
3321 if (uvalue
> long.MaxValue
) {
3322 if (type
== TypeManager
.byte_type
||
3323 type
== TypeManager
.sbyte_type
||
3324 type
== TypeManager
.short_type
||
3325 type
== TypeManager
.ushort_type
||
3326 type
== TypeManager
.int32_type
||
3327 type
== TypeManager
.uint32_type
||
3328 type
== TypeManager
.int64_type
||
3329 type
== TypeManager
.char_type
)
3330 WarnUselessComparison (ec
, type
);
3333 value = (long) uvalue
;
3335 else if (c
is ByteConstant
)
3336 value = ((ByteConstant
) c
).Value
;
3337 else if (c
is SByteConstant
)
3338 value = ((SByteConstant
) c
).Value
;
3339 else if (c
is ShortConstant
)
3340 value = ((ShortConstant
) c
).Value
;
3341 else if (c
is UShortConstant
)
3342 value = ((UShortConstant
) c
).Value
;
3343 else if (c
is IntConstant
)
3344 value = ((IntConstant
) c
).Value
;
3345 else if (c
is UIntConstant
)
3346 value = ((UIntConstant
) c
).Value
;
3347 else if (c
is LongConstant
)
3348 value = ((LongConstant
) c
).Value
;
3349 else if (c
is CharConstant
)
3350 value = ((CharConstant
)c
).Value
;
3355 if (IsValueOutOfRange (value, type
))
3356 WarnUselessComparison (ec
, type
);
3359 static bool IsValueOutOfRange (long value, TypeSpec type
)
3361 if (IsTypeUnsigned (type
) && value < 0)
3363 return type
== TypeManager
.sbyte_type
&& (value >= 0x80 || value < -0x80) ||
3364 type
== TypeManager
.byte_type
&& value >= 0x100 ||
3365 type
== TypeManager
.short_type
&& (value >= 0x8000 || value < -0x8000) ||
3366 type
== TypeManager
.ushort_type
&& value >= 0x10000 ||
3367 type
== TypeManager
.int32_type
&& (value >= 0x80000000 || value < -0x80000000) ||
3368 type
== TypeManager
.uint32_type
&& value >= 0x100000000;
3371 static bool IsBuildInEqualityOperator (TypeSpec t
)
3373 return t
== TypeManager
.object_type
|| t
== TypeManager
.string_type
||
3374 t
== TypeManager
.delegate_type
|| TypeManager
.IsDelegateType (t
);
3377 static bool IsPredefinedUserOperator (TypeSpec t
, Operator op
)
3380 // Some predefined types have user operators
3382 return (op
& Operator
.EqualityMask
) != 0 && (t
== TypeManager
.string_type
|| t
== TypeManager
.decimal_type
);
3385 private static bool IsTypeIntegral (TypeSpec type
)
3387 return type
== TypeManager
.uint64_type
||
3388 type
== TypeManager
.int64_type
||
3389 type
== TypeManager
.uint32_type
||
3390 type
== TypeManager
.int32_type
||
3391 type
== TypeManager
.ushort_type
||
3392 type
== TypeManager
.short_type
||
3393 type
== TypeManager
.sbyte_type
||
3394 type
== TypeManager
.byte_type
||
3395 type
== TypeManager
.char_type
;
3398 private static bool IsTypeUnsigned (TypeSpec type
)
3400 return type
== TypeManager
.uint64_type
||
3401 type
== TypeManager
.uint32_type
||
3402 type
== TypeManager
.ushort_type
||
3403 type
== TypeManager
.byte_type
||
3404 type
== TypeManager
.char_type
;
3407 private void WarnUselessComparison (ResolveContext ec
, TypeSpec type
)
3409 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}'",
3410 TypeManager
.CSharpName (type
));
3414 /// EmitBranchable is called from Statement.EmitBoolExpression in the
3415 /// context of a conditional bool expression. This function will return
3416 /// false if it is was possible to use EmitBranchable, or true if it was.
3418 /// The expression's code is generated, and we will generate a branch to `target'
3419 /// if the resulting expression value is equal to isTrue
3421 public override void EmitBranchable (EmitContext ec
, Label target
, bool on_true
)
3424 // This is more complicated than it looks, but its just to avoid
3425 // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
3426 // but on top of that we want for == and != to use a special path
3427 // if we are comparing against null
3429 if ((oper
& Operator
.EqualityMask
) != 0 && (left
is Constant
|| right
is Constant
)) {
3430 bool my_on_true
= oper
== Operator
.Inequality
? on_true
: !on_true
;
3433 // put the constant on the rhs, for simplicity
3435 if (left
is Constant
) {
3436 Expression swap
= right
;
3442 // brtrue/brfalse works with native int only
3444 if (((Constant
) right
).IsZeroInteger
&& right
.Type
!= TypeManager
.int64_type
&& right
.Type
!= TypeManager
.uint64_type
) {
3445 left
.EmitBranchable (ec
, target
, my_on_true
);
3448 if (right
.Type
== TypeManager
.bool_type
) {
3449 // right is a boolean, and it's not 'false' => it is 'true'
3450 left
.EmitBranchable (ec
, target
, !my_on_true
);
3454 } else if (oper
== Operator
.LogicalAnd
) {
3457 Label tests_end
= ec
.DefineLabel ();
3459 left
.EmitBranchable (ec
, tests_end
, false);
3460 right
.EmitBranchable (ec
, target
, true);
3461 ec
.MarkLabel (tests_end
);
3464 // This optimizes code like this
3465 // if (true && i > 4)
3467 if (!(left
is Constant
))
3468 left
.EmitBranchable (ec
, target
, false);
3470 if (!(right
is Constant
))
3471 right
.EmitBranchable (ec
, target
, false);
3476 } else if (oper
== Operator
.LogicalOr
){
3478 left
.EmitBranchable (ec
, target
, true);
3479 right
.EmitBranchable (ec
, target
, true);
3482 Label tests_end
= ec
.DefineLabel ();
3483 left
.EmitBranchable (ec
, tests_end
, true);
3484 right
.EmitBranchable (ec
, target
, false);
3485 ec
.MarkLabel (tests_end
);
3490 } else if ((oper
& Operator
.ComparisonMask
) == 0) {
3491 base.EmitBranchable (ec
, target
, on_true
);
3498 TypeSpec t
= left
.Type
;
3499 bool is_float
= IsFloat (t
);
3500 bool is_unsigned
= is_float
|| IsUnsigned (t
);
3503 case Operator
.Equality
:
3505 ec
.Emit (OpCodes
.Beq
, target
);
3507 ec
.Emit (OpCodes
.Bne_Un
, target
);
3510 case Operator
.Inequality
:
3512 ec
.Emit (OpCodes
.Bne_Un
, target
);
3514 ec
.Emit (OpCodes
.Beq
, target
);
3517 case Operator
.LessThan
:
3519 if (is_unsigned
&& !is_float
)
3520 ec
.Emit (OpCodes
.Blt_Un
, target
);
3522 ec
.Emit (OpCodes
.Blt
, target
);
3525 ec
.Emit (OpCodes
.Bge_Un
, target
);
3527 ec
.Emit (OpCodes
.Bge
, target
);
3530 case Operator
.GreaterThan
:
3532 if (is_unsigned
&& !is_float
)
3533 ec
.Emit (OpCodes
.Bgt_Un
, target
);
3535 ec
.Emit (OpCodes
.Bgt
, target
);
3538 ec
.Emit (OpCodes
.Ble_Un
, target
);
3540 ec
.Emit (OpCodes
.Ble
, target
);
3543 case Operator
.LessThanOrEqual
:
3545 if (is_unsigned
&& !is_float
)
3546 ec
.Emit (OpCodes
.Ble_Un
, target
);
3548 ec
.Emit (OpCodes
.Ble
, target
);
3551 ec
.Emit (OpCodes
.Bgt_Un
, target
);
3553 ec
.Emit (OpCodes
.Bgt
, target
);
3557 case Operator
.GreaterThanOrEqual
:
3559 if (is_unsigned
&& !is_float
)
3560 ec
.Emit (OpCodes
.Bge_Un
, target
);
3562 ec
.Emit (OpCodes
.Bge
, target
);
3565 ec
.Emit (OpCodes
.Blt_Un
, target
);
3567 ec
.Emit (OpCodes
.Blt
, target
);
3570 throw new InternalErrorException (oper
.ToString ());
3574 public override void Emit (EmitContext ec
)
3576 EmitOperator (ec
, left
.Type
);
3579 protected virtual void EmitOperator (EmitContext ec
, TypeSpec l
)
3582 // Handle short-circuit operators differently
3585 if ((oper
& Operator
.LogicalMask
) != 0) {
3586 Label load_result
= ec
.DefineLabel ();
3587 Label end
= ec
.DefineLabel ();
3589 bool is_or
= oper
== Operator
.LogicalOr
;
3590 left
.EmitBranchable (ec
, load_result
, is_or
);
3592 ec
.Emit (OpCodes
.Br_S
, end
);
3594 ec
.MarkLabel (load_result
);
3595 ec
.Emit (is_or
? OpCodes
.Ldc_I4_1
: OpCodes
.Ldc_I4_0
);
3601 // Optimize zero-based operations which cannot be optimized at expression level
3603 if (oper
== Operator
.Subtraction
) {
3604 var lc
= left
as IntegralConstant
;
3605 if (lc
!= null && lc
.IsDefaultValue
) {
3607 ec
.Emit (OpCodes
.Neg
);
3614 EmitOperatorOpcode (ec
, oper
, l
);
3617 // Nullable enum could require underlying type cast and we cannot simply wrap binary
3618 // expression because that would wrap lifted binary operation
3620 if (enum_conversion
!= null)
3621 enum_conversion
.Emit (ec
);
3624 public override void EmitSideEffect (EmitContext ec
)
3626 if ((oper
& Operator
.LogicalMask
) != 0 ||
3627 (ec
.HasSet (EmitContext
.Options
.CheckedScope
) && (oper
== Operator
.Multiply
|| oper
== Operator
.Addition
|| oper
== Operator
.Subtraction
))) {
3628 base.EmitSideEffect (ec
);
3630 left
.EmitSideEffect (ec
);
3631 right
.EmitSideEffect (ec
);
3635 protected override void CloneTo (CloneContext clonectx
, Expression t
)
3637 Binary target
= (Binary
) t
;
3639 target
.left
= left
.Clone (clonectx
);
3640 target
.right
= right
.Clone (clonectx
);
3643 public Expression
CreateCallSiteBinder (ResolveContext ec
, Arguments args
)
3645 Arguments binder_args
= new Arguments (4);
3647 MemberAccess sle
= new MemberAccess (new MemberAccess (
3648 new QualifiedAliasMember (QualifiedAliasMember
.GlobalAlias
, "System", loc
), "Linq", loc
), "Expressions", loc
);
3650 CSharpBinderFlags flags
= 0;
3651 if (ec
.HasSet (ResolveContext
.Options
.CheckedScope
))
3652 flags
= CSharpBinderFlags
.CheckedContext
;
3654 if ((oper
& Operator
.LogicalMask
) != 0)
3655 flags
|= CSharpBinderFlags
.BinaryOperationLogical
;
3657 binder_args
.Add (new Argument (new EnumConstant (new IntLiteral ((int) flags
, loc
), TypeManager
.binder_flags
)));
3658 binder_args
.Add (new Argument (new MemberAccess (new MemberAccess (sle
, "ExpressionType", loc
), GetOperatorExpressionTypeName (), loc
)));
3659 binder_args
.Add (new Argument (new TypeOf (new TypeExpression (ec
.CurrentType
, loc
), loc
)));
3660 binder_args
.Add (new Argument (new ImplicitlyTypedArrayCreation ("[]", args
.CreateDynamicBinderArguments (ec
), loc
)));
3662 return new Invocation (DynamicExpressionStatement
.GetBinder ("BinaryOperation", loc
), binder_args
);
3665 public override Expression
CreateExpressionTree (ResolveContext ec
)
3667 return CreateExpressionTree (ec
, null);
3670 Expression
CreateExpressionTree (ResolveContext ec
, MethodGroupExpr method
)
3673 bool lift_arg
= false;
3676 case Operator
.Addition
:
3677 if (method
== null && ec
.HasSet (ResolveContext
.Options
.CheckedScope
) && !IsFloat (type
))
3678 method_name
= "AddChecked";
3680 method_name
= "Add";
3682 case Operator
.BitwiseAnd
:
3683 method_name
= "And";
3685 case Operator
.BitwiseOr
:
3688 case Operator
.Division
:
3689 method_name
= "Divide";
3691 case Operator
.Equality
:
3692 method_name
= "Equal";
3695 case Operator
.ExclusiveOr
:
3696 method_name
= "ExclusiveOr";
3698 case Operator
.GreaterThan
:
3699 method_name
= "GreaterThan";
3702 case Operator
.GreaterThanOrEqual
:
3703 method_name
= "GreaterThanOrEqual";
3706 case Operator
.Inequality
:
3707 method_name
= "NotEqual";
3710 case Operator
.LeftShift
:
3711 method_name
= "LeftShift";
3713 case Operator
.LessThan
:
3714 method_name
= "LessThan";
3717 case Operator
.LessThanOrEqual
:
3718 method_name
= "LessThanOrEqual";
3721 case Operator
.LogicalAnd
:
3722 method_name
= "AndAlso";
3724 case Operator
.LogicalOr
:
3725 method_name
= "OrElse";
3727 case Operator
.Modulus
:
3728 method_name
= "Modulo";
3730 case Operator
.Multiply
:
3731 if (method
== null && ec
.HasSet (ResolveContext
.Options
.CheckedScope
) && !IsFloat (type
))
3732 method_name
= "MultiplyChecked";
3734 method_name
= "Multiply";
3736 case Operator
.RightShift
:
3737 method_name
= "RightShift";
3739 case Operator
.Subtraction
:
3740 if (method
== null && ec
.HasSet (ResolveContext
.Options
.CheckedScope
) && !IsFloat (type
))
3741 method_name
= "SubtractChecked";
3743 method_name
= "Subtract";
3747 throw new InternalErrorException ("Unknown expression tree binary operator " + oper
);
3750 Arguments args
= new Arguments (2);
3751 args
.Add (new Argument (left
.CreateExpressionTree (ec
)));
3752 args
.Add (new Argument (right
.CreateExpressionTree (ec
)));
3753 if (method
!= null) {
3755 args
.Add (new Argument (new BoolConstant (false, loc
)));
3757 args
.Add (new Argument (method
.CreateExpressionTree (ec
)));
3760 return CreateExpressionFactoryCall (ec
, method_name
, args
);
3765 // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
3766 // b, c, d... may be strings or objects.
3768 public class StringConcat
: Expression
{
3769 Arguments arguments
;
3771 public StringConcat (Expression left
, Expression right
, Location loc
)
3774 type
= TypeManager
.string_type
;
3775 eclass
= ExprClass
.Value
;
3777 arguments
= new Arguments (2);
3780 public static StringConcat
Create (ResolveContext rc
, Expression left
, Expression right
, Location loc
)
3782 if (left
.eclass
== ExprClass
.Unresolved
|| right
.eclass
== ExprClass
.Unresolved
)
3783 throw new ArgumentException ();
3785 var s
= new StringConcat (left
, right
, loc
);
3786 s
.Append (rc
, left
);
3787 s
.Append (rc
, right
);
3791 public override Expression
CreateExpressionTree (ResolveContext ec
)
3793 Argument arg
= arguments
[0];
3794 return CreateExpressionAddCall (ec
, arg
, arg
.CreateExpressionTree (ec
), 1);
3798 // Creates nested calls tree from an array of arguments used for IL emit
3800 Expression
CreateExpressionAddCall (ResolveContext ec
, Argument left
, Expression left_etree
, int pos
)
3802 Arguments concat_args
= new Arguments (2);
3803 Arguments add_args
= new Arguments (3);
3805 concat_args
.Add (left
);
3806 add_args
.Add (new Argument (left_etree
));
3808 concat_args
.Add (arguments
[pos
]);
3809 add_args
.Add (new Argument (arguments
[pos
].CreateExpressionTree (ec
)));
3811 MethodGroupExpr method
= CreateConcatMemberExpression ().Resolve (ec
) as MethodGroupExpr
;
3815 method
= method
.OverloadResolve (ec
, ref concat_args
, false, loc
);
3819 add_args
.Add (new Argument (method
.CreateExpressionTree (ec
)));
3821 Expression expr
= CreateExpressionFactoryCall (ec
, "Add", add_args
);
3822 if (++pos
== arguments
.Count
)
3825 left
= new Argument (new EmptyExpression (method
.BestCandidate
.ReturnType
));
3826 return CreateExpressionAddCall (ec
, left
, expr
, pos
);
3829 protected override Expression
DoResolve (ResolveContext ec
)
3834 void Append (ResolveContext rc
, Expression operand
)
3839 StringConstant sc
= operand
as StringConstant
;
3841 if (arguments
.Count
!= 0) {
3842 Argument last_argument
= arguments
[arguments
.Count
- 1];
3843 StringConstant last_expr_constant
= last_argument
.Expr
as StringConstant
;
3844 if (last_expr_constant
!= null) {
3845 last_argument
.Expr
= new StringConstant (
3846 last_expr_constant
.Value
+ sc
.Value
, sc
.Location
).Resolve (rc
);
3852 // Multiple (3+) concatenation are resolved as multiple StringConcat instances
3854 StringConcat concat_oper
= operand
as StringConcat
;
3855 if (concat_oper
!= null) {
3856 arguments
.AddRange (concat_oper
.arguments
);
3861 arguments
.Add (new Argument (operand
));
3864 Expression
CreateConcatMemberExpression ()
3866 return new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc
), "String", loc
), "Concat", loc
);
3869 public override void Emit (EmitContext ec
)
3871 Expression concat
= new Invocation (CreateConcatMemberExpression (), arguments
, true);
3872 concat
= concat
.Resolve (new ResolveContext (ec
.MemberContext
));
3877 public override SLE
.Expression
MakeExpression (BuilderContext ctx
)
3879 if (arguments
.Count
!= 2)
3880 throw new NotImplementedException ("arguments.Count != 2");
3882 var concat
= typeof (string).GetMethod ("Concat", new[] { typeof (object), typeof (object) }
);
3883 return SLE
.Expression
.Add (arguments
[0].Expr
.MakeExpression (ctx
), arguments
[1].Expr
.MakeExpression (ctx
), concat
);
3888 // User-defined conditional logical operator
3890 public class ConditionalLogicalOperator
: UserOperatorCall
{
3891 readonly bool is_and
;
3894 public ConditionalLogicalOperator (MethodGroupExpr oper_method
, Arguments arguments
,
3895 ExpressionTreeExpression expr_tree
, bool is_and
, Location loc
)
3896 : base (oper_method
, arguments
, expr_tree
, loc
)
3898 this.is_and
= is_and
;
3899 eclass
= ExprClass
.Unresolved
;
3902 protected override Expression
DoResolve (ResolveContext ec
)
3904 var method
= mg
.BestCandidate
;
3905 type
= method
.ReturnType
;
3906 AParametersCollection pd
= method
.Parameters
;
3907 if (!TypeManager
.IsEqual (type
, type
) || !TypeManager
.IsEqual (type
, pd
.Types
[0]) || !TypeManager
.IsEqual (type
, pd
.Types
[1])) {
3908 ec
.Report
.Error (217, loc
,
3909 "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",
3910 TypeManager
.CSharpSignature (method
));
3914 Expression left_dup
= new EmptyExpression (type
);
3915 Expression op_true
= GetOperatorTrue (ec
, left_dup
, loc
);
3916 Expression op_false
= GetOperatorFalse (ec
, left_dup
, loc
);
3917 if (op_true
== null || op_false
== null) {
3918 ec
.Report
.Error (218, loc
,
3919 "The type `{0}' must have operator `true' and operator `false' defined when `{1}' is used as a short circuit operator",
3920 TypeManager
.CSharpName (type
), TypeManager
.CSharpSignature (method
));
3924 oper
= is_and
? op_false
: op_true
;
3925 eclass
= ExprClass
.Value
;
3929 public override void Emit (EmitContext ec
)
3931 Label end_target
= ec
.DefineLabel ();
3934 // Emit and duplicate left argument
3936 arguments
[0].Expr
.Emit (ec
);
3937 ec
.Emit (OpCodes
.Dup
);
3938 arguments
.RemoveAt (0);
3940 oper
.EmitBranchable (ec
, end_target
, true);
3942 ec
.MarkLabel (end_target
);
3946 public class PointerArithmetic
: Expression
{
3947 Expression left
, right
;
3951 // We assume that `l' is always a pointer
3953 public PointerArithmetic (Binary
.Operator op
, Expression l
, Expression r
, TypeSpec t
, Location loc
)
3962 public override Expression
CreateExpressionTree (ResolveContext ec
)
3964 Error_PointerInsideExpressionTree (ec
);
3968 protected override Expression
DoResolve (ResolveContext ec
)
3970 eclass
= ExprClass
.Variable
;
3972 if (left
.Type
== TypeManager
.void_ptr_type
) {
3973 ec
.Report
.Error (242, loc
, "The operation in question is undefined on void pointers");
3980 public override void Emit (EmitContext ec
)
3982 TypeSpec op_type
= left
.Type
;
3984 // It must be either array or fixed buffer
3986 if (TypeManager
.HasElementType (op_type
)) {
3987 element
= TypeManager
.GetElementType (op_type
);
3989 FieldExpr fe
= left
as FieldExpr
;
3991 element
= ((FixedFieldSpec
) (fe
.Spec
)).ElementType
;
3996 int size
= GetTypeSize (element
);
3997 TypeSpec rtype
= right
.Type
;
3999 if ((op
& Binary
.Operator
.SubtractionMask
) != 0 && rtype
.IsPointer
){
4001 // handle (pointer - pointer)
4005 ec
.Emit (OpCodes
.Sub
);
4009 ec
.Emit (OpCodes
.Sizeof
, element
);
4012 ec
.Emit (OpCodes
.Div
);
4014 ec
.Emit (OpCodes
.Conv_I8
);
4017 // handle + and - on (pointer op int)
4019 Constant left_const
= left
as Constant
;
4020 if (left_const
!= null) {
4022 // Optimize ((T*)null) pointer operations
4024 if (left_const
.IsDefaultValue
) {
4025 left
= EmptyExpression
.Null
;
4033 var right_const
= right
as Constant
;
4034 if (right_const
!= null) {
4036 // Optimize 0-based arithmetic
4038 if (right_const
.IsDefaultValue
)
4042 right
= new IntConstant (size
, right
.Location
);
4044 right
= new SizeOf (new TypeExpression (element
, right
.Location
), right
.Location
);
4046 // TODO: Should be the checks resolve context sensitive?
4047 ResolveContext rc
= new ResolveContext (ec
.MemberContext
, ResolveContext
.Options
.UnsafeScope
);
4048 right
= new Binary (Binary
.Operator
.Multiply
, right
, right_const
, loc
).Resolve (rc
);
4054 if (rtype
== TypeManager
.sbyte_type
|| rtype
== TypeManager
.byte_type
||
4055 rtype
== TypeManager
.short_type
|| rtype
== TypeManager
.ushort_type
) {
4056 ec
.Emit (OpCodes
.Conv_I
);
4057 } else if (rtype
== TypeManager
.uint32_type
) {
4058 ec
.Emit (OpCodes
.Conv_U
);
4061 if (right_const
== null && size
!= 1){
4063 ec
.Emit (OpCodes
.Sizeof
, element
);
4066 if (rtype
== TypeManager
.int64_type
|| rtype
== TypeManager
.uint64_type
)
4067 ec
.Emit (OpCodes
.Conv_I8
);
4069 Binary
.EmitOperatorOpcode (ec
, Binary
.Operator
.Multiply
, rtype
);
4072 if (left_const
== null) {
4073 if (rtype
== TypeManager
.int64_type
)
4074 ec
.Emit (OpCodes
.Conv_I
);
4075 else if (rtype
== TypeManager
.uint64_type
)
4076 ec
.Emit (OpCodes
.Conv_U
);
4078 Binary
.EmitOperatorOpcode (ec
, op
, op_type
);
4085 // A boolean-expression is an expression that yields a result
4088 public class BooleanExpression
: ShimExpression
4090 public BooleanExpression (Expression expr
)
4093 this.loc
= expr
.Location
;
4096 public override Expression
CreateExpressionTree (ResolveContext ec
)
4098 // TODO: We should emit IsTrue (v4) instead of direct user operator
4099 // call but that would break csc compatibility
4100 return base.CreateExpressionTree (ec
);
4103 protected override Expression
DoResolve (ResolveContext ec
)
4105 // A boolean-expression is required to be of a type
4106 // that can be implicitly converted to bool or of
4107 // a type that implements operator true
4109 expr
= expr
.Resolve (ec
);
4113 Assign ass
= expr
as Assign
;
4114 if (ass
!= null && ass
.Source
is Constant
) {
4115 ec
.Report
.Warning (665, 3, loc
,
4116 "Assignment in conditional expression is always constant. Did you mean to use `==' instead ?");
4119 if (expr
.Type
== TypeManager
.bool_type
)
4122 if (expr
.Type
== InternalType
.Dynamic
) {
4123 Arguments args
= new Arguments (1);
4124 args
.Add (new Argument (expr
));
4125 return new DynamicUnaryConversion ("IsTrue", args
, loc
).Resolve (ec
);
4128 type
= TypeManager
.bool_type
;
4129 Expression converted
= Convert
.ImplicitConversion (ec
, expr
, type
, loc
);
4130 if (converted
!= null)
4134 // If no implicit conversion to bool exists, try using `operator true'
4136 converted
= GetOperatorTrue (ec
, expr
, loc
);
4137 if (converted
== null) {
4138 expr
.Error_ValueCannotBeConverted (ec
, loc
, type
, false);
4147 /// Implements the ternary conditional operator (?:)
4149 public class Conditional
: Expression
{
4150 Expression expr
, true_expr
, false_expr
;
4152 public Conditional (BooleanExpression expr
, Expression true_expr
, Expression false_expr
)
4155 this.true_expr
= true_expr
;
4156 this.false_expr
= false_expr
;
4157 this.loc
= expr
.Location
;
4160 public Expression Expr
{
4166 public Expression TrueExpr
{
4172 public Expression FalseExpr
{
4178 public override Expression
CreateExpressionTree (ResolveContext ec
)
4180 Arguments args
= new Arguments (3);
4181 args
.Add (new Argument (expr
.CreateExpressionTree (ec
)));
4182 args
.Add (new Argument (true_expr
.CreateExpressionTree (ec
)));
4183 args
.Add (new Argument (false_expr
.CreateExpressionTree (ec
)));
4184 return CreateExpressionFactoryCall (ec
, "Condition", args
);
4187 protected override Expression
DoResolve (ResolveContext ec
)
4189 expr
= expr
.Resolve (ec
);
4190 true_expr
= true_expr
.Resolve (ec
);
4191 false_expr
= false_expr
.Resolve (ec
);
4193 if (true_expr
== null || false_expr
== null || expr
== null)
4196 eclass
= ExprClass
.Value
;
4197 TypeSpec true_type
= true_expr
.Type
;
4198 TypeSpec false_type
= false_expr
.Type
;
4202 // First, if an implicit conversion exists from true_expr
4203 // to false_expr, then the result type is of type false_expr.Type
4205 if (!TypeManager
.IsEqual (true_type
, false_type
)) {
4206 Expression conv
= Convert
.ImplicitConversion (ec
, true_expr
, false_type
, loc
);
4209 // Check if both can convert implicitly to each other's type
4211 if (Convert
.ImplicitConversion (ec
, false_expr
, true_type
, loc
) != null) {
4212 ec
.Report
.Error (172, true_expr
.Location
,
4213 "Type of conditional expression cannot be determined as `{0}' and `{1}' convert implicitly to each other",
4214 TypeManager
.CSharpName (true_type
), TypeManager
.CSharpName (false_type
));
4219 } else if ((conv
= Convert
.ImplicitConversion (ec
, false_expr
, true_type
, loc
)) != null) {
4222 ec
.Report
.Error (173, true_expr
.Location
,
4223 "Type of conditional expression cannot be determined because there is no implicit conversion between `{0}' and `{1}'",
4224 TypeManager
.CSharpName (true_type
), TypeManager
.CSharpName (false_type
));
4229 // Dead code optimalization
4230 Constant c
= expr
as Constant
;
4232 bool is_false
= c
.IsDefaultValue
;
4233 ec
.Report
.Warning (429, 4, is_false
? true_expr
.Location
: false_expr
.Location
, "Unreachable expression code detected");
4234 return ReducedExpression
.Create (is_false
? false_expr
: true_expr
, this).Resolve (ec
);
4240 public override TypeExpr
ResolveAsTypeTerminal (IMemberContext ec
, bool silent
)
4245 public override void Emit (EmitContext ec
)
4247 Label false_target
= ec
.DefineLabel ();
4248 Label end_target
= ec
.DefineLabel ();
4250 expr
.EmitBranchable (ec
, false_target
, false);
4251 true_expr
.Emit (ec
);
4253 if (type
.IsInterface
) {
4254 LocalBuilder temp
= ec
.GetTemporaryLocal (type
);
4255 ec
.Emit (OpCodes
.Stloc
, temp
);
4256 ec
.Emit (OpCodes
.Ldloc
, temp
);
4257 ec
.FreeTemporaryLocal (temp
, type
);
4260 ec
.Emit (OpCodes
.Br
, end_target
);
4261 ec
.MarkLabel (false_target
);
4262 false_expr
.Emit (ec
);
4263 ec
.MarkLabel (end_target
);
4266 protected override void CloneTo (CloneContext clonectx
, Expression t
)
4268 Conditional target
= (Conditional
) t
;
4270 target
.expr
= expr
.Clone (clonectx
);
4271 target
.true_expr
= true_expr
.Clone (clonectx
);
4272 target
.false_expr
= false_expr
.Clone (clonectx
);
4276 public abstract class VariableReference
: Expression
, IAssignMethod
, IMemoryLocation
, IVariableReference
{
4277 LocalTemporary temp
;
4280 public abstract HoistedVariable
GetHoistedVariable (AnonymousExpression ae
);
4281 public abstract bool IsFixed { get; }
4282 public abstract bool IsRef { get; }
4283 public abstract string Name { get; }
4284 public abstract void SetHasAddressTaken ();
4287 // Variable IL data, it has to be protected to encapsulate hoisted variables
4289 protected abstract ILocalVariable Variable { get; }
4292 // Variable flow-analysis data
4294 public abstract VariableInfo VariableInfo { get; }
4297 public virtual void AddressOf (EmitContext ec
, AddressOp mode
)
4299 HoistedVariable hv
= GetHoistedVariable (ec
);
4301 hv
.AddressOf (ec
, mode
);
4305 Variable
.EmitAddressOf (ec
);
4308 public HoistedVariable
GetHoistedVariable (ResolveContext rc
)
4310 return GetHoistedVariable (rc
.CurrentAnonymousMethod
);
4313 public HoistedVariable
GetHoistedVariable (EmitContext ec
)
4315 return GetHoistedVariable (ec
.CurrentAnonymousMethod
);
4318 public override string GetSignatureForError ()
4323 public override void Emit (EmitContext ec
)
4328 public override void EmitSideEffect (EmitContext ec
)
4334 // This method is used by parameters that are references, that are
4335 // being passed as references: we only want to pass the pointer (that
4336 // is already stored in the parameter, not the address of the pointer,
4337 // and not the value of the variable).
4339 public void EmitLoad (EmitContext ec
)
4344 public void Emit (EmitContext ec
, bool leave_copy
)
4346 Report
.Debug (64, "VARIABLE EMIT", this, Variable
, type
, IsRef
, loc
);
4348 HoistedVariable hv
= GetHoistedVariable (ec
);
4350 hv
.Emit (ec
, leave_copy
);
4358 // If we are a reference, we loaded on the stack a pointer
4359 // Now lets load the real value
4361 ec
.EmitLoadFromPtr (type
);
4365 ec
.Emit (OpCodes
.Dup
);
4368 temp
= new LocalTemporary (Type
);
4374 public void EmitAssign (EmitContext ec
, Expression source
, bool leave_copy
,
4375 bool prepare_for_load
)
4377 HoistedVariable hv
= GetHoistedVariable (ec
);
4379 hv
.EmitAssign (ec
, source
, leave_copy
, prepare_for_load
);
4383 New n_source
= source
as New
;
4384 if (n_source
!= null) {
4385 if (!n_source
.Emit (ec
, this)) {
4398 ec
.Emit (OpCodes
.Dup
);
4400 temp
= new LocalTemporary (Type
);
4406 ec
.EmitStoreFromPtr (type
);
4408 Variable
.EmitAssign (ec
);
4416 public bool IsHoisted
{
4417 get { return GetHoistedVariable ((AnonymousExpression) null) != null; }
4424 public class LocalVariableReference
: VariableReference
{
4425 readonly string name
;
4427 public LocalInfo local_info
;
4430 public LocalVariableReference (Block block
, string name
, Location l
)
4438 // Setting `is_readonly' to false will allow you to create a writable
4439 // reference to a read-only variable. This is used by foreach and using.
4441 public LocalVariableReference (Block block
, string name
, Location l
,
4442 LocalInfo local_info
, bool is_readonly
)
4443 : this (block
, name
, l
)
4445 this.local_info
= local_info
;
4446 this.is_readonly
= is_readonly
;
4449 public override VariableInfo VariableInfo
{
4450 get { return local_info.VariableInfo; }
4453 public override HoistedVariable
GetHoistedVariable (AnonymousExpression ae
)
4455 return local_info
.HoistedVariant
;
4459 // A local variable is always fixed
4461 public override bool IsFixed
{
4462 get { return true; }
4465 public override bool IsRef
{
4466 get { return false; }
4469 public bool IsReadOnly
{
4470 get { return is_readonly; }
4473 public override string Name
{
4474 get { return name; }
4477 public bool VerifyAssigned (ResolveContext ec
)
4479 VariableInfo variable_info
= local_info
.VariableInfo
;
4480 return variable_info
== null || variable_info
.IsAssigned (ec
, loc
);
4483 void ResolveLocalInfo ()
4485 if (local_info
== null) {
4486 local_info
= Block
.GetLocalInfo (Name
);
4487 type
= local_info
.VariableType
;
4488 is_readonly
= local_info
.ReadOnly
;
4492 public override void SetHasAddressTaken ()
4494 local_info
.AddressTaken
= true;
4497 public override Expression
CreateExpressionTree (ResolveContext ec
)
4499 HoistedVariable hv
= GetHoistedVariable (ec
);
4501 return hv
.CreateExpressionTree ();
4503 Arguments arg
= new Arguments (1);
4504 arg
.Add (new Argument (this));
4505 return CreateExpressionFactoryCall (ec
, "Constant", arg
);
4508 Expression
DoResolveBase (ResolveContext ec
)
4510 Expression e
= Block
.GetConstantExpression (Name
);
4512 return e
.Resolve (ec
);
4514 VerifyAssigned (ec
);
4517 // If we are referencing a variable from the external block
4518 // flag it for capturing
4520 if (ec
.MustCaptureVariable (local_info
)) {
4521 if (local_info
.AddressTaken
)
4522 AnonymousMethodExpression
.Error_AddressOfCapturedVar (ec
, this, loc
);
4524 if (ec
.IsVariableCapturingRequired
) {
4525 AnonymousMethodStorey storey
= local_info
.Block
.Explicit
.CreateAnonymousMethodStorey (ec
);
4526 storey
.CaptureLocalVariable (ec
, local_info
);
4530 eclass
= ExprClass
.Variable
;
4531 type
= local_info
.VariableType
;
4535 protected override Expression
DoResolve (ResolveContext ec
)
4537 ResolveLocalInfo ();
4538 local_info
.Used
= true;
4540 if (type
== null && local_info
.Type
is VarExpr
) {
4541 local_info
.VariableType
= TypeManager
.object_type
;
4542 Error_VariableIsUsedBeforeItIsDeclared (ec
.Report
, Name
);
4546 return DoResolveBase (ec
);
4549 public override Expression
DoResolveLValue (ResolveContext ec
, Expression right_side
)
4551 ResolveLocalInfo ();
4554 if (right_side
== EmptyExpression
.OutAccess
.Instance
)
4555 local_info
.Used
= true;
4557 // Infer implicitly typed local variable
4559 VarExpr ve
= local_info
.Type
as VarExpr
;
4561 if (!ve
.InferType (ec
, right_side
))
4563 type
= local_info
.VariableType
= ve
.Type
;
4570 if (right_side
== EmptyExpression
.OutAccess
.Instance
) {
4571 code
= 1657; msg
= "Cannot pass `{0}' as a ref or out argument because it is a `{1}'";
4572 } else if (right_side
== EmptyExpression
.LValueMemberAccess
) {
4573 code
= 1654; msg
= "Cannot assign to members of `{0}' because it is a `{1}'";
4574 } else if (right_side
== EmptyExpression
.LValueMemberOutAccess
) {
4575 code
= 1655; msg
= "Cannot pass members of `{0}' as ref or out arguments because it is a `{1}'";
4576 } else if (right_side
== EmptyExpression
.UnaryAddress
) {
4577 code
= 459; msg
= "Cannot take the address of {1} `{0}'";
4579 code
= 1656; msg
= "Cannot assign to `{0}' because it is a `{1}'";
4581 ec
.Report
.Error (code
, loc
, msg
, Name
, local_info
.GetReadOnlyContext ());
4582 } else if (VariableInfo
!= null) {
4583 VariableInfo
.SetAssigned (ec
);
4586 return DoResolveBase (ec
);
4589 public override int GetHashCode ()
4591 return Name
.GetHashCode ();
4594 public override bool Equals (object obj
)
4596 LocalVariableReference lvr
= obj
as LocalVariableReference
;
4600 return Name
== lvr
.Name
&& Block
== lvr
.Block
;
4603 protected override ILocalVariable Variable
{
4604 get { return local_info; }
4607 public override string ToString ()
4609 return String
.Format ("{0} ({1}:{2})", GetType (), Name
, loc
);
4612 protected override void CloneTo (CloneContext clonectx
, Expression t
)
4614 LocalVariableReference target
= (LocalVariableReference
) t
;
4616 target
.Block
= clonectx
.LookupBlock (Block
);
4617 if (local_info
!= null)
4618 target
.local_info
= clonectx
.LookupVariable (local_info
);
4623 /// This represents a reference to a parameter in the intermediate
4626 public class ParameterReference
: VariableReference
{
4627 readonly ToplevelParameterInfo pi
;
4629 public ParameterReference (ToplevelParameterInfo pi
, Location loc
)
4635 public override bool IsRef
{
4636 get { return (pi.Parameter.ModFlags & Parameter.Modifier.ISBYREF) != 0; }
4639 bool HasOutModifier
{
4640 get { return pi.Parameter.ModFlags == Parameter.Modifier.OUT; }
4643 public override HoistedVariable
GetHoistedVariable (AnonymousExpression ae
)
4645 return pi
.Parameter
.HoistedVariant
;
4649 // A ref or out parameter is classified as a moveable variable, even
4650 // if the argument given for the parameter is a fixed variable
4652 public override bool IsFixed
{
4653 get { return !IsRef; }
4656 public override string Name
{
4657 get { return Parameter.Name; }
4660 public Parameter Parameter
{
4661 get { return pi.Parameter; }
4664 public override VariableInfo VariableInfo
{
4665 get { return pi.VariableInfo; }
4668 protected override ILocalVariable Variable
{
4669 get { return Parameter; }
4672 public bool IsAssigned (ResolveContext ec
, Location loc
)
4674 // HACK: Variables are not captured in probing mode
4675 if (ec
.IsInProbingMode
)
4678 if (!ec
.DoFlowAnalysis
|| !HasOutModifier
|| ec
.CurrentBranching
.IsAssigned (VariableInfo
))
4681 ec
.Report
.Error (269, loc
, "Use of unassigned out parameter `{0}'", Name
);
4685 public override void SetHasAddressTaken ()
4687 Parameter
.HasAddressTaken
= true;
4690 void SetAssigned (ResolveContext ec
)
4692 if (HasOutModifier
&& ec
.DoFlowAnalysis
)
4693 ec
.CurrentBranching
.SetAssigned (VariableInfo
);
4696 bool DoResolveBase (ResolveContext ec
)
4698 type
= pi
.ParameterType
;
4699 eclass
= ExprClass
.Variable
;
4701 AnonymousExpression am
= ec
.CurrentAnonymousMethod
;
4705 Block b
= ec
.CurrentBlock
;
4708 IParameterData
[] p
= b
.Toplevel
.Parameters
.FixedParameters
;
4709 for (int i
= 0; i
< p
.Length
; ++i
) {
4710 if (p
[i
] != Parameter
)
4714 // Don't capture local parameters
4716 if (b
== ec
.CurrentBlock
.Toplevel
&& !am
.IsIterator
)
4720 ec
.Report
.Error (1628, loc
,
4721 "Parameter `{0}' cannot be used inside `{1}' when using `ref' or `out' modifier",
4722 Name
, am
.ContainerType
);
4725 if (pi
.Parameter
.HasAddressTaken
)
4726 AnonymousMethodExpression
.Error_AddressOfCapturedVar (ec
, this, loc
);
4728 if (ec
.IsVariableCapturingRequired
&& !b
.Toplevel
.IsExpressionTree
) {
4729 AnonymousMethodStorey storey
= pi
.Block
.CreateAnonymousMethodStorey (ec
);
4730 storey
.CaptureParameter (ec
, this);
4742 public override int GetHashCode ()
4744 return Name
.GetHashCode ();
4747 public override bool Equals (object obj
)
4749 ParameterReference pr
= obj
as ParameterReference
;
4753 return Name
== pr
.Name
;
4756 public override void AddressOf (EmitContext ec
, AddressOp mode
)
4759 // ParameterReferences might already be a reference
4766 base.AddressOf (ec
, mode
);
4769 protected override void CloneTo (CloneContext clonectx
, Expression target
)
4774 public override Expression
CreateExpressionTree (ResolveContext ec
)
4776 HoistedVariable hv
= GetHoistedVariable (ec
);
4778 return hv
.CreateExpressionTree ();
4780 return Parameter
.ExpressionTreeVariableReference ();
4784 // Notice that for ref/out parameters, the type exposed is not the
4785 // same type exposed externally.
4788 // externally we expose "int&"
4789 // here we expose "int".
4791 // We record this in "is_ref". This means that the type system can treat
4792 // the type as it is expected, but when we generate the code, we generate
4793 // the alternate kind of code.
4795 protected override Expression
DoResolve (ResolveContext ec
)
4797 if (!DoResolveBase (ec
))
4800 // HACK: Variables are not captured in probing mode
4801 if (ec
.IsInProbingMode
)
4804 if (HasOutModifier
&& ec
.DoFlowAnalysis
&&
4805 (!ec
.OmitStructFlowAnalysis
|| !VariableInfo
.TypeInfo
.IsStruct
) && !IsAssigned (ec
, loc
))
4811 override public Expression
DoResolveLValue (ResolveContext ec
, Expression right_side
)
4813 if (!DoResolveBase (ec
))
4820 static public void EmitLdArg (EmitContext ec
, int x
)
4823 case 0: ec
.Emit (OpCodes
.Ldarg_0
); break;
4824 case 1: ec
.Emit (OpCodes
.Ldarg_1
); break;
4825 case 2: ec
.Emit (OpCodes
.Ldarg_2
); break;
4826 case 3: ec
.Emit (OpCodes
.Ldarg_3
); break;
4828 if (x
> byte.MaxValue
)
4829 ec
.Emit (OpCodes
.Ldarg
, x
);
4831 ec
.Emit (OpCodes
.Ldarg_S
, (byte) x
);
4838 /// Invocation of methods or delegates.
4840 public class Invocation
: ExpressionStatement
4842 protected Arguments arguments
;
4843 protected Expression expr
;
4844 protected MethodGroupExpr mg
;
4845 bool arguments_resolved
;
4848 // arguments is an ArrayList, but we do not want to typecast,
4849 // as it might be null.
4851 public Invocation (Expression expr
, Arguments arguments
)
4853 SimpleName sn
= expr
as SimpleName
;
4855 this.expr
= sn
.GetMethodGroup ();
4859 this.arguments
= arguments
;
4861 loc
= expr
.Location
;
4864 public Invocation (Expression expr
, Arguments arguments
, bool arguments_resolved
)
4865 : this (expr
, arguments
)
4867 this.arguments_resolved
= arguments_resolved
;
4870 public override Expression
CreateExpressionTree (ResolveContext ec
)
4872 Expression instance
= mg
.IsInstance
?
4873 mg
.InstanceExpression
.CreateExpressionTree (ec
) :
4874 new NullLiteral (loc
);
4876 var args
= Arguments
.CreateForExpressionTree (ec
, arguments
,
4878 mg
.CreateExpressionTree (ec
));
4881 MemberExpr
.Error_BaseAccessInExpressionTree (ec
, loc
);
4883 return CreateExpressionFactoryCall (ec
, "Call", args
);
4886 protected override Expression
DoResolve (ResolveContext ec
)
4888 Expression member_expr
= expr
.Resolve (ec
, ResolveFlags
.VariableOrValue
| ResolveFlags
.MethodGroup
);
4889 if (member_expr
== null)
4893 // Next, evaluate all the expressions in the argument list
4895 bool dynamic_arg
= false;
4896 if (arguments
!= null && !arguments_resolved
)
4897 arguments
.Resolve (ec
, out dynamic_arg
);
4899 TypeSpec expr_type
= member_expr
.Type
;
4900 mg
= member_expr
as MethodGroupExpr
;
4902 bool dynamic_member
= expr_type
== InternalType
.Dynamic
;
4904 if (!dynamic_member
) {
4905 Expression invoke
= null;
4908 if (expr_type
!= null && TypeManager
.IsDelegateType (expr_type
)) {
4909 invoke
= new DelegateInvocation (member_expr
, arguments
, loc
);
4910 invoke
= invoke
.Resolve (ec
);
4911 if (invoke
== null || !dynamic_arg
)
4914 MemberExpr me
= member_expr
as MemberExpr
;
4916 member_expr
.Error_UnexpectedKind (ec
, ResolveFlags
.MethodGroup
, loc
);
4920 mg
= ec
.LookupExtensionMethod (me
.Type
, me
.Name
, -1, loc
);
4922 ec
.Report
.Error (1955, loc
, "The member `{0}' cannot be used as method or delegate",
4923 member_expr
.GetSignatureForError ());
4927 ((ExtensionMethodGroupExpr
) mg
).ExtensionExpression
= me
.InstanceExpression
;
4931 if (invoke
== null) {
4932 mg
= DoResolveOverload (ec
);
4938 if (dynamic_arg
|| dynamic_member
)
4939 return DoResolveDynamic (ec
, member_expr
);
4941 var method
= mg
.BestCandidate
;
4942 if (method
!= null) {
4943 type
= method
.ReturnType
;
4947 // Only base will allow this invocation to happen.
4949 if (mg
.IsBase
&& method
.IsAbstract
){
4950 Error_CannotCallAbstractBase (ec
, TypeManager
.CSharpSignature (method
));
4954 if (arguments
== null && method
.DeclaringType
== TypeManager
.object_type
&& method
.Name
== Destructor
.MetadataName
) {
4956 ec
.Report
.Error (250, loc
, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
4958 ec
.Report
.Error (245, loc
, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
4962 IsSpecialMethodInvocation (ec
, method
, loc
);
4964 if (mg
.InstanceExpression
!= null)
4965 mg
.InstanceExpression
.CheckMarshalByRefAccess (ec
);
4967 eclass
= ExprClass
.Value
;
4971 Expression
DoResolveDynamic (ResolveContext ec
, Expression memberExpr
)
4974 DynamicMemberBinder dmb
= memberExpr
as DynamicMemberBinder
;
4976 args
= dmb
.Arguments
;
4977 if (arguments
!= null)
4978 args
.AddRange (arguments
);
4979 } else if (mg
== null) {
4980 if (arguments
== null)
4981 args
= new Arguments (1);
4985 args
.Insert (0, new Argument (memberExpr
));
4989 ec
.Report
.Error (1971, loc
,
4990 "The base call to method `{0}' cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access",
4997 if (mg
.IsStatic
!= mg
.IsInstance
) {
4999 args
= new Arguments (1);
5002 args
.Insert (0, new Argument (new TypeOf (new TypeExpression (mg
.DeclaringType
, loc
), loc
).Resolve (ec
), Argument
.AType
.DynamicTypeName
));
5004 MemberAccess ma
= expr
as MemberAccess
;
5006 args
.Insert (0, new Argument (ma
.Left
.Resolve (ec
)));
5008 args
.Insert (0, new Argument (new This (loc
).Resolve (ec
)));
5013 return new DynamicInvocation (expr
as ATypeNameExpression
, args
, loc
).Resolve (ec
);
5016 protected virtual MethodGroupExpr
DoResolveOverload (ResolveContext ec
)
5018 return mg
.OverloadResolve (ec
, ref arguments
, false, loc
);
5021 public static bool IsSpecialMethodInvocation (ResolveContext ec
, MethodSpec method
, Location loc
)
5023 if (!method
.IsReservedMethod
)
5026 if (ec
.HasSet (ResolveContext
.Options
.InvokeSpecialName
))
5029 ec
.Report
.SymbolRelatedToPreviousError (method
);
5030 ec
.Report
.Error (571, loc
, "`{0}': cannot explicitly call operator or accessor",
5031 method
.GetSignatureForError ());
5036 static Type
[] GetVarargsTypes (MethodSpec mb
, Arguments arguments
)
5038 AParametersCollection pd
= mb
.Parameters
;
5040 Argument a
= arguments
[pd
.Count
- 1];
5041 Arglist list
= (Arglist
) a
.Expr
;
5043 return list
.ArgumentTypes
;
5047 /// is_base tells whether we want to force the use of the `call'
5048 /// opcode instead of using callvirt. Call is required to call
5049 /// a specific method, while callvirt will always use the most
5050 /// recent method in the vtable.
5052 /// is_static tells whether this is an invocation on a static method
5054 /// instance_expr is an expression that represents the instance
5055 /// it must be non-null if is_static is false.
5057 /// method is the method to invoke.
5059 /// Arguments is the list of arguments to pass to the method or constructor.
5061 public static void EmitCall (EmitContext ec
, bool is_base
,
5062 Expression instance_expr
,
5063 MethodSpec method
, Arguments Arguments
, Location loc
)
5065 EmitCall (ec
, is_base
, instance_expr
, method
, Arguments
, loc
, false, false);
5068 // `dup_args' leaves an extra copy of the arguments on the stack
5069 // `omit_args' does not leave any arguments at all.
5070 // So, basically, you could make one call with `dup_args' set to true,
5071 // and then another with `omit_args' set to true, and the two calls
5072 // would have the same set of arguments. However, each argument would
5073 // only have been evaluated once.
5074 public static void EmitCall (EmitContext ec
, bool is_base
,
5075 Expression instance_expr
,
5076 MethodSpec method
, Arguments Arguments
, Location loc
,
5077 bool dup_args
, bool omit_args
)
5079 LocalTemporary this_arg
= null;
5081 TypeSpec decl_type
= method
.DeclaringType
;
5083 // Speed up the check by not doing it on not allowed targets
5084 if (method
.ReturnType
== TypeManager
.void_type
&& method
.IsConditionallyExcluded (loc
))
5088 TypeSpec iexpr_type
;
5090 if (method
.IsStatic
) {
5092 call_op
= OpCodes
.Call
;
5094 iexpr_type
= instance_expr
.Type
;
5096 if (is_base
|| decl_type
.IsStruct
|| decl_type
.IsEnum
|| (instance_expr
is This
&& !method
.IsVirtual
)) {
5097 call_op
= OpCodes
.Call
;
5099 call_op
= OpCodes
.Callvirt
;
5103 // If this is ourselves, push "this"
5106 TypeSpec t
= iexpr_type
;
5109 // Push the instance expression
5111 if ((iexpr_type
.IsStruct
&& (call_op
== OpCodes
.Callvirt
|| (call_op
== OpCodes
.Call
&& decl_type
== iexpr_type
))) ||
5112 iexpr_type
.IsGenericParameter
|| TypeManager
.IsNullableType (decl_type
)) {
5114 // If the expression implements IMemoryLocation, then
5115 // we can optimize and use AddressOf on the
5118 // If not we have to use some temporary storage for
5120 var iml
= instance_expr
as IMemoryLocation
;
5122 iml
.AddressOf (ec
, AddressOp
.LoadStore
);
5124 LocalTemporary temp
= new LocalTemporary (iexpr_type
);
5125 instance_expr
.Emit (ec
);
5127 temp
.AddressOf (ec
, AddressOp
.Load
);
5130 // avoid the overhead of doing this all the time.
5132 t
= ReferenceContainer
.MakeType (iexpr_type
);
5133 } else if (iexpr_type
.IsEnum
|| iexpr_type
.IsStruct
) {
5134 instance_expr
.Emit (ec
);
5135 ec
.Emit (OpCodes
.Box
, iexpr_type
);
5136 t
= iexpr_type
= TypeManager
.object_type
;
5138 instance_expr
.Emit (ec
);
5142 ec
.Emit (OpCodes
.Dup
);
5143 if (Arguments
!= null && Arguments
.Count
!= 0) {
5144 this_arg
= new LocalTemporary (t
);
5145 this_arg
.Store (ec
);
5151 if (!omit_args
&& Arguments
!= null)
5152 Arguments
.Emit (ec
, dup_args
, this_arg
);
5154 if (call_op
== OpCodes
.Callvirt
&& (iexpr_type
.IsGenericParameter
|| iexpr_type
.IsStruct
)) {
5155 ec
.Emit (OpCodes
.Constrained
, iexpr_type
);
5158 if (method
.Parameters
.HasArglist
) {
5159 Type
[] varargs_types
= GetVarargsTypes (method
, Arguments
);
5160 ec
.Emit (call_op
, method
, varargs_types
);
5167 // and DoFoo is not virtual, you can omit the callvirt,
5168 // because you don't need the null checking behavior.
5170 ec
.Emit (call_op
, method
);
5173 public override void Emit (EmitContext ec
)
5175 mg
.EmitCall (ec
, arguments
);
5178 public override void EmitStatement (EmitContext ec
)
5183 // Pop the return value if there is one
5185 if (type
!= TypeManager
.void_type
)
5186 ec
.Emit (OpCodes
.Pop
);
5189 protected override void CloneTo (CloneContext clonectx
, Expression t
)
5191 Invocation target
= (Invocation
) t
;
5193 if (arguments
!= null)
5194 target
.arguments
= arguments
.Clone (clonectx
);
5196 target
.expr
= expr
.Clone (clonectx
);
5199 public override SLE
.Expression
MakeExpression (BuilderContext ctx
)
5201 return MakeExpression (ctx
, mg
.InstanceExpression
, (MethodSpec
) mg
, arguments
);
5204 public static SLE
.Expression
MakeExpression (BuilderContext ctx
, Expression instance
, MethodSpec mi
, Arguments args
)
5206 var instance_expr
= instance
== null ? null : instance
.MakeExpression (ctx
);
5207 return SLE
.Expression
.Call (instance_expr
, (MethodInfo
) mi
.GetMetaInfo (), Arguments
.MakeExpression (args
, ctx
));
5212 /// Implements the new expression
5214 public class New
: ExpressionStatement
, IMemoryLocation
{
5215 protected Arguments Arguments
;
5218 // During bootstrap, it contains the RequestedType,
5219 // but if `type' is not null, it *might* contain a NewDelegate
5220 // (because of field multi-initialization)
5222 protected Expression RequestedType
;
5224 protected MethodGroupExpr method
;
5226 public New (Expression requested_type
, Arguments arguments
, Location l
)
5228 RequestedType
= requested_type
;
5229 Arguments
= arguments
;
5234 /// Converts complex core type syntax like 'new int ()' to simple constant
5236 public static Constant
Constantify (TypeSpec t
)
5238 if (t
== TypeManager
.int32_type
)
5239 return new IntConstant (0, Location
.Null
);
5240 if (t
== TypeManager
.uint32_type
)
5241 return new UIntConstant (0, Location
.Null
);
5242 if (t
== TypeManager
.int64_type
)
5243 return new LongConstant (0, Location
.Null
);
5244 if (t
== TypeManager
.uint64_type
)
5245 return new ULongConstant (0, Location
.Null
);
5246 if (t
== TypeManager
.float_type
)
5247 return new FloatConstant (0, Location
.Null
);
5248 if (t
== TypeManager
.double_type
)
5249 return new DoubleConstant (0, Location
.Null
);
5250 if (t
== TypeManager
.short_type
)
5251 return new ShortConstant (0, Location
.Null
);
5252 if (t
== TypeManager
.ushort_type
)
5253 return new UShortConstant (0, Location
.Null
);
5254 if (t
== TypeManager
.sbyte_type
)
5255 return new SByteConstant (0, Location
.Null
);
5256 if (t
== TypeManager
.byte_type
)
5257 return new ByteConstant (0, Location
.Null
);
5258 if (t
== TypeManager
.char_type
)
5259 return new CharConstant ('\0', Location
.Null
);
5260 if (t
== TypeManager
.bool_type
)
5261 return new BoolConstant (false, Location
.Null
);
5262 if (t
== TypeManager
.decimal_type
)
5263 return new DecimalConstant (0, Location
.Null
);
5264 if (TypeManager
.IsEnumType (t
))
5265 return new EnumConstant (Constantify (EnumSpec
.GetUnderlyingType (t
)), t
);
5266 if (TypeManager
.IsNullableType (t
))
5267 return Nullable
.LiftedNull
.Create (t
, Location
.Null
);
5273 // Checks whether the type is an interface that has the
5274 // [ComImport, CoClass] attributes and must be treated
5277 public Expression
CheckComImport (ResolveContext ec
)
5279 if (!type
.IsInterface
)
5283 // Turn the call into:
5284 // (the-interface-stated) (new class-referenced-in-coclassattribute ())
5286 var real_class
= type
.MemberDefinition
.GetAttributeCoClass ();
5287 if (real_class
== null)
5290 New proxy
= new New (new TypeExpression (real_class
, loc
), Arguments
, loc
);
5291 Cast cast
= new Cast (new TypeExpression (type
, loc
), proxy
, loc
);
5292 return cast
.Resolve (ec
);
5295 public override Expression
CreateExpressionTree (ResolveContext ec
)
5298 if (method
== null) {
5299 args
= new Arguments (1);
5300 args
.Add (new Argument (new TypeOf (new TypeExpression (type
, loc
), loc
)));
5302 args
= Arguments
.CreateForExpressionTree (ec
,
5304 method
.CreateExpressionTree (ec
));
5307 return CreateExpressionFactoryCall (ec
, "New", args
);
5310 protected override Expression
DoResolve (ResolveContext ec
)
5313 // The New DoResolve might be called twice when initializing field
5314 // expressions (see EmitFieldInitializers, the call to
5315 // GetInitializerExpression will perform a resolve on the expression,
5316 // and later the assign will trigger another resolution
5318 // This leads to bugs (#37014)
5321 if (RequestedType
is NewDelegate
)
5322 return RequestedType
;
5326 TypeExpr texpr
= RequestedType
.ResolveAsTypeTerminal (ec
, false);
5332 if (type
.IsPointer
) {
5333 ec
.Report
.Error (1919, loc
, "Unsafe type `{0}' cannot be used in an object creation expression",
5334 TypeManager
.CSharpName (type
));
5338 if (Arguments
== null) {
5339 Constant c
= Constantify (type
);
5341 return ReducedExpression
.Create (c
.Resolve (ec
), this);
5344 if (TypeManager
.IsDelegateType (type
)) {
5345 return (new NewDelegate (type
, Arguments
, loc
)).Resolve (ec
);
5348 var tparam
= type
as TypeParameterSpec
;
5349 if (tparam
!= null) {
5350 if (!tparam
.HasSpecialConstructor
&& !tparam
.HasSpecialStruct
) {
5351 ec
.Report
.Error (304, loc
,
5352 "Cannot create an instance of the variable type `{0}' because it does not have the new() constraint",
5353 TypeManager
.CSharpName (type
));
5356 if ((Arguments
!= null) && (Arguments
.Count
!= 0)) {
5357 ec
.Report
.Error (417, loc
,
5358 "`{0}': cannot provide arguments when creating an instance of a variable type",
5359 TypeManager
.CSharpName (type
));
5362 if (TypeManager
.activator_create_instance
== null) {
5363 TypeSpec activator_type
= TypeManager
.CoreLookupType (ec
.Compiler
, "System", "Activator", MemberKind
.Class
, true);
5364 if (activator_type
!= null) {
5365 TypeManager
.activator_create_instance
= TypeManager
.GetPredefinedMethod (
5366 activator_type
, MemberFilter
.Method ("CreateInstance", 1, ParametersCompiled
.EmptyReadOnlyParameters
, null), loc
);
5370 eclass
= ExprClass
.Value
;
5374 if (type
.IsStatic
) {
5375 ec
.Report
.SymbolRelatedToPreviousError (type
);
5376 ec
.Report
.Error (712, loc
, "Cannot create an instance of the static class `{0}'", TypeManager
.CSharpName (type
));
5380 if (type
.IsInterface
|| type
.IsAbstract
){
5381 if (!TypeManager
.IsGenericType (type
)) {
5382 RequestedType
= CheckComImport (ec
);
5383 if (RequestedType
!= null)
5384 return RequestedType
;
5387 ec
.Report
.SymbolRelatedToPreviousError (type
);
5388 ec
.Report
.Error (144, loc
, "Cannot create an instance of the abstract class or interface `{0}'", TypeManager
.CSharpName (type
));
5392 bool is_struct
= TypeManager
.IsStruct (type
);
5393 eclass
= ExprClass
.Value
;
5396 // SRE returns a match for .ctor () on structs (the object constructor),
5397 // so we have to manually ignore it.
5399 if (is_struct
&& Arguments
== null)
5402 // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
5403 Expression ml
= MemberLookupFinal (ec
, type
, type
, ConstructorInfo
.ConstructorName
, 0,
5404 MemberKind
.Constructor
, BindingRestriction
.AccessibleOnly
| BindingRestriction
.DeclaredOnly
, loc
);
5407 if (Arguments
!= null) {
5408 Arguments
.Resolve (ec
, out dynamic);
5416 method
= ml
as MethodGroupExpr
;
5417 if (method
== null) {
5418 ml
.Error_UnexpectedKind (ec
, ResolveFlags
.MethodGroup
, loc
);
5422 method
= method
.OverloadResolve (ec
, ref Arguments
, false, loc
);
5427 Arguments
.Insert (0, new Argument (new TypeOf (texpr
, loc
).Resolve (ec
), Argument
.AType
.DynamicTypeName
));
5428 return new DynamicConstructorBinder (type
, Arguments
, loc
).Resolve (ec
);
5434 bool DoEmitTypeParameter (EmitContext ec
)
5436 var ctor_factory
= TypeManager
.activator_create_instance
.MakeGenericMethod (type
);
5437 var tparam
= (TypeParameterSpec
) type
;
5439 if (tparam
.IsReferenceType
) {
5440 ec
.Emit (OpCodes
.Call
, ctor_factory
);
5444 // Allow DoEmit() to be called multiple times.
5445 // We need to create a new LocalTemporary each time since
5446 // you can't share LocalBuilders among ILGeneators.
5447 LocalTemporary temp
= new LocalTemporary (type
);
5449 Label label_activator
= ec
.DefineLabel ();
5450 Label label_end
= ec
.DefineLabel ();
5452 temp
.AddressOf (ec
, AddressOp
.Store
);
5453 ec
.Emit (OpCodes
.Initobj
, type
);
5456 ec
.Emit (OpCodes
.Box
, type
);
5457 ec
.Emit (OpCodes
.Brfalse
, label_activator
);
5459 temp
.AddressOf (ec
, AddressOp
.Store
);
5460 ec
.Emit (OpCodes
.Initobj
, type
);
5462 ec
.Emit (OpCodes
.Br_S
, label_end
);
5464 ec
.MarkLabel (label_activator
);
5466 ec
.Emit (OpCodes
.Call
, ctor_factory
);
5467 ec
.MarkLabel (label_end
);
5472 // This Emit can be invoked in two contexts:
5473 // * As a mechanism that will leave a value on the stack (new object)
5474 // * As one that wont (init struct)
5476 // If we are dealing with a ValueType, we have a few
5477 // situations to deal with:
5479 // * The target is a ValueType, and we have been provided
5480 // the instance (this is easy, we are being assigned).
5482 // * The target of New is being passed as an argument,
5483 // to a boxing operation or a function that takes a
5486 // In this case, we need to create a temporary variable
5487 // that is the argument of New.
5489 // Returns whether a value is left on the stack
5491 // *** Implementation note ***
5493 // To benefit from this optimization, each assignable expression
5494 // has to manually cast to New and call this Emit.
5496 // TODO: It's worth to implement it for arrays and fields
5498 public virtual bool Emit (EmitContext ec
, IMemoryLocation target
)
5500 bool is_value_type
= TypeManager
.IsValueType (type
);
5501 VariableReference vr
= target
as VariableReference
;
5503 if (target
!= null && is_value_type
&& (vr
!= null || method
== null)) {
5504 target
.AddressOf (ec
, AddressOp
.Store
);
5505 } else if (vr
!= null && vr
.IsRef
) {
5509 if (Arguments
!= null)
5510 Arguments
.Emit (ec
);
5512 if (is_value_type
) {
5513 if (method
== null) {
5514 ec
.Emit (OpCodes
.Initobj
, type
);
5519 ec
.Emit (OpCodes
.Call
, method
.BestCandidate
);
5524 if (type
is TypeParameterSpec
)
5525 return DoEmitTypeParameter (ec
);
5527 ec
.Emit (OpCodes
.Newobj
, method
.BestCandidate
);
5531 public override void Emit (EmitContext ec
)
5533 LocalTemporary v
= null;
5534 if (method
== null && TypeManager
.IsValueType (type
)) {
5535 // TODO: Use temporary variable from pool
5536 v
= new LocalTemporary (type
);
5543 public override void EmitStatement (EmitContext ec
)
5545 LocalTemporary v
= null;
5546 if (method
== null && TypeManager
.IsValueType (type
)) {
5547 // TODO: Use temporary variable from pool
5548 v
= new LocalTemporary (type
);
5552 ec
.Emit (OpCodes
.Pop
);
5555 public virtual bool HasInitializer
{
5561 public void AddressOf (EmitContext ec
, AddressOp mode
)
5563 EmitAddressOf (ec
, mode
);
5566 protected virtual IMemoryLocation
EmitAddressOf (EmitContext ec
, AddressOp mode
)
5568 LocalTemporary value_target
= new LocalTemporary (type
);
5570 if (type
is TypeParameterSpec
) {
5571 DoEmitTypeParameter (ec
);
5572 value_target
.Store (ec
);
5573 value_target
.AddressOf (ec
, mode
);
5574 return value_target
;
5577 if (!TypeManager
.IsStruct (type
)){
5579 // We throw an exception. So far, I believe we only need to support
5581 // foreach (int j in new StructType ())
5584 throw new Exception ("AddressOf should not be used for classes");
5587 value_target
.AddressOf (ec
, AddressOp
.Store
);
5589 if (method
== null) {
5590 ec
.Emit (OpCodes
.Initobj
, type
);
5592 if (Arguments
!= null)
5593 Arguments
.Emit (ec
);
5595 ec
.Emit (OpCodes
.Call
, method
.BestCandidate
);
5598 value_target
.AddressOf (ec
, mode
);
5599 return value_target
;
5602 protected override void CloneTo (CloneContext clonectx
, Expression t
)
5604 New target
= (New
) t
;
5606 target
.RequestedType
= RequestedType
.Clone (clonectx
);
5607 if (Arguments
!= null){
5608 target
.Arguments
= Arguments
.Clone (clonectx
);
5612 public override SLE
.Expression
MakeExpression (BuilderContext ctx
)
5614 return SLE
.Expression
.New ((ConstructorInfo
) method
.BestCandidate
.GetMetaInfo (), Arguments
.MakeExpression (Arguments
, ctx
));
5618 public class ArrayInitializer
: ShimExpression
5620 List
<Expression
> elements
;
5622 public ArrayInitializer (List
<Expression
> init
, Location loc
)
5628 public ArrayInitializer (int count
, Location loc
)
5631 elements
= new List
<Expression
> (count
);
5634 public ArrayInitializer (Location loc
)
5639 public void Add (Expression expr
)
5641 elements
.Add (expr
);
5644 protected override void CloneTo (CloneContext clonectx
, Expression t
)
5646 var target
= (ArrayInitializer
) t
;
5648 target
.elements
= new List
<Expression
> (elements
.Count
);
5649 foreach (var element
in elements
)
5650 target
.elements
.Add (element
.Clone (clonectx
));
5652 base.CloneTo (clonectx
, t
);
5656 get { return elements.Count; }
5659 protected override Expression
DoResolve (ResolveContext rc
)
5661 throw new NotImplementedException ();
5664 public Expression
this [int index
] {
5665 get { return elements [index]; }
5670 /// 14.5.10.2: Represents an array creation expression.
5674 /// There are two possible scenarios here: one is an array creation
5675 /// expression that specifies the dimensions and optionally the
5676 /// initialization data and the other which does not need dimensions
5677 /// specified but where initialization data is mandatory.
5679 public class ArrayCreation
: Expression
5681 FullNamedExpression requested_base_type
;
5682 ArrayInitializer initializers
;
5685 // The list of Argument types.
5686 // This is used to construct the `newarray' or constructor signature
5688 protected List
<Expression
> arguments
;
5690 protected TypeSpec array_element_type
;
5691 int num_arguments
= 0;
5692 protected int dimensions
;
5693 protected readonly string rank
;
5694 Expression first_emit
;
5695 LocalTemporary first_emit_temp
;
5697 protected List
<Expression
> array_data
;
5699 Dictionary
<int, int> bounds
;
5701 // The number of constants in array initializers
5702 int const_initializers_count
;
5703 bool only_constant_initializers
;
5705 public ArrayCreation (FullNamedExpression requested_base_type
, List
<Expression
> exprs
, string rank
, ArrayInitializer initializers
, Location l
)
5707 this.requested_base_type
= requested_base_type
;
5708 this.initializers
= initializers
;
5712 arguments
= new List
<Expression
> (exprs
);
5713 num_arguments
= arguments
.Count
;
5716 public ArrayCreation (FullNamedExpression requested_base_type
, string rank
, ArrayInitializer initializers
, Location l
)
5718 this.requested_base_type
= requested_base_type
;
5719 this.initializers
= initializers
;
5724 protected override void Error_NegativeArrayIndex (ResolveContext ec
, Location loc
)
5726 ec
.Report
.Error (248, loc
, "Cannot create an array with a negative size");
5729 bool CheckIndices (ResolveContext ec
, ArrayInitializer probe
, int idx
, bool specified_dims
, int child_bounds
)
5731 if (initializers
!= null && bounds
== null) {
5733 // We use this to store all the date values in the order in which we
5734 // will need to store them in the byte blob later
5736 array_data
= new List
<Expression
> ();
5737 bounds
= new Dictionary
<int, int> ();
5740 if (specified_dims
) {
5741 Expression a
= arguments
[idx
];
5746 a
= ConvertExpressionToArrayIndex (ec
, a
);
5752 if (initializers
!= null) {
5753 Constant c
= a
as Constant
;
5754 if (c
== null && a
is ArrayIndexCast
)
5755 c
= ((ArrayIndexCast
) a
).Child
as Constant
;
5758 ec
.Report
.Error (150, a
.Location
, "A constant value is expected");
5764 value = System
.Convert
.ToInt32 (c
.GetValue ());
5766 ec
.Report
.Error (150, a
.Location
, "A constant value is expected");
5770 // TODO: probe.Count does not fit ulong in
5771 if (value != probe
.Count
) {
5772 ec
.Report
.Error (847, loc
, "An array initializer of length `{0}' was expected", value.ToString ());
5776 bounds
[idx
] = value;
5780 if (initializers
== null)
5783 only_constant_initializers
= true;
5784 for (int i
= 0; i
< probe
.Count
; ++i
) {
5786 if (o
is ArrayInitializer
) {
5787 var sub_probe
= o
as ArrayInitializer
;
5788 if (idx
+ 1 >= dimensions
){
5789 ec
.Report
.Error (623, loc
, "Array initializers can only be used in a variable or field initializer. Try using a new expression instead");
5793 bool ret
= CheckIndices (ec
, sub_probe
, idx
+ 1, specified_dims
, child_bounds
- 1);
5796 } else if (child_bounds
> 1) {
5797 ec
.Report
.Error (846, o
.Location
, "A nested array initializer was expected");
5799 Expression element
= ResolveArrayElement (ec
, o
);
5800 if (element
== null)
5803 // Initializers with the default values can be ignored
5804 Constant c
= element
as Constant
;
5806 if (!c
.IsDefaultInitializer (array_element_type
)) {
5807 ++const_initializers_count
;
5810 only_constant_initializers
= false;
5813 array_data
.Add (element
);
5820 public override Expression
CreateExpressionTree (ResolveContext ec
)
5824 if (array_data
== null) {
5825 args
= new Arguments (arguments
.Count
+ 1);
5826 args
.Add (new Argument (new TypeOf (new TypeExpression (array_element_type
, loc
), loc
)));
5827 foreach (Expression a
in arguments
)
5828 args
.Add (new Argument (a
.CreateExpressionTree (ec
)));
5830 return CreateExpressionFactoryCall (ec
, "NewArrayBounds", args
);
5833 if (dimensions
> 1) {
5834 ec
.Report
.Error (838, loc
, "An expression tree cannot contain a multidimensional array initializer");
5838 args
= new Arguments (array_data
== null ? 1 : array_data
.Count
+ 1);
5839 args
.Add (new Argument (new TypeOf (new TypeExpression (array_element_type
, loc
), loc
)));
5840 if (array_data
!= null) {
5841 for (int i
= 0; i
< array_data
.Count
; ++i
) {
5842 Expression e
= array_data
[i
];
5843 args
.Add (new Argument (e
.CreateExpressionTree (ec
)));
5847 return CreateExpressionFactoryCall (ec
, "NewArrayInit", args
);
5850 public void UpdateIndices ()
5853 for (var probe
= initializers
; probe
!= null;) {
5854 if (probe
.Count
> 0 && probe
[0] is ArrayInitializer
) {
5855 Expression e
= new IntConstant (probe
.Count
, Location
.Null
);
5858 bounds
[i
++] = probe
.Count
;
5860 probe
= (ArrayInitializer
) probe
[0];
5863 Expression e
= new IntConstant (probe
.Count
, Location
.Null
);
5866 bounds
[i
++] = probe
.Count
;
5872 protected virtual Expression
ResolveArrayElement (ResolveContext ec
, Expression element
)
5874 element
= element
.Resolve (ec
);
5875 if (element
== null)
5878 if (element
is CompoundAssign
.TargetExpression
) {
5879 if (first_emit
!= null)
5880 throw new InternalErrorException ("Can only handle one mutator at a time");
5881 first_emit
= element
;
5882 element
= first_emit_temp
= new LocalTemporary (element
.Type
);
5885 return Convert
.ImplicitConversionRequired (
5886 ec
, element
, array_element_type
, loc
);
5889 protected bool ResolveInitializers (ResolveContext ec
)
5891 if (arguments
!= null) {
5893 for (int i
= 0; i
< arguments
.Count
; ++i
) {
5894 res
&= CheckIndices (ec
, initializers
, i
, true, dimensions
);
5895 if (initializers
!= null)
5902 arguments
= new List
<Expression
> ();
5904 if (!CheckIndices (ec
, initializers
, 0, false, dimensions
))
5913 // Resolved the type of the array
5915 bool ResolveArrayType (ResolveContext ec
)
5917 if (requested_base_type
is VarExpr
) {
5918 ec
.Report
.Error (820, loc
, "An implicitly typed local variable declarator cannot use an array initializer");
5922 StringBuilder array_qualifier
= new StringBuilder ();
5925 // `In the first form allocates an array instace of the type that results
5926 // from deleting each of the individual expression from the expression list'
5928 if (num_arguments
> 0) {
5929 array_qualifier
.Append ("[");
5930 for (int i
= num_arguments
-1; i
> 0; i
--)
5931 array_qualifier
.Append (",");
5932 array_qualifier
.Append ("]");
5935 array_qualifier
.Append (rank
);
5940 TypeExpr array_type_expr
;
5941 array_type_expr
= new ComposedCast (requested_base_type
, array_qualifier
.ToString (), loc
);
5942 array_type_expr
= array_type_expr
.ResolveAsTypeTerminal (ec
, false);
5943 if (array_type_expr
== null)
5946 type
= array_type_expr
.Type
;
5947 var ac
= type
as ArrayContainer
;
5949 ec
.Report
.Error (622, loc
, "Can only use array initializer expressions to assign to array types. Try using a new expression instead");
5953 array_element_type
= ac
.Element
;
5954 dimensions
= ac
.Rank
;
5959 protected override Expression
DoResolve (ResolveContext ec
)
5964 if (!ResolveArrayType (ec
))
5968 // validate the initializers and fill in any missing bits
5970 if (!ResolveInitializers (ec
))
5973 eclass
= ExprClass
.Value
;
5977 byte [] MakeByteBlob ()
5982 int count
= array_data
.Count
;
5984 TypeSpec element_type
= array_element_type
;
5985 if (TypeManager
.IsEnumType (element_type
))
5986 element_type
= EnumSpec
.GetUnderlyingType (element_type
);
5988 factor
= GetTypeSize (element_type
);
5990 throw new Exception ("unrecognized type in MakeByteBlob: " + element_type
);
5992 data
= new byte [(count
* factor
+ 3) & ~
3];
5995 for (int i
= 0; i
< count
; ++i
) {
5996 object v
= array_data
[i
];
5998 if (v
is EnumConstant
)
5999 v
= ((EnumConstant
) v
).Child
;
6001 if (v
is Constant
&& !(v
is StringConstant
))
6002 v
= ((Constant
) v
).GetValue ();
6008 if (element_type
== TypeManager
.int64_type
){
6009 if (!(v
is Expression
)){
6010 long val
= (long) v
;
6012 for (int j
= 0; j
< factor
; ++j
) {
6013 data
[idx
+ j
] = (byte) (val
& 0xFF);
6017 } else if (element_type
== TypeManager
.uint64_type
){
6018 if (!(v
is Expression
)){
6019 ulong val
= (ulong) v
;
6021 for (int j
= 0; j
< factor
; ++j
) {
6022 data
[idx
+ j
] = (byte) (val
& 0xFF);
6026 } else if (element_type
== TypeManager
.float_type
) {
6027 if (!(v
is Expression
)){
6028 element
= BitConverter
.GetBytes ((float) v
);
6030 for (int j
= 0; j
< factor
; ++j
)
6031 data
[idx
+ j
] = element
[j
];
6032 if (!BitConverter
.IsLittleEndian
)
6033 System
.Array
.Reverse (data
, idx
, 4);
6035 } else if (element_type
== TypeManager
.double_type
) {
6036 if (!(v
is Expression
)){
6037 element
= BitConverter
.GetBytes ((double) v
);
6039 for (int j
= 0; j
< factor
; ++j
)
6040 data
[idx
+ j
] = element
[j
];
6042 // FIXME: Handle the ARM float format.
6043 if (!BitConverter
.IsLittleEndian
)
6044 System
.Array
.Reverse (data
, idx
, 8);
6046 } else if (element_type
== TypeManager
.char_type
){
6047 if (!(v
is Expression
)){
6048 int val
= (int) ((char) v
);
6050 data
[idx
] = (byte) (val
& 0xff);
6051 data
[idx
+1] = (byte) (val
>> 8);
6053 } else if (element_type
== TypeManager
.short_type
){
6054 if (!(v
is Expression
)){
6055 int val
= (int) ((short) v
);
6057 data
[idx
] = (byte) (val
& 0xff);
6058 data
[idx
+1] = (byte) (val
>> 8);
6060 } else if (element_type
== TypeManager
.ushort_type
){
6061 if (!(v
is Expression
)){
6062 int val
= (int) ((ushort) v
);
6064 data
[idx
] = (byte) (val
& 0xff);
6065 data
[idx
+1] = (byte) (val
>> 8);
6067 } else if (element_type
== TypeManager
.int32_type
) {
6068 if (!(v
is Expression
)){
6071 data
[idx
] = (byte) (val
& 0xff);
6072 data
[idx
+1] = (byte) ((val
>> 8) & 0xff);
6073 data
[idx
+2] = (byte) ((val
>> 16) & 0xff);
6074 data
[idx
+3] = (byte) (val
>> 24);
6076 } else if (element_type
== TypeManager
.uint32_type
) {
6077 if (!(v
is Expression
)){
6078 uint val
= (uint) v
;
6080 data
[idx
] = (byte) (val
& 0xff);
6081 data
[idx
+1] = (byte) ((val
>> 8) & 0xff);
6082 data
[idx
+2] = (byte) ((val
>> 16) & 0xff);
6083 data
[idx
+3] = (byte) (val
>> 24);
6085 } else if (element_type
== TypeManager
.sbyte_type
) {
6086 if (!(v
is Expression
)){
6087 sbyte val
= (sbyte) v
;
6088 data
[idx
] = (byte) val
;
6090 } else if (element_type
== TypeManager
.byte_type
) {
6091 if (!(v
is Expression
)){
6092 byte val
= (byte) v
;
6093 data
[idx
] = (byte) val
;
6095 } else if (element_type
== TypeManager
.bool_type
) {
6096 if (!(v
is Expression
)){
6097 bool val
= (bool) v
;
6098 data
[idx
] = (byte) (val
? 1 : 0);
6100 } else if (element_type
== TypeManager
.decimal_type
){
6101 if (!(v
is Expression
)){
6102 int [] bits
= Decimal
.GetBits ((decimal) v
);
6105 // FIXME: For some reason, this doesn't work on the MS runtime.
6106 int [] nbits
= new int [4];
6107 nbits
[0] = bits
[3];
6108 nbits
[1] = bits
[2];
6109 nbits
[2] = bits
[0];
6110 nbits
[3] = bits
[1];
6112 for (int j
= 0; j
< 4; j
++){
6113 data
[p
++] = (byte) (nbits
[j
] & 0xff);
6114 data
[p
++] = (byte) ((nbits
[j
] >> 8) & 0xff);
6115 data
[p
++] = (byte) ((nbits
[j
] >> 16) & 0xff);
6116 data
[p
++] = (byte) (nbits
[j
] >> 24);
6120 throw new Exception ("Unrecognized type in MakeByteBlob: " + element_type
);
6130 public override SLE
.Expression
MakeExpression (BuilderContext ctx
)
6132 var initializers
= new SLE
.Expression
[array_data
.Count
];
6133 for (var i
= 0; i
< initializers
.Length
; i
++) {
6134 if (array_data
[i
] == null)
6135 initializers
[i
] = SLE
.Expression
.Default (array_element_type
.GetMetaInfo ());
6137 initializers
[i
] = array_data
[i
].MakeExpression (ctx
);
6140 return SLE
.Expression
.NewArrayInit (array_element_type
.GetMetaInfo (), initializers
);
6144 // Emits the initializers for the array
6146 void EmitStaticInitializers (EmitContext ec
)
6148 // FIXME: This should go to Resolve !
6149 if (TypeManager
.void_initializearray_array_fieldhandle
== null) {
6150 TypeManager
.void_initializearray_array_fieldhandle
= TypeManager
.GetPredefinedMethod (
6151 TypeManager
.runtime_helpers_type
, "InitializeArray", loc
,
6152 TypeManager
.array_type
, TypeManager
.runtime_field_handle_type
);
6153 if (TypeManager
.void_initializearray_array_fieldhandle
== null)
6158 // First, the static data
6162 byte [] data
= MakeByteBlob ();
6164 fb
= RootContext
.MakeStaticData (data
);
6166 ec
.Emit (OpCodes
.Dup
);
6167 ec
.Emit (OpCodes
.Ldtoken
, fb
);
6168 ec
.Emit (OpCodes
.Call
, TypeManager
.void_initializearray_array_fieldhandle
);
6172 // Emits pieces of the array that can not be computed at compile
6173 // time (variables and string locations).
6175 // This always expect the top value on the stack to be the array
6177 void EmitDynamicInitializers (EmitContext ec
, bool emitConstants
)
6179 int dims
= bounds
.Count
;
6180 var current_pos
= new int [dims
];
6182 for (int i
= 0; i
< array_data
.Count
; i
++){
6184 Expression e
= array_data
[i
];
6185 var c
= e
as Constant
;
6187 // Constant can be initialized via StaticInitializer
6188 if (c
== null || (c
!= null && emitConstants
&& !c
.IsDefaultInitializer (array_element_type
))) {
6189 TypeSpec etype
= e
.Type
;
6191 ec
.Emit (OpCodes
.Dup
);
6193 for (int idx
= 0; idx
< dims
; idx
++)
6194 ec
.EmitInt (current_pos
[idx
]);
6197 // If we are dealing with a struct, get the
6198 // address of it, so we can store it.
6200 if ((dims
== 1) && TypeManager
.IsStruct (etype
) &&
6201 (!TypeManager
.IsBuiltinOrEnum (etype
) ||
6202 etype
== TypeManager
.decimal_type
)) {
6204 ec
.Emit (OpCodes
.Ldelema
, etype
);
6209 ec
.EmitArrayStore ((ArrayContainer
) type
);
6215 for (int j
= dims
- 1; j
>= 0; j
--){
6217 if (current_pos
[j
] < bounds
[j
])
6219 current_pos
[j
] = 0;
6224 public override void Emit (EmitContext ec
)
6226 if (first_emit
!= null) {
6227 first_emit
.Emit (ec
);
6228 first_emit_temp
.Store (ec
);
6231 foreach (Expression e
in arguments
)
6234 ec
.EmitArrayNew ((ArrayContainer
) type
);
6236 if (initializers
== null)
6239 // Emit static initializer for arrays which have contain more than 2 items and
6240 // the static initializer will initialize at least 25% of array values.
6241 // NOTE: const_initializers_count does not contain default constant values.
6242 if (const_initializers_count
> 2 && const_initializers_count
* 4 > (array_data
.Count
) &&
6243 (TypeManager
.IsPrimitiveType (array_element_type
) || TypeManager
.IsEnumType (array_element_type
))) {
6244 EmitStaticInitializers (ec
);
6246 if (!only_constant_initializers
)
6247 EmitDynamicInitializers (ec
, false);
6249 EmitDynamicInitializers (ec
, true);
6252 if (first_emit_temp
!= null)
6253 first_emit_temp
.Release (ec
);
6256 public override void EncodeAttributeValue (IMemberContext rc
, AttributeEncoder enc
, TypeSpec targetType
)
6258 // no multi dimensional or jagged arrays
6259 if (arguments
.Count
!= 1 || array_element_type
.IsArray
) {
6260 base.EncodeAttributeValue (rc
, enc
, targetType
);
6264 // No array covariance, except for array -> object
6265 if (type
!= targetType
) {
6266 if (targetType
!= TypeManager
.object_type
) {
6267 base.EncodeAttributeValue (rc
, enc
, targetType
);
6274 // Single dimensional array of 0 size
6275 if (array_data
== null) {
6276 IntConstant ic
= arguments
[0] as IntConstant
;
6277 if (ic
== null || !ic
.IsDefaultValue
) {
6278 base.EncodeAttributeValue (rc
, enc
, targetType
);
6280 enc
.Stream
.Write (0);
6286 enc
.Stream
.Write ((int) array_data
.Count
);
6287 foreach (var element
in array_data
) {
6288 element
.EncodeAttributeValue (rc
, enc
, array_element_type
);
6292 protected override void CloneTo (CloneContext clonectx
, Expression t
)
6294 ArrayCreation target
= (ArrayCreation
) t
;
6296 if (requested_base_type
!= null)
6297 target
.requested_base_type
= (FullNamedExpression
)requested_base_type
.Clone (clonectx
);
6299 if (arguments
!= null){
6300 target
.arguments
= new List
<Expression
> (arguments
.Count
);
6301 foreach (Expression e
in arguments
)
6302 target
.arguments
.Add (e
.Clone (clonectx
));
6305 if (initializers
!= null)
6306 target
.initializers
= (ArrayInitializer
) initializers
.Clone (clonectx
);
6311 // Represents an implicitly typed array epxression
6313 class ImplicitlyTypedArrayCreation
: ArrayCreation
6315 public ImplicitlyTypedArrayCreation (string rank
, ArrayInitializer initializers
, Location loc
)
6316 : base (null, rank
, initializers
, loc
)
6318 if (rank
.Length
> 2) {
6319 while (rank
[++dimensions
] == ',');
6325 protected override Expression
DoResolve (ResolveContext ec
)
6330 if (!ResolveInitializers (ec
))
6333 if (array_element_type
== null || array_element_type
== TypeManager
.null_type
||
6334 array_element_type
== TypeManager
.void_type
|| array_element_type
== InternalType
.AnonymousMethod
||
6335 array_element_type
== InternalType
.MethodGroup
||
6336 arguments
.Count
!= dimensions
) {
6337 Error_NoBestType (ec
);
6342 // At this point we found common base type for all initializer elements
6343 // but we have to be sure that all static initializer elements are of
6346 UnifyInitializerElement (ec
);
6348 type
= TypeManager
.GetConstructedType (array_element_type
, rank
);
6349 eclass
= ExprClass
.Value
;
6353 void Error_NoBestType (ResolveContext ec
)
6355 ec
.Report
.Error (826, loc
,
6356 "The type of an implicitly typed array cannot be inferred from the initializer. Try specifying array type explicitly");
6360 // Converts static initializer only
6362 void UnifyInitializerElement (ResolveContext ec
)
6364 for (int i
= 0; i
< array_data
.Count
; ++i
) {
6365 Expression e
= (Expression
)array_data
[i
];
6367 array_data
[i
] = Convert
.ImplicitConversion (ec
, e
, array_element_type
, Location
.Null
);
6371 protected override Expression
ResolveArrayElement (ResolveContext ec
, Expression element
)
6373 element
= element
.Resolve (ec
);
6374 if (element
== null)
6377 if (array_element_type
== null) {
6378 if (element
.Type
!= TypeManager
.null_type
)
6379 array_element_type
= element
.Type
;
6384 if (Convert
.ImplicitConversionExists (ec
, element
, array_element_type
)) {
6388 if (Convert
.ImplicitConversionExists (ec
, new TypeExpression (array_element_type
, loc
), element
.Type
)) {
6389 array_element_type
= element
.Type
;
6393 Error_NoBestType (ec
);
6398 public sealed class CompilerGeneratedThis
: This
6400 public static This Instance
= new CompilerGeneratedThis ();
6402 private CompilerGeneratedThis ()
6403 : base (Location
.Null
)
6407 public CompilerGeneratedThis (TypeSpec type
, Location loc
)
6413 protected override Expression
DoResolve (ResolveContext ec
)
6415 eclass
= ExprClass
.Variable
;
6417 type
= ec
.CurrentType
;
6422 public override HoistedVariable
GetHoistedVariable (AnonymousExpression ae
)
6429 /// Represents the `this' construct
6432 public class This
: VariableReference
6434 sealed class ThisVariable
: ILocalVariable
6436 public static readonly ILocalVariable Instance
= new ThisVariable ();
6438 public void Emit (EmitContext ec
)
6440 ec
.Emit (OpCodes
.Ldarg_0
);
6443 public void EmitAssign (EmitContext ec
)
6445 throw new InvalidOperationException ();
6448 public void EmitAddressOf (EmitContext ec
)
6450 ec
.Emit (OpCodes
.Ldarg_0
);
6454 VariableInfo variable_info
;
6456 public This (Location loc
)
6461 public override VariableInfo VariableInfo
{
6462 get { return variable_info; }
6465 public override bool IsFixed
{
6466 get { return false; }
6469 public override HoistedVariable
GetHoistedVariable (AnonymousExpression ae
)
6474 AnonymousMethodStorey storey
= ae
.Storey
;
6475 while (storey
!= null) {
6476 AnonymousMethodStorey temp
= storey
.Parent
as AnonymousMethodStorey
;
6478 return storey
.HoistedThis
;
6486 public override bool IsRef
{
6487 get { return type.IsStruct; }
6490 protected override ILocalVariable Variable
{
6491 get { return ThisVariable.Instance; }
6494 public static bool IsThisAvailable (ResolveContext ec
, bool ignoreAnonymous
)
6496 if (ec
.IsStatic
|| ec
.HasAny (ResolveContext
.Options
.FieldInitializerScope
| ResolveContext
.Options
.BaseInitializer
| ResolveContext
.Options
.ConstantScope
))
6499 if (ignoreAnonymous
|| ec
.CurrentAnonymousMethod
== null)
6502 if (TypeManager
.IsStruct (ec
.CurrentType
) && ec
.CurrentIterator
== null)
6508 public bool ResolveBase (ResolveContext ec
)
6510 eclass
= ExprClass
.Variable
;
6511 type
= ec
.CurrentType
;
6513 if (!IsThisAvailable (ec
, false)) {
6514 if (ec
.IsStatic
&& !ec
.HasSet (ResolveContext
.Options
.ConstantScope
)) {
6515 ec
.Report
.Error (26, loc
, "Keyword `this' is not valid in a static property, static method, or static field initializer");
6516 } else if (ec
.CurrentAnonymousMethod
!= null) {
6517 ec
.Report
.Error (1673, loc
,
6518 "Anonymous methods inside structs cannot access instance members of `this'. " +
6519 "Consider copying `this' to a local variable outside the anonymous method and using the local instead");
6521 ec
.Report
.Error (27, loc
, "Keyword `this' is not available in the current context");
6525 var block
= ec
.CurrentBlock
;
6526 if (block
!= null) {
6527 if (block
.Toplevel
.ThisVariable
!= null)
6528 variable_info
= block
.Toplevel
.ThisVariable
.VariableInfo
;
6530 AnonymousExpression am
= ec
.CurrentAnonymousMethod
;
6531 if (am
!= null && ec
.IsVariableCapturingRequired
) {
6532 am
.SetHasThisAccess ();
6540 // Called from Invocation to check if the invocation is correct
6542 public override void CheckMarshalByRefAccess (ResolveContext ec
)
6544 if ((variable_info
!= null) && !(TypeManager
.IsStruct (type
) && ec
.OmitStructFlowAnalysis
) &&
6545 !variable_info
.IsAssigned (ec
)) {
6546 ec
.Report
.Error (188, loc
,
6547 "The `this' object cannot be used before all of its fields are assigned to");
6548 variable_info
.SetAssigned (ec
);
6552 public override Expression
CreateExpressionTree (ResolveContext ec
)
6554 Arguments args
= new Arguments (1);
6555 args
.Add (new Argument (this));
6557 // Use typeless constant for ldarg.0 to save some
6558 // space and avoid problems with anonymous stories
6559 return CreateExpressionFactoryCall (ec
, "Constant", args
);
6562 protected override Expression
DoResolve (ResolveContext ec
)
6568 override public Expression
DoResolveLValue (ResolveContext ec
, Expression right_side
)
6570 if (!ResolveBase (ec
))
6573 if (variable_info
!= null)
6574 variable_info
.SetAssigned (ec
);
6576 if (ec
.CurrentType
.IsClass
){
6577 if (right_side
== EmptyExpression
.UnaryAddress
)
6578 ec
.Report
.Error (459, loc
, "Cannot take the address of `this' because it is read-only");
6579 else if (right_side
== EmptyExpression
.OutAccess
.Instance
)
6580 ec
.Report
.Error (1605, loc
, "Cannot pass `this' as a ref or out argument because it is read-only");
6582 ec
.Report
.Error (1604, loc
, "Cannot assign to `this' because it is read-only");
6588 public override int GetHashCode()
6590 throw new NotImplementedException ();
6593 public override string Name
{
6594 get { return "this"; }
6597 public override bool Equals (object obj
)
6599 This t
= obj
as This
;
6606 protected override void CloneTo (CloneContext clonectx
, Expression t
)
6611 public override void SetHasAddressTaken ()
6618 /// Represents the `__arglist' construct
6620 public class ArglistAccess
: Expression
6622 public ArglistAccess (Location loc
)
6627 public override Expression
CreateExpressionTree (ResolveContext ec
)
6629 throw new NotSupportedException ("ET");
6632 protected override Expression
DoResolve (ResolveContext ec
)
6634 eclass
= ExprClass
.Variable
;
6635 type
= TypeManager
.runtime_argument_handle_type
;
6637 if (ec
.HasSet (ResolveContext
.Options
.FieldInitializerScope
) || !ec
.CurrentBlock
.Toplevel
.Parameters
.HasArglist
) {
6638 ec
.Report
.Error (190, loc
,
6639 "The __arglist construct is valid only within a variable argument method");
6645 public override void Emit (EmitContext ec
)
6647 ec
.Emit (OpCodes
.Arglist
);
6650 protected override void CloneTo (CloneContext clonectx
, Expression target
)
6657 /// Represents the `__arglist (....)' construct
6659 public class Arglist
: Expression
6661 Arguments Arguments
;
6663 public Arglist (Location loc
)
6668 public Arglist (Arguments args
, Location l
)
6674 public Type
[] ArgumentTypes
{
6676 if (Arguments
== null)
6677 return System
.Type
.EmptyTypes
;
6679 var retval
= new Type
[Arguments
.Count
];
6680 for (int i
= 0; i
< retval
.Length
; i
++)
6681 retval
[i
] = Arguments
[i
].Expr
.Type
.GetMetaInfo ();
6687 public override Expression
CreateExpressionTree (ResolveContext ec
)
6689 ec
.Report
.Error (1952, loc
, "An expression tree cannot contain a method with variable arguments");
6693 protected override Expression
DoResolve (ResolveContext ec
)
6695 eclass
= ExprClass
.Variable
;
6696 type
= InternalType
.Arglist
;
6697 if (Arguments
!= null) {
6698 bool dynamic; // Can be ignored as there is always only 1 overload
6699 Arguments
.Resolve (ec
, out dynamic);
6705 public override void Emit (EmitContext ec
)
6707 if (Arguments
!= null)
6708 Arguments
.Emit (ec
);
6711 protected override void CloneTo (CloneContext clonectx
, Expression t
)
6713 Arglist target
= (Arglist
) t
;
6715 if (Arguments
!= null)
6716 target
.Arguments
= Arguments
.Clone (clonectx
);
6721 /// Implements the typeof operator
6723 public class TypeOf
: Expression
{
6724 Expression QueriedType
;
6725 protected TypeSpec typearg
;
6727 public TypeOf (Expression queried_type
, Location l
)
6729 QueriedType
= queried_type
;
6733 public override Expression
CreateExpressionTree (ResolveContext ec
)
6735 Arguments args
= new Arguments (2);
6736 args
.Add (new Argument (this));
6737 args
.Add (new Argument (new TypeOf (new TypeExpression (type
, loc
), loc
)));
6738 return CreateExpressionFactoryCall (ec
, "Constant", args
);
6741 protected override Expression
DoResolve (ResolveContext ec
)
6743 TypeExpr texpr
= QueriedType
.ResolveAsTypeTerminal (ec
, false);
6747 typearg
= texpr
.Type
;
6750 // Get generic type definition for unbounded type arguments
6752 var tne
= QueriedType
as ATypeNameExpression
;
6753 if (tne
!= null && typearg
.IsGeneric
&& !tne
.HasTypeArguments
)
6754 typearg
= typearg
.GetDefinition ();
6756 if (typearg
== TypeManager
.void_type
) {
6757 ec
.Report
.Error (673, loc
, "System.Void cannot be used from C#. Use typeof (void) to get the void type object");
6758 } else if (typearg
.IsPointer
&& !ec
.IsUnsafe
){
6759 UnsafeError (ec
, loc
);
6760 } else if (texpr
is DynamicTypeExpr
) {
6761 ec
.Report
.Error (1962, QueriedType
.Location
,
6762 "The typeof operator cannot be used on the dynamic type");
6765 type
= TypeManager
.type_type
;
6767 return DoResolveBase ();
6770 protected Expression
DoResolveBase ()
6772 if (TypeManager
.system_type_get_type_from_handle
== null) {
6773 TypeManager
.system_type_get_type_from_handle
= TypeManager
.GetPredefinedMethod (
6774 TypeManager
.type_type
, "GetTypeFromHandle", loc
, TypeManager
.runtime_handle_type
);
6777 // Even though what is returned is a type object, it's treated as a value by the compiler.
6778 // In particular, 'typeof (Foo).X' is something totally different from 'Foo.X'.
6779 eclass
= ExprClass
.Value
;
6783 public override void EncodeAttributeValue (IMemberContext rc
, AttributeEncoder enc
, TypeSpec targetType
)
6785 // Target type is not System.Type therefore must be object
6786 // and we need to use different encoding sequence
6787 if (targetType
!= type
)
6791 var gi = typearg as InflatedTypeSpec;
6793 // TODO: This has to be recursive, handle arrays, etc.
6794 // I could probably do it after CustomAttribute encoder rewrite
6795 foreach (var ta in gi.TypeArguments) {
6796 if (ta.IsGenericParameter) {
6797 ec.Report.SymbolRelatedToPreviousError (typearg);
6798 ec.Report.Error (416, loc, "`{0}': an attribute argument cannot use type parameters",
6799 TypeManager.CSharpName (typearg));
6807 if (!enc
.EncodeTypeName (typearg
)) {
6808 rc
.Compiler
.Report
.SymbolRelatedToPreviousError (typearg
);
6809 rc
.Compiler
.Report
.Error (416, loc
, "`{0}': an attribute argument cannot use type parameters",
6810 TypeManager
.CSharpName (typearg
));
6814 public override void Emit (EmitContext ec
)
6816 ec
.Emit (OpCodes
.Ldtoken
, typearg
);
6817 ec
.Emit (OpCodes
.Call
, TypeManager
.system_type_get_type_from_handle
);
6820 public TypeSpec TypeArgument
{
6826 protected override void CloneTo (CloneContext clonectx
, Expression t
)
6828 TypeOf target
= (TypeOf
) t
;
6829 if (QueriedType
!= null)
6830 target
.QueriedType
= QueriedType
.Clone (clonectx
);
6835 /// Implements the `typeof (void)' operator
6837 public class TypeOfVoid
: TypeOf
{
6838 public TypeOfVoid (Location l
) : base (null, l
)
6843 protected override Expression
DoResolve (ResolveContext ec
)
6845 type
= TypeManager
.type_type
;
6846 typearg
= TypeManager
.void_type
;
6848 return DoResolveBase ();
6852 class TypeOfMethod
: TypeOfMember
<MethodSpec
>
6854 public TypeOfMethod (MethodSpec method
, Location loc
)
6855 : base (method
, loc
)
6859 protected override Expression
DoResolve (ResolveContext ec
)
6861 if (member
.IsConstructor
) {
6862 type
= TypeManager
.ctorinfo_type
;
6864 type
= TypeManager
.ctorinfo_type
= TypeManager
.CoreLookupType (ec
.Compiler
, "System.Reflection", "ConstructorInfo", MemberKind
.Class
, true);
6866 type
= TypeManager
.methodinfo_type
;
6868 type
= TypeManager
.methodinfo_type
= TypeManager
.CoreLookupType (ec
.Compiler
, "System.Reflection", "MethodInfo", MemberKind
.Class
, true);
6871 return base.DoResolve (ec
);
6874 public override void Emit (EmitContext ec
)
6876 ec
.Emit (OpCodes
.Ldtoken
, member
);
6879 ec
.Emit (OpCodes
.Castclass
, type
);
6882 protected override string GetMethodName
{
6883 get { return "GetMethodFromHandle"; }
6886 protected override string RuntimeHandleName
{
6887 get { return "RuntimeMethodHandle"; }
6890 protected override MethodSpec TypeFromHandle
{
6892 return TypeManager
.methodbase_get_type_from_handle
;
6895 TypeManager
.methodbase_get_type_from_handle
= value;
6899 protected override MethodSpec TypeFromHandleGeneric
{
6901 return TypeManager
.methodbase_get_type_from_handle_generic
;
6904 TypeManager
.methodbase_get_type_from_handle_generic
= value;
6908 protected override string TypeName
{
6909 get { return "MethodBase"; }
6913 abstract class TypeOfMember
<T
> : Expression where T
: MemberSpec
6915 protected readonly T member
;
6917 protected TypeOfMember (T member
, Location loc
)
6919 this.member
= member
;
6923 public override Expression
CreateExpressionTree (ResolveContext ec
)
6925 Arguments args
= new Arguments (2);
6926 args
.Add (new Argument (this));
6927 args
.Add (new Argument (new TypeOf (new TypeExpression (type
, loc
), loc
)));
6928 return CreateExpressionFactoryCall (ec
, "Constant", args
);
6931 protected override Expression
DoResolve (ResolveContext ec
)
6933 bool is_generic
= member
.DeclaringType
.IsGenericOrParentIsGeneric
;
6934 var mi
= is_generic
? TypeFromHandleGeneric
: TypeFromHandle
;
6937 TypeSpec t
= TypeManager
.CoreLookupType (ec
.Compiler
, "System.Reflection", TypeName
, MemberKind
.Class
, true);
6938 TypeSpec handle_type
= TypeManager
.CoreLookupType (ec
.Compiler
, "System", RuntimeHandleName
, MemberKind
.Struct
, true);
6940 if (t
== null || handle_type
== null)
6943 mi
= TypeManager
.GetPredefinedMethod (t
, GetMethodName
, loc
,
6945 new TypeSpec
[] { handle_type, TypeManager.runtime_handle_type }
:
6946 new TypeSpec
[] { handle_type }
);
6949 TypeFromHandleGeneric
= mi
;
6951 TypeFromHandle
= mi
;
6954 eclass
= ExprClass
.Value
;
6958 public override void Emit (EmitContext ec
)
6960 bool is_generic
= member
.DeclaringType
.IsGenericOrParentIsGeneric
;
6963 mi
= TypeFromHandleGeneric
;
6964 ec
.Emit (OpCodes
.Ldtoken
, member
.DeclaringType
);
6966 mi
= TypeFromHandle
;
6969 ec
.Emit (OpCodes
.Call
, mi
);
6972 protected abstract string GetMethodName { get; }
6973 protected abstract string RuntimeHandleName { get; }
6974 protected abstract MethodSpec TypeFromHandle { get; set; }
6975 protected abstract MethodSpec TypeFromHandleGeneric { get; set; }
6976 protected abstract string TypeName { get; }
6979 class TypeOfField
: TypeOfMember
<FieldSpec
>
6981 public TypeOfField (FieldSpec field
, Location loc
)
6986 protected override Expression
DoResolve (ResolveContext ec
)
6988 if (TypeManager
.fieldinfo_type
== null)
6989 TypeManager
.fieldinfo_type
= TypeManager
.CoreLookupType (ec
.Compiler
, "System.Reflection", TypeName
, MemberKind
.Class
, true);
6991 type
= TypeManager
.fieldinfo_type
;
6992 return base.DoResolve (ec
);
6995 public override void Emit (EmitContext ec
)
6997 ec
.Emit (OpCodes
.Ldtoken
, member
);
7001 protected override string GetMethodName
{
7002 get { return "GetFieldFromHandle"; }
7005 protected override string RuntimeHandleName
{
7006 get { return "RuntimeFieldHandle"; }
7009 protected override MethodSpec TypeFromHandle
{
7011 return TypeManager
.fieldinfo_get_field_from_handle
;
7014 TypeManager
.fieldinfo_get_field_from_handle
= value;
7018 protected override MethodSpec TypeFromHandleGeneric
{
7020 return TypeManager
.fieldinfo_get_field_from_handle_generic
;
7023 TypeManager
.fieldinfo_get_field_from_handle_generic
= value;
7027 protected override string TypeName
{
7028 get { return "FieldInfo"; }
7033 /// Implements the sizeof expression
7035 public class SizeOf
: Expression
{
7036 readonly Expression QueriedType
;
7037 TypeSpec type_queried
;
7039 public SizeOf (Expression queried_type
, Location l
)
7041 this.QueriedType
= queried_type
;
7045 public override Expression
CreateExpressionTree (ResolveContext ec
)
7047 Error_PointerInsideExpressionTree (ec
);
7051 protected override Expression
DoResolve (ResolveContext ec
)
7053 TypeExpr texpr
= QueriedType
.ResolveAsTypeTerminal (ec
, false);
7057 type_queried
= texpr
.Type
;
7058 if (TypeManager
.IsEnumType (type_queried
))
7059 type_queried
= EnumSpec
.GetUnderlyingType (type_queried
);
7061 int size_of
= GetTypeSize (type_queried
);
7063 return new IntConstant (size_of
, loc
).Resolve (ec
);
7066 if (!TypeManager
.VerifyUnmanaged (ec
.Compiler
, type_queried
, loc
)){
7071 ec
.Report
.Error (233, loc
,
7072 "`{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)",
7073 TypeManager
.CSharpName (type_queried
));
7076 type
= TypeManager
.int32_type
;
7077 eclass
= ExprClass
.Value
;
7081 public override void Emit (EmitContext ec
)
7083 ec
.Emit (OpCodes
.Sizeof
, type_queried
);
7086 protected override void CloneTo (CloneContext clonectx
, Expression t
)
7092 /// Implements the qualified-alias-member (::) expression.
7094 public class QualifiedAliasMember
: MemberAccess
7096 readonly string alias;
7097 public static readonly string GlobalAlias
= "global";
7099 public QualifiedAliasMember (string alias, string identifier
, Location l
)
7100 : base (null, identifier
, l
)
7105 public QualifiedAliasMember (string alias, string identifier
, TypeArguments targs
, Location l
)
7106 : base (null, identifier
, targs
, l
)
7111 public QualifiedAliasMember (string alias, string identifier
, int arity
, Location l
)
7112 : base (null, identifier
, arity
, l
)
7117 public override FullNamedExpression
ResolveAsTypeStep (IMemberContext ec
, bool silent
)
7119 if (alias == GlobalAlias
) {
7120 expr
= GlobalRootNamespace
.Instance
;
7121 return base.ResolveAsTypeStep (ec
, silent
);
7124 int errors
= ec
.Compiler
.Report
.Errors
;
7125 expr
= ec
.LookupNamespaceAlias (alias);
7127 if (errors
== ec
.Compiler
.Report
.Errors
)
7128 ec
.Compiler
.Report
.Error (432, loc
, "Alias `{0}' not found", alias);
7132 FullNamedExpression fne
= base.ResolveAsTypeStep (ec
, silent
);
7136 if (expr
.eclass
== ExprClass
.Type
) {
7138 ec
.Compiler
.Report
.Error (431, loc
,
7139 "Alias `{0}' cannot be used with '::' since it denotes a type. Consider replacing '::' with '.'", alias);
7147 protected override Expression
DoResolve (ResolveContext ec
)
7149 return ResolveAsTypeStep (ec
, false);
7152 protected override void Error_IdentifierNotFound (IMemberContext rc
, TypeSpec expr_type
, string identifier
)
7154 rc
.Compiler
.Report
.Error (687, loc
,
7155 "A namespace alias qualifier `{0}' did not resolve to a namespace or a type",
7156 GetSignatureForError ());
7159 public override string GetSignatureForError ()
7162 if (targs
!= null) {
7163 name
= Name
+ "<" + targs
.GetSignatureForError () + ">";
7166 return alias + "::" + name
;
7169 protected override void CloneTo (CloneContext clonectx
, Expression t
)
7176 /// Implements the member access expression
7178 public class MemberAccess
: ATypeNameExpression
{
7179 protected Expression expr
;
7181 public MemberAccess (Expression expr
, string id
)
7182 : base (id
, expr
.Location
)
7187 public MemberAccess (Expression expr
, string identifier
, Location loc
)
7188 : base (identifier
, loc
)
7193 public MemberAccess (Expression expr
, string identifier
, TypeArguments args
, Location loc
)
7194 : base (identifier
, args
, loc
)
7199 public MemberAccess (Expression expr
, string identifier
, int arity
, Location loc
)
7200 : base (identifier
, arity
, loc
)
7205 Expression
DoResolve (ResolveContext ec
, Expression right_side
)
7208 throw new Exception ();
7211 // Resolve the expression with flow analysis turned off, we'll do the definite
7212 // assignment checks later. This is because we don't know yet what the expression
7213 // will resolve to - it may resolve to a FieldExpr and in this case we must do the
7214 // definite assignment check on the actual field and not on the whole struct.
7217 SimpleName original
= expr
as SimpleName
;
7218 Expression expr_resolved
;
7219 const ResolveFlags flags
= ResolveFlags
.VariableOrValue
| ResolveFlags
.Type
;
7221 using (ec
.Set (ResolveContext
.Options
.OmitStructFlowAnalysis
)) {
7222 if (original
!= null) {
7223 expr_resolved
= original
.DoResolve (ec
, true);
7224 if (expr_resolved
!= null) {
7225 // Ugly, simulate skipped Resolve
7226 if (expr_resolved
is ConstantExpr
) {
7227 expr_resolved
= expr_resolved
.Resolve (ec
);
7228 } else if (expr_resolved
is FieldExpr
|| expr_resolved
is PropertyExpr
) {
7230 } else if ((flags
& expr_resolved
.ExprClassToResolveFlags
) == 0) {
7231 expr_resolved
.Error_UnexpectedKind (ec
, flags
, expr
.Location
);
7232 expr_resolved
= null;
7236 expr_resolved
= expr
.Resolve (ec
, flags
);
7240 if (expr_resolved
== null)
7243 Namespace ns
= expr_resolved
as Namespace
;
7245 FullNamedExpression retval
= ns
.Lookup (ec
.Compiler
, Name
, Arity
, loc
);
7248 ns
.Error_NamespaceDoesNotExist (loc
, Name
, Arity
, ec
);
7249 else if (HasTypeArguments
)
7250 retval
= new GenericTypeExpr (retval
.Type
, targs
, loc
).ResolveAsTypeStep (ec
, false);
7255 TypeSpec expr_type
= expr_resolved
.Type
;
7256 if (expr_type
== InternalType
.Dynamic
) {
7257 Arguments args
= new Arguments (1);
7258 args
.Add (new Argument (expr_resolved
.Resolve (ec
)));
7259 expr
= new DynamicMemberBinder (Name
, args
, loc
);
7260 if (right_side
!= null)
7261 return expr
.DoResolveLValue (ec
, right_side
);
7263 return expr
.Resolve (ec
);
7266 const MemberKind dot_kinds
= MemberKind
.Class
| MemberKind
.Struct
| MemberKind
.Delegate
| MemberKind
.Enum
| MemberKind
.Interface
| MemberKind
.TypeParameter
;
7267 if ((expr_type
.Kind
& dot_kinds
) == 0 || expr_type
== TypeManager
.void_type
) {
7268 Unary
.Error_OperatorCannotBeApplied (ec
, loc
, ".", expr_type
);
7272 var arity
= HasTypeArguments
? targs
.Count
: -1;
7274 var member_lookup
= MemberLookup (ec
.Compiler
,
7275 ec
.CurrentType
, expr_type
, expr_type
, Name
, arity
, BindingRestriction
.NoOverrides
, loc
);
7277 if (member_lookup
== null) {
7278 expr
= expr_resolved
.Resolve (ec
);
7280 ExprClass expr_eclass
= expr
.eclass
;
7283 // Extension methods are not allowed on all expression types
7285 if (expr_eclass
== ExprClass
.Value
|| expr_eclass
== ExprClass
.Variable
||
7286 expr_eclass
== ExprClass
.IndexerAccess
|| expr_eclass
== ExprClass
.PropertyAccess
||
7287 expr_eclass
== ExprClass
.EventAccess
) {
7288 ExtensionMethodGroupExpr ex_method_lookup
= ec
.LookupExtensionMethod (expr_type
, Name
, arity
, loc
);
7289 if (ex_method_lookup
!= null) {
7290 ex_method_lookup
.ExtensionExpression
= expr
;
7292 if (HasTypeArguments
) {
7293 if (!targs
.Resolve (ec
))
7296 ex_method_lookup
.SetTypeArguments (ec
, targs
);
7299 return ex_method_lookup
.Resolve (ec
);
7303 member_lookup
= Error_MemberLookupFailed (ec
,
7304 ec
.CurrentType
, expr_type
, expr_type
, Name
, arity
, null,
7305 MemberKind
.All
, BindingRestriction
.AccessibleOnly
);
7306 if (member_lookup
== null)
7311 TypeExpr texpr
= member_lookup
as TypeExpr
;
7312 if (texpr
!= null) {
7313 if (!(expr_resolved
is TypeExpr
)) {
7314 me
= expr_resolved
as MemberExpr
;
7315 if (me
== null || me
.ProbeIdenticalTypeName (ec
, expr_resolved
, original
) == expr_resolved
) {
7316 ec
.Report
.Error (572, loc
, "`{0}': cannot reference a type through an expression; try `{1}' instead",
7317 Name
, member_lookup
.GetSignatureForError ());
7322 if (!texpr
.CheckAccessLevel (ec
.MemberContext
)) {
7323 ec
.Report
.SymbolRelatedToPreviousError (member_lookup
.Type
);
7324 ErrorIsInaccesible (loc
, TypeManager
.CSharpName (member_lookup
.Type
), ec
.Report
);
7328 if (HasTypeArguments
) {
7329 var ct
= new GenericTypeExpr (member_lookup
.Type
, targs
, loc
);
7330 return ct
.ResolveAsTypeStep (ec
, false);
7333 return member_lookup
;
7336 me
= (MemberExpr
) member_lookup
;
7338 if (original
!= null && me
.IsStatic
)
7339 expr_resolved
= me
.ProbeIdenticalTypeName (ec
, expr_resolved
, original
);
7341 me
= me
.ResolveMemberAccess (ec
, expr_resolved
, original
);
7343 if (HasTypeArguments
) {
7344 if (!targs
.Resolve (ec
))
7347 me
.SetTypeArguments (ec
, targs
);
7350 if (original
!= null && (!TypeManager
.IsValueType (expr_type
) || me
is PropertyExpr
)) {
7351 if (me
.IsInstance
) {
7352 LocalVariableReference
var = expr_resolved
as LocalVariableReference
;
7353 if (var != null && !var.VerifyAssigned (ec
))
7358 // The following DoResolve/DoResolveLValue will do the definite assignment
7361 if (right_side
!= null)
7362 return me
.DoResolveLValue (ec
, right_side
);
7364 return me
.Resolve (ec
);
7367 protected override Expression
DoResolve (ResolveContext ec
)
7369 return DoResolve (ec
, null);
7372 public override Expression
DoResolveLValue (ResolveContext ec
, Expression right_side
)
7374 return DoResolve (ec
, right_side
);
7377 public override FullNamedExpression
ResolveAsTypeStep (IMemberContext ec
, bool silent
)
7379 return ResolveNamespaceOrType (ec
, silent
);
7382 public FullNamedExpression
ResolveNamespaceOrType (IMemberContext rc
, bool silent
)
7384 FullNamedExpression expr_resolved
= expr
.ResolveAsTypeStep (rc
, silent
);
7386 if (expr_resolved
== null)
7389 Namespace ns
= expr_resolved
as Namespace
;
7391 FullNamedExpression retval
= ns
.Lookup (rc
.Compiler
, Name
, Arity
, loc
);
7393 if (retval
== null) {
7395 ns
.Error_NamespaceDoesNotExist (loc
, Name
, Arity
, rc
);
7396 } else if (HasTypeArguments
) {
7397 retval
= new GenericTypeExpr (retval
.Type
, targs
, loc
).ResolveAsTypeStep (rc
, silent
);
7403 TypeExpr tnew_expr
= expr_resolved
.ResolveAsTypeTerminal (rc
, false);
7404 if (tnew_expr
== null)
7407 TypeSpec expr_type
= tnew_expr
.Type
;
7408 if (TypeManager
.IsGenericParameter (expr_type
)) {
7409 rc
.Compiler
.Report
.Error (704, loc
, "A nested type cannot be specified through a type parameter `{0}'",
7410 tnew_expr
.GetSignatureForError ());
7414 var nested
= MemberCache
.FindNestedType (expr_type
, Name
, Arity
);
7415 if (nested
== null) {
7419 Error_IdentifierNotFound (rc
, expr_type
, Name
);
7424 if (!IsMemberAccessible (rc
.CurrentType
?? InternalType
.FakeInternalType
, nested
, out extra_check
)) {
7425 ErrorIsInaccesible (loc
, nested
.GetSignatureForError (), rc
.Compiler
.Report
);
7429 if (HasTypeArguments
) {
7430 texpr
= new GenericTypeExpr (nested
, targs
, loc
);
7432 texpr
= new TypeExpression (nested
, loc
);
7435 return texpr
.ResolveAsTypeStep (rc
, false);
7438 protected virtual void Error_IdentifierNotFound (IMemberContext rc
, TypeSpec expr_type
, string identifier
)
7440 var nested
= MemberCache
.FindNestedType (expr_type
, Name
, -System
.Math
.Max (1, Arity
));
7442 if (nested
!= null) {
7443 Error_TypeArgumentsCannotBeUsed (rc
.Compiler
.Report
, expr
.Location
, nested
, Arity
);
7447 var member_lookup
= MemberLookup (rc
.Compiler
,
7448 rc
.CurrentType
, expr_type
, expr_type
, identifier
, -1,
7449 MemberKind
.All
, BindingRestriction
.None
, loc
);
7451 if (member_lookup
== null) {
7452 rc
.Compiler
.Report
.Error (426, loc
, "The nested type `{0}' does not exist in the type `{1}'",
7453 Name
, expr_type
.GetSignatureForError ());
7455 // TODO: Report.SymbolRelatedToPreviousError
7456 member_lookup
.Error_UnexpectedKind (rc
.Compiler
.Report
, null, "type", loc
);
7460 protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec
, TypeSpec type
, string name
)
7462 if (RootContext
.Version
> LanguageVersion
.ISO_2
&& !ec
.Compiler
.IsRuntimeBinder
&&
7463 ((expr
.eclass
& (ExprClass
.Value
| ExprClass
.Variable
)) != 0)) {
7464 ec
.Report
.Error (1061, loc
, "Type `{0}' does not contain a definition for `{1}' and no " +
7465 "extension method `{1}' of type `{0}' could be found " +
7466 "(are you missing a using directive or an assembly reference?)",
7467 TypeManager
.CSharpName (type
), name
);
7471 base.Error_TypeDoesNotContainDefinition (ec
, type
, name
);
7474 public override string GetSignatureForError ()
7476 return expr
.GetSignatureForError () + "." + base.GetSignatureForError ();
7479 public Expression Left
{
7485 protected override void CloneTo (CloneContext clonectx
, Expression t
)
7487 MemberAccess target
= (MemberAccess
) t
;
7489 target
.expr
= expr
.Clone (clonectx
);
7494 /// Implements checked expressions
7496 public class CheckedExpr
: Expression
{
7498 public Expression Expr
;
7500 public CheckedExpr (Expression e
, Location l
)
7506 public override Expression
CreateExpressionTree (ResolveContext ec
)
7508 using (ec
.With (ResolveContext
.Options
.AllCheckStateFlags
, true))
7509 return Expr
.CreateExpressionTree (ec
);
7512 protected override Expression
DoResolve (ResolveContext ec
)
7514 using (ec
.With (ResolveContext
.Options
.AllCheckStateFlags
, true))
7515 Expr
= Expr
.Resolve (ec
);
7520 if (Expr
is Constant
|| Expr
is MethodGroupExpr
|| Expr
is AnonymousMethodExpression
|| Expr
is DefaultValueExpression
)
7523 eclass
= Expr
.eclass
;
7528 public override void Emit (EmitContext ec
)
7530 using (ec
.With (EmitContext
.Options
.AllCheckStateFlags
, true))
7534 public override void EmitBranchable (EmitContext ec
, Label target
, bool on_true
)
7536 using (ec
.With (EmitContext
.Options
.AllCheckStateFlags
, true))
7537 Expr
.EmitBranchable (ec
, target
, on_true
);
7540 public override SLE
.Expression
MakeExpression (BuilderContext ctx
)
7542 using (ctx
.With (BuilderContext
.Options
.AllCheckStateFlags
, true)) {
7543 return Expr
.MakeExpression (ctx
);
7547 protected override void CloneTo (CloneContext clonectx
, Expression t
)
7549 CheckedExpr target
= (CheckedExpr
) t
;
7551 target
.Expr
= Expr
.Clone (clonectx
);
7556 /// Implements the unchecked expression
7558 public class UnCheckedExpr
: Expression
{
7560 public Expression Expr
;
7562 public UnCheckedExpr (Expression e
, Location l
)
7568 public override Expression
CreateExpressionTree (ResolveContext ec
)
7570 using (ec
.With (ResolveContext
.Options
.AllCheckStateFlags
, false))
7571 return Expr
.CreateExpressionTree (ec
);
7574 protected override Expression
DoResolve (ResolveContext ec
)
7576 using (ec
.With (ResolveContext
.Options
.AllCheckStateFlags
, false))
7577 Expr
= Expr
.Resolve (ec
);
7582 if (Expr
is Constant
|| Expr
is MethodGroupExpr
|| Expr
is AnonymousMethodExpression
|| Expr
is DefaultValueExpression
)
7585 eclass
= Expr
.eclass
;
7590 public override void Emit (EmitContext ec
)
7592 using (ec
.With (EmitContext
.Options
.AllCheckStateFlags
, false))
7596 public override void EmitBranchable (EmitContext ec
, Label target
, bool on_true
)
7598 using (ec
.With (EmitContext
.Options
.AllCheckStateFlags
, false))
7599 Expr
.EmitBranchable (ec
, target
, on_true
);
7602 protected override void CloneTo (CloneContext clonectx
, Expression t
)
7604 UnCheckedExpr target
= (UnCheckedExpr
) t
;
7606 target
.Expr
= Expr
.Clone (clonectx
);
7611 /// An Element Access expression.
7613 /// During semantic analysis these are transformed into
7614 /// IndexerAccess, ArrayAccess or a PointerArithmetic.
7616 public class ElementAccess
: Expression
{
7617 public Arguments Arguments
;
7618 public Expression Expr
;
7620 public ElementAccess (Expression e
, Arguments args
)
7624 this.Arguments
= args
;
7627 public override Expression
CreateExpressionTree (ResolveContext ec
)
7629 Arguments args
= Arguments
.CreateForExpressionTree (ec
, Arguments
,
7630 Expr
.CreateExpressionTree (ec
));
7632 return CreateExpressionFactoryCall (ec
, "ArrayIndex", args
);
7635 Expression
MakePointerAccess (ResolveContext ec
, TypeSpec t
)
7637 if (Arguments
.Count
!= 1){
7638 ec
.Report
.Error (196, loc
, "A pointer must be indexed by only one value");
7642 if (Arguments
[0] is NamedArgument
)
7643 Error_NamedArgument ((NamedArgument
) Arguments
[0], ec
.Report
);
7645 Expression p
= new PointerArithmetic (Binary
.Operator
.Addition
, Expr
, Arguments
[0].Expr
.Resolve (ec
), t
, loc
);
7646 return new Indirection (p
, loc
).Resolve (ec
);
7649 protected override Expression
DoResolve (ResolveContext ec
)
7651 Expr
= Expr
.Resolve (ec
);
7656 // We perform some simple tests, and then to "split" the emit and store
7657 // code we create an instance of a different class, and return that.
7659 // I am experimenting with this pattern.
7661 TypeSpec t
= Expr
.Type
;
7663 if (t
== TypeManager
.array_type
){
7664 ec
.Report
.Error (21, loc
, "Cannot apply indexing with [] to an expression of type `System.Array'");
7669 return (new ArrayAccess (this, loc
)).Resolve (ec
);
7671 return MakePointerAccess (ec
, t
);
7673 FieldExpr fe
= Expr
as FieldExpr
;
7675 var ff
= fe
.Spec
as FixedFieldSpec
;
7677 return MakePointerAccess (ec
, ff
.ElementType
);
7680 return (new IndexerAccess (this, loc
)).Resolve (ec
);
7683 public override Expression
DoResolveLValue (ResolveContext ec
, Expression right_side
)
7685 Expr
= Expr
.Resolve (ec
);
7691 return (new ArrayAccess (this, loc
)).DoResolveLValue (ec
, right_side
);
7694 return MakePointerAccess (ec
, type
);
7696 if (Expr
.eclass
!= ExprClass
.Variable
&& TypeManager
.IsStruct (type
))
7697 Error_CannotModifyIntermediateExpressionValue (ec
);
7699 return (new IndexerAccess (this, loc
)).DoResolveLValue (ec
, right_side
);
7702 public override void Emit (EmitContext ec
)
7704 throw new Exception ("Should never be reached");
7707 public static void Error_NamedArgument (NamedArgument na
, Report Report
)
7709 Report
.Error (1742, na
.Location
, "An element access expression cannot use named argument");
7712 public override string GetSignatureForError ()
7714 return Expr
.GetSignatureForError ();
7717 protected override void CloneTo (CloneContext clonectx
, Expression t
)
7719 ElementAccess target
= (ElementAccess
) t
;
7721 target
.Expr
= Expr
.Clone (clonectx
);
7722 if (Arguments
!= null)
7723 target
.Arguments
= Arguments
.Clone (clonectx
);
7728 /// Implements array access
7730 public class ArrayAccess
: Expression
, IDynamicAssign
, IMemoryLocation
{
7732 // Points to our "data" repository
7736 LocalTemporary temp
;
7740 public ArrayAccess (ElementAccess ea_data
, Location l
)
7746 public override Expression
CreateExpressionTree (ResolveContext ec
)
7748 return ea
.CreateExpressionTree (ec
);
7751 public override Expression
DoResolveLValue (ResolveContext ec
, Expression right_side
)
7753 return DoResolve (ec
);
7756 protected override Expression
DoResolve (ResolveContext ec
)
7758 // dynamic is used per argument in ConvertExpressionToArrayIndex case
7760 ea
.Arguments
.Resolve (ec
, out dynamic);
7762 TypeSpec t
= ea
.Expr
.Type
;
7763 int rank
= ea
.Arguments
.Count
;
7764 if (t
.GetMetaInfo ().GetArrayRank () != rank
) {
7765 ec
.Report
.Error (22, ea
.Location
, "Wrong number of indexes `{0}' inside [], expected `{1}'",
7766 ea
.Arguments
.Count
.ToString (), t
.GetMetaInfo ().GetArrayRank ().ToString ());
7770 type
= TypeManager
.GetElementType (t
);
7771 if (type
.IsPointer
&& !ec
.IsUnsafe
) {
7772 UnsafeError (ec
, ea
.Location
);
7775 foreach (Argument a
in ea
.Arguments
) {
7776 if (a
is NamedArgument
)
7777 ElementAccess
.Error_NamedArgument ((NamedArgument
) a
, ec
.Report
);
7779 a
.Expr
= ConvertExpressionToArrayIndex (ec
, a
.Expr
);
7782 eclass
= ExprClass
.Variable
;
7787 protected override void Error_NegativeArrayIndex (ResolveContext ec
, Location loc
)
7789 ec
.Report
.Warning (251, 2, loc
, "Indexing an array with a negative index (array indices always start at zero)");
7793 // Load the array arguments into the stack.
7795 void LoadArrayAndArguments (EmitContext ec
)
7799 for (int i
= 0; i
< ea
.Arguments
.Count
; ++i
) {
7800 ea
.Arguments
[i
].Emit (ec
);
7804 public void Emit (EmitContext ec
, bool leave_copy
)
7806 var ac
= ea
.Expr
.Type
as ArrayContainer
;
7809 ec
.EmitLoadFromPtr (type
);
7811 LoadArrayAndArguments (ec
);
7812 ec
.EmitArrayLoad (ac
);
7816 ec
.Emit (OpCodes
.Dup
);
7817 temp
= new LocalTemporary (this.type
);
7822 public override void Emit (EmitContext ec
)
7827 public void EmitAssign (EmitContext ec
, Expression source
, bool leave_copy
, bool prepare_for_load
)
7829 var ac
= (ArrayContainer
) ea
.Expr
.Type
;
7830 TypeSpec t
= source
.Type
;
7831 prepared
= prepare_for_load
;
7834 AddressOf (ec
, AddressOp
.LoadStore
);
7835 ec
.Emit (OpCodes
.Dup
);
7837 LoadArrayAndArguments (ec
);
7840 // If we are dealing with a struct, get the
7841 // address of it, so we can store it.
7843 // The stobj opcode used by value types will need
7844 // an address on the stack, not really an array/array
7847 if (ac
.Rank
== 1 && TypeManager
.IsStruct (t
) &&
7848 (!TypeManager
.IsBuiltinOrEnum (t
) ||
7849 t
== TypeManager
.decimal_type
)) {
7851 ec
.Emit (OpCodes
.Ldelema
, t
);
7857 ec
.Emit (OpCodes
.Dup
);
7858 temp
= new LocalTemporary (this.type
);
7863 ec
.EmitStoreFromPtr (t
);
7865 ec
.EmitArrayStore (ac
);
7874 public void EmitNew (EmitContext ec
, New source
, bool leave_copy
)
7876 if (!source
.Emit (ec
, this)) {
7878 throw new NotImplementedException ();
7883 throw new NotImplementedException ();
7886 public void AddressOf (EmitContext ec
, AddressOp mode
)
7888 var ac
= (ArrayContainer
) ea
.Expr
.Type
;
7890 LoadArrayAndArguments (ec
);
7891 ec
.EmitArrayAddress (ac
);
7895 public SLE
.Expression
MakeAssignExpression (BuilderContext ctx
)
7897 return SLE
.Expression
.ArrayAccess (
7898 ea
.Expr
.MakeExpression (ctx
),
7899 Arguments
.MakeExpression (ea
.Arguments
, ctx
));
7903 public override SLE
.Expression
MakeExpression (BuilderContext ctx
)
7905 return SLE
.Expression
.ArrayIndex (
7906 ea
.Expr
.MakeExpression (ctx
),
7907 Arguments
.MakeExpression (ea
.Arguments
, ctx
));
7912 /// Expressions that represent an indexer call.
7914 public class IndexerAccess
: Expression
, IDynamicAssign
7916 class IndexerMethodGroupExpr
: MethodGroupExpr
7918 IEnumerable
<IndexerSpec
> candidates
;
7920 public IndexerMethodGroupExpr (IEnumerable
<IndexerSpec
> indexers
, Location loc
)
7921 : base (FilterAccessors (indexers
).ToList (), null, loc
)
7923 candidates
= indexers
;
7926 public IndexerSpec
BestIndexer ()
7928 return MemberCache
.FindIndexers (BestCandidate
.DeclaringType
, BindingRestriction
.None
).
7930 (l
.HasGet
&& l
.Get
.MemberDefinition
== BestCandidate
.MemberDefinition
) ||
7931 (l
.HasSet
&& l
.Set
.MemberDefinition
== BestCandidate
.MemberDefinition
)).First ();
7934 static IEnumerable
<MemberSpec
> FilterAccessors (IEnumerable
<IndexerSpec
> indexers
)
7936 foreach (IndexerSpec i
in indexers
) {
7944 protected override IList
<MemberSpec
> GetBaseTypeMethods (ResolveContext rc
, TypeSpec type
)
7946 candidates
= GetIndexersForType (type
);
7947 if (candidates
== null)
7950 return FilterAccessors (candidates
).ToList ();
7953 public override string Name
{
7959 protected override int GetApplicableParametersCount (MethodSpec method
, AParametersCollection parameters
)
7962 // Here is the trick, decrease number of arguments by 1 when only
7963 // available property method is setter. This makes overload resolution
7964 // work correctly for indexers.
7967 if (method
.Name
[0] == 'g')
7968 return parameters
.Count
;
7970 return parameters
.Count
- 1;
7975 // Points to our "data" repository
7978 bool is_base_indexer
;
7980 LocalTemporary temp
;
7981 LocalTemporary prepared_value
;
7982 Expression set_expr
;
7984 protected TypeSpec indexer_type
;
7985 protected TypeSpec current_type
;
7986 protected Expression instance_expr
;
7987 protected Arguments arguments
;
7989 public IndexerAccess (ElementAccess ea
, Location loc
)
7990 : this (ea
.Expr
, false, loc
)
7992 this.arguments
= ea
.Arguments
;
7995 protected IndexerAccess (Expression instance_expr
, bool is_base_indexer
,
7998 this.instance_expr
= instance_expr
;
7999 this.is_base_indexer
= is_base_indexer
;
8003 static string GetAccessorName (bool isSet
)
8005 return isSet
? "set" : "get";
8008 public override Expression
CreateExpressionTree (ResolveContext ec
)
8010 Arguments args
= Arguments
.CreateForExpressionTree (ec
, arguments
,
8011 instance_expr
.CreateExpressionTree (ec
),
8012 new TypeOfMethod (spec
.Get
, loc
));
8014 return CreateExpressionFactoryCall (ec
, "Call", args
);
8017 static IEnumerable
<IndexerSpec
> GetIndexersForType (TypeSpec lookup_type
)
8019 return MemberCache
.FindIndexers (lookup_type
, BindingRestriction
.AccessibleOnly
| BindingRestriction
.NoOverrides
);
8022 protected virtual void CommonResolve (ResolveContext ec
)
8024 indexer_type
= instance_expr
.Type
;
8025 current_type
= ec
.CurrentType
;
8028 protected override Expression
DoResolve (ResolveContext ec
)
8030 return ResolveAccessor (ec
, null);
8033 public override Expression
DoResolveLValue (ResolveContext ec
, Expression right_side
)
8035 if (right_side
== EmptyExpression
.OutAccess
.Instance
) {
8036 right_side
.DoResolveLValue (ec
, this);
8040 // if the indexer returns a value type, and we try to set a field in it
8041 if (right_side
== EmptyExpression
.LValueMemberAccess
|| right_side
== EmptyExpression
.LValueMemberOutAccess
) {
8042 Error_CannotModifyIntermediateExpressionValue (ec
);
8045 return ResolveAccessor (ec
, right_side
);
8048 Expression
ResolveAccessor (ResolveContext ec
, Expression right_side
)
8054 arguments
.Resolve (ec
, out dynamic);
8056 if (indexer_type
== InternalType
.Dynamic
) {
8059 var ilist
= GetIndexersForType (indexer_type
);
8060 if (ilist
== null) {
8061 ec
.Report
.Error (21, loc
, "Cannot apply indexing with [] to an expression of type `{0}'",
8062 TypeManager
.CSharpName (indexer_type
));
8066 var mg
= new IndexerMethodGroupExpr (ilist
, loc
) {
8067 InstanceExpression
= instance_expr
8070 if (is_base_indexer
)
8071 mg
.QueriedBaseType
= current_type
;
8073 mg
= mg
.OverloadResolve (ec
, ref arguments
, false, loc
) as IndexerMethodGroupExpr
;
8078 spec
= mg
.BestIndexer ();
8082 Arguments args
= new Arguments (arguments
.Count
+ 1);
8083 if (is_base_indexer
) {
8084 ec
.Report
.Error (1972, loc
, "The indexer base access cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access");
8086 args
.Add (new Argument (instance_expr
));
8088 args
.AddRange (arguments
);
8090 var expr
= new DynamicIndexBinder (args
, loc
);
8091 if (right_side
!= null)
8092 return expr
.ResolveLValue (ec
, right_side
);
8094 return expr
.Resolve (ec
);
8097 type
= spec
.MemberType
;
8098 if (type
.IsPointer
&& !ec
.IsUnsafe
)
8099 UnsafeError (ec
, loc
);
8101 MethodSpec accessor
;
8102 if (right_side
== null) {
8103 accessor
= spec
.Get
;
8105 accessor
= spec
.Set
;
8106 if (!spec
.HasSet
&& spec
.HasGet
) {
8107 ec
.Report
.SymbolRelatedToPreviousError (spec
);
8108 ec
.Report
.Error (200, loc
, "The read only property or indexer `{0}' cannot be assigned to",
8109 spec
.GetSignatureForError ());
8113 set_expr
= Convert
.ImplicitConversion (ec
, right_side
, type
, loc
);
8116 if (accessor
== null || accessor
.Kind
== MemberKind
.FakeMethod
) {
8117 ec
.Report
.SymbolRelatedToPreviousError (spec
);
8118 ec
.Report
.Error (154, loc
, "The property or indexer `{0}' cannot be used in this context because it lacks a `{1}' accessor",
8119 spec
.GetSignatureForError (), GetAccessorName (right_side
!= null));
8124 // Only base will allow this invocation to happen.
8126 if (spec
.IsAbstract
&& this is BaseIndexerAccess
) {
8127 Error_CannotCallAbstractBase (ec
, spec
.GetSignatureForError ());
8130 bool must_do_cs1540_check
;
8131 if (!IsMemberAccessible (ec
.CurrentType
, accessor
, out must_do_cs1540_check
)) {
8132 if (spec
.HasDifferentAccessibility
) {
8133 ec
.Report
.SymbolRelatedToPreviousError (accessor
);
8134 ec
.Report
.Error (271, loc
, "The property or indexer `{0}' cannot be used in this context because a `{1}' accessor is inaccessible",
8135 TypeManager
.GetFullNameSignature (spec
), GetAccessorName (right_side
!= null));
8137 ec
.Report
.SymbolRelatedToPreviousError (spec
);
8138 ErrorIsInaccesible (loc
, TypeManager
.GetFullNameSignature (spec
), ec
.Report
);
8142 instance_expr
.CheckMarshalByRefAccess (ec
);
8144 if (must_do_cs1540_check
&& (instance_expr
!= EmptyExpression
.Null
) &&
8145 !TypeManager
.IsInstantiationOfSameGenericType (instance_expr
.Type
, ec
.CurrentType
) &&
8146 !TypeManager
.IsNestedChildOf (ec
.CurrentType
, instance_expr
.Type
) &&
8147 !TypeManager
.IsSubclassOf (instance_expr
.Type
, ec
.CurrentType
)) {
8148 ec
.Report
.SymbolRelatedToPreviousError (accessor
);
8149 Error_CannotAccessProtected (ec
, loc
, spec
, instance_expr
.Type
, ec
.CurrentType
);
8153 eclass
= ExprClass
.IndexerAccess
;
8157 public override void Emit (EmitContext ec
)
8162 public void Emit (EmitContext ec
, bool leave_copy
)
8165 prepared_value
.Emit (ec
);
8167 Invocation
.EmitCall (ec
, is_base_indexer
, instance_expr
, spec
.Get
,
8168 arguments
, loc
, false, false);
8172 ec
.Emit (OpCodes
.Dup
);
8173 temp
= new LocalTemporary (Type
);
8179 // source is ignored, because we already have a copy of it from the
8180 // LValue resolution and we have already constructed a pre-cached
8181 // version of the arguments (ea.set_arguments);
8183 public void EmitAssign (EmitContext ec
, Expression source
, bool leave_copy
, bool prepare_for_load
)
8185 prepared
= prepare_for_load
;
8186 Expression
value = set_expr
;
8189 Invocation
.EmitCall (ec
, is_base_indexer
, instance_expr
, spec
.Get
,
8190 arguments
, loc
, true, false);
8192 prepared_value
= new LocalTemporary (type
);
8193 prepared_value
.Store (ec
);
8195 prepared_value
.Release (ec
);
8198 ec
.Emit (OpCodes
.Dup
);
8199 temp
= new LocalTemporary (Type
);
8202 } else if (leave_copy
) {
8203 temp
= new LocalTemporary (Type
);
8210 arguments
.Add (new Argument (value));
8212 Invocation
.EmitCall (ec
, is_base_indexer
, instance_expr
, spec
.Set
, arguments
, loc
, false, prepared
);
8220 public override string GetSignatureForError ()
8222 return spec
.GetSignatureForError ();
8226 public SLE
.Expression
MakeAssignExpression (BuilderContext ctx
)
8228 var value = new[] { set_expr.MakeExpression (ctx) }
;
8229 var args
= Arguments
.MakeExpression (arguments
, ctx
).Concat (value);
8231 return SLE
.Expression
.Block (
8232 SLE
.Expression
.Call (instance_expr
.MakeExpression (ctx
), (MethodInfo
) spec
.Set
.GetMetaInfo (), args
),
8237 public override SLE
.Expression
MakeExpression (BuilderContext ctx
)
8239 var args
= Arguments
.MakeExpression (arguments
, ctx
);
8240 return SLE
.Expression
.Call (instance_expr
.MakeExpression (ctx
), (MethodInfo
) spec
.Get
.GetMetaInfo (), args
);
8243 protected override void CloneTo (CloneContext clonectx
, Expression t
)
8245 IndexerAccess target
= (IndexerAccess
) t
;
8247 if (arguments
!= null)
8248 target
.arguments
= arguments
.Clone (clonectx
);
8250 if (instance_expr
!= null)
8251 target
.instance_expr
= instance_expr
.Clone (clonectx
);
8256 /// The base operator for method names
8258 public class BaseAccess
: Expression
{
8259 public readonly string Identifier
;
8262 public BaseAccess (string member
, Location l
)
8264 this.Identifier
= member
;
8268 public BaseAccess (string member
, TypeArguments args
, Location l
)
8274 public override Expression
CreateExpressionTree (ResolveContext ec
)
8276 throw new NotSupportedException ("ET");
8279 protected override Expression
DoResolve (ResolveContext ec
)
8281 Expression c
= CommonResolve (ec
);
8287 // MethodGroups use this opportunity to flag an error on lacking ()
8289 if (!(c
is MethodGroupExpr
))
8290 return c
.Resolve (ec
);
8294 public override Expression
DoResolveLValue (ResolveContext ec
, Expression right_side
)
8296 Expression c
= CommonResolve (ec
);
8302 // MethodGroups use this opportunity to flag an error on lacking ()
8304 if (! (c
is MethodGroupExpr
))
8305 return c
.DoResolveLValue (ec
, right_side
);
8310 Expression
CommonResolve (ResolveContext ec
)
8312 Expression member_lookup
;
8313 TypeSpec current_type
= ec
.CurrentType
;
8314 TypeSpec base_type
= current_type
.BaseType
;
8316 if (!This
.IsThisAvailable (ec
, false)) {
8318 ec
.Report
.Error (1511, loc
, "Keyword `base' is not available in a static method");
8320 ec
.Report
.Error (1512, loc
, "Keyword `base' is not available in the current context");
8325 var arity
= args
== null ? -1 : args
.Count
;
8326 member_lookup
= MemberLookup (ec
.Compiler
, ec
.CurrentType
, null, base_type
, Identifier
, arity
,
8327 MemberKind
.All
, BindingRestriction
.AccessibleOnly
| BindingRestriction
.NoOverrides
, loc
);
8328 if (member_lookup
== null) {
8329 Error_MemberLookupFailed (ec
, ec
.CurrentType
, base_type
, base_type
, Identifier
, arity
,
8330 null, MemberKind
.All
, BindingRestriction
.AccessibleOnly
);
8334 MemberExpr me
= member_lookup
as MemberExpr
;
8336 if (member_lookup
is TypeExpression
){
8337 ec
.Report
.Error (582, loc
, "{0}: Can not reference a type through an expression, try `{1}' instead",
8338 Identifier
, member_lookup
.GetSignatureForError ());
8340 ec
.Report
.Error (582, loc
, "{0}: Can not reference a {1} through an expression",
8341 Identifier
, member_lookup
.ExprClassName
);
8347 me
.QueriedBaseType
= base_type
;
8351 me
.SetTypeArguments (ec
, args
);
8357 public override void Emit (EmitContext ec
)
8359 throw new Exception ("Should never be called");
8362 protected override void CloneTo (CloneContext clonectx
, Expression t
)
8364 BaseAccess target
= (BaseAccess
) t
;
8367 target
.args
= args
.Clone ();
8372 /// The base indexer operator
8374 public class BaseIndexerAccess
: IndexerAccess
{
8375 public BaseIndexerAccess (Arguments args
, Location loc
)
8376 : base (null, true, loc
)
8378 this.arguments
= args
;
8381 protected override void CommonResolve (ResolveContext ec
)
8383 instance_expr
= ec
.GetThis (loc
);
8385 current_type
= ec
.CurrentType
.BaseType
;
8386 indexer_type
= current_type
;
8389 public override Expression
CreateExpressionTree (ResolveContext ec
)
8391 MemberExpr
.Error_BaseAccessInExpressionTree (ec
, loc
);
8392 return base.CreateExpressionTree (ec
);
8397 /// This class exists solely to pass the Type around and to be a dummy
8398 /// that can be passed to the conversion functions (this is used by
8399 /// foreach implementation to typecast the object return value from
8400 /// get_Current into the proper type. All code has been generated and
8401 /// we only care about the side effect conversions to be performed
8403 /// This is also now used as a placeholder where a no-action expression
8404 /// is needed (the `New' class).
8406 public class EmptyExpression
: Expression
{
8407 public static readonly Expression Null
= new EmptyExpression ();
8409 public class OutAccess
: EmptyExpression
8411 public static readonly OutAccess Instance
= new OutAccess ();
8413 public override Expression
DoResolveLValue (ResolveContext rc
, Expression right_side
)
8415 rc
.Report
.Error (206, right_side
.Location
,
8416 "A property, indexer or dynamic member access may not be passed as `ref' or `out' parameter");
8422 public static readonly EmptyExpression LValueMemberAccess
= new EmptyExpression ();
8423 public static readonly EmptyExpression LValueMemberOutAccess
= new EmptyExpression ();
8424 public static readonly EmptyExpression UnaryAddress
= new EmptyExpression ();
8426 static EmptyExpression temp
= new EmptyExpression ();
8427 public static EmptyExpression
Grab ()
8429 EmptyExpression retval
= temp
== null ? new EmptyExpression () : temp
;
8434 public static void Release (EmptyExpression e
)
8441 // FIXME: Don't set to object
8442 type
= TypeManager
.object_type
;
8443 eclass
= ExprClass
.Value
;
8444 loc
= Location
.Null
;
8447 public EmptyExpression (TypeSpec t
)
8450 eclass
= ExprClass
.Value
;
8451 loc
= Location
.Null
;
8454 public override Expression
CreateExpressionTree (ResolveContext ec
)
8456 throw new NotSupportedException ("ET");
8459 protected override Expression
DoResolve (ResolveContext ec
)
8464 public override void Emit (EmitContext ec
)
8466 // nothing, as we only exist to not do anything.
8469 public override void EmitSideEffect (EmitContext ec
)
8474 // This is just because we might want to reuse this bad boy
8475 // instead of creating gazillions of EmptyExpressions.
8476 // (CanImplicitConversion uses it)
8478 public void SetType (TypeSpec t
)
8485 // Empty statement expression
8487 public sealed class EmptyExpressionStatement
: ExpressionStatement
8489 public static readonly EmptyExpressionStatement Instance
= new EmptyExpressionStatement ();
8491 private EmptyExpressionStatement ()
8493 loc
= Location
.Null
;
8496 public override Expression
CreateExpressionTree (ResolveContext ec
)
8501 public override void EmitStatement (EmitContext ec
)
8506 protected override Expression
DoResolve (ResolveContext ec
)
8508 eclass
= ExprClass
.Value
;
8509 type
= TypeManager
.object_type
;
8513 public override void Emit (EmitContext ec
)
8519 public class UserCast
: Expression
{
8523 public UserCast (MethodSpec method
, Expression source
, Location l
)
8525 this.method
= method
;
8526 this.source
= source
;
8527 type
= method
.ReturnType
;
8531 public Expression Source
{
8537 public override Expression
CreateExpressionTree (ResolveContext ec
)
8539 Arguments args
= new Arguments (3);
8540 args
.Add (new Argument (source
.CreateExpressionTree (ec
)));
8541 args
.Add (new Argument (new TypeOf (new TypeExpression (type
, loc
), loc
)));
8542 args
.Add (new Argument (new TypeOfMethod (method
, loc
)));
8543 return CreateExpressionFactoryCall (ec
, "Convert", args
);
8546 protected override Expression
DoResolve (ResolveContext ec
)
8548 ObsoleteAttribute oa
= method
.GetAttributeObsolete ();
8550 AttributeTester
.Report_ObsoleteMessage (oa
, GetSignatureForError (), loc
, ec
.Report
);
8552 eclass
= ExprClass
.Value
;
8556 public override void Emit (EmitContext ec
)
8559 ec
.Emit (OpCodes
.Call
, method
);
8562 public override string GetSignatureForError ()
8564 return TypeManager
.CSharpSignature (method
);
8567 public override SLE
.Expression
MakeExpression (BuilderContext ctx
)
8569 return SLE
.Expression
.Convert (source
.MakeExpression (ctx
), type
.GetMetaInfo (), (MethodInfo
) method
.GetMetaInfo ());
8574 // This class is used to "construct" the type during a typecast
8575 // operation. Since the Type.GetType class in .NET can parse
8576 // the type specification, we just use this to construct the type
8577 // one bit at a time.
8579 public class ComposedCast
: TypeExpr
{
8580 FullNamedExpression left
;
8583 public ComposedCast (FullNamedExpression left
, string dim
)
8584 : this (left
, dim
, left
.Location
)
8588 public ComposedCast (FullNamedExpression left
, string dim
, Location l
)
8595 protected override TypeExpr
DoResolveAsTypeStep (IMemberContext ec
)
8597 TypeExpr lexpr
= left
.ResolveAsTypeTerminal (ec
, false);
8601 TypeSpec ltype
= lexpr
.Type
;
8602 if ((dim
.Length
> 0) && (dim
[0] == '?')) {
8603 TypeExpr nullable
= new Nullable
.NullableType (lexpr
, loc
);
8605 nullable
= new ComposedCast (nullable
, dim
.Substring (1), loc
);
8606 return nullable
.ResolveAsTypeTerminal (ec
, false);
8609 if (dim
== "*" && !TypeManager
.VerifyUnmanaged (ec
.Compiler
, ltype
, loc
))
8612 if (dim
.Length
!= 0 && dim
[0] == '[') {
8613 if (TypeManager
.IsSpecialType (ltype
)) {
8614 ec
.Compiler
.Report
.Error (611, loc
, "Array elements cannot be of type `{0}'", TypeManager
.CSharpName (ltype
));
8618 if (ltype
.IsStatic
) {
8619 ec
.Compiler
.Report
.SymbolRelatedToPreviousError (ltype
);
8620 ec
.Compiler
.Report
.Error (719, loc
, "Array elements cannot be of static type `{0}'",
8621 TypeManager
.CSharpName (ltype
));
8626 type
= TypeManager
.GetConstructedType (ltype
, dim
);
8631 throw new InternalErrorException ("Couldn't create computed type " + ltype
+ dim
);
8633 if (type
.IsPointer
&& !ec
.IsUnsafe
){
8634 UnsafeError (ec
.Compiler
.Report
, loc
);
8637 eclass
= ExprClass
.Type
;
8641 public override string GetSignatureForError ()
8643 return left
.GetSignatureForError () + dim
;
8647 public class FixedBufferPtr
: Expression
{
8650 public FixedBufferPtr (Expression array
, TypeSpec array_type
, Location l
)
8655 type
= PointerContainer
.MakeType (array_type
);
8656 eclass
= ExprClass
.Value
;
8659 public override Expression
CreateExpressionTree (ResolveContext ec
)
8661 Error_PointerInsideExpressionTree (ec
);
8665 public override void Emit(EmitContext ec
)
8670 protected override Expression
DoResolve (ResolveContext ec
)
8673 // We are born fully resolved
8681 // This class is used to represent the address of an array, used
8682 // only by the Fixed statement, this generates "&a [0]" construct
8683 // for fixed (char *pa = a)
8685 public class ArrayPtr
: FixedBufferPtr
{
8686 TypeSpec array_type
;
8688 public ArrayPtr (Expression array
, TypeSpec array_type
, Location l
):
8689 base (array
, array_type
, l
)
8691 this.array_type
= array_type
;
8694 public override void Emit (EmitContext ec
)
8699 ec
.Emit (OpCodes
.Ldelema
, array_type
);
8704 // Encapsulates a conversion rules required for array indexes
8706 public class ArrayIndexCast
: TypeCast
8708 public ArrayIndexCast (Expression expr
)
8709 : base (expr
, TypeManager
.int32_type
)
8711 if (expr
.Type
== TypeManager
.int32_type
)
8712 throw new ArgumentException ("unnecessary array index conversion");
8715 public override Expression
CreateExpressionTree (ResolveContext ec
)
8717 using (ec
.Set (ResolveContext
.Options
.CheckedScope
)) {
8718 return base.CreateExpressionTree (ec
);
8722 public override void Emit (EmitContext ec
)
8726 var expr_type
= child
.Type
;
8728 if (expr_type
== TypeManager
.uint32_type
)
8729 ec
.Emit (OpCodes
.Conv_U
);
8730 else if (expr_type
== TypeManager
.int64_type
)
8731 ec
.Emit (OpCodes
.Conv_Ovf_I
);
8732 else if (expr_type
== TypeManager
.uint64_type
)
8733 ec
.Emit (OpCodes
.Conv_Ovf_I_Un
);
8735 throw new InternalErrorException ("Cannot emit cast to unknown array element type", type
);
8740 // Implements the `stackalloc' keyword
8742 public class StackAlloc
: Expression
{
8747 public StackAlloc (Expression type
, Expression count
, Location l
)
8754 public override Expression
CreateExpressionTree (ResolveContext ec
)
8756 throw new NotSupportedException ("ET");
8759 protected override Expression
DoResolve (ResolveContext ec
)
8761 count
= count
.Resolve (ec
);
8765 if (count
.Type
!= TypeManager
.uint32_type
){
8766 count
= Convert
.ImplicitConversionRequired (ec
, count
, TypeManager
.int32_type
, loc
);
8771 Constant c
= count
as Constant
;
8772 if (c
!= null && c
.IsNegative
) {
8773 ec
.Report
.Error (247, loc
, "Cannot use a negative size with stackalloc");
8776 if (ec
.HasAny (ResolveContext
.Options
.CatchScope
| ResolveContext
.Options
.FinallyScope
)) {
8777 ec
.Report
.Error (255, loc
, "Cannot use stackalloc in finally or catch");
8780 TypeExpr texpr
= t
.ResolveAsTypeTerminal (ec
, false);
8786 if (!TypeManager
.VerifyUnmanaged (ec
.Compiler
, otype
, loc
))
8789 type
= PointerContainer
.MakeType (otype
);
8790 eclass
= ExprClass
.Value
;
8795 public override void Emit (EmitContext ec
)
8797 int size
= GetTypeSize (otype
);
8802 ec
.Emit (OpCodes
.Sizeof
, otype
);
8806 ec
.Emit (OpCodes
.Mul_Ovf_Un
);
8807 ec
.Emit (OpCodes
.Localloc
);
8810 protected override void CloneTo (CloneContext clonectx
, Expression t
)
8812 StackAlloc target
= (StackAlloc
) t
;
8813 target
.count
= count
.Clone (clonectx
);
8814 target
.t
= t
.Clone (clonectx
);
8819 // An object initializer expression
8821 public class ElementInitializer
: Assign
8823 public readonly string Name
;
8825 public ElementInitializer (string name
, Expression initializer
, Location loc
)
8826 : base (null, initializer
, loc
)
8831 protected override void CloneTo (CloneContext clonectx
, Expression t
)
8833 ElementInitializer target
= (ElementInitializer
) t
;
8834 target
.source
= source
.Clone (clonectx
);
8837 public override Expression
CreateExpressionTree (ResolveContext ec
)
8839 Arguments args
= new Arguments (2);
8840 FieldExpr fe
= target
as FieldExpr
;
8842 args
.Add (new Argument (fe
.CreateTypeOfExpression ()));
8844 args
.Add (new Argument (((PropertyExpr
)target
).CreateSetterTypeOfExpression ()));
8846 args
.Add (new Argument (source
.CreateExpressionTree (ec
)));
8847 return CreateExpressionFactoryCall (ec
,
8848 source
is CollectionOrObjectInitializers
? "ListBind" : "Bind",
8852 protected override Expression
DoResolve (ResolveContext ec
)
8855 return EmptyExpressionStatement
.Instance
;
8857 MemberExpr me
= MemberLookupFinal (ec
, ec
.CurrentInitializerVariable
.Type
, ec
.CurrentInitializerVariable
.Type
,
8858 Name
, 0, MemberKind
.Field
| MemberKind
.Property
, BindingRestriction
.AccessibleOnly
| BindingRestriction
.InstanceOnly
, loc
) as MemberExpr
;
8864 me
.InstanceExpression
= ec
.CurrentInitializerVariable
;
8866 if (source
is CollectionOrObjectInitializers
) {
8867 Expression previous
= ec
.CurrentInitializerVariable
;
8868 ec
.CurrentInitializerVariable
= target
;
8869 source
= source
.Resolve (ec
);
8870 ec
.CurrentInitializerVariable
= previous
;
8874 eclass
= source
.eclass
;
8879 Expression expr
= base.DoResolve (ec
);
8884 // Ignore field initializers with default value
8886 Constant c
= source
as Constant
;
8887 if (c
!= null && c
.IsDefaultInitializer (type
) && target
.eclass
== ExprClass
.Variable
)
8888 return EmptyExpressionStatement
.Instance
.Resolve (ec
);
8893 protected override MemberExpr
Error_MemberLookupFailed (ResolveContext ec
, TypeSpec type
, IList
<MemberSpec
> members
)
8895 var member
= members
.First ();
8896 if (member
.Kind
!= MemberKind
.Property
&& member
.Kind
!= MemberKind
.Field
)
8897 ec
.Report
.Error (1913, loc
, "Member `{0}' cannot be initialized. An object " +
8898 "initializer may only be used for fields, or properties", TypeManager
.GetFullNameSignature (member
));
8900 ec
.Report
.Error (1914, loc
, " Static field or property `{0}' cannot be assigned in an object initializer",
8901 TypeManager
.GetFullNameSignature (member
));
8906 public override void EmitStatement (EmitContext ec
)
8908 if (source
is CollectionOrObjectInitializers
)
8911 base.EmitStatement (ec
);
8916 // A collection initializer expression
8918 class CollectionElementInitializer
: Invocation
8920 public class ElementInitializerArgument
: Argument
8922 public ElementInitializerArgument (Expression e
)
8928 sealed class AddMemberAccess
: MemberAccess
8930 public AddMemberAccess (Expression expr
, Location loc
)
8931 : base (expr
, "Add", loc
)
8935 protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec
, TypeSpec type
, string name
)
8937 if (TypeManager
.HasElementType (type
))
8940 base.Error_TypeDoesNotContainDefinition (ec
, type
, name
);
8944 public CollectionElementInitializer (Expression argument
)
8945 : base (null, new Arguments (1))
8947 base.arguments
.Add (new ElementInitializerArgument (argument
));
8948 this.loc
= argument
.Location
;
8951 public CollectionElementInitializer (List
<Expression
> arguments
, Location loc
)
8952 : base (null, new Arguments (arguments
.Count
))
8954 foreach (Expression e
in arguments
)
8955 base.arguments
.Add (new ElementInitializerArgument (e
));
8960 public override Expression
CreateExpressionTree (ResolveContext ec
)
8962 Arguments args
= new Arguments (2);
8963 args
.Add (new Argument (mg
.CreateExpressionTree (ec
)));
8965 var expr_initializers
= new ArrayInitializer (arguments
.Count
, loc
);
8966 foreach (Argument a
in arguments
)
8967 expr_initializers
.Add (a
.CreateExpressionTree (ec
));
8969 args
.Add (new Argument (new ArrayCreation (
8970 CreateExpressionTypeExpression (ec
, loc
), "[]", expr_initializers
, loc
)));
8971 return CreateExpressionFactoryCall (ec
, "ElementInit", args
);
8974 protected override void CloneTo (CloneContext clonectx
, Expression t
)
8976 CollectionElementInitializer target
= (CollectionElementInitializer
) t
;
8977 if (arguments
!= null)
8978 target
.arguments
= arguments
.Clone (clonectx
);
8981 protected override Expression
DoResolve (ResolveContext ec
)
8983 base.expr
= new AddMemberAccess (ec
.CurrentInitializerVariable
, loc
);
8985 return base.DoResolve (ec
);
8990 // A block of object or collection initializers
8992 public class CollectionOrObjectInitializers
: ExpressionStatement
8994 IList
<Expression
> initializers
;
8995 bool is_collection_initialization
;
8997 public static readonly CollectionOrObjectInitializers Empty
=
8998 new CollectionOrObjectInitializers (Array
.AsReadOnly (new Expression
[0]), Location
.Null
);
9000 public CollectionOrObjectInitializers (IList
<Expression
> initializers
, Location loc
)
9002 this.initializers
= initializers
;
9006 public bool IsEmpty
{
9008 return initializers
.Count
== 0;
9012 public bool IsCollectionInitializer
{
9014 return is_collection_initialization
;
9018 protected override void CloneTo (CloneContext clonectx
, Expression target
)
9020 CollectionOrObjectInitializers t
= (CollectionOrObjectInitializers
) target
;
9022 t
.initializers
= new List
<Expression
> (initializers
.Count
);
9023 foreach (var e
in initializers
)
9024 t
.initializers
.Add (e
.Clone (clonectx
));
9027 public override Expression
CreateExpressionTree (ResolveContext ec
)
9029 var expr_initializers
= new ArrayInitializer (initializers
.Count
, loc
);
9030 foreach (Expression e
in initializers
) {
9031 Expression expr
= e
.CreateExpressionTree (ec
);
9033 expr_initializers
.Add (expr
);
9036 return new ImplicitlyTypedArrayCreation ("[]", expr_initializers
, loc
);
9039 protected override Expression
DoResolve (ResolveContext ec
)
9041 List
<string> element_names
= null;
9042 for (int i
= 0; i
< initializers
.Count
; ++i
) {
9043 Expression initializer
= (Expression
) initializers
[i
];
9044 ElementInitializer element_initializer
= initializer
as ElementInitializer
;
9047 if (element_initializer
!= null) {
9048 element_names
= new List
<string> (initializers
.Count
);
9049 element_names
.Add (element_initializer
.Name
);
9050 } else if (initializer
is CompletingExpression
){
9051 initializer
.Resolve (ec
);
9052 throw new InternalErrorException ("This line should never be reached");
9054 if (!ec
.CurrentInitializerVariable
.Type
.ImplementsInterface (TypeManager
.ienumerable_type
)) {
9055 ec
.Report
.Error (1922, loc
, "A field or property `{0}' cannot be initialized with a collection " +
9056 "object initializer because type `{1}' does not implement `{2}' interface",
9057 ec
.CurrentInitializerVariable
.GetSignatureForError (),
9058 TypeManager
.CSharpName (ec
.CurrentInitializerVariable
.Type
),
9059 TypeManager
.CSharpName (TypeManager
.ienumerable_type
));
9062 is_collection_initialization
= true;
9065 if (is_collection_initialization
!= (element_initializer
== null)) {
9066 ec
.Report
.Error (747, initializer
.Location
, "Inconsistent `{0}' member declaration",
9067 is_collection_initialization
? "collection initializer" : "object initializer");
9071 if (!is_collection_initialization
) {
9072 if (element_names
.Contains (element_initializer
.Name
)) {
9073 ec
.Report
.Error (1912, element_initializer
.Location
,
9074 "An object initializer includes more than one member `{0}' initialization",
9075 element_initializer
.Name
);
9077 element_names
.Add (element_initializer
.Name
);
9082 Expression e
= initializer
.Resolve (ec
);
9083 if (e
== EmptyExpressionStatement
.Instance
)
9084 initializers
.RemoveAt (i
--);
9086 initializers
[i
] = e
;
9089 type
= ec
.CurrentInitializerVariable
.Type
;
9090 if (is_collection_initialization
) {
9091 if (TypeManager
.HasElementType (type
)) {
9092 ec
.Report
.Error (1925, loc
, "Cannot initialize object of type `{0}' with a collection initializer",
9093 TypeManager
.CSharpName (type
));
9097 eclass
= ExprClass
.Variable
;
9101 public override void Emit (EmitContext ec
)
9106 public override void EmitStatement (EmitContext ec
)
9108 foreach (ExpressionStatement e
in initializers
)
9109 e
.EmitStatement (ec
);
9114 // New expression with element/object initializers
9116 public class NewInitialize
: New
9119 // This class serves as a proxy for variable initializer target instances.
9120 // A real variable is assigned later when we resolve left side of an
9123 sealed class InitializerTargetExpression
: Expression
, IMemoryLocation
9125 NewInitialize new_instance
;
9127 public InitializerTargetExpression (NewInitialize newInstance
)
9129 this.type
= newInstance
.type
;
9130 this.loc
= newInstance
.loc
;
9131 this.eclass
= newInstance
.eclass
;
9132 this.new_instance
= newInstance
;
9135 public override Expression
CreateExpressionTree (ResolveContext ec
)
9137 // Should not be reached
9138 throw new NotSupportedException ("ET");
9141 protected override Expression
DoResolve (ResolveContext ec
)
9146 public override Expression
DoResolveLValue (ResolveContext ec
, Expression right_side
)
9151 public override void Emit (EmitContext ec
)
9153 Expression e
= (Expression
) new_instance
.instance
;
9157 #region IMemoryLocation Members
9159 public void AddressOf (EmitContext ec
, AddressOp mode
)
9161 new_instance
.instance
.AddressOf (ec
, mode
);
9167 CollectionOrObjectInitializers initializers
;
9168 IMemoryLocation instance
;
9170 public NewInitialize (Expression requested_type
, Arguments arguments
, CollectionOrObjectInitializers initializers
, Location l
)
9171 : base (requested_type
, arguments
, l
)
9173 this.initializers
= initializers
;
9176 protected override IMemoryLocation
EmitAddressOf (EmitContext ec
, AddressOp Mode
)
9178 instance
= base.EmitAddressOf (ec
, Mode
);
9180 if (!initializers
.IsEmpty
)
9181 initializers
.Emit (ec
);
9186 protected override void CloneTo (CloneContext clonectx
, Expression t
)
9188 base.CloneTo (clonectx
, t
);
9190 NewInitialize target
= (NewInitialize
) t
;
9191 target
.initializers
= (CollectionOrObjectInitializers
) initializers
.Clone (clonectx
);
9194 public override Expression
CreateExpressionTree (ResolveContext ec
)
9196 Arguments args
= new Arguments (2);
9197 args
.Add (new Argument (base.CreateExpressionTree (ec
)));
9198 if (!initializers
.IsEmpty
)
9199 args
.Add (new Argument (initializers
.CreateExpressionTree (ec
)));
9201 return CreateExpressionFactoryCall (ec
,
9202 initializers
.IsCollectionInitializer
? "ListInit" : "MemberInit",
9206 protected override Expression
DoResolve (ResolveContext ec
)
9208 Expression e
= base.DoResolve (ec
);
9212 Expression previous
= ec
.CurrentInitializerVariable
;
9213 ec
.CurrentInitializerVariable
= new InitializerTargetExpression (this);
9214 initializers
.Resolve (ec
);
9215 ec
.CurrentInitializerVariable
= previous
;
9219 public override bool Emit (EmitContext ec
, IMemoryLocation target
)
9221 bool left_on_stack
= base.Emit (ec
, target
);
9223 if (initializers
.IsEmpty
)
9224 return left_on_stack
;
9226 LocalTemporary temp
= target
as LocalTemporary
;
9228 if (!left_on_stack
) {
9229 VariableReference vr
= target
as VariableReference
;
9231 // FIXME: This still does not work correctly for pre-set variables
9232 if (vr
!= null && vr
.IsRef
)
9233 target
.AddressOf (ec
, AddressOp
.Load
);
9235 ((Expression
) target
).Emit (ec
);
9236 left_on_stack
= true;
9239 temp
= new LocalTemporary (type
);
9246 initializers
.Emit (ec
);
9248 if (left_on_stack
) {
9253 return left_on_stack
;
9256 public override bool HasInitializer
{
9258 return !initializers
.IsEmpty
;
9263 public class NewAnonymousType
: New
9265 static readonly AnonymousTypeParameter
[] EmptyParameters
= new AnonymousTypeParameter
[0];
9267 List
<AnonymousTypeParameter
> parameters
;
9268 readonly TypeContainer parent
;
9269 AnonymousTypeClass anonymous_type
;
9271 public NewAnonymousType (List
<AnonymousTypeParameter
> parameters
, TypeContainer parent
, Location loc
)
9272 : base (null, null, loc
)
9274 this.parameters
= parameters
;
9275 this.parent
= parent
;
9278 protected override void CloneTo (CloneContext clonectx
, Expression target
)
9280 if (parameters
== null)
9283 NewAnonymousType t
= (NewAnonymousType
) target
;
9284 t
.parameters
= new List
<AnonymousTypeParameter
> (parameters
.Count
);
9285 foreach (AnonymousTypeParameter atp
in parameters
)
9286 t
.parameters
.Add ((AnonymousTypeParameter
) atp
.Clone (clonectx
));
9289 AnonymousTypeClass
CreateAnonymousType (ResolveContext ec
, IList
<AnonymousTypeParameter
> parameters
)
9291 AnonymousTypeClass type
= parent
.Module
.Compiled
.GetAnonymousType (parameters
);
9295 type
= AnonymousTypeClass
.Create (ec
.Compiler
, parent
, parameters
, loc
);
9301 type
.ResolveTypeParameters ();
9304 if (ec
.Report
.Errors
== 0)
9307 parent
.Module
.Compiled
.AddAnonymousType (type
);
9311 public override Expression
CreateExpressionTree (ResolveContext ec
)
9313 if (parameters
== null)
9314 return base.CreateExpressionTree (ec
);
9316 var init
= new ArrayInitializer (parameters
.Count
, loc
);
9317 foreach (Property p
in anonymous_type
.Properties
)
9318 init
.Add (new TypeOfMethod (MemberCache
.GetMember (type
, p
.Get
.Spec
), loc
));
9320 var ctor_args
= new ArrayInitializer (Arguments
.Count
, loc
);
9321 foreach (Argument a
in Arguments
)
9322 ctor_args
.Add (a
.CreateExpressionTree (ec
));
9324 Arguments args
= new Arguments (3);
9325 args
.Add (new Argument (method
.CreateExpressionTree (ec
)));
9326 args
.Add (new Argument (new ArrayCreation (TypeManager
.expression_type_expr
, "[]", ctor_args
, loc
)));
9327 args
.Add (new Argument (new ImplicitlyTypedArrayCreation ("[]", init
, loc
)));
9329 return CreateExpressionFactoryCall (ec
, "New", args
);
9332 protected override Expression
DoResolve (ResolveContext ec
)
9334 if (ec
.HasSet (ResolveContext
.Options
.ConstantScope
)) {
9335 ec
.Report
.Error (836, loc
, "Anonymous types cannot be used in this expression");
9339 if (parameters
== null) {
9340 anonymous_type
= CreateAnonymousType (ec
, EmptyParameters
);
9341 RequestedType
= new TypeExpression (anonymous_type
.Definition
, loc
);
9342 return base.DoResolve (ec
);
9346 Arguments
= new Arguments (parameters
.Count
);
9347 TypeExpression
[] t_args
= new TypeExpression
[parameters
.Count
];
9348 for (int i
= 0; i
< parameters
.Count
; ++i
) {
9349 Expression e
= ((AnonymousTypeParameter
) parameters
[i
]).Resolve (ec
);
9355 Arguments
.Add (new Argument (e
));
9356 t_args
[i
] = new TypeExpression (e
.Type
, e
.Location
);
9362 anonymous_type
= CreateAnonymousType (ec
, parameters
);
9363 if (anonymous_type
== null)
9366 RequestedType
= new GenericTypeExpr (anonymous_type
.Definition
, new TypeArguments (t_args
), loc
);
9367 return base.DoResolve (ec
);
9371 public class AnonymousTypeParameter
: ShimExpression
9373 public readonly string Name
;
9375 public AnonymousTypeParameter (Expression initializer
, string name
, Location loc
)
9376 : base (initializer
)
9382 public AnonymousTypeParameter (Parameter parameter
)
9383 : base (new SimpleName (parameter
.Name
, parameter
.Location
))
9385 this.Name
= parameter
.Name
;
9386 this.loc
= parameter
.Location
;
9389 public override bool Equals (object o
)
9391 AnonymousTypeParameter other
= o
as AnonymousTypeParameter
;
9392 return other
!= null && Name
== other
.Name
;
9395 public override int GetHashCode ()
9397 return Name
.GetHashCode ();
9400 protected override Expression
DoResolve (ResolveContext ec
)
9402 Expression e
= expr
.Resolve (ec
);
9406 if (e
.eclass
== ExprClass
.MethodGroup
) {
9407 Error_InvalidInitializer (ec
, e
.ExprClassName
);
9412 if (type
== TypeManager
.void_type
|| type
== TypeManager
.null_type
||
9413 type
== InternalType
.AnonymousMethod
|| type
.IsPointer
) {
9414 Error_InvalidInitializer (ec
, e
.GetSignatureForError ());
9421 protected virtual void Error_InvalidInitializer (ResolveContext ec
, string initializer
)
9423 ec
.Report
.Error (828, loc
, "An anonymous type property `{0}' cannot be initialized with `{1}'",